View.java revision d047116fade5a9fc826c0caa5ae24333138565e1
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
21import static android.os.Build.VERSION_CODES.KITKAT;
22import static android.os.Build.VERSION_CODES.M;
23import static android.os.Build.VERSION_CODES.N;
24
25import static java.lang.Math.max;
26
27import android.animation.AnimatorInflater;
28import android.animation.StateListAnimator;
29import android.annotation.CallSuper;
30import android.annotation.ColorInt;
31import android.annotation.DrawableRes;
32import android.annotation.FloatRange;
33import android.annotation.IdRes;
34import android.annotation.IntDef;
35import android.annotation.IntRange;
36import android.annotation.LayoutRes;
37import android.annotation.NonNull;
38import android.annotation.Nullable;
39import android.annotation.Size;
40import android.annotation.TestApi;
41import android.annotation.UiThread;
42import android.content.ClipData;
43import android.content.Context;
44import android.content.ContextWrapper;
45import android.content.Intent;
46import android.content.res.ColorStateList;
47import android.content.res.Configuration;
48import android.content.res.Resources;
49import android.content.res.TypedArray;
50import android.graphics.Bitmap;
51import android.graphics.Canvas;
52import android.graphics.Color;
53import android.graphics.Insets;
54import android.graphics.Interpolator;
55import android.graphics.LinearGradient;
56import android.graphics.Matrix;
57import android.graphics.Outline;
58import android.graphics.Paint;
59import android.graphics.PixelFormat;
60import android.graphics.Point;
61import android.graphics.PorterDuff;
62import android.graphics.PorterDuffXfermode;
63import android.graphics.Rect;
64import android.graphics.RectF;
65import android.graphics.Region;
66import android.graphics.Shader;
67import android.graphics.drawable.ColorDrawable;
68import android.graphics.drawable.Drawable;
69import android.hardware.display.DisplayManagerGlobal;
70import android.os.Build.VERSION_CODES;
71import android.os.Bundle;
72import android.os.Handler;
73import android.os.IBinder;
74import android.os.Parcel;
75import android.os.Parcelable;
76import android.os.RemoteException;
77import android.os.SystemClock;
78import android.os.SystemProperties;
79import android.os.Trace;
80import android.text.TextUtils;
81import android.util.AttributeSet;
82import android.util.FloatProperty;
83import android.util.LayoutDirection;
84import android.util.Log;
85import android.util.LongSparseLongArray;
86import android.util.Pools.SynchronizedPool;
87import android.util.Property;
88import android.util.SparseArray;
89import android.util.StateSet;
90import android.util.SuperNotCalledException;
91import android.util.TypedValue;
92import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
93import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
94import android.view.AccessibilityIterators.TextSegmentIterator;
95import android.view.AccessibilityIterators.WordTextSegmentIterator;
96import android.view.ContextMenu.ContextMenuInfo;
97import android.view.accessibility.AccessibilityEvent;
98import android.view.accessibility.AccessibilityEventSource;
99import android.view.accessibility.AccessibilityManager;
100import android.view.accessibility.AccessibilityNodeInfo;
101import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
102import android.view.accessibility.AccessibilityNodeProvider;
103import android.view.animation.Animation;
104import android.view.animation.AnimationUtils;
105import android.view.animation.Transformation;
106import android.view.inputmethod.EditorInfo;
107import android.view.inputmethod.InputConnection;
108import android.view.inputmethod.InputMethodManager;
109import android.widget.Checkable;
110import android.widget.FrameLayout;
111import android.widget.ScrollBarDrawable;
112
113import com.android.internal.R;
114import com.android.internal.util.Predicate;
115import com.android.internal.view.TooltipPopup;
116import com.android.internal.view.menu.MenuBuilder;
117import com.android.internal.widget.ScrollBarUtils;
118
119import com.google.android.collect.Lists;
120import com.google.android.collect.Maps;
121
122import java.lang.annotation.Retention;
123import java.lang.annotation.RetentionPolicy;
124import java.lang.ref.WeakReference;
125import java.lang.reflect.Field;
126import java.lang.reflect.InvocationTargetException;
127import java.lang.reflect.Method;
128import java.lang.reflect.Modifier;
129import java.util.ArrayList;
130import java.util.Arrays;
131import java.util.Collections;
132import java.util.HashMap;
133import java.util.List;
134import java.util.Locale;
135import java.util.Map;
136import java.util.concurrent.CopyOnWriteArrayList;
137import java.util.concurrent.atomic.AtomicInteger;
138
139/**
140 * <p>
141 * This class represents the basic building block for user interface components. A View
142 * occupies a rectangular area on the screen and is responsible for drawing and
143 * event handling. View is the base class for <em>widgets</em>, which are
144 * used to create interactive UI components (buttons, text fields, etc.). The
145 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
146 * are invisible containers that hold other Views (or other ViewGroups) and define
147 * their layout properties.
148 * </p>
149 *
150 * <div class="special reference">
151 * <h3>Developer Guides</h3>
152 * <p>For information about using this class to develop your application's user interface,
153 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
154 * </div>
155 *
156 * <a name="Using"></a>
157 * <h3>Using Views</h3>
158 * <p>
159 * All of the views in a window are arranged in a single tree. You can add views
160 * either from code or by specifying a tree of views in one or more XML layout
161 * files. There are many specialized subclasses of views that act as controls or
162 * are capable of displaying text, images, or other content.
163 * </p>
164 * <p>
165 * Once you have created a tree of views, there are typically a few types of
166 * common operations you may wish to perform:
167 * <ul>
168 * <li><strong>Set properties:</strong> for example setting the text of a
169 * {@link android.widget.TextView}. The available properties and the methods
170 * that set them will vary among the different subclasses of views. Note that
171 * properties that are known at build time can be set in the XML layout
172 * files.</li>
173 * <li><strong>Set focus:</strong> The framework will handle moving focus in
174 * response to user input. To force focus to a specific view, call
175 * {@link #requestFocus}.</li>
176 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
177 * that will be notified when something interesting happens to the view. For
178 * example, all views will let you set a listener to be notified when the view
179 * gains or loses focus. You can register such a listener using
180 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
181 * Other view subclasses offer more specialized listeners. For example, a Button
182 * exposes a listener to notify clients when the button is clicked.</li>
183 * <li><strong>Set visibility:</strong> You can hide or show views using
184 * {@link #setVisibility(int)}.</li>
185 * </ul>
186 * </p>
187 * <p><em>
188 * Note: The Android framework is responsible for measuring, laying out and
189 * drawing views. You should not call methods that perform these actions on
190 * views yourself unless you are actually implementing a
191 * {@link android.view.ViewGroup}.
192 * </em></p>
193 *
194 * <a name="Lifecycle"></a>
195 * <h3>Implementing a Custom View</h3>
196 *
197 * <p>
198 * To implement a custom view, you will usually begin by providing overrides for
199 * some of the standard methods that the framework calls on all views. You do
200 * not need to override all of these methods. In fact, you can start by just
201 * overriding {@link #onDraw(android.graphics.Canvas)}.
202 * <table border="2" width="85%" align="center" cellpadding="5">
203 *     <thead>
204 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
205 *     </thead>
206 *
207 *     <tbody>
208 *     <tr>
209 *         <td rowspan="2">Creation</td>
210 *         <td>Constructors</td>
211 *         <td>There is a form of the constructor that are called when the view
212 *         is created from code and a form that is called when the view is
213 *         inflated from a layout file. The second form should parse and apply
214 *         any attributes defined in the layout file.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onFinishInflate()}</code></td>
219 *         <td>Called after a view and all of its children has been inflated
220 *         from XML.</td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="3">Layout</td>
225 *         <td><code>{@link #onMeasure(int, int)}</code></td>
226 *         <td>Called to determine the size requirements for this view and all
227 *         of its children.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
232 *         <td>Called when this view should assign a size and position to all
233 *         of its children.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
238 *         <td>Called when the size of this view has changed.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td>Drawing</td>
244 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
245 *         <td>Called when the view should render its content.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td rowspan="4">Event processing</td>
251 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
252 *         <td>Called when a new hardware key event occurs.
253 *         </td>
254 *     </tr>
255 *     <tr>
256 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
257 *         <td>Called when a hardware key up event occurs.
258 *         </td>
259 *     </tr>
260 *     <tr>
261 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
262 *         <td>Called when a trackball motion event occurs.
263 *         </td>
264 *     </tr>
265 *     <tr>
266 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
267 *         <td>Called when a touch screen motion event occurs.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td rowspan="2">Focus</td>
273 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
274 *         <td>Called when the view gains or loses focus.
275 *         </td>
276 *     </tr>
277 *
278 *     <tr>
279 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
280 *         <td>Called when the window containing the view gains or loses focus.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td rowspan="3">Attaching</td>
286 *         <td><code>{@link #onAttachedToWindow()}</code></td>
287 *         <td>Called when the view is attached to a window.
288 *         </td>
289 *     </tr>
290 *
291 *     <tr>
292 *         <td><code>{@link #onDetachedFromWindow}</code></td>
293 *         <td>Called when the view is detached from its window.
294 *         </td>
295 *     </tr>
296 *
297 *     <tr>
298 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
299 *         <td>Called when the visibility of the window containing the view
300 *         has changed.
301 *         </td>
302 *     </tr>
303 *     </tbody>
304 *
305 * </table>
306 * </p>
307 *
308 * <a name="IDs"></a>
309 * <h3>IDs</h3>
310 * Views may have an integer id associated with them. These ids are typically
311 * assigned in the layout XML files, and are used to find specific views within
312 * the view tree. A common pattern is to:
313 * <ul>
314 * <li>Define a Button in the layout file and assign it a unique ID.
315 * <pre>
316 * &lt;Button
317 *     android:id="@+id/my_button"
318 *     android:layout_width="wrap_content"
319 *     android:layout_height="wrap_content"
320 *     android:text="@string/my_button_text"/&gt;
321 * </pre></li>
322 * <li>From the onCreate method of an Activity, find the Button
323 * <pre class="prettyprint">
324 *      Button myButton = (Button) findViewById(R.id.my_button);
325 * </pre></li>
326 * </ul>
327 * <p>
328 * View IDs need not be unique throughout the tree, but it is good practice to
329 * ensure that they are at least unique within the part of the tree you are
330 * searching.
331 * </p>
332 *
333 * <a name="Position"></a>
334 * <h3>Position</h3>
335 * <p>
336 * The geometry of a view is that of a rectangle. A view has a location,
337 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
338 * two dimensions, expressed as a width and a height. The unit for location
339 * and dimensions is the pixel.
340 * </p>
341 *
342 * <p>
343 * It is possible to retrieve the location of a view by invoking the methods
344 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
345 * coordinate of the rectangle representing the view. The latter returns the
346 * top, or Y, coordinate of the rectangle representing the view. These methods
347 * both return the location of the view relative to its parent. For instance,
348 * when getLeft() returns 20, that means the view is located 20 pixels to the
349 * right of the left edge of its direct parent.
350 * </p>
351 *
352 * <p>
353 * In addition, several convenience methods are offered to avoid unnecessary
354 * computations, namely {@link #getRight()} and {@link #getBottom()}.
355 * These methods return the coordinates of the right and bottom edges of the
356 * rectangle representing the view. For instance, calling {@link #getRight()}
357 * is similar to the following computation: <code>getLeft() + getWidth()</code>
358 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
359 * </p>
360 *
361 * <a name="SizePaddingMargins"></a>
362 * <h3>Size, padding and margins</h3>
363 * <p>
364 * The size of a view is expressed with a width and a height. A view actually
365 * possess two pairs of width and height values.
366 * </p>
367 *
368 * <p>
369 * The first pair is known as <em>measured width</em> and
370 * <em>measured height</em>. These dimensions define how big a view wants to be
371 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
372 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
373 * and {@link #getMeasuredHeight()}.
374 * </p>
375 *
376 * <p>
377 * The second pair is simply known as <em>width</em> and <em>height</em>, or
378 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
379 * dimensions define the actual size of the view on screen, at drawing time and
380 * after layout. These values may, but do not have to, be different from the
381 * measured width and height. The width and height can be obtained by calling
382 * {@link #getWidth()} and {@link #getHeight()}.
383 * </p>
384 *
385 * <p>
386 * To measure its dimensions, a view takes into account its padding. The padding
387 * is expressed in pixels for the left, top, right and bottom parts of the view.
388 * Padding can be used to offset the content of the view by a specific amount of
389 * pixels. For instance, a left padding of 2 will push the view's content by
390 * 2 pixels to the right of the left edge. Padding can be set using the
391 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
392 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
393 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
394 * {@link #getPaddingEnd()}.
395 * </p>
396 *
397 * <p>
398 * Even though a view can define a padding, it does not provide any support for
399 * margins. However, view groups provide such a support. Refer to
400 * {@link android.view.ViewGroup} and
401 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
402 * </p>
403 *
404 * <a name="Layout"></a>
405 * <h3>Layout</h3>
406 * <p>
407 * Layout is a two pass process: a measure pass and a layout pass. The measuring
408 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
409 * of the view tree. Each view pushes dimension specifications down the tree
410 * during the recursion. At the end of the measure pass, every view has stored
411 * its measurements. The second pass happens in
412 * {@link #layout(int,int,int,int)} and is also top-down. During
413 * this pass each parent is responsible for positioning all of its children
414 * using the sizes computed in the measure pass.
415 * </p>
416 *
417 * <p>
418 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
419 * {@link #getMeasuredHeight()} values must be set, along with those for all of
420 * that view's descendants. A view's measured width and measured height values
421 * must respect the constraints imposed by the view's parents. This guarantees
422 * that at the end of the measure pass, all parents accept all of their
423 * children's measurements. A parent view may call measure() more than once on
424 * its children. For example, the parent may measure each child once with
425 * unspecified dimensions to find out how big they want to be, then call
426 * measure() on them again with actual numbers if the sum of all the children's
427 * unconstrained sizes is too big or too small.
428 * </p>
429 *
430 * <p>
431 * The measure pass uses two classes to communicate dimensions. The
432 * {@link MeasureSpec} class is used by views to tell their parents how they
433 * want to be measured and positioned. The base LayoutParams class just
434 * describes how big the view wants to be for both width and height. For each
435 * dimension, it can specify one of:
436 * <ul>
437 * <li> an exact number
438 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
439 * (minus padding)
440 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
441 * enclose its content (plus padding).
442 * </ul>
443 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
444 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
445 * an X and Y value.
446 * </p>
447 *
448 * <p>
449 * MeasureSpecs are used to push requirements down the tree from parent to
450 * child. A MeasureSpec can be in one of three modes:
451 * <ul>
452 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
453 * of a child view. For example, a LinearLayout may call measure() on its child
454 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
455 * tall the child view wants to be given a width of 240 pixels.
456 * <li>EXACTLY: This is used by the parent to impose an exact size on the
457 * child. The child must use this size, and guarantee that all of its
458 * descendants will fit within this size.
459 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
460 * child. The child must guarantee that it and all of its descendants will fit
461 * within this size.
462 * </ul>
463 * </p>
464 *
465 * <p>
466 * To initiate a layout, call {@link #requestLayout}. This method is typically
467 * called by a view on itself when it believes that is can no longer fit within
468 * its current bounds.
469 * </p>
470 *
471 * <a name="Drawing"></a>
472 * <h3>Drawing</h3>
473 * <p>
474 * Drawing is handled by walking the tree and recording the drawing commands of
475 * any View that needs to update. After this, the drawing commands of the
476 * entire tree are issued to screen, clipped to the newly damaged area.
477 * </p>
478 *
479 * <p>
480 * The tree is largely recorded and drawn in order, with parents drawn before
481 * (i.e., behind) their children, with siblings drawn in the order they appear
482 * in the tree. If you set a background drawable for a View, then the View will
483 * draw it before calling back to its <code>onDraw()</code> method. The child
484 * drawing order can be overridden with
485 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
486 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
487 * </p>
488 *
489 * <p>
490 * To force a view to draw, call {@link #invalidate()}.
491 * </p>
492 *
493 * <a name="EventHandlingThreading"></a>
494 * <h3>Event Handling and Threading</h3>
495 * <p>
496 * The basic cycle of a view is as follows:
497 * <ol>
498 * <li>An event comes in and is dispatched to the appropriate view. The view
499 * handles the event and notifies any listeners.</li>
500 * <li>If in the course of processing the event, the view's bounds may need
501 * to be changed, the view will call {@link #requestLayout()}.</li>
502 * <li>Similarly, if in the course of processing the event the view's appearance
503 * may need to be changed, the view will call {@link #invalidate()}.</li>
504 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
505 * the framework will take care of measuring, laying out, and drawing the tree
506 * as appropriate.</li>
507 * </ol>
508 * </p>
509 *
510 * <p><em>Note: The entire view tree is single threaded. You must always be on
511 * the UI thread when calling any method on any view.</em>
512 * If you are doing work on other threads and want to update the state of a view
513 * from that thread, you should use a {@link Handler}.
514 * </p>
515 *
516 * <a name="FocusHandling"></a>
517 * <h3>Focus Handling</h3>
518 * <p>
519 * The framework will handle routine focus movement in response to user input.
520 * This includes changing the focus as views are removed or hidden, or as new
521 * views become available. Views indicate their willingness to take focus
522 * through the {@link #isFocusable} method. To change whether a view can take
523 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
524 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
525 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
526 * </p>
527 * <p>
528 * Focus movement is based on an algorithm which finds the nearest neighbor in a
529 * given direction. In rare cases, the default algorithm may not match the
530 * intended behavior of the developer. In these situations, you can provide
531 * explicit overrides by using these XML attributes in the layout file:
532 * <pre>
533 * nextFocusDown
534 * nextFocusLeft
535 * nextFocusRight
536 * nextFocusUp
537 * </pre>
538 * </p>
539 *
540 *
541 * <p>
542 * To get a particular view to take focus, call {@link #requestFocus()}.
543 * </p>
544 *
545 * <a name="TouchMode"></a>
546 * <h3>Touch Mode</h3>
547 * <p>
548 * When a user is navigating a user interface via directional keys such as a D-pad, it is
549 * necessary to give focus to actionable items such as buttons so the user can see
550 * what will take input.  If the device has touch capabilities, however, and the user
551 * begins interacting with the interface by touching it, it is no longer necessary to
552 * always highlight, or give focus to, a particular view.  This motivates a mode
553 * for interaction named 'touch mode'.
554 * </p>
555 * <p>
556 * For a touch capable device, once the user touches the screen, the device
557 * will enter touch mode.  From this point onward, only views for which
558 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
559 * Other views that are touchable, like buttons, will not take focus when touched; they will
560 * only fire the on click listeners.
561 * </p>
562 * <p>
563 * Any time a user hits a directional key, such as a D-pad direction, the view device will
564 * exit touch mode, and find a view to take focus, so that the user may resume interacting
565 * with the user interface without touching the screen again.
566 * </p>
567 * <p>
568 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
569 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
570 * </p>
571 *
572 * <a name="Scrolling"></a>
573 * <h3>Scrolling</h3>
574 * <p>
575 * The framework provides basic support for views that wish to internally
576 * scroll their content. This includes keeping track of the X and Y scroll
577 * offset as well as mechanisms for drawing scrollbars. See
578 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
579 * {@link #awakenScrollBars()} for more details.
580 * </p>
581 *
582 * <a name="Tags"></a>
583 * <h3>Tags</h3>
584 * <p>
585 * Unlike IDs, tags are not used to identify views. Tags are essentially an
586 * extra piece of information that can be associated with a view. They are most
587 * often used as a convenience to store data related to views in the views
588 * themselves rather than by putting them in a separate structure.
589 * </p>
590 * <p>
591 * Tags may be specified with character sequence values in layout XML as either
592 * a single tag using the {@link android.R.styleable#View_tag android:tag}
593 * attribute or multiple tags using the {@code <tag>} child element:
594 * <pre>
595 *     &ltView ...
596 *           android:tag="@string/mytag_value" /&gt;
597 *     &ltView ...&gt;
598 *         &lttag android:id="@+id/mytag"
599 *              android:value="@string/mytag_value" /&gt;
600 *     &lt/View>
601 * </pre>
602 * </p>
603 * <p>
604 * Tags may also be specified with arbitrary objects from code using
605 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
606 * </p>
607 *
608 * <a name="Themes"></a>
609 * <h3>Themes</h3>
610 * <p>
611 * By default, Views are created using the theme of the Context object supplied
612 * to their constructor; however, a different theme may be specified by using
613 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
614 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
615 * code.
616 * </p>
617 * <p>
618 * When the {@link android.R.styleable#View_theme android:theme} attribute is
619 * used in XML, the specified theme is applied on top of the inflation
620 * context's theme (see {@link LayoutInflater}) and used for the view itself as
621 * well as any child elements.
622 * </p>
623 * <p>
624 * In the following example, both views will be created using the Material dark
625 * color scheme; however, because an overlay theme is used which only defines a
626 * subset of attributes, the value of
627 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
628 * the inflation context's theme (e.g. the Activity theme) will be preserved.
629 * <pre>
630 *     &ltLinearLayout
631 *             ...
632 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
633 *         &ltView ...&gt;
634 *     &lt/LinearLayout&gt;
635 * </pre>
636 * </p>
637 *
638 * <a name="Properties"></a>
639 * <h3>Properties</h3>
640 * <p>
641 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
642 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
643 * available both in the {@link Property} form as well as in similarly-named setter/getter
644 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
645 * be used to set persistent state associated with these rendering-related properties on the view.
646 * The properties and methods can also be used in conjunction with
647 * {@link android.animation.Animator Animator}-based animations, described more in the
648 * <a href="#Animation">Animation</a> section.
649 * </p>
650 *
651 * <a name="Animation"></a>
652 * <h3>Animation</h3>
653 * <p>
654 * Starting with Android 3.0, the preferred way of animating views is to use the
655 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
656 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
657 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
658 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
659 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
660 * makes animating these View properties particularly easy and efficient.
661 * </p>
662 * <p>
663 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
664 * You can attach an {@link Animation} object to a view using
665 * {@link #setAnimation(Animation)} or
666 * {@link #startAnimation(Animation)}. The animation can alter the scale,
667 * rotation, translation and alpha of a view over time. If the animation is
668 * attached to a view that has children, the animation will affect the entire
669 * subtree rooted by that node. When an animation is started, the framework will
670 * take care of redrawing the appropriate views until the animation completes.
671 * </p>
672 *
673 * <a name="Security"></a>
674 * <h3>Security</h3>
675 * <p>
676 * Sometimes it is essential that an application be able to verify that an action
677 * is being performed with the full knowledge and consent of the user, such as
678 * granting a permission request, making a purchase or clicking on an advertisement.
679 * Unfortunately, a malicious application could try to spoof the user into
680 * performing these actions, unaware, by concealing the intended purpose of the view.
681 * As a remedy, the framework offers a touch filtering mechanism that can be used to
682 * improve the security of views that provide access to sensitive functionality.
683 * </p><p>
684 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
685 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
686 * will discard touches that are received whenever the view's window is obscured by
687 * another visible window.  As a result, the view will not receive touches whenever a
688 * toast, dialog or other window appears above the view's window.
689 * </p><p>
690 * For more fine-grained control over security, consider overriding the
691 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
692 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
693 * </p>
694 *
695 * @attr ref android.R.styleable#View_alpha
696 * @attr ref android.R.styleable#View_background
697 * @attr ref android.R.styleable#View_clickable
698 * @attr ref android.R.styleable#View_contentDescription
699 * @attr ref android.R.styleable#View_drawingCacheQuality
700 * @attr ref android.R.styleable#View_duplicateParentState
701 * @attr ref android.R.styleable#View_id
702 * @attr ref android.R.styleable#View_requiresFadingEdge
703 * @attr ref android.R.styleable#View_fadeScrollbars
704 * @attr ref android.R.styleable#View_fadingEdgeLength
705 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
706 * @attr ref android.R.styleable#View_fitsSystemWindows
707 * @attr ref android.R.styleable#View_isScrollContainer
708 * @attr ref android.R.styleable#View_focusable
709 * @attr ref android.R.styleable#View_focusableInTouchMode
710 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
711 * @attr ref android.R.styleable#View_keepScreenOn
712 * @attr ref android.R.styleable#View_layerType
713 * @attr ref android.R.styleable#View_layoutDirection
714 * @attr ref android.R.styleable#View_longClickable
715 * @attr ref android.R.styleable#View_minHeight
716 * @attr ref android.R.styleable#View_minWidth
717 * @attr ref android.R.styleable#View_nextFocusDown
718 * @attr ref android.R.styleable#View_nextFocusLeft
719 * @attr ref android.R.styleable#View_nextFocusRight
720 * @attr ref android.R.styleable#View_nextFocusUp
721 * @attr ref android.R.styleable#View_onClick
722 * @attr ref android.R.styleable#View_padding
723 * @attr ref android.R.styleable#View_paddingBottom
724 * @attr ref android.R.styleable#View_paddingLeft
725 * @attr ref android.R.styleable#View_paddingRight
726 * @attr ref android.R.styleable#View_paddingTop
727 * @attr ref android.R.styleable#View_paddingStart
728 * @attr ref android.R.styleable#View_paddingEnd
729 * @attr ref android.R.styleable#View_saveEnabled
730 * @attr ref android.R.styleable#View_rotation
731 * @attr ref android.R.styleable#View_rotationX
732 * @attr ref android.R.styleable#View_rotationY
733 * @attr ref android.R.styleable#View_scaleX
734 * @attr ref android.R.styleable#View_scaleY
735 * @attr ref android.R.styleable#View_scrollX
736 * @attr ref android.R.styleable#View_scrollY
737 * @attr ref android.R.styleable#View_scrollbarSize
738 * @attr ref android.R.styleable#View_scrollbarStyle
739 * @attr ref android.R.styleable#View_scrollbars
740 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
741 * @attr ref android.R.styleable#View_scrollbarFadeDuration
742 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
743 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
744 * @attr ref android.R.styleable#View_scrollbarThumbVertical
745 * @attr ref android.R.styleable#View_scrollbarTrackVertical
746 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
747 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
748 * @attr ref android.R.styleable#View_stateListAnimator
749 * @attr ref android.R.styleable#View_transitionName
750 * @attr ref android.R.styleable#View_soundEffectsEnabled
751 * @attr ref android.R.styleable#View_tag
752 * @attr ref android.R.styleable#View_textAlignment
753 * @attr ref android.R.styleable#View_textDirection
754 * @attr ref android.R.styleable#View_transformPivotX
755 * @attr ref android.R.styleable#View_transformPivotY
756 * @attr ref android.R.styleable#View_translationX
757 * @attr ref android.R.styleable#View_translationY
758 * @attr ref android.R.styleable#View_translationZ
759 * @attr ref android.R.styleable#View_visibility
760 * @attr ref android.R.styleable#View_theme
761 *
762 * @see android.view.ViewGroup
763 */
764@UiThread
765public class View implements Drawable.Callback, KeyEvent.Callback,
766        AccessibilityEventSource {
767    private static final boolean DBG = false;
768
769    /** @hide */
770    public static boolean DEBUG_DRAW = false;
771
772    /**
773     * The logging tag used by this class with android.util.Log.
774     */
775    protected static final String VIEW_LOG_TAG = "View";
776
777    /**
778     * When set to true, apps will draw debugging information about their layouts.
779     *
780     * @hide
781     */
782    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
783
784    /**
785     * When set to true, this view will save its attribute data.
786     *
787     * @hide
788     */
789    public static boolean mDebugViewAttributes = false;
790
791    /**
792     * Used to mark a View that has no ID.
793     */
794    public static final int NO_ID = -1;
795
796    /**
797     * Signals that compatibility booleans have been initialized according to
798     * target SDK versions.
799     */
800    private static boolean sCompatibilityDone = false;
801
802    /**
803     * Use the old (broken) way of building MeasureSpecs.
804     */
805    private static boolean sUseBrokenMakeMeasureSpec = false;
806
807    /**
808     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
809     */
810    static boolean sUseZeroUnspecifiedMeasureSpec = false;
811
812    /**
813     * Ignore any optimizations using the measure cache.
814     */
815    private static boolean sIgnoreMeasureCache = false;
816
817    /**
818     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
819     */
820    private static boolean sAlwaysRemeasureExactly = false;
821
822    /**
823     * Relax constraints around whether setLayoutParams() must be called after
824     * modifying the layout params.
825     */
826    private static boolean sLayoutParamsAlwaysChanged = false;
827
828    /**
829     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
830     * without throwing
831     */
832    static boolean sTextureViewIgnoresDrawableSetters = false;
833
834    /**
835     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
836     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
837     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
838     * check is implemented for backwards compatibility.
839     *
840     * {@hide}
841     */
842    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
843
844    /**
845     * Prior to N, when drag enters into child of a view that has already received an
846     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
847     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
848     * false from its event handler for these events.
849     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
850     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
851     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
852     */
853    static boolean sCascadedDragDrop;
854
855    /**
856     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
857     * calling setFlags.
858     */
859    private static final int NOT_FOCUSABLE = 0x00000000;
860
861    /**
862     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
863     * setFlags.
864     */
865    private static final int FOCUSABLE = 0x00000001;
866
867    /**
868     * Mask for use with setFlags indicating bits used for focus.
869     */
870    private static final int FOCUSABLE_MASK = 0x00000001;
871
872    /**
873     * This view will adjust its padding to fit sytem windows (e.g. status bar)
874     */
875    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
876
877    /** @hide */
878    @IntDef({VISIBLE, INVISIBLE, GONE})
879    @Retention(RetentionPolicy.SOURCE)
880    public @interface Visibility {}
881
882    /**
883     * This view is visible.
884     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
885     * android:visibility}.
886     */
887    public static final int VISIBLE = 0x00000000;
888
889    /**
890     * This view is invisible, but it still takes up space for layout purposes.
891     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
892     * android:visibility}.
893     */
894    public static final int INVISIBLE = 0x00000004;
895
896    /**
897     * This view is invisible, and it doesn't take any space for layout
898     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
899     * android:visibility}.
900     */
901    public static final int GONE = 0x00000008;
902
903    /**
904     * Mask for use with setFlags indicating bits used for visibility.
905     * {@hide}
906     */
907    static final int VISIBILITY_MASK = 0x0000000C;
908
909    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
910
911    /**
912     * This view is enabled. Interpretation varies by subclass.
913     * Use with ENABLED_MASK when calling setFlags.
914     * {@hide}
915     */
916    static final int ENABLED = 0x00000000;
917
918    /**
919     * This view is disabled. Interpretation varies by subclass.
920     * Use with ENABLED_MASK when calling setFlags.
921     * {@hide}
922     */
923    static final int DISABLED = 0x00000020;
924
925   /**
926    * Mask for use with setFlags indicating bits used for indicating whether
927    * this view is enabled
928    * {@hide}
929    */
930    static final int ENABLED_MASK = 0x00000020;
931
932    /**
933     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
934     * called and further optimizations will be performed. It is okay to have
935     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
936     * {@hide}
937     */
938    static final int WILL_NOT_DRAW = 0x00000080;
939
940    /**
941     * Mask for use with setFlags indicating bits used for indicating whether
942     * this view is will draw
943     * {@hide}
944     */
945    static final int DRAW_MASK = 0x00000080;
946
947    /**
948     * <p>This view doesn't show scrollbars.</p>
949     * {@hide}
950     */
951    static final int SCROLLBARS_NONE = 0x00000000;
952
953    /**
954     * <p>This view shows horizontal scrollbars.</p>
955     * {@hide}
956     */
957    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
958
959    /**
960     * <p>This view shows vertical scrollbars.</p>
961     * {@hide}
962     */
963    static final int SCROLLBARS_VERTICAL = 0x00000200;
964
965    /**
966     * <p>Mask for use with setFlags indicating bits used for indicating which
967     * scrollbars are enabled.</p>
968     * {@hide}
969     */
970    static final int SCROLLBARS_MASK = 0x00000300;
971
972    /**
973     * Indicates that the view should filter touches when its window is obscured.
974     * Refer to the class comments for more information about this security feature.
975     * {@hide}
976     */
977    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
978
979    /**
980     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
981     * that they are optional and should be skipped if the window has
982     * requested system UI flags that ignore those insets for layout.
983     */
984    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
985
986    /**
987     * <p>This view doesn't show fading edges.</p>
988     * {@hide}
989     */
990    static final int FADING_EDGE_NONE = 0x00000000;
991
992    /**
993     * <p>This view shows horizontal fading edges.</p>
994     * {@hide}
995     */
996    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
997
998    /**
999     * <p>This view shows vertical fading edges.</p>
1000     * {@hide}
1001     */
1002    static final int FADING_EDGE_VERTICAL = 0x00002000;
1003
1004    /**
1005     * <p>Mask for use with setFlags indicating bits used for indicating which
1006     * fading edges are enabled.</p>
1007     * {@hide}
1008     */
1009    static final int FADING_EDGE_MASK = 0x00003000;
1010
1011    /**
1012     * <p>Indicates this view can be clicked. When clickable, a View reacts
1013     * to clicks by notifying the OnClickListener.<p>
1014     * {@hide}
1015     */
1016    static final int CLICKABLE = 0x00004000;
1017
1018    /**
1019     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1020     * {@hide}
1021     */
1022    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1023
1024    /**
1025     * <p>Indicates that no icicle should be saved for this view.<p>
1026     * {@hide}
1027     */
1028    static final int SAVE_DISABLED = 0x000010000;
1029
1030    /**
1031     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1032     * property.</p>
1033     * {@hide}
1034     */
1035    static final int SAVE_DISABLED_MASK = 0x000010000;
1036
1037    /**
1038     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1039     * {@hide}
1040     */
1041    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1042
1043    /**
1044     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1045     * {@hide}
1046     */
1047    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1048
1049    /** @hide */
1050    @Retention(RetentionPolicy.SOURCE)
1051    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1052    public @interface DrawingCacheQuality {}
1053
1054    /**
1055     * <p>Enables low quality mode for the drawing cache.</p>
1056     */
1057    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1058
1059    /**
1060     * <p>Enables high quality mode for the drawing cache.</p>
1061     */
1062    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1063
1064    /**
1065     * <p>Enables automatic quality mode for the drawing cache.</p>
1066     */
1067    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1068
1069    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1070            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1071    };
1072
1073    /**
1074     * <p>Mask for use with setFlags indicating bits used for the cache
1075     * quality property.</p>
1076     * {@hide}
1077     */
1078    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1079
1080    /**
1081     * <p>
1082     * Indicates this view can be long clicked. When long clickable, a View
1083     * reacts to long clicks by notifying the OnLongClickListener or showing a
1084     * context menu.
1085     * </p>
1086     * {@hide}
1087     */
1088    static final int LONG_CLICKABLE = 0x00200000;
1089
1090    /**
1091     * <p>Indicates that this view gets its drawable states from its direct parent
1092     * and ignores its original internal states.</p>
1093     *
1094     * @hide
1095     */
1096    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1097
1098    /**
1099     * <p>
1100     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1101     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1102     * OnContextClickListener.
1103     * </p>
1104     * {@hide}
1105     */
1106    static final int CONTEXT_CLICKABLE = 0x00800000;
1107
1108
1109    /** @hide */
1110    @IntDef({
1111        SCROLLBARS_INSIDE_OVERLAY,
1112        SCROLLBARS_INSIDE_INSET,
1113        SCROLLBARS_OUTSIDE_OVERLAY,
1114        SCROLLBARS_OUTSIDE_INSET
1115    })
1116    @Retention(RetentionPolicy.SOURCE)
1117    public @interface ScrollBarStyle {}
1118
1119    /**
1120     * The scrollbar style to display the scrollbars inside the content area,
1121     * without increasing the padding. The scrollbars will be overlaid with
1122     * translucency on the view's content.
1123     */
1124    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1125
1126    /**
1127     * The scrollbar style to display the scrollbars inside the padded area,
1128     * increasing the padding of the view. The scrollbars will not overlap the
1129     * content area of the view.
1130     */
1131    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1132
1133    /**
1134     * The scrollbar style to display the scrollbars at the edge of the view,
1135     * without increasing the padding. The scrollbars will be overlaid with
1136     * translucency.
1137     */
1138    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1139
1140    /**
1141     * The scrollbar style to display the scrollbars at the edge of the view,
1142     * increasing the padding of the view. The scrollbars will only overlap the
1143     * background, if any.
1144     */
1145    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1146
1147    /**
1148     * Mask to check if the scrollbar style is overlay or inset.
1149     * {@hide}
1150     */
1151    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1152
1153    /**
1154     * Mask to check if the scrollbar style is inside or outside.
1155     * {@hide}
1156     */
1157    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1158
1159    /**
1160     * Mask for scrollbar style.
1161     * {@hide}
1162     */
1163    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1164
1165    /**
1166     * View flag indicating that the screen should remain on while the
1167     * window containing this view is visible to the user.  This effectively
1168     * takes care of automatically setting the WindowManager's
1169     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1170     */
1171    public static final int KEEP_SCREEN_ON = 0x04000000;
1172
1173    /**
1174     * View flag indicating whether this view should have sound effects enabled
1175     * for events such as clicking and touching.
1176     */
1177    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1178
1179    /**
1180     * View flag indicating whether this view should have haptic feedback
1181     * enabled for events such as long presses.
1182     */
1183    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1184
1185    /**
1186     * <p>Indicates that the view hierarchy should stop saving state when
1187     * it reaches this view.  If state saving is initiated immediately at
1188     * the view, it will be allowed.
1189     * {@hide}
1190     */
1191    static final int PARENT_SAVE_DISABLED = 0x20000000;
1192
1193    /**
1194     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1195     * {@hide}
1196     */
1197    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1198
1199    private static Paint sDebugPaint;
1200
1201    /**
1202     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1203     * {@hide}
1204     */
1205    static final int TOOLTIP = 0x40000000;
1206
1207    /** @hide */
1208    @IntDef(flag = true,
1209            value = {
1210                FOCUSABLES_ALL,
1211                FOCUSABLES_TOUCH_MODE
1212            })
1213    @Retention(RetentionPolicy.SOURCE)
1214    public @interface FocusableMode {}
1215
1216    /**
1217     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1218     * should add all focusable Views regardless if they are focusable in touch mode.
1219     */
1220    public static final int FOCUSABLES_ALL = 0x00000000;
1221
1222    /**
1223     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1224     * should add only Views focusable in touch mode.
1225     */
1226    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1227
1228    /** @hide */
1229    @IntDef({
1230            FOCUS_BACKWARD,
1231            FOCUS_FORWARD,
1232            FOCUS_LEFT,
1233            FOCUS_UP,
1234            FOCUS_RIGHT,
1235            FOCUS_DOWN
1236    })
1237    @Retention(RetentionPolicy.SOURCE)
1238    public @interface FocusDirection {}
1239
1240    /** @hide */
1241    @IntDef({
1242            FOCUS_LEFT,
1243            FOCUS_UP,
1244            FOCUS_RIGHT,
1245            FOCUS_DOWN
1246    })
1247    @Retention(RetentionPolicy.SOURCE)
1248    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1249
1250    /**
1251     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1252     * item.
1253     */
1254    public static final int FOCUS_BACKWARD = 0x00000001;
1255
1256    /**
1257     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1258     * item.
1259     */
1260    public static final int FOCUS_FORWARD = 0x00000002;
1261
1262    /**
1263     * Use with {@link #focusSearch(int)}. Move focus to the left.
1264     */
1265    public static final int FOCUS_LEFT = 0x00000011;
1266
1267    /**
1268     * Use with {@link #focusSearch(int)}. Move focus up.
1269     */
1270    public static final int FOCUS_UP = 0x00000021;
1271
1272    /**
1273     * Use with {@link #focusSearch(int)}. Move focus to the right.
1274     */
1275    public static final int FOCUS_RIGHT = 0x00000042;
1276
1277    /**
1278     * Use with {@link #focusSearch(int)}. Move focus down.
1279     */
1280    public static final int FOCUS_DOWN = 0x00000082;
1281
1282    /**
1283     * Bits of {@link #getMeasuredWidthAndState()} and
1284     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1285     */
1286    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1287
1288    /**
1289     * Bits of {@link #getMeasuredWidthAndState()} and
1290     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1291     */
1292    public static final int MEASURED_STATE_MASK = 0xff000000;
1293
1294    /**
1295     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1296     * for functions that combine both width and height into a single int,
1297     * such as {@link #getMeasuredState()} and the childState argument of
1298     * {@link #resolveSizeAndState(int, int, int)}.
1299     */
1300    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1301
1302    /**
1303     * Bit of {@link #getMeasuredWidthAndState()} and
1304     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1305     * is smaller that the space the view would like to have.
1306     */
1307    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1308
1309    /**
1310     * Base View state sets
1311     */
1312    // Singles
1313    /**
1314     * Indicates the view has no states set. States are used with
1315     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1316     * view depending on its state.
1317     *
1318     * @see android.graphics.drawable.Drawable
1319     * @see #getDrawableState()
1320     */
1321    protected static final int[] EMPTY_STATE_SET;
1322    /**
1323     * Indicates the view is enabled. States are used with
1324     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1325     * view depending on its state.
1326     *
1327     * @see android.graphics.drawable.Drawable
1328     * @see #getDrawableState()
1329     */
1330    protected static final int[] ENABLED_STATE_SET;
1331    /**
1332     * Indicates the view is focused. States are used with
1333     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1334     * view depending on its state.
1335     *
1336     * @see android.graphics.drawable.Drawable
1337     * @see #getDrawableState()
1338     */
1339    protected static final int[] FOCUSED_STATE_SET;
1340    /**
1341     * Indicates the view is selected. States are used with
1342     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1343     * view depending on its state.
1344     *
1345     * @see android.graphics.drawable.Drawable
1346     * @see #getDrawableState()
1347     */
1348    protected static final int[] SELECTED_STATE_SET;
1349    /**
1350     * Indicates the view is pressed. States are used with
1351     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1352     * view depending on its state.
1353     *
1354     * @see android.graphics.drawable.Drawable
1355     * @see #getDrawableState()
1356     */
1357    protected static final int[] PRESSED_STATE_SET;
1358    /**
1359     * Indicates the view's window has focus. States are used with
1360     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1361     * view depending on its state.
1362     *
1363     * @see android.graphics.drawable.Drawable
1364     * @see #getDrawableState()
1365     */
1366    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1367    // Doubles
1368    /**
1369     * Indicates the view is enabled and has the focus.
1370     *
1371     * @see #ENABLED_STATE_SET
1372     * @see #FOCUSED_STATE_SET
1373     */
1374    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1375    /**
1376     * Indicates the view is enabled and selected.
1377     *
1378     * @see #ENABLED_STATE_SET
1379     * @see #SELECTED_STATE_SET
1380     */
1381    protected static final int[] ENABLED_SELECTED_STATE_SET;
1382    /**
1383     * Indicates the view is enabled and that its window has focus.
1384     *
1385     * @see #ENABLED_STATE_SET
1386     * @see #WINDOW_FOCUSED_STATE_SET
1387     */
1388    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1389    /**
1390     * Indicates the view is focused and selected.
1391     *
1392     * @see #FOCUSED_STATE_SET
1393     * @see #SELECTED_STATE_SET
1394     */
1395    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1396    /**
1397     * Indicates the view has the focus and that its window has the focus.
1398     *
1399     * @see #FOCUSED_STATE_SET
1400     * @see #WINDOW_FOCUSED_STATE_SET
1401     */
1402    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is selected and that its window has the focus.
1405     *
1406     * @see #SELECTED_STATE_SET
1407     * @see #WINDOW_FOCUSED_STATE_SET
1408     */
1409    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1410    // Triples
1411    /**
1412     * Indicates the view is enabled, focused and selected.
1413     *
1414     * @see #ENABLED_STATE_SET
1415     * @see #FOCUSED_STATE_SET
1416     * @see #SELECTED_STATE_SET
1417     */
1418    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1419    /**
1420     * Indicates the view is enabled, focused and its window has the focus.
1421     *
1422     * @see #ENABLED_STATE_SET
1423     * @see #FOCUSED_STATE_SET
1424     * @see #WINDOW_FOCUSED_STATE_SET
1425     */
1426    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1427    /**
1428     * Indicates the view is enabled, selected and its window has the focus.
1429     *
1430     * @see #ENABLED_STATE_SET
1431     * @see #SELECTED_STATE_SET
1432     * @see #WINDOW_FOCUSED_STATE_SET
1433     */
1434    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1435    /**
1436     * Indicates the view is focused, selected and its window has the focus.
1437     *
1438     * @see #FOCUSED_STATE_SET
1439     * @see #SELECTED_STATE_SET
1440     * @see #WINDOW_FOCUSED_STATE_SET
1441     */
1442    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1443    /**
1444     * Indicates the view is enabled, focused, selected and its window
1445     * has the focus.
1446     *
1447     * @see #ENABLED_STATE_SET
1448     * @see #FOCUSED_STATE_SET
1449     * @see #SELECTED_STATE_SET
1450     * @see #WINDOW_FOCUSED_STATE_SET
1451     */
1452    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1453    /**
1454     * Indicates the view is pressed and its window has the focus.
1455     *
1456     * @see #PRESSED_STATE_SET
1457     * @see #WINDOW_FOCUSED_STATE_SET
1458     */
1459    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1460    /**
1461     * Indicates the view is pressed and selected.
1462     *
1463     * @see #PRESSED_STATE_SET
1464     * @see #SELECTED_STATE_SET
1465     */
1466    protected static final int[] PRESSED_SELECTED_STATE_SET;
1467    /**
1468     * Indicates the view is pressed, selected and its window has the focus.
1469     *
1470     * @see #PRESSED_STATE_SET
1471     * @see #SELECTED_STATE_SET
1472     * @see #WINDOW_FOCUSED_STATE_SET
1473     */
1474    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1475    /**
1476     * Indicates the view is pressed and focused.
1477     *
1478     * @see #PRESSED_STATE_SET
1479     * @see #FOCUSED_STATE_SET
1480     */
1481    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1482    /**
1483     * Indicates the view is pressed, focused and its window has the focus.
1484     *
1485     * @see #PRESSED_STATE_SET
1486     * @see #FOCUSED_STATE_SET
1487     * @see #WINDOW_FOCUSED_STATE_SET
1488     */
1489    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1490    /**
1491     * Indicates the view is pressed, focused and selected.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #SELECTED_STATE_SET
1495     * @see #FOCUSED_STATE_SET
1496     */
1497    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1498    /**
1499     * Indicates the view is pressed, focused, selected and its window has the focus.
1500     *
1501     * @see #PRESSED_STATE_SET
1502     * @see #FOCUSED_STATE_SET
1503     * @see #SELECTED_STATE_SET
1504     * @see #WINDOW_FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed and enabled.
1509     *
1510     * @see #PRESSED_STATE_SET
1511     * @see #ENABLED_STATE_SET
1512     */
1513    protected static final int[] PRESSED_ENABLED_STATE_SET;
1514    /**
1515     * Indicates the view is pressed, enabled and its window has the focus.
1516     *
1517     * @see #PRESSED_STATE_SET
1518     * @see #ENABLED_STATE_SET
1519     * @see #WINDOW_FOCUSED_STATE_SET
1520     */
1521    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1522    /**
1523     * Indicates the view is pressed, enabled and selected.
1524     *
1525     * @see #PRESSED_STATE_SET
1526     * @see #ENABLED_STATE_SET
1527     * @see #SELECTED_STATE_SET
1528     */
1529    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1530    /**
1531     * Indicates the view is pressed, enabled, selected and its window has the
1532     * focus.
1533     *
1534     * @see #PRESSED_STATE_SET
1535     * @see #ENABLED_STATE_SET
1536     * @see #SELECTED_STATE_SET
1537     * @see #WINDOW_FOCUSED_STATE_SET
1538     */
1539    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1540    /**
1541     * Indicates the view is pressed, enabled and focused.
1542     *
1543     * @see #PRESSED_STATE_SET
1544     * @see #ENABLED_STATE_SET
1545     * @see #FOCUSED_STATE_SET
1546     */
1547    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1548    /**
1549     * Indicates the view is pressed, enabled, focused and its window has the
1550     * focus.
1551     *
1552     * @see #PRESSED_STATE_SET
1553     * @see #ENABLED_STATE_SET
1554     * @see #FOCUSED_STATE_SET
1555     * @see #WINDOW_FOCUSED_STATE_SET
1556     */
1557    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1558    /**
1559     * Indicates the view is pressed, enabled, focused and selected.
1560     *
1561     * @see #PRESSED_STATE_SET
1562     * @see #ENABLED_STATE_SET
1563     * @see #SELECTED_STATE_SET
1564     * @see #FOCUSED_STATE_SET
1565     */
1566    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1567    /**
1568     * Indicates the view is pressed, enabled, focused, selected and its window
1569     * has the focus.
1570     *
1571     * @see #PRESSED_STATE_SET
1572     * @see #ENABLED_STATE_SET
1573     * @see #SELECTED_STATE_SET
1574     * @see #FOCUSED_STATE_SET
1575     * @see #WINDOW_FOCUSED_STATE_SET
1576     */
1577    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1578
1579    static {
1580        EMPTY_STATE_SET = StateSet.get(0);
1581
1582        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1583
1584        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1585        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1586                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1587
1588        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1589        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1591        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1592                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1593        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1594                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1595                        | StateSet.VIEW_STATE_FOCUSED);
1596
1597        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1598        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1599                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1600        ENABLED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1602        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1603                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1604                        | StateSet.VIEW_STATE_ENABLED);
1605        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1606                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1607        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1608                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1609                        | StateSet.VIEW_STATE_ENABLED);
1610        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1611                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1612                        | StateSet.VIEW_STATE_ENABLED);
1613        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1614                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1615                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1616
1617        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1618        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1619                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1620        PRESSED_SELECTED_STATE_SET = StateSet.get(
1621                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1622        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1623                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1624                        | StateSet.VIEW_STATE_PRESSED);
1625        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1626                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1627        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1628                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1629                        | StateSet.VIEW_STATE_PRESSED);
1630        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1631                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1632                        | StateSet.VIEW_STATE_PRESSED);
1633        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1634                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1635                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1636        PRESSED_ENABLED_STATE_SET = StateSet.get(
1637                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1638        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1639                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1640                        | StateSet.VIEW_STATE_PRESSED);
1641        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1642                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1643                        | StateSet.VIEW_STATE_PRESSED);
1644        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1645                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1646                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1647        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1648                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1649                        | StateSet.VIEW_STATE_PRESSED);
1650        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1651                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1652                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1653        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1654                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1655                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1656        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1657                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1658                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1659                        | StateSet.VIEW_STATE_PRESSED);
1660    }
1661
1662    /**
1663     * Accessibility event types that are dispatched for text population.
1664     */
1665    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1666            AccessibilityEvent.TYPE_VIEW_CLICKED
1667            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1668            | AccessibilityEvent.TYPE_VIEW_SELECTED
1669            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1670            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1671            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1672            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1673            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1674            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1675            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1676            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1677
1678    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1679
1680    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1681
1682    /**
1683     * Temporary Rect currently for use in setBackground().  This will probably
1684     * be extended in the future to hold our own class with more than just
1685     * a Rect. :)
1686     */
1687    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1688
1689    /**
1690     * Map used to store views' tags.
1691     */
1692    private SparseArray<Object> mKeyedTags;
1693
1694    /**
1695     * The next available accessibility id.
1696     */
1697    private static int sNextAccessibilityViewId;
1698
1699    /**
1700     * The animation currently associated with this view.
1701     * @hide
1702     */
1703    protected Animation mCurrentAnimation = null;
1704
1705    /**
1706     * Width as measured during measure pass.
1707     * {@hide}
1708     */
1709    @ViewDebug.ExportedProperty(category = "measurement")
1710    int mMeasuredWidth;
1711
1712    /**
1713     * Height as measured during measure pass.
1714     * {@hide}
1715     */
1716    @ViewDebug.ExportedProperty(category = "measurement")
1717    int mMeasuredHeight;
1718
1719    /**
1720     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1721     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1722     * its display list. This flag, used only when hw accelerated, allows us to clear the
1723     * flag while retaining this information until it's needed (at getDisplayList() time and
1724     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1725     *
1726     * {@hide}
1727     */
1728    boolean mRecreateDisplayList = false;
1729
1730    /**
1731     * The view's identifier.
1732     * {@hide}
1733     *
1734     * @see #setId(int)
1735     * @see #getId()
1736     */
1737    @IdRes
1738    @ViewDebug.ExportedProperty(resolveId = true)
1739    int mID = NO_ID;
1740
1741    /**
1742     * The stable ID of this view for accessibility purposes.
1743     */
1744    int mAccessibilityViewId = NO_ID;
1745
1746    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1747
1748    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1749
1750    /**
1751     * The view's tag.
1752     * {@hide}
1753     *
1754     * @see #setTag(Object)
1755     * @see #getTag()
1756     */
1757    protected Object mTag = null;
1758
1759    // for mPrivateFlags:
1760    /** {@hide} */
1761    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1762    /** {@hide} */
1763    static final int PFLAG_FOCUSED                     = 0x00000002;
1764    /** {@hide} */
1765    static final int PFLAG_SELECTED                    = 0x00000004;
1766    /** {@hide} */
1767    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1768    /** {@hide} */
1769    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1770    /** {@hide} */
1771    static final int PFLAG_DRAWN                       = 0x00000020;
1772    /**
1773     * When this flag is set, this view is running an animation on behalf of its
1774     * children and should therefore not cancel invalidate requests, even if they
1775     * lie outside of this view's bounds.
1776     *
1777     * {@hide}
1778     */
1779    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1780    /** {@hide} */
1781    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1782    /** {@hide} */
1783    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1784    /** {@hide} */
1785    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1786    /** {@hide} */
1787    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1788    /** {@hide} */
1789    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1790    /** {@hide} */
1791    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1792
1793    private static final int PFLAG_PRESSED             = 0x00004000;
1794
1795    /** {@hide} */
1796    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1797    /**
1798     * Flag used to indicate that this view should be drawn once more (and only once
1799     * more) after its animation has completed.
1800     * {@hide}
1801     */
1802    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1803
1804    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1805
1806    /**
1807     * Indicates that the View returned true when onSetAlpha() was called and that
1808     * the alpha must be restored.
1809     * {@hide}
1810     */
1811    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1812
1813    /**
1814     * Set by {@link #setScrollContainer(boolean)}.
1815     */
1816    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1817
1818    /**
1819     * Set by {@link #setScrollContainer(boolean)}.
1820     */
1821    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1822
1823    /**
1824     * View flag indicating whether this view was invalidated (fully or partially.)
1825     *
1826     * @hide
1827     */
1828    static final int PFLAG_DIRTY                       = 0x00200000;
1829
1830    /**
1831     * View flag indicating whether this view was invalidated by an opaque
1832     * invalidate request.
1833     *
1834     * @hide
1835     */
1836    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1837
1838    /**
1839     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1840     *
1841     * @hide
1842     */
1843    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1844
1845    /**
1846     * Indicates whether the background is opaque.
1847     *
1848     * @hide
1849     */
1850    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1851
1852    /**
1853     * Indicates whether the scrollbars are opaque.
1854     *
1855     * @hide
1856     */
1857    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1858
1859    /**
1860     * Indicates whether the view is opaque.
1861     *
1862     * @hide
1863     */
1864    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1865
1866    /**
1867     * Indicates a prepressed state;
1868     * the short time between ACTION_DOWN and recognizing
1869     * a 'real' press. Prepressed is used to recognize quick taps
1870     * even when they are shorter than ViewConfiguration.getTapTimeout().
1871     *
1872     * @hide
1873     */
1874    private static final int PFLAG_PREPRESSED          = 0x02000000;
1875
1876    /**
1877     * Indicates whether the view is temporarily detached.
1878     *
1879     * @hide
1880     */
1881    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1882
1883    /**
1884     * Indicates that we should awaken scroll bars once attached
1885     *
1886     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1887     * during window attachment and it is no longer needed. Feel free to repurpose it.
1888     *
1889     * @hide
1890     */
1891    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1892
1893    /**
1894     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1895     * @hide
1896     */
1897    private static final int PFLAG_HOVERED             = 0x10000000;
1898
1899    /**
1900     * no longer needed, should be reused
1901     */
1902    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1903
1904    /** {@hide} */
1905    static final int PFLAG_ACTIVATED                   = 0x40000000;
1906
1907    /**
1908     * Indicates that this view was specifically invalidated, not just dirtied because some
1909     * child view was invalidated. The flag is used to determine when we need to recreate
1910     * a view's display list (as opposed to just returning a reference to its existing
1911     * display list).
1912     *
1913     * @hide
1914     */
1915    static final int PFLAG_INVALIDATED                 = 0x80000000;
1916
1917    /**
1918     * Masks for mPrivateFlags2, as generated by dumpFlags():
1919     *
1920     * |-------|-------|-------|-------|
1921     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1922     *                                1  PFLAG2_DRAG_HOVERED
1923     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1924     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1925     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1926     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1927     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1928     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1929     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1930     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1931     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1932     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1933     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1934     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1935     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1936     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1937     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1938     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1939     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1940     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1941     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1942     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1943     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1944     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1945     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1946     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1947     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1948     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1949     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1950     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1951     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1952     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1953     *    1                              PFLAG2_PADDING_RESOLVED
1954     *   1                               PFLAG2_DRAWABLE_RESOLVED
1955     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1956     * |-------|-------|-------|-------|
1957     */
1958
1959    /**
1960     * Indicates that this view has reported that it can accept the current drag's content.
1961     * Cleared when the drag operation concludes.
1962     * @hide
1963     */
1964    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1965
1966    /**
1967     * Indicates that this view is currently directly under the drag location in a
1968     * drag-and-drop operation involving content that it can accept.  Cleared when
1969     * the drag exits the view, or when the drag operation concludes.
1970     * @hide
1971     */
1972    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1973
1974    /** @hide */
1975    @IntDef({
1976        LAYOUT_DIRECTION_LTR,
1977        LAYOUT_DIRECTION_RTL,
1978        LAYOUT_DIRECTION_INHERIT,
1979        LAYOUT_DIRECTION_LOCALE
1980    })
1981    @Retention(RetentionPolicy.SOURCE)
1982    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1983    public @interface LayoutDir {}
1984
1985    /** @hide */
1986    @IntDef({
1987        LAYOUT_DIRECTION_LTR,
1988        LAYOUT_DIRECTION_RTL
1989    })
1990    @Retention(RetentionPolicy.SOURCE)
1991    public @interface ResolvedLayoutDir {}
1992
1993    /**
1994     * A flag to indicate that the layout direction of this view has not been defined yet.
1995     * @hide
1996     */
1997    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1998
1999    /**
2000     * Horizontal layout direction of this view is from Left to Right.
2001     * Use with {@link #setLayoutDirection}.
2002     */
2003    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2004
2005    /**
2006     * Horizontal layout direction of this view is from Right to Left.
2007     * Use with {@link #setLayoutDirection}.
2008     */
2009    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2010
2011    /**
2012     * Horizontal layout direction of this view is inherited from its parent.
2013     * Use with {@link #setLayoutDirection}.
2014     */
2015    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2016
2017    /**
2018     * Horizontal layout direction of this view is from deduced from the default language
2019     * script for the locale. Use with {@link #setLayoutDirection}.
2020     */
2021    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2022
2023    /**
2024     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2025     * @hide
2026     */
2027    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2028
2029    /**
2030     * Mask for use with private flags indicating bits used for horizontal layout direction.
2031     * @hide
2032     */
2033    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2034
2035    /**
2036     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2037     * right-to-left direction.
2038     * @hide
2039     */
2040    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2041
2042    /**
2043     * Indicates whether the view horizontal layout direction has been resolved.
2044     * @hide
2045     */
2046    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2047
2048    /**
2049     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2050     * @hide
2051     */
2052    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2053            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2054
2055    /*
2056     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2057     * flag value.
2058     * @hide
2059     */
2060    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2061            LAYOUT_DIRECTION_LTR,
2062            LAYOUT_DIRECTION_RTL,
2063            LAYOUT_DIRECTION_INHERIT,
2064            LAYOUT_DIRECTION_LOCALE
2065    };
2066
2067    /**
2068     * Default horizontal layout direction.
2069     */
2070    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2071
2072    /**
2073     * Default horizontal layout direction.
2074     * @hide
2075     */
2076    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2077
2078    /**
2079     * Text direction is inherited through {@link ViewGroup}
2080     */
2081    public static final int TEXT_DIRECTION_INHERIT = 0;
2082
2083    /**
2084     * Text direction is using "first strong algorithm". The first strong directional character
2085     * determines the paragraph direction. If there is no strong directional character, the
2086     * paragraph direction is the view's resolved layout direction.
2087     */
2088    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2089
2090    /**
2091     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2092     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2093     * If there are neither, the paragraph direction is the view's resolved layout direction.
2094     */
2095    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2096
2097    /**
2098     * Text direction is forced to LTR.
2099     */
2100    public static final int TEXT_DIRECTION_LTR = 3;
2101
2102    /**
2103     * Text direction is forced to RTL.
2104     */
2105    public static final int TEXT_DIRECTION_RTL = 4;
2106
2107    /**
2108     * Text direction is coming from the system Locale.
2109     */
2110    public static final int TEXT_DIRECTION_LOCALE = 5;
2111
2112    /**
2113     * Text direction is using "first strong algorithm". The first strong directional character
2114     * determines the paragraph direction. If there is no strong directional character, the
2115     * paragraph direction is LTR.
2116     */
2117    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2118
2119    /**
2120     * Text direction is using "first strong algorithm". The first strong directional character
2121     * determines the paragraph direction. If there is no strong directional character, the
2122     * paragraph direction is RTL.
2123     */
2124    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2125
2126    /**
2127     * Default text direction is inherited
2128     */
2129    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2130
2131    /**
2132     * Default resolved text direction
2133     * @hide
2134     */
2135    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2136
2137    /**
2138     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2139     * @hide
2140     */
2141    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2142
2143    /**
2144     * Mask for use with private flags indicating bits used for text direction.
2145     * @hide
2146     */
2147    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2148            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2149
2150    /**
2151     * Array of text direction flags for mapping attribute "textDirection" to correct
2152     * flag value.
2153     * @hide
2154     */
2155    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2156            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2157            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2158            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2159            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2160            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2161            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2162            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2163            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2164    };
2165
2166    /**
2167     * Indicates whether the view text direction has been resolved.
2168     * @hide
2169     */
2170    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2171            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2172
2173    /**
2174     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2175     * @hide
2176     */
2177    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2178
2179    /**
2180     * Mask for use with private flags indicating bits used for resolved text direction.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2184            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2185
2186    /**
2187     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2188     * @hide
2189     */
2190    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2191            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2192
2193    /** @hide */
2194    @IntDef({
2195        TEXT_ALIGNMENT_INHERIT,
2196        TEXT_ALIGNMENT_GRAVITY,
2197        TEXT_ALIGNMENT_CENTER,
2198        TEXT_ALIGNMENT_TEXT_START,
2199        TEXT_ALIGNMENT_TEXT_END,
2200        TEXT_ALIGNMENT_VIEW_START,
2201        TEXT_ALIGNMENT_VIEW_END
2202    })
2203    @Retention(RetentionPolicy.SOURCE)
2204    public @interface TextAlignment {}
2205
2206    /**
2207     * Default text alignment. The text alignment of this View is inherited from its parent.
2208     * Use with {@link #setTextAlignment(int)}
2209     */
2210    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2211
2212    /**
2213     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2214     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2215     *
2216     * Use with {@link #setTextAlignment(int)}
2217     */
2218    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2219
2220    /**
2221     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2222     *
2223     * Use with {@link #setTextAlignment(int)}
2224     */
2225    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2226
2227    /**
2228     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2229     *
2230     * Use with {@link #setTextAlignment(int)}
2231     */
2232    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2233
2234    /**
2235     * Center the paragraph, e.g. ALIGN_CENTER.
2236     *
2237     * Use with {@link #setTextAlignment(int)}
2238     */
2239    public static final int TEXT_ALIGNMENT_CENTER = 4;
2240
2241    /**
2242     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2243     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2244     *
2245     * Use with {@link #setTextAlignment(int)}
2246     */
2247    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2248
2249    /**
2250     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2251     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2252     *
2253     * Use with {@link #setTextAlignment(int)}
2254     */
2255    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2256
2257    /**
2258     * Default text alignment is inherited
2259     */
2260    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2261
2262    /**
2263     * Default resolved text alignment
2264     * @hide
2265     */
2266    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2267
2268    /**
2269      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2270      * @hide
2271      */
2272    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
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_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2279
2280    /**
2281     * Array of text direction flags for mapping attribute "textAlignment" to correct
2282     * flag value.
2283     * @hide
2284     */
2285    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2286            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2287            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2288            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2289            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2290            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2291            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2292            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2293    };
2294
2295    /**
2296     * Indicates whether the view text alignment has been resolved.
2297     * @hide
2298     */
2299    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2300
2301    /**
2302     * Bit shift to get the resolved text alignment.
2303     * @hide
2304     */
2305    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2306
2307    /**
2308     * Mask for use with private flags indicating bits used for text alignment.
2309     * @hide
2310     */
2311    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2312            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2313
2314    /**
2315     * Indicates whether if the view text alignment has been resolved to gravity
2316     */
2317    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2318            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2319
2320    // Accessiblity constants for mPrivateFlags2
2321
2322    /**
2323     * Shift for the bits in {@link #mPrivateFlags2} related to the
2324     * "importantForAccessibility" attribute.
2325     */
2326    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2327
2328    /**
2329     * Automatically determine whether a view is important for accessibility.
2330     */
2331    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2332
2333    /**
2334     * The view is important for accessibility.
2335     */
2336    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2337
2338    /**
2339     * The view is not important for accessibility.
2340     */
2341    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2342
2343    /**
2344     * The view is not important for accessibility, nor are any of its
2345     * descendant views.
2346     */
2347    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2348
2349    /**
2350     * The default whether the view is important for accessibility.
2351     */
2352    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2353
2354    /**
2355     * Mask for obtaining the bits which specify how to determine
2356     * whether a view is important for accessibility.
2357     */
2358    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2359        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2360        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2361        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2362
2363    /**
2364     * Shift for the bits in {@link #mPrivateFlags2} related to the
2365     * "accessibilityLiveRegion" attribute.
2366     */
2367    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2368
2369    /**
2370     * Live region mode specifying that accessibility services should not
2371     * automatically announce changes to this view. This is the default live
2372     * region mode for most views.
2373     * <p>
2374     * Use with {@link #setAccessibilityLiveRegion(int)}.
2375     */
2376    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2377
2378    /**
2379     * Live region mode specifying that accessibility services should announce
2380     * changes to this view.
2381     * <p>
2382     * Use with {@link #setAccessibilityLiveRegion(int)}.
2383     */
2384    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2385
2386    /**
2387     * Live region mode specifying that accessibility services should interrupt
2388     * ongoing speech to immediately announce changes to this view.
2389     * <p>
2390     * Use with {@link #setAccessibilityLiveRegion(int)}.
2391     */
2392    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2393
2394    /**
2395     * The default whether the view is important for accessibility.
2396     */
2397    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2398
2399    /**
2400     * Mask for obtaining the bits which specify a view's accessibility live
2401     * region mode.
2402     */
2403    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2404            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2405            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2406
2407    /**
2408     * Flag indicating whether a view has accessibility focus.
2409     */
2410    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2411
2412    /**
2413     * Flag whether the accessibility state of the subtree rooted at this view changed.
2414     */
2415    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2416
2417    /**
2418     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2419     * is used to check whether later changes to the view's transform should invalidate the
2420     * view to force the quickReject test to run again.
2421     */
2422    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2423
2424    /**
2425     * Flag indicating that start/end padding has been resolved into left/right padding
2426     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2427     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2428     * during measurement. In some special cases this is required such as when an adapter-based
2429     * view measures prospective children without attaching them to a window.
2430     */
2431    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2432
2433    /**
2434     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2435     */
2436    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2437
2438    /**
2439     * Indicates that the view is tracking some sort of transient state
2440     * that the app should not need to be aware of, but that the framework
2441     * should take special care to preserve.
2442     */
2443    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2444
2445    /**
2446     * Group of bits indicating that RTL properties resolution is done.
2447     */
2448    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2449            PFLAG2_TEXT_DIRECTION_RESOLVED |
2450            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2451            PFLAG2_PADDING_RESOLVED |
2452            PFLAG2_DRAWABLE_RESOLVED;
2453
2454    // There are a couple of flags left in mPrivateFlags2
2455
2456    /* End of masks for mPrivateFlags2 */
2457
2458    /**
2459     * Masks for mPrivateFlags3, as generated by dumpFlags():
2460     *
2461     * |-------|-------|-------|-------|
2462     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2463     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2464     *                               1   PFLAG3_IS_LAID_OUT
2465     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2466     *                             1     PFLAG3_CALLED_SUPER
2467     *                            1      PFLAG3_APPLYING_INSETS
2468     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2469     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2470     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2471     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2472     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2473     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2474     *                     1             PFLAG3_SCROLL_INDICATOR_START
2475     *                    1              PFLAG3_SCROLL_INDICATOR_END
2476     *                   1               PFLAG3_ASSIST_BLOCKED
2477     *                  1                PFLAG3_CLUSTER
2478     *                 1                 PFLAG3_SECTION
2479     *           xxxxxx                  * NO LONGER NEEDED, SHOULD BE REUSED *
2480     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2481     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2482     *        1                          PFLAG3_TEMPORARY_DETACH
2483     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2484     * |-------|-------|-------|-------|
2485     */
2486
2487    /**
2488     * Flag indicating that view has a transform animation set on it. This is used to track whether
2489     * an animation is cleared between successive frames, in order to tell the associated
2490     * DisplayList to clear its animation matrix.
2491     */
2492    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2493
2494    /**
2495     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2496     * animation is cleared between successive frames, in order to tell the associated
2497     * DisplayList to restore its alpha value.
2498     */
2499    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2500
2501    /**
2502     * Flag indicating that the view has been through at least one layout since it
2503     * was last attached to a window.
2504     */
2505    static final int PFLAG3_IS_LAID_OUT = 0x4;
2506
2507    /**
2508     * Flag indicating that a call to measure() was skipped and should be done
2509     * instead when layout() is invoked.
2510     */
2511    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2512
2513    /**
2514     * Flag indicating that an overridden method correctly called down to
2515     * the superclass implementation as required by the API spec.
2516     */
2517    static final int PFLAG3_CALLED_SUPER = 0x10;
2518
2519    /**
2520     * Flag indicating that we're in the process of applying window insets.
2521     */
2522    static final int PFLAG3_APPLYING_INSETS = 0x20;
2523
2524    /**
2525     * Flag indicating that we're in the process of fitting system windows using the old method.
2526     */
2527    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2528
2529    /**
2530     * Flag indicating that nested scrolling is enabled for this view.
2531     * The view will optionally cooperate with views up its parent chain to allow for
2532     * integrated nested scrolling along the same axis.
2533     */
2534    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2535
2536    /**
2537     * Flag indicating that the bottom scroll indicator should be displayed
2538     * when this view can scroll up.
2539     */
2540    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2541
2542    /**
2543     * Flag indicating that the bottom scroll indicator should be displayed
2544     * when this view can scroll down.
2545     */
2546    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2547
2548    /**
2549     * Flag indicating that the left scroll indicator should be displayed
2550     * when this view can scroll left.
2551     */
2552    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2553
2554    /**
2555     * Flag indicating that the right scroll indicator should be displayed
2556     * when this view can scroll right.
2557     */
2558    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2559
2560    /**
2561     * Flag indicating that the start scroll indicator should be displayed
2562     * when this view can scroll in the start direction.
2563     */
2564    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2565
2566    /**
2567     * Flag indicating that the end scroll indicator should be displayed
2568     * when this view can scroll in the end direction.
2569     */
2570    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2571
2572    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2573
2574    static final int SCROLL_INDICATORS_NONE = 0x0000;
2575
2576    /**
2577     * Mask for use with setFlags indicating bits used for indicating which
2578     * scroll indicators are enabled.
2579     */
2580    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2581            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2582            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2583            | PFLAG3_SCROLL_INDICATOR_END;
2584
2585    /**
2586     * Left-shift required to translate between public scroll indicator flags
2587     * and internal PFLAGS3 flags. When used as a right-shift, translates
2588     * PFLAGS3 flags to public flags.
2589     */
2590    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2591
2592    /** @hide */
2593    @Retention(RetentionPolicy.SOURCE)
2594    @IntDef(flag = true,
2595            value = {
2596                    SCROLL_INDICATOR_TOP,
2597                    SCROLL_INDICATOR_BOTTOM,
2598                    SCROLL_INDICATOR_LEFT,
2599                    SCROLL_INDICATOR_RIGHT,
2600                    SCROLL_INDICATOR_START,
2601                    SCROLL_INDICATOR_END,
2602            })
2603    public @interface ScrollIndicators {}
2604
2605    /**
2606     * Scroll indicator direction for the top edge of the view.
2607     *
2608     * @see #setScrollIndicators(int)
2609     * @see #setScrollIndicators(int, int)
2610     * @see #getScrollIndicators()
2611     */
2612    public static final int SCROLL_INDICATOR_TOP =
2613            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2614
2615    /**
2616     * Scroll indicator direction for the bottom edge of the view.
2617     *
2618     * @see #setScrollIndicators(int)
2619     * @see #setScrollIndicators(int, int)
2620     * @see #getScrollIndicators()
2621     */
2622    public static final int SCROLL_INDICATOR_BOTTOM =
2623            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2624
2625    /**
2626     * Scroll indicator direction for the left edge of the view.
2627     *
2628     * @see #setScrollIndicators(int)
2629     * @see #setScrollIndicators(int, int)
2630     * @see #getScrollIndicators()
2631     */
2632    public static final int SCROLL_INDICATOR_LEFT =
2633            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2634
2635    /**
2636     * Scroll indicator direction for the right edge of the view.
2637     *
2638     * @see #setScrollIndicators(int)
2639     * @see #setScrollIndicators(int, int)
2640     * @see #getScrollIndicators()
2641     */
2642    public static final int SCROLL_INDICATOR_RIGHT =
2643            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2644
2645    /**
2646     * Scroll indicator direction for the starting edge of the view.
2647     * <p>
2648     * Resolved according to the view's layout direction, see
2649     * {@link #getLayoutDirection()} for more information.
2650     *
2651     * @see #setScrollIndicators(int)
2652     * @see #setScrollIndicators(int, int)
2653     * @see #getScrollIndicators()
2654     */
2655    public static final int SCROLL_INDICATOR_START =
2656            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2657
2658    /**
2659     * Scroll indicator direction for the ending edge of the view.
2660     * <p>
2661     * Resolved according to the view's layout direction, see
2662     * {@link #getLayoutDirection()} for more information.
2663     *
2664     * @see #setScrollIndicators(int)
2665     * @see #setScrollIndicators(int, int)
2666     * @see #getScrollIndicators()
2667     */
2668    public static final int SCROLL_INDICATOR_END =
2669            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2670
2671    /**
2672     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2673     * into this view.<p>
2674     */
2675    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2676
2677    /**
2678     * Flag indicating that the view is a root of a keyboard navigation cluster.
2679     *
2680     * @see #isKeyboardNavigationCluster()
2681     * @see #setKeyboardNavigationCluster(boolean)
2682     */
2683    private static final int PFLAG3_CLUSTER = 0x8000;
2684
2685    /**
2686     * Flag indicating that the view is a root of a keyboard navigation section.
2687     *
2688     * @see #isKeyboardNavigationSection()
2689     * @see #setKeyboardNavigationSection(boolean)
2690     */
2691    private static final int PFLAG3_SECTION = 0x10000;
2692
2693    /**
2694     * Whether this view has rendered elements that overlap (see {@link
2695     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2696     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2697     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2698     * determined by whatever {@link #hasOverlappingRendering()} returns.
2699     */
2700    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2701
2702    /**
2703     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2704     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2705     */
2706    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2707
2708    /**
2709     * Flag indicating that the view is temporarily detached from the parent view.
2710     *
2711     * @see #onStartTemporaryDetach()
2712     * @see #onFinishTemporaryDetach()
2713     */
2714    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2715
2716    /**
2717     * Flag indicating that the view does not wish to be revealed within its parent
2718     * hierarchy when it gains focus. Expressed in the negative since the historical
2719     * default behavior is to reveal on focus; this flag suppresses that behavior.
2720     *
2721     * @see #setRevealOnFocusHint(boolean)
2722     * @see #getRevealOnFocusHint()
2723     */
2724    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2725
2726    /* End of masks for mPrivateFlags3 */
2727
2728    /**
2729     * Always allow a user to over-scroll this view, provided it is a
2730     * view that can scroll.
2731     *
2732     * @see #getOverScrollMode()
2733     * @see #setOverScrollMode(int)
2734     */
2735    public static final int OVER_SCROLL_ALWAYS = 0;
2736
2737    /**
2738     * Allow a user to over-scroll this view only if the content is large
2739     * enough to meaningfully scroll, provided it is a view that can scroll.
2740     *
2741     * @see #getOverScrollMode()
2742     * @see #setOverScrollMode(int)
2743     */
2744    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2745
2746    /**
2747     * Never allow a user to over-scroll this view.
2748     *
2749     * @see #getOverScrollMode()
2750     * @see #setOverScrollMode(int)
2751     */
2752    public static final int OVER_SCROLL_NEVER = 2;
2753
2754    /**
2755     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2756     * requested the system UI (status bar) to be visible (the default).
2757     *
2758     * @see #setSystemUiVisibility(int)
2759     */
2760    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2761
2762    /**
2763     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2764     * system UI to enter an unobtrusive "low profile" mode.
2765     *
2766     * <p>This is for use in games, book readers, video players, or any other
2767     * "immersive" application where the usual system chrome is deemed too distracting.
2768     *
2769     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2770     *
2771     * @see #setSystemUiVisibility(int)
2772     */
2773    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2774
2775    /**
2776     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2777     * system navigation be temporarily hidden.
2778     *
2779     * <p>This is an even less obtrusive state than that called for by
2780     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2781     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2782     * those to disappear. This is useful (in conjunction with the
2783     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2784     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2785     * window flags) for displaying content using every last pixel on the display.
2786     *
2787     * <p>There is a limitation: because navigation controls are so important, the least user
2788     * interaction will cause them to reappear immediately.  When this happens, both
2789     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2790     * so that both elements reappear at the same time.
2791     *
2792     * @see #setSystemUiVisibility(int)
2793     */
2794    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2795
2796    /**
2797     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2798     * into the normal fullscreen mode so that its content can take over the screen
2799     * while still allowing the user to interact with the application.
2800     *
2801     * <p>This has the same visual effect as
2802     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2803     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2804     * meaning that non-critical screen decorations (such as the status bar) will be
2805     * hidden while the user is in the View's window, focusing the experience on
2806     * that content.  Unlike the window flag, if you are using ActionBar in
2807     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2808     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2809     * hide the action bar.
2810     *
2811     * <p>This approach to going fullscreen is best used over the window flag when
2812     * it is a transient state -- that is, the application does this at certain
2813     * points in its user interaction where it wants to allow the user to focus
2814     * on content, but not as a continuous state.  For situations where the application
2815     * would like to simply stay full screen the entire time (such as a game that
2816     * wants to take over the screen), the
2817     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2818     * is usually a better approach.  The state set here will be removed by the system
2819     * in various situations (such as the user moving to another application) like
2820     * the other system UI states.
2821     *
2822     * <p>When using this flag, the application should provide some easy facility
2823     * for the user to go out of it.  A common example would be in an e-book
2824     * reader, where tapping on the screen brings back whatever screen and UI
2825     * decorations that had been hidden while the user was immersed in reading
2826     * the book.
2827     *
2828     * @see #setSystemUiVisibility(int)
2829     */
2830    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2831
2832    /**
2833     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2834     * flags, we would like a stable view of the content insets given to
2835     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2836     * will always represent the worst case that the application can expect
2837     * as a continuous state.  In the stock Android UI this is the space for
2838     * the system bar, nav bar, and status bar, but not more transient elements
2839     * such as an input method.
2840     *
2841     * The stable layout your UI sees is based on the system UI modes you can
2842     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2843     * then you will get a stable layout for changes of the
2844     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2845     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2846     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2847     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2848     * with a stable layout.  (Note that you should avoid using
2849     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2850     *
2851     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2852     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2853     * then a hidden status bar will be considered a "stable" state for purposes
2854     * here.  This allows your UI to continually hide the status bar, while still
2855     * using the system UI flags to hide the action bar while still retaining
2856     * a stable layout.  Note that changing the window fullscreen flag will never
2857     * provide a stable layout for a clean transition.
2858     *
2859     * <p>If you are using ActionBar in
2860     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2861     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2862     * insets it adds to those given to the application.
2863     */
2864    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2865
2866    /**
2867     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2868     * to be laid out as if it has requested
2869     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2870     * allows it to avoid artifacts when switching in and out of that mode, at
2871     * the expense that some of its user interface may be covered by screen
2872     * decorations when they are shown.  You can perform layout of your inner
2873     * UI elements to account for the navigation system UI through the
2874     * {@link #fitSystemWindows(Rect)} method.
2875     */
2876    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2877
2878    /**
2879     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2880     * to be laid out as if it has requested
2881     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2882     * allows it to avoid artifacts when switching in and out of that mode, at
2883     * the expense that some of its user interface may be covered by screen
2884     * decorations when they are shown.  You can perform layout of your inner
2885     * UI elements to account for non-fullscreen system UI through the
2886     * {@link #fitSystemWindows(Rect)} method.
2887     */
2888    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2889
2890    /**
2891     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2892     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2893     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2894     * user interaction.
2895     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2896     * has an effect when used in combination with that flag.</p>
2897     */
2898    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2899
2900    /**
2901     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2902     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2903     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2904     * experience while also hiding the system bars.  If this flag is not set,
2905     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2906     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2907     * if the user swipes from the top of the screen.
2908     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2909     * system gestures, such as swiping from the top of the screen.  These transient system bars
2910     * will overlay app’s content, may have some degree of transparency, and will automatically
2911     * hide after a short timeout.
2912     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2913     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2914     * with one or both of those flags.</p>
2915     */
2916    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2917
2918    /**
2919     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2920     * is compatible with light status bar backgrounds.
2921     *
2922     * <p>For this to take effect, the window must request
2923     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2924     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2925     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2926     *         FLAG_TRANSLUCENT_STATUS}.
2927     *
2928     * @see android.R.attr#windowLightStatusBar
2929     */
2930    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2931
2932    /**
2933     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2934     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2935     */
2936    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
2937
2938    /**
2939     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2940     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2941     */
2942    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
2943
2944    /**
2945     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
2946     * that is compatible with light navigation bar backgrounds.
2947     *
2948     * <p>For this to take effect, the window must request
2949     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2950     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2951     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
2952     *         FLAG_TRANSLUCENT_NAVIGATION}.
2953     */
2954    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
2955
2956    /**
2957     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2958     */
2959    @Deprecated
2960    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2961
2962    /**
2963     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2964     */
2965    @Deprecated
2966    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2967
2968    /**
2969     * @hide
2970     *
2971     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2972     * out of the public fields to keep the undefined bits out of the developer's way.
2973     *
2974     * Flag to make the status bar not expandable.  Unless you also
2975     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2976     */
2977    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2978
2979    /**
2980     * @hide
2981     *
2982     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2983     * out of the public fields to keep the undefined bits out of the developer's way.
2984     *
2985     * Flag to hide notification icons and scrolling ticker text.
2986     */
2987    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2988
2989    /**
2990     * @hide
2991     *
2992     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2993     * out of the public fields to keep the undefined bits out of the developer's way.
2994     *
2995     * Flag to disable incoming notification alerts.  This will not block
2996     * icons, but it will block sound, vibrating and other visual or aural notifications.
2997     */
2998    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2999
3000    /**
3001     * @hide
3002     *
3003     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3004     * out of the public fields to keep the undefined bits out of the developer's way.
3005     *
3006     * Flag to hide only the scrolling ticker.  Note that
3007     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3008     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3009     */
3010    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3011
3012    /**
3013     * @hide
3014     *
3015     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3016     * out of the public fields to keep the undefined bits out of the developer's way.
3017     *
3018     * Flag to hide the center system info area.
3019     */
3020    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3021
3022    /**
3023     * @hide
3024     *
3025     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3026     * out of the public fields to keep the undefined bits out of the developer's way.
3027     *
3028     * Flag to hide only the home button.  Don't use this
3029     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3030     */
3031    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3032
3033    /**
3034     * @hide
3035     *
3036     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3037     * out of the public fields to keep the undefined bits out of the developer's way.
3038     *
3039     * Flag to hide only the back button. Don't use this
3040     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3041     */
3042    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3043
3044    /**
3045     * @hide
3046     *
3047     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3048     * out of the public fields to keep the undefined bits out of the developer's way.
3049     *
3050     * Flag to hide only the clock.  You might use this if your activity has
3051     * its own clock making the status bar's clock redundant.
3052     */
3053    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3054
3055    /**
3056     * @hide
3057     *
3058     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3059     * out of the public fields to keep the undefined bits out of the developer's way.
3060     *
3061     * Flag to hide only the recent apps button. Don't use this
3062     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3063     */
3064    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3065
3066    /**
3067     * @hide
3068     *
3069     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3070     * out of the public fields to keep the undefined bits out of the developer's way.
3071     *
3072     * Flag to disable the global search gesture. Don't use this
3073     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3074     */
3075    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3076
3077    /**
3078     * @hide
3079     *
3080     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3081     * out of the public fields to keep the undefined bits out of the developer's way.
3082     *
3083     * Flag to specify that the status bar is displayed in transient mode.
3084     */
3085    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3086
3087    /**
3088     * @hide
3089     *
3090     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3091     * out of the public fields to keep the undefined bits out of the developer's way.
3092     *
3093     * Flag to specify that the navigation bar is displayed in transient mode.
3094     */
3095    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3096
3097    /**
3098     * @hide
3099     *
3100     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3101     * out of the public fields to keep the undefined bits out of the developer's way.
3102     *
3103     * Flag to specify that the hidden status bar would like to be shown.
3104     */
3105    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3106
3107    /**
3108     * @hide
3109     *
3110     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3111     * out of the public fields to keep the undefined bits out of the developer's way.
3112     *
3113     * Flag to specify that the hidden navigation bar would like to be shown.
3114     */
3115    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3116
3117    /**
3118     * @hide
3119     *
3120     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3121     * out of the public fields to keep the undefined bits out of the developer's way.
3122     *
3123     * Flag to specify that the status bar is displayed in translucent mode.
3124     */
3125    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3126
3127    /**
3128     * @hide
3129     *
3130     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3131     * out of the public fields to keep the undefined bits out of the developer's way.
3132     *
3133     * Flag to specify that the navigation bar is displayed in translucent mode.
3134     */
3135    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3136
3137    /**
3138     * @hide
3139     *
3140     * Makes navigation bar transparent (but not the status bar).
3141     */
3142    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3143
3144    /**
3145     * @hide
3146     *
3147     * Makes status bar transparent (but not the navigation bar).
3148     */
3149    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3150
3151    /**
3152     * @hide
3153     *
3154     * Makes both status bar and navigation bar transparent.
3155     */
3156    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3157            | STATUS_BAR_TRANSPARENT;
3158
3159    /**
3160     * @hide
3161     */
3162    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3163
3164    /**
3165     * These are the system UI flags that can be cleared by events outside
3166     * of an application.  Currently this is just the ability to tap on the
3167     * screen while hiding the navigation bar to have it return.
3168     * @hide
3169     */
3170    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3171            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3172            | SYSTEM_UI_FLAG_FULLSCREEN;
3173
3174    /**
3175     * Flags that can impact the layout in relation to system UI.
3176     */
3177    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3178            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3179            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3180
3181    /** @hide */
3182    @IntDef(flag = true,
3183            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3184    @Retention(RetentionPolicy.SOURCE)
3185    public @interface FindViewFlags {}
3186
3187    /**
3188     * Find views that render the specified text.
3189     *
3190     * @see #findViewsWithText(ArrayList, CharSequence, int)
3191     */
3192    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3193
3194    /**
3195     * Find find views that contain the specified content description.
3196     *
3197     * @see #findViewsWithText(ArrayList, CharSequence, int)
3198     */
3199    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3200
3201    /**
3202     * Find views that contain {@link AccessibilityNodeProvider}. Such
3203     * a View is a root of virtual view hierarchy and may contain the searched
3204     * text. If this flag is set Views with providers are automatically
3205     * added and it is a responsibility of the client to call the APIs of
3206     * the provider to determine whether the virtual tree rooted at this View
3207     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3208     * representing the virtual views with this text.
3209     *
3210     * @see #findViewsWithText(ArrayList, CharSequence, int)
3211     *
3212     * @hide
3213     */
3214    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3215
3216    /**
3217     * The undefined cursor position.
3218     *
3219     * @hide
3220     */
3221    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3222
3223    /**
3224     * Indicates that the screen has changed state and is now off.
3225     *
3226     * @see #onScreenStateChanged(int)
3227     */
3228    public static final int SCREEN_STATE_OFF = 0x0;
3229
3230    /**
3231     * Indicates that the screen has changed state and is now on.
3232     *
3233     * @see #onScreenStateChanged(int)
3234     */
3235    public static final int SCREEN_STATE_ON = 0x1;
3236
3237    /**
3238     * Indicates no axis of view scrolling.
3239     */
3240    public static final int SCROLL_AXIS_NONE = 0;
3241
3242    /**
3243     * Indicates scrolling along the horizontal axis.
3244     */
3245    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3246
3247    /**
3248     * Indicates scrolling along the vertical axis.
3249     */
3250    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3251
3252    /**
3253     * Controls the over-scroll mode for this view.
3254     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3255     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3256     * and {@link #OVER_SCROLL_NEVER}.
3257     */
3258    private int mOverScrollMode;
3259
3260    /**
3261     * The parent this view is attached to.
3262     * {@hide}
3263     *
3264     * @see #getParent()
3265     */
3266    protected ViewParent mParent;
3267
3268    /**
3269     * {@hide}
3270     */
3271    AttachInfo mAttachInfo;
3272
3273    /**
3274     * {@hide}
3275     */
3276    @ViewDebug.ExportedProperty(flagMapping = {
3277        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3278                name = "FORCE_LAYOUT"),
3279        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3280                name = "LAYOUT_REQUIRED"),
3281        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3282            name = "DRAWING_CACHE_INVALID", outputIf = false),
3283        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3284        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3285        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3286        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3287    }, formatToHexString = true)
3288    int mPrivateFlags;
3289    int mPrivateFlags2;
3290    int mPrivateFlags3;
3291
3292    /**
3293     * This view's request for the visibility of the status bar.
3294     * @hide
3295     */
3296    @ViewDebug.ExportedProperty(flagMapping = {
3297        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3298                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3299                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3300        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3301                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3302                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3303        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3304                                equals = SYSTEM_UI_FLAG_VISIBLE,
3305                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3306    }, formatToHexString = true)
3307    int mSystemUiVisibility;
3308
3309    /**
3310     * Reference count for transient state.
3311     * @see #setHasTransientState(boolean)
3312     */
3313    int mTransientStateCount = 0;
3314
3315    /**
3316     * Count of how many windows this view has been attached to.
3317     */
3318    int mWindowAttachCount;
3319
3320    /**
3321     * The layout parameters associated with this view and used by the parent
3322     * {@link android.view.ViewGroup} to determine how this view should be
3323     * laid out.
3324     * {@hide}
3325     */
3326    protected ViewGroup.LayoutParams mLayoutParams;
3327
3328    /**
3329     * The view flags hold various views states.
3330     * {@hide}
3331     */
3332    @ViewDebug.ExportedProperty(formatToHexString = true)
3333    int mViewFlags;
3334
3335    static class TransformationInfo {
3336        /**
3337         * The transform matrix for the View. This transform is calculated internally
3338         * based on the translation, rotation, and scale properties.
3339         *
3340         * Do *not* use this variable directly; instead call getMatrix(), which will
3341         * load the value from the View's RenderNode.
3342         */
3343        private final Matrix mMatrix = new Matrix();
3344
3345        /**
3346         * The inverse transform matrix for the View. This transform is calculated
3347         * internally based on the translation, rotation, and scale properties.
3348         *
3349         * Do *not* use this variable directly; instead call getInverseMatrix(),
3350         * which will load the value from the View's RenderNode.
3351         */
3352        private Matrix mInverseMatrix;
3353
3354        /**
3355         * The opacity of the View. This is a value from 0 to 1, where 0 means
3356         * completely transparent and 1 means completely opaque.
3357         */
3358        @ViewDebug.ExportedProperty
3359        float mAlpha = 1f;
3360
3361        /**
3362         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3363         * property only used by transitions, which is composited with the other alpha
3364         * values to calculate the final visual alpha value.
3365         */
3366        float mTransitionAlpha = 1f;
3367    }
3368
3369    TransformationInfo mTransformationInfo;
3370
3371    /**
3372     * Current clip bounds. to which all drawing of this view are constrained.
3373     */
3374    Rect mClipBounds = null;
3375
3376    private boolean mLastIsOpaque;
3377
3378    /**
3379     * The distance in pixels from the left edge of this view's parent
3380     * to the left edge of this view.
3381     * {@hide}
3382     */
3383    @ViewDebug.ExportedProperty(category = "layout")
3384    protected int mLeft;
3385    /**
3386     * The distance in pixels from the left edge of this view's parent
3387     * to the right edge of this view.
3388     * {@hide}
3389     */
3390    @ViewDebug.ExportedProperty(category = "layout")
3391    protected int mRight;
3392    /**
3393     * The distance in pixels from the top edge of this view's parent
3394     * to the top edge of this view.
3395     * {@hide}
3396     */
3397    @ViewDebug.ExportedProperty(category = "layout")
3398    protected int mTop;
3399    /**
3400     * The distance in pixels from the top edge of this view's parent
3401     * to the bottom edge of this view.
3402     * {@hide}
3403     */
3404    @ViewDebug.ExportedProperty(category = "layout")
3405    protected int mBottom;
3406
3407    /**
3408     * The offset, in pixels, by which the content of this view is scrolled
3409     * horizontally.
3410     * {@hide}
3411     */
3412    @ViewDebug.ExportedProperty(category = "scrolling")
3413    protected int mScrollX;
3414    /**
3415     * The offset, in pixels, by which the content of this view is scrolled
3416     * vertically.
3417     * {@hide}
3418     */
3419    @ViewDebug.ExportedProperty(category = "scrolling")
3420    protected int mScrollY;
3421
3422    /**
3423     * The left padding in pixels, that is the distance in pixels between the
3424     * left edge of this view and the left edge of its content.
3425     * {@hide}
3426     */
3427    @ViewDebug.ExportedProperty(category = "padding")
3428    protected int mPaddingLeft = 0;
3429    /**
3430     * The right padding in pixels, that is the distance in pixels between the
3431     * right edge of this view and the right edge of its content.
3432     * {@hide}
3433     */
3434    @ViewDebug.ExportedProperty(category = "padding")
3435    protected int mPaddingRight = 0;
3436    /**
3437     * The top padding in pixels, that is the distance in pixels between the
3438     * top edge of this view and the top edge of its content.
3439     * {@hide}
3440     */
3441    @ViewDebug.ExportedProperty(category = "padding")
3442    protected int mPaddingTop;
3443    /**
3444     * The bottom padding in pixels, that is the distance in pixels between the
3445     * bottom edge of this view and the bottom edge of its content.
3446     * {@hide}
3447     */
3448    @ViewDebug.ExportedProperty(category = "padding")
3449    protected int mPaddingBottom;
3450
3451    /**
3452     * The layout insets in pixels, that is the distance in pixels between the
3453     * visible edges of this view its bounds.
3454     */
3455    private Insets mLayoutInsets;
3456
3457    /**
3458     * Briefly describes the view and is primarily used for accessibility support.
3459     */
3460    private CharSequence mContentDescription;
3461
3462    /**
3463     * Specifies the id of a view for which this view serves as a label for
3464     * accessibility purposes.
3465     */
3466    private int mLabelForId = View.NO_ID;
3467
3468    /**
3469     * Predicate for matching labeled view id with its label for
3470     * accessibility purposes.
3471     */
3472    private MatchLabelForPredicate mMatchLabelForPredicate;
3473
3474    /**
3475     * Specifies a view before which this one is visited in accessibility traversal.
3476     */
3477    private int mAccessibilityTraversalBeforeId = NO_ID;
3478
3479    /**
3480     * Specifies a view after which this one is visited in accessibility traversal.
3481     */
3482    private int mAccessibilityTraversalAfterId = NO_ID;
3483
3484    /**
3485     * Predicate for matching a view by its id.
3486     */
3487    private MatchIdPredicate mMatchIdPredicate;
3488
3489    /**
3490     * Cache the paddingRight set by the user to append to the scrollbar's size.
3491     *
3492     * @hide
3493     */
3494    @ViewDebug.ExportedProperty(category = "padding")
3495    protected int mUserPaddingRight;
3496
3497    /**
3498     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3499     *
3500     * @hide
3501     */
3502    @ViewDebug.ExportedProperty(category = "padding")
3503    protected int mUserPaddingBottom;
3504
3505    /**
3506     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3507     *
3508     * @hide
3509     */
3510    @ViewDebug.ExportedProperty(category = "padding")
3511    protected int mUserPaddingLeft;
3512
3513    /**
3514     * Cache the paddingStart set by the user to append to the scrollbar's size.
3515     *
3516     */
3517    @ViewDebug.ExportedProperty(category = "padding")
3518    int mUserPaddingStart;
3519
3520    /**
3521     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3522     *
3523     */
3524    @ViewDebug.ExportedProperty(category = "padding")
3525    int mUserPaddingEnd;
3526
3527    /**
3528     * Cache initial left padding.
3529     *
3530     * @hide
3531     */
3532    int mUserPaddingLeftInitial;
3533
3534    /**
3535     * Cache initial right padding.
3536     *
3537     * @hide
3538     */
3539    int mUserPaddingRightInitial;
3540
3541    /**
3542     * Default undefined padding
3543     */
3544    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3545
3546    /**
3547     * Cache if a left padding has been defined
3548     */
3549    private boolean mLeftPaddingDefined = false;
3550
3551    /**
3552     * Cache if a right padding has been defined
3553     */
3554    private boolean mRightPaddingDefined = false;
3555
3556    /**
3557     * @hide
3558     */
3559    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3560    /**
3561     * @hide
3562     */
3563    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3564
3565    private LongSparseLongArray mMeasureCache;
3566
3567    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3568    private Drawable mBackground;
3569    private TintInfo mBackgroundTint;
3570
3571    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3572    private ForegroundInfo mForegroundInfo;
3573
3574    private Drawable mScrollIndicatorDrawable;
3575
3576    /**
3577     * RenderNode used for backgrounds.
3578     * <p>
3579     * When non-null and valid, this is expected to contain an up-to-date copy
3580     * of the background drawable. It is cleared on temporary detach, and reset
3581     * on cleanup.
3582     */
3583    private RenderNode mBackgroundRenderNode;
3584
3585    private int mBackgroundResource;
3586    private boolean mBackgroundSizeChanged;
3587
3588    private String mTransitionName;
3589
3590    static class TintInfo {
3591        ColorStateList mTintList;
3592        PorterDuff.Mode mTintMode;
3593        boolean mHasTintMode;
3594        boolean mHasTintList;
3595    }
3596
3597    private static class ForegroundInfo {
3598        private Drawable mDrawable;
3599        private TintInfo mTintInfo;
3600        private int mGravity = Gravity.FILL;
3601        private boolean mInsidePadding = true;
3602        private boolean mBoundsChanged = true;
3603        private final Rect mSelfBounds = new Rect();
3604        private final Rect mOverlayBounds = new Rect();
3605    }
3606
3607    static class ListenerInfo {
3608        /**
3609         * Listener used to dispatch focus change events.
3610         * This field should be made private, so it is hidden from the SDK.
3611         * {@hide}
3612         */
3613        protected OnFocusChangeListener mOnFocusChangeListener;
3614
3615        /**
3616         * Listeners for layout change events.
3617         */
3618        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3619
3620        protected OnScrollChangeListener mOnScrollChangeListener;
3621
3622        /**
3623         * Listeners for attach events.
3624         */
3625        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3626
3627        /**
3628         * Listener used to dispatch click events.
3629         * This field should be made private, so it is hidden from the SDK.
3630         * {@hide}
3631         */
3632        public OnClickListener mOnClickListener;
3633
3634        /**
3635         * Listener used to dispatch long click events.
3636         * This field should be made private, so it is hidden from the SDK.
3637         * {@hide}
3638         */
3639        protected OnLongClickListener mOnLongClickListener;
3640
3641        /**
3642         * Listener used to dispatch context click events. This field should be made private, so it
3643         * is hidden from the SDK.
3644         * {@hide}
3645         */
3646        protected OnContextClickListener mOnContextClickListener;
3647
3648        /**
3649         * Listener used to build the context menu.
3650         * This field should be made private, so it is hidden from the SDK.
3651         * {@hide}
3652         */
3653        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3654
3655        private OnKeyListener mOnKeyListener;
3656
3657        private OnTouchListener mOnTouchListener;
3658
3659        private OnHoverListener mOnHoverListener;
3660
3661        private OnGenericMotionListener mOnGenericMotionListener;
3662
3663        private OnDragListener mOnDragListener;
3664
3665        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3666
3667        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3668    }
3669
3670    ListenerInfo mListenerInfo;
3671
3672    private static class TooltipInfo {
3673        /**
3674         * Text to be displayed in a tooltip popup.
3675         */
3676        @Nullable
3677        CharSequence mTooltip;
3678
3679        /**
3680         * View-relative position of the tooltip anchor point.
3681         */
3682        int mAnchorX;
3683        int mAnchorY;
3684
3685        /**
3686         * The tooltip popup.
3687         */
3688        @Nullable
3689        TooltipPopup mTooltipPopup;
3690
3691        /**
3692         * Set to true if the tooltip was shown as a result of a long click.
3693         */
3694        boolean mTooltipFromLongClick;
3695
3696        /**
3697         * Keep these Runnables so that they can be used to reschedule.
3698         */
3699        Runnable mShowTooltipRunnable;
3700        Runnable mHideTooltipRunnable;
3701    }
3702
3703    TooltipInfo mTooltipInfo;
3704
3705    // Temporary values used to hold (x,y) coordinates when delegating from the
3706    // two-arg performLongClick() method to the legacy no-arg version.
3707    private float mLongClickX = Float.NaN;
3708    private float mLongClickY = Float.NaN;
3709
3710    /**
3711     * The application environment this view lives in.
3712     * This field should be made private, so it is hidden from the SDK.
3713     * {@hide}
3714     */
3715    @ViewDebug.ExportedProperty(deepExport = true)
3716    protected Context mContext;
3717
3718    private final Resources mResources;
3719
3720    private ScrollabilityCache mScrollCache;
3721
3722    private int[] mDrawableState = null;
3723
3724    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3725
3726    /**
3727     * Animator that automatically runs based on state changes.
3728     */
3729    private StateListAnimator mStateListAnimator;
3730
3731    /**
3732     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3733     * the user may specify which view to go to next.
3734     */
3735    private int mNextFocusLeftId = View.NO_ID;
3736
3737    /**
3738     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3739     * the user may specify which view to go to next.
3740     */
3741    private int mNextFocusRightId = View.NO_ID;
3742
3743    /**
3744     * When this view has focus and the next focus is {@link #FOCUS_UP},
3745     * the user may specify which view to go to next.
3746     */
3747    private int mNextFocusUpId = View.NO_ID;
3748
3749    /**
3750     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3751     * the user may specify which view to go to next.
3752     */
3753    private int mNextFocusDownId = View.NO_ID;
3754
3755    /**
3756     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3757     * the user may specify which view to go to next.
3758     */
3759    int mNextFocusForwardId = View.NO_ID;
3760
3761    /**
3762     * User-specified next keyboard navigation cluster.
3763     */
3764    int mNextClusterForwardId = View.NO_ID;
3765
3766    /**
3767     * User-specified next keyboard navigation section.
3768     */
3769    int mNextSectionForwardId = View.NO_ID;
3770
3771    private CheckForLongPress mPendingCheckForLongPress;
3772    private CheckForTap mPendingCheckForTap = null;
3773    private PerformClick mPerformClick;
3774    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3775
3776    private UnsetPressedState mUnsetPressedState;
3777
3778    /**
3779     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3780     * up event while a long press is invoked as soon as the long press duration is reached, so
3781     * a long press could be performed before the tap is checked, in which case the tap's action
3782     * should not be invoked.
3783     */
3784    private boolean mHasPerformedLongPress;
3785
3786    /**
3787     * Whether a context click button is currently pressed down. This is true when the stylus is
3788     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3789     * pressed. This is false once the button is released or if the stylus has been lifted.
3790     */
3791    private boolean mInContextButtonPress;
3792
3793    /**
3794     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3795     * true after a stylus button press has occured, when the next up event should not be recognized
3796     * as a tap.
3797     */
3798    private boolean mIgnoreNextUpEvent;
3799
3800    /**
3801     * The minimum height of the view. We'll try our best to have the height
3802     * of this view to at least this amount.
3803     */
3804    @ViewDebug.ExportedProperty(category = "measurement")
3805    private int mMinHeight;
3806
3807    /**
3808     * The minimum width of the view. We'll try our best to have the width
3809     * of this view to at least this amount.
3810     */
3811    @ViewDebug.ExportedProperty(category = "measurement")
3812    private int mMinWidth;
3813
3814    /**
3815     * The delegate to handle touch events that are physically in this view
3816     * but should be handled by another view.
3817     */
3818    private TouchDelegate mTouchDelegate = null;
3819
3820    /**
3821     * Solid color to use as a background when creating the drawing cache. Enables
3822     * the cache to use 16 bit bitmaps instead of 32 bit.
3823     */
3824    private int mDrawingCacheBackgroundColor = 0;
3825
3826    /**
3827     * Special tree observer used when mAttachInfo is null.
3828     */
3829    private ViewTreeObserver mFloatingTreeObserver;
3830
3831    /**
3832     * Cache the touch slop from the context that created the view.
3833     */
3834    private int mTouchSlop;
3835
3836    /**
3837     * Object that handles automatic animation of view properties.
3838     */
3839    private ViewPropertyAnimator mAnimator = null;
3840
3841    /**
3842     * List of registered FrameMetricsObservers.
3843     */
3844    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3845
3846    /**
3847     * Flag indicating that a drag can cross window boundaries.  When
3848     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3849     * with this flag set, all visible applications with targetSdkVersion >=
3850     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3851     * in the drag operation and receive the dragged content.
3852     *
3853     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3854     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3855     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3856     */
3857    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3858
3859    /**
3860     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3861     * request read access to the content URI(s) contained in the {@link ClipData} object.
3862     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3863     */
3864    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3865
3866    /**
3867     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3868     * request write access to the content URI(s) contained in the {@link ClipData} object.
3869     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3870     */
3871    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3872
3873    /**
3874     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3875     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3876     * reboots until explicitly revoked with
3877     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3878     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3879     */
3880    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3881            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3882
3883    /**
3884     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3885     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3886     * match against the original granted URI.
3887     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3888     */
3889    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3890            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3891
3892    /**
3893     * Flag indicating that the drag shadow will be opaque.  When
3894     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3895     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3896     */
3897    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3898
3899    /**
3900     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3901     */
3902    private float mVerticalScrollFactor;
3903
3904    /**
3905     * Position of the vertical scroll bar.
3906     */
3907    private int mVerticalScrollbarPosition;
3908
3909    /**
3910     * Position the scroll bar at the default position as determined by the system.
3911     */
3912    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3913
3914    /**
3915     * Position the scroll bar along the left edge.
3916     */
3917    public static final int SCROLLBAR_POSITION_LEFT = 1;
3918
3919    /**
3920     * Position the scroll bar along the right edge.
3921     */
3922    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3923
3924    /**
3925     * Indicates that the view does not have a layer.
3926     *
3927     * @see #getLayerType()
3928     * @see #setLayerType(int, android.graphics.Paint)
3929     * @see #LAYER_TYPE_SOFTWARE
3930     * @see #LAYER_TYPE_HARDWARE
3931     */
3932    public static final int LAYER_TYPE_NONE = 0;
3933
3934    /**
3935     * <p>Indicates that the view has a software layer. A software layer is backed
3936     * by a bitmap and causes the view to be rendered using Android's software
3937     * rendering pipeline, even if hardware acceleration is enabled.</p>
3938     *
3939     * <p>Software layers have various usages:</p>
3940     * <p>When the application is not using hardware acceleration, a software layer
3941     * is useful to apply a specific color filter and/or blending mode and/or
3942     * translucency to a view and all its children.</p>
3943     * <p>When the application is using hardware acceleration, a software layer
3944     * is useful to render drawing primitives not supported by the hardware
3945     * accelerated pipeline. It can also be used to cache a complex view tree
3946     * into a texture and reduce the complexity of drawing operations. For instance,
3947     * when animating a complex view tree with a translation, a software layer can
3948     * be used to render the view tree only once.</p>
3949     * <p>Software layers should be avoided when the affected view tree updates
3950     * often. Every update will require to re-render the software layer, which can
3951     * potentially be slow (particularly when hardware acceleration is turned on
3952     * since the layer will have to be uploaded into a hardware texture after every
3953     * update.)</p>
3954     *
3955     * @see #getLayerType()
3956     * @see #setLayerType(int, android.graphics.Paint)
3957     * @see #LAYER_TYPE_NONE
3958     * @see #LAYER_TYPE_HARDWARE
3959     */
3960    public static final int LAYER_TYPE_SOFTWARE = 1;
3961
3962    /**
3963     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3964     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3965     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3966     * rendering pipeline, but only if hardware acceleration is turned on for the
3967     * view hierarchy. When hardware acceleration is turned off, hardware layers
3968     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3969     *
3970     * <p>A hardware layer is useful to apply a specific color filter and/or
3971     * blending mode and/or translucency to a view and all its children.</p>
3972     * <p>A hardware layer can be used to cache a complex view tree into a
3973     * texture and reduce the complexity of drawing operations. For instance,
3974     * when animating a complex view tree with a translation, a hardware layer can
3975     * be used to render the view tree only once.</p>
3976     * <p>A hardware layer can also be used to increase the rendering quality when
3977     * rotation transformations are applied on a view. It can also be used to
3978     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3979     *
3980     * @see #getLayerType()
3981     * @see #setLayerType(int, android.graphics.Paint)
3982     * @see #LAYER_TYPE_NONE
3983     * @see #LAYER_TYPE_SOFTWARE
3984     */
3985    public static final int LAYER_TYPE_HARDWARE = 2;
3986
3987    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3988            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3989            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3990            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3991    })
3992    int mLayerType = LAYER_TYPE_NONE;
3993    Paint mLayerPaint;
3994
3995
3996    /**
3997     * <p>When setting a {@link android.app.assist.AssistStructure}, its nodes should not contain
3998     * PII (Personally Identifiable Information).
3999     */
4000    // TODO(b/33197203) (b/33269702): improve documentation: mention all cases, show examples, etc.
4001    public static final int ASSIST_FLAG_SANITIZED_TEXT = 0x1;
4002
4003    /**
4004     * <p>When setting a {@link android.app.assist.AssistStructure}, its nodes should contain all
4005     * type of data, even sensitive PII (Personally Identifiable Information) like passwords or
4006     * credit card numbers.
4007     */
4008    public static final int ASSIST_FLAG_NON_SANITIZED_TEXT = 0x2;
4009
4010    /**
4011     * Set to true when drawing cache is enabled and cannot be created.
4012     *
4013     * @hide
4014     */
4015    public boolean mCachingFailed;
4016    private Bitmap mDrawingCache;
4017    private Bitmap mUnscaledDrawingCache;
4018
4019    /**
4020     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4021     * <p>
4022     * When non-null and valid, this is expected to contain an up-to-date copy
4023     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4024     * cleanup.
4025     */
4026    final RenderNode mRenderNode;
4027
4028    /**
4029     * Set to true when the view is sending hover accessibility events because it
4030     * is the innermost hovered view.
4031     */
4032    private boolean mSendingHoverAccessibilityEvents;
4033
4034    /**
4035     * Delegate for injecting accessibility functionality.
4036     */
4037    AccessibilityDelegate mAccessibilityDelegate;
4038
4039    /**
4040     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4041     * and add/remove objects to/from the overlay directly through the Overlay methods.
4042     */
4043    ViewOverlay mOverlay;
4044
4045    /**
4046     * The currently active parent view for receiving delegated nested scrolling events.
4047     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4048     * by {@link #stopNestedScroll()} at the same point where we clear
4049     * requestDisallowInterceptTouchEvent.
4050     */
4051    private ViewParent mNestedScrollingParent;
4052
4053    /**
4054     * Consistency verifier for debugging purposes.
4055     * @hide
4056     */
4057    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4058            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4059                    new InputEventConsistencyVerifier(this, 0) : null;
4060
4061    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4062
4063    private int[] mTempNestedScrollConsumed;
4064
4065    /**
4066     * An overlay is going to draw this View instead of being drawn as part of this
4067     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4068     * when this view is invalidated.
4069     */
4070    GhostView mGhostView;
4071
4072    /**
4073     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4074     * @hide
4075     */
4076    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4077    public String[] mAttributes;
4078
4079    /**
4080     * Maps a Resource id to its name.
4081     */
4082    private static SparseArray<String> mAttributeMap;
4083
4084    /**
4085     * Queue of pending runnables. Used to postpone calls to post() until this
4086     * view is attached and has a handler.
4087     */
4088    private HandlerActionQueue mRunQueue;
4089
4090    /**
4091     * The pointer icon when the mouse hovers on this view. The default is null.
4092     */
4093    private PointerIcon mPointerIcon;
4094
4095    /**
4096     * @hide
4097     */
4098    String mStartActivityRequestWho;
4099
4100    @Nullable
4101    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4102
4103    /**
4104     * Simple constructor to use when creating a view from code.
4105     *
4106     * @param context The Context the view is running in, through which it can
4107     *        access the current theme, resources, etc.
4108     */
4109    public View(Context context) {
4110        mContext = context;
4111        mResources = context != null ? context.getResources() : null;
4112        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
4113        // Set some flags defaults
4114        mPrivateFlags2 =
4115                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4116                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4117                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4118                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4119                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4120                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4121        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4122        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4123        mUserPaddingStart = UNDEFINED_PADDING;
4124        mUserPaddingEnd = UNDEFINED_PADDING;
4125        mRenderNode = RenderNode.create(getClass().getName(), this);
4126
4127        if (!sCompatibilityDone && context != null) {
4128            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4129
4130            // Older apps may need this compatibility hack for measurement.
4131            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4132
4133            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4134            // of whether a layout was requested on that View.
4135            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4136
4137            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4138
4139            // In M and newer, our widgets can pass a "hint" value in the size
4140            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4141            // know what the expected parent size is going to be, so e.g. list items can size
4142            // themselves at 1/3 the size of their container. It breaks older apps though,
4143            // specifically apps that use some popular open source libraries.
4144            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4145
4146            // Old versions of the platform would give different results from
4147            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4148            // modes, so we always need to run an additional EXACTLY pass.
4149            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4150
4151            // Prior to N, layout params could change without requiring a
4152            // subsequent call to setLayoutParams() and they would usually
4153            // work. Partial layout breaks this assumption.
4154            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4155
4156            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4157            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4158            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4159
4160            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4161            // in apps so we target check it to avoid breaking existing apps.
4162            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4163
4164            sCascadedDragDrop = targetSdkVersion < N;
4165
4166            sCompatibilityDone = true;
4167        }
4168    }
4169
4170    /**
4171     * Constructor that is called when inflating a view from XML. This is called
4172     * when a view is being constructed from an XML file, supplying attributes
4173     * that were specified in the XML file. This version uses a default style of
4174     * 0, so the only attribute values applied are those in the Context's Theme
4175     * and the given AttributeSet.
4176     *
4177     * <p>
4178     * The method onFinishInflate() will be called after all children have been
4179     * added.
4180     *
4181     * @param context The Context the view is running in, through which it can
4182     *        access the current theme, resources, etc.
4183     * @param attrs The attributes of the XML tag that is inflating the view.
4184     * @see #View(Context, AttributeSet, int)
4185     */
4186    public View(Context context, @Nullable AttributeSet attrs) {
4187        this(context, attrs, 0);
4188    }
4189
4190    /**
4191     * Perform inflation from XML and apply a class-specific base style from a
4192     * theme attribute. This constructor of View allows subclasses to use their
4193     * own base style when they are inflating. For example, a Button class's
4194     * constructor would call this version of the super class constructor and
4195     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4196     * allows the theme's button style to modify all of the base view attributes
4197     * (in particular its background) as well as the Button class's attributes.
4198     *
4199     * @param context The Context the view is running in, through which it can
4200     *        access the current theme, resources, etc.
4201     * @param attrs The attributes of the XML tag that is inflating the view.
4202     * @param defStyleAttr An attribute in the current theme that contains a
4203     *        reference to a style resource that supplies default values for
4204     *        the view. Can be 0 to not look for defaults.
4205     * @see #View(Context, AttributeSet)
4206     */
4207    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4208        this(context, attrs, defStyleAttr, 0);
4209    }
4210
4211    /**
4212     * Perform inflation from XML and apply a class-specific base style from a
4213     * theme attribute or style resource. This constructor of View allows
4214     * subclasses to use their own base style when they are inflating.
4215     * <p>
4216     * When determining the final value of a particular attribute, there are
4217     * four inputs that come into play:
4218     * <ol>
4219     * <li>Any attribute values in the given AttributeSet.
4220     * <li>The style resource specified in the AttributeSet (named "style").
4221     * <li>The default style specified by <var>defStyleAttr</var>.
4222     * <li>The default style specified by <var>defStyleRes</var>.
4223     * <li>The base values in this theme.
4224     * </ol>
4225     * <p>
4226     * Each of these inputs is considered in-order, with the first listed taking
4227     * precedence over the following ones. In other words, if in the
4228     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4229     * , then the button's text will <em>always</em> be black, regardless of
4230     * what is specified in any of the styles.
4231     *
4232     * @param context The Context the view is running in, through which it can
4233     *        access the current theme, resources, etc.
4234     * @param attrs The attributes of the XML tag that is inflating the view.
4235     * @param defStyleAttr An attribute in the current theme that contains a
4236     *        reference to a style resource that supplies default values for
4237     *        the view. Can be 0 to not look for defaults.
4238     * @param defStyleRes A resource identifier of a style resource that
4239     *        supplies default values for the view, used only if
4240     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4241     *        to not look for defaults.
4242     * @see #View(Context, AttributeSet, int)
4243     */
4244    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4245        this(context);
4246
4247        final TypedArray a = context.obtainStyledAttributes(
4248                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4249
4250        if (mDebugViewAttributes) {
4251            saveAttributeData(attrs, a);
4252        }
4253
4254        Drawable background = null;
4255
4256        int leftPadding = -1;
4257        int topPadding = -1;
4258        int rightPadding = -1;
4259        int bottomPadding = -1;
4260        int startPadding = UNDEFINED_PADDING;
4261        int endPadding = UNDEFINED_PADDING;
4262
4263        int padding = -1;
4264        int paddingHorizontal = -1;
4265        int paddingVertical = -1;
4266
4267        int viewFlagValues = 0;
4268        int viewFlagMasks = 0;
4269
4270        boolean setScrollContainer = false;
4271
4272        int x = 0;
4273        int y = 0;
4274
4275        float tx = 0;
4276        float ty = 0;
4277        float tz = 0;
4278        float elevation = 0;
4279        float rotation = 0;
4280        float rotationX = 0;
4281        float rotationY = 0;
4282        float sx = 1f;
4283        float sy = 1f;
4284        boolean transformSet = false;
4285
4286        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4287        int overScrollMode = mOverScrollMode;
4288        boolean initializeScrollbars = false;
4289        boolean initializeScrollIndicators = false;
4290
4291        boolean startPaddingDefined = false;
4292        boolean endPaddingDefined = false;
4293        boolean leftPaddingDefined = false;
4294        boolean rightPaddingDefined = false;
4295
4296        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4297
4298        final int N = a.getIndexCount();
4299        for (int i = 0; i < N; i++) {
4300            int attr = a.getIndex(i);
4301            switch (attr) {
4302                case com.android.internal.R.styleable.View_background:
4303                    background = a.getDrawable(attr);
4304                    break;
4305                case com.android.internal.R.styleable.View_padding:
4306                    padding = a.getDimensionPixelSize(attr, -1);
4307                    mUserPaddingLeftInitial = padding;
4308                    mUserPaddingRightInitial = padding;
4309                    leftPaddingDefined = true;
4310                    rightPaddingDefined = true;
4311                    break;
4312                case com.android.internal.R.styleable.View_paddingHorizontal:
4313                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4314                    mUserPaddingLeftInitial = paddingHorizontal;
4315                    mUserPaddingRightInitial = paddingHorizontal;
4316                    leftPaddingDefined = true;
4317                    rightPaddingDefined = true;
4318                    break;
4319                case com.android.internal.R.styleable.View_paddingVertical:
4320                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4321                    break;
4322                 case com.android.internal.R.styleable.View_paddingLeft:
4323                    leftPadding = a.getDimensionPixelSize(attr, -1);
4324                    mUserPaddingLeftInitial = leftPadding;
4325                    leftPaddingDefined = true;
4326                    break;
4327                case com.android.internal.R.styleable.View_paddingTop:
4328                    topPadding = a.getDimensionPixelSize(attr, -1);
4329                    break;
4330                case com.android.internal.R.styleable.View_paddingRight:
4331                    rightPadding = a.getDimensionPixelSize(attr, -1);
4332                    mUserPaddingRightInitial = rightPadding;
4333                    rightPaddingDefined = true;
4334                    break;
4335                case com.android.internal.R.styleable.View_paddingBottom:
4336                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4337                    break;
4338                case com.android.internal.R.styleable.View_paddingStart:
4339                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4340                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4341                    break;
4342                case com.android.internal.R.styleable.View_paddingEnd:
4343                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4344                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4345                    break;
4346                case com.android.internal.R.styleable.View_scrollX:
4347                    x = a.getDimensionPixelOffset(attr, 0);
4348                    break;
4349                case com.android.internal.R.styleable.View_scrollY:
4350                    y = a.getDimensionPixelOffset(attr, 0);
4351                    break;
4352                case com.android.internal.R.styleable.View_alpha:
4353                    setAlpha(a.getFloat(attr, 1f));
4354                    break;
4355                case com.android.internal.R.styleable.View_transformPivotX:
4356                    setPivotX(a.getDimension(attr, 0));
4357                    break;
4358                case com.android.internal.R.styleable.View_transformPivotY:
4359                    setPivotY(a.getDimension(attr, 0));
4360                    break;
4361                case com.android.internal.R.styleable.View_translationX:
4362                    tx = a.getDimension(attr, 0);
4363                    transformSet = true;
4364                    break;
4365                case com.android.internal.R.styleable.View_translationY:
4366                    ty = a.getDimension(attr, 0);
4367                    transformSet = true;
4368                    break;
4369                case com.android.internal.R.styleable.View_translationZ:
4370                    tz = a.getDimension(attr, 0);
4371                    transformSet = true;
4372                    break;
4373                case com.android.internal.R.styleable.View_elevation:
4374                    elevation = a.getDimension(attr, 0);
4375                    transformSet = true;
4376                    break;
4377                case com.android.internal.R.styleable.View_rotation:
4378                    rotation = a.getFloat(attr, 0);
4379                    transformSet = true;
4380                    break;
4381                case com.android.internal.R.styleable.View_rotationX:
4382                    rotationX = a.getFloat(attr, 0);
4383                    transformSet = true;
4384                    break;
4385                case com.android.internal.R.styleable.View_rotationY:
4386                    rotationY = a.getFloat(attr, 0);
4387                    transformSet = true;
4388                    break;
4389                case com.android.internal.R.styleable.View_scaleX:
4390                    sx = a.getFloat(attr, 1f);
4391                    transformSet = true;
4392                    break;
4393                case com.android.internal.R.styleable.View_scaleY:
4394                    sy = a.getFloat(attr, 1f);
4395                    transformSet = true;
4396                    break;
4397                case com.android.internal.R.styleable.View_id:
4398                    mID = a.getResourceId(attr, NO_ID);
4399                    break;
4400                case com.android.internal.R.styleable.View_tag:
4401                    mTag = a.getText(attr);
4402                    break;
4403                case com.android.internal.R.styleable.View_fitsSystemWindows:
4404                    if (a.getBoolean(attr, false)) {
4405                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4406                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4407                    }
4408                    break;
4409                case com.android.internal.R.styleable.View_focusable:
4410                    if (a.getBoolean(attr, false)) {
4411                        viewFlagValues |= FOCUSABLE;
4412                        viewFlagMasks |= FOCUSABLE_MASK;
4413                    }
4414                    break;
4415                case com.android.internal.R.styleable.View_focusableInTouchMode:
4416                    if (a.getBoolean(attr, false)) {
4417                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4418                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4419                    }
4420                    break;
4421                case com.android.internal.R.styleable.View_clickable:
4422                    if (a.getBoolean(attr, false)) {
4423                        viewFlagValues |= CLICKABLE;
4424                        viewFlagMasks |= CLICKABLE;
4425                    }
4426                    break;
4427                case com.android.internal.R.styleable.View_longClickable:
4428                    if (a.getBoolean(attr, false)) {
4429                        viewFlagValues |= LONG_CLICKABLE;
4430                        viewFlagMasks |= LONG_CLICKABLE;
4431                    }
4432                    break;
4433                case com.android.internal.R.styleable.View_contextClickable:
4434                    if (a.getBoolean(attr, false)) {
4435                        viewFlagValues |= CONTEXT_CLICKABLE;
4436                        viewFlagMasks |= CONTEXT_CLICKABLE;
4437                    }
4438                    break;
4439                case com.android.internal.R.styleable.View_saveEnabled:
4440                    if (!a.getBoolean(attr, true)) {
4441                        viewFlagValues |= SAVE_DISABLED;
4442                        viewFlagMasks |= SAVE_DISABLED_MASK;
4443                    }
4444                    break;
4445                case com.android.internal.R.styleable.View_duplicateParentState:
4446                    if (a.getBoolean(attr, false)) {
4447                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4448                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4449                    }
4450                    break;
4451                case com.android.internal.R.styleable.View_visibility:
4452                    final int visibility = a.getInt(attr, 0);
4453                    if (visibility != 0) {
4454                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4455                        viewFlagMasks |= VISIBILITY_MASK;
4456                    }
4457                    break;
4458                case com.android.internal.R.styleable.View_layoutDirection:
4459                    // Clear any layout direction flags (included resolved bits) already set
4460                    mPrivateFlags2 &=
4461                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4462                    // Set the layout direction flags depending on the value of the attribute
4463                    final int layoutDirection = a.getInt(attr, -1);
4464                    final int value = (layoutDirection != -1) ?
4465                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4466                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4467                    break;
4468                case com.android.internal.R.styleable.View_drawingCacheQuality:
4469                    final int cacheQuality = a.getInt(attr, 0);
4470                    if (cacheQuality != 0) {
4471                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4472                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4473                    }
4474                    break;
4475                case com.android.internal.R.styleable.View_contentDescription:
4476                    setContentDescription(a.getString(attr));
4477                    break;
4478                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4479                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4480                    break;
4481                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4482                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4483                    break;
4484                case com.android.internal.R.styleable.View_labelFor:
4485                    setLabelFor(a.getResourceId(attr, NO_ID));
4486                    break;
4487                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4488                    if (!a.getBoolean(attr, true)) {
4489                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4490                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4491                    }
4492                    break;
4493                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4494                    if (!a.getBoolean(attr, true)) {
4495                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4496                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4497                    }
4498                    break;
4499                case R.styleable.View_scrollbars:
4500                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4501                    if (scrollbars != SCROLLBARS_NONE) {
4502                        viewFlagValues |= scrollbars;
4503                        viewFlagMasks |= SCROLLBARS_MASK;
4504                        initializeScrollbars = true;
4505                    }
4506                    break;
4507                //noinspection deprecation
4508                case R.styleable.View_fadingEdge:
4509                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4510                        // Ignore the attribute starting with ICS
4511                        break;
4512                    }
4513                    // With builds < ICS, fall through and apply fading edges
4514                case R.styleable.View_requiresFadingEdge:
4515                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4516                    if (fadingEdge != FADING_EDGE_NONE) {
4517                        viewFlagValues |= fadingEdge;
4518                        viewFlagMasks |= FADING_EDGE_MASK;
4519                        initializeFadingEdgeInternal(a);
4520                    }
4521                    break;
4522                case R.styleable.View_scrollbarStyle:
4523                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4524                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4525                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4526                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4527                    }
4528                    break;
4529                case R.styleable.View_isScrollContainer:
4530                    setScrollContainer = true;
4531                    if (a.getBoolean(attr, false)) {
4532                        setScrollContainer(true);
4533                    }
4534                    break;
4535                case com.android.internal.R.styleable.View_keepScreenOn:
4536                    if (a.getBoolean(attr, false)) {
4537                        viewFlagValues |= KEEP_SCREEN_ON;
4538                        viewFlagMasks |= KEEP_SCREEN_ON;
4539                    }
4540                    break;
4541                case R.styleable.View_filterTouchesWhenObscured:
4542                    if (a.getBoolean(attr, false)) {
4543                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4544                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4545                    }
4546                    break;
4547                case R.styleable.View_nextFocusLeft:
4548                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4549                    break;
4550                case R.styleable.View_nextFocusRight:
4551                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4552                    break;
4553                case R.styleable.View_nextFocusUp:
4554                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4555                    break;
4556                case R.styleable.View_nextFocusDown:
4557                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4558                    break;
4559                case R.styleable.View_nextFocusForward:
4560                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4561                    break;
4562                case R.styleable.View_nextClusterForward:
4563                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4564                    break;
4565                case R.styleable.View_nextSectionForward:
4566                    mNextSectionForwardId = a.getResourceId(attr, View.NO_ID);
4567                    break;
4568                case R.styleable.View_minWidth:
4569                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4570                    break;
4571                case R.styleable.View_minHeight:
4572                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4573                    break;
4574                case R.styleable.View_onClick:
4575                    if (context.isRestricted()) {
4576                        throw new IllegalStateException("The android:onClick attribute cannot "
4577                                + "be used within a restricted context");
4578                    }
4579
4580                    final String handlerName = a.getString(attr);
4581                    if (handlerName != null) {
4582                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4583                    }
4584                    break;
4585                case R.styleable.View_overScrollMode:
4586                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4587                    break;
4588                case R.styleable.View_verticalScrollbarPosition:
4589                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4590                    break;
4591                case R.styleable.View_layerType:
4592                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4593                    break;
4594                case R.styleable.View_textDirection:
4595                    // Clear any text direction flag already set
4596                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4597                    // Set the text direction flags depending on the value of the attribute
4598                    final int textDirection = a.getInt(attr, -1);
4599                    if (textDirection != -1) {
4600                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4601                    }
4602                    break;
4603                case R.styleable.View_textAlignment:
4604                    // Clear any text alignment flag already set
4605                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4606                    // Set the text alignment flag depending on the value of the attribute
4607                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4608                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4609                    break;
4610                case R.styleable.View_importantForAccessibility:
4611                    setImportantForAccessibility(a.getInt(attr,
4612                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4613                    break;
4614                case R.styleable.View_accessibilityLiveRegion:
4615                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4616                    break;
4617                case R.styleable.View_transitionName:
4618                    setTransitionName(a.getString(attr));
4619                    break;
4620                case R.styleable.View_nestedScrollingEnabled:
4621                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4622                    break;
4623                case R.styleable.View_stateListAnimator:
4624                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4625                            a.getResourceId(attr, 0)));
4626                    break;
4627                case R.styleable.View_backgroundTint:
4628                    // This will get applied later during setBackground().
4629                    if (mBackgroundTint == null) {
4630                        mBackgroundTint = new TintInfo();
4631                    }
4632                    mBackgroundTint.mTintList = a.getColorStateList(
4633                            R.styleable.View_backgroundTint);
4634                    mBackgroundTint.mHasTintList = true;
4635                    break;
4636                case R.styleable.View_backgroundTintMode:
4637                    // This will get applied later during setBackground().
4638                    if (mBackgroundTint == null) {
4639                        mBackgroundTint = new TintInfo();
4640                    }
4641                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4642                            R.styleable.View_backgroundTintMode, -1), null);
4643                    mBackgroundTint.mHasTintMode = true;
4644                    break;
4645                case R.styleable.View_outlineProvider:
4646                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4647                            PROVIDER_BACKGROUND));
4648                    break;
4649                case R.styleable.View_foreground:
4650                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4651                        setForeground(a.getDrawable(attr));
4652                    }
4653                    break;
4654                case R.styleable.View_foregroundGravity:
4655                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4656                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4657                    }
4658                    break;
4659                case R.styleable.View_foregroundTintMode:
4660                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4661                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4662                    }
4663                    break;
4664                case R.styleable.View_foregroundTint:
4665                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4666                        setForegroundTintList(a.getColorStateList(attr));
4667                    }
4668                    break;
4669                case R.styleable.View_foregroundInsidePadding:
4670                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4671                        if (mForegroundInfo == null) {
4672                            mForegroundInfo = new ForegroundInfo();
4673                        }
4674                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4675                                mForegroundInfo.mInsidePadding);
4676                    }
4677                    break;
4678                case R.styleable.View_scrollIndicators:
4679                    final int scrollIndicators =
4680                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4681                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4682                    if (scrollIndicators != 0) {
4683                        mPrivateFlags3 |= scrollIndicators;
4684                        initializeScrollIndicators = true;
4685                    }
4686                    break;
4687                case R.styleable.View_pointerIcon:
4688                    final int resourceId = a.getResourceId(attr, 0);
4689                    if (resourceId != 0) {
4690                        setPointerIcon(PointerIcon.load(
4691                                context.getResources(), resourceId));
4692                    } else {
4693                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4694                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4695                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4696                        }
4697                    }
4698                    break;
4699                case R.styleable.View_forceHasOverlappingRendering:
4700                    if (a.peekValue(attr) != null) {
4701                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4702                    }
4703                    break;
4704                case R.styleable.View_tooltip:
4705                    setTooltip(a.getText(attr));
4706                    break;
4707                case R.styleable.View_keyboardNavigationCluster:
4708                    if (a.peekValue(attr) != null) {
4709                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4710                    }
4711                    break;
4712                case R.styleable.View_keyboardNavigationSection:
4713                    if (a.peekValue(attr) != null) {
4714                        setKeyboardNavigationSection(a.getBoolean(attr, true));
4715                    }
4716                    break;
4717            }
4718        }
4719
4720        setOverScrollMode(overScrollMode);
4721
4722        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4723        // the resolved layout direction). Those cached values will be used later during padding
4724        // resolution.
4725        mUserPaddingStart = startPadding;
4726        mUserPaddingEnd = endPadding;
4727
4728        if (background != null) {
4729            setBackground(background);
4730        }
4731
4732        // setBackground above will record that padding is currently provided by the background.
4733        // If we have padding specified via xml, record that here instead and use it.
4734        mLeftPaddingDefined = leftPaddingDefined;
4735        mRightPaddingDefined = rightPaddingDefined;
4736
4737        if (padding >= 0) {
4738            leftPadding = padding;
4739            topPadding = padding;
4740            rightPadding = padding;
4741            bottomPadding = padding;
4742            mUserPaddingLeftInitial = padding;
4743            mUserPaddingRightInitial = padding;
4744        } else {
4745            if (paddingHorizontal >= 0) {
4746                leftPadding = paddingHorizontal;
4747                rightPadding = paddingHorizontal;
4748                mUserPaddingLeftInitial = paddingHorizontal;
4749                mUserPaddingRightInitial = paddingHorizontal;
4750            }
4751            if (paddingVertical >= 0) {
4752                topPadding = paddingVertical;
4753                bottomPadding = paddingVertical;
4754            }
4755        }
4756
4757        if (isRtlCompatibilityMode()) {
4758            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4759            // left / right padding are used if defined (meaning here nothing to do). If they are not
4760            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4761            // start / end and resolve them as left / right (layout direction is not taken into account).
4762            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4763            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4764            // defined.
4765            if (!mLeftPaddingDefined && startPaddingDefined) {
4766                leftPadding = startPadding;
4767            }
4768            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4769            if (!mRightPaddingDefined && endPaddingDefined) {
4770                rightPadding = endPadding;
4771            }
4772            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4773        } else {
4774            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4775            // values defined. Otherwise, left /right values are used.
4776            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4777            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4778            // defined.
4779            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4780
4781            if (mLeftPaddingDefined && !hasRelativePadding) {
4782                mUserPaddingLeftInitial = leftPadding;
4783            }
4784            if (mRightPaddingDefined && !hasRelativePadding) {
4785                mUserPaddingRightInitial = rightPadding;
4786            }
4787        }
4788
4789        internalSetPadding(
4790                mUserPaddingLeftInitial,
4791                topPadding >= 0 ? topPadding : mPaddingTop,
4792                mUserPaddingRightInitial,
4793                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4794
4795        if (viewFlagMasks != 0) {
4796            setFlags(viewFlagValues, viewFlagMasks);
4797        }
4798
4799        if (initializeScrollbars) {
4800            initializeScrollbarsInternal(a);
4801        }
4802
4803        if (initializeScrollIndicators) {
4804            initializeScrollIndicatorsInternal();
4805        }
4806
4807        a.recycle();
4808
4809        // Needs to be called after mViewFlags is set
4810        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4811            recomputePadding();
4812        }
4813
4814        if (x != 0 || y != 0) {
4815            scrollTo(x, y);
4816        }
4817
4818        if (transformSet) {
4819            setTranslationX(tx);
4820            setTranslationY(ty);
4821            setTranslationZ(tz);
4822            setElevation(elevation);
4823            setRotation(rotation);
4824            setRotationX(rotationX);
4825            setRotationY(rotationY);
4826            setScaleX(sx);
4827            setScaleY(sy);
4828        }
4829
4830        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4831            setScrollContainer(true);
4832        }
4833
4834        computeOpaqueFlags();
4835    }
4836
4837    /**
4838     * An implementation of OnClickListener that attempts to lazily load a
4839     * named click handling method from a parent or ancestor context.
4840     */
4841    private static class DeclaredOnClickListener implements OnClickListener {
4842        private final View mHostView;
4843        private final String mMethodName;
4844
4845        private Method mResolvedMethod;
4846        private Context mResolvedContext;
4847
4848        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4849            mHostView = hostView;
4850            mMethodName = methodName;
4851        }
4852
4853        @Override
4854        public void onClick(@NonNull View v) {
4855            if (mResolvedMethod == null) {
4856                resolveMethod(mHostView.getContext(), mMethodName);
4857            }
4858
4859            try {
4860                mResolvedMethod.invoke(mResolvedContext, v);
4861            } catch (IllegalAccessException e) {
4862                throw new IllegalStateException(
4863                        "Could not execute non-public method for android:onClick", e);
4864            } catch (InvocationTargetException e) {
4865                throw new IllegalStateException(
4866                        "Could not execute method for android:onClick", e);
4867            }
4868        }
4869
4870        @NonNull
4871        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4872            while (context != null) {
4873                try {
4874                    if (!context.isRestricted()) {
4875                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4876                        if (method != null) {
4877                            mResolvedMethod = method;
4878                            mResolvedContext = context;
4879                            return;
4880                        }
4881                    }
4882                } catch (NoSuchMethodException e) {
4883                    // Failed to find method, keep searching up the hierarchy.
4884                }
4885
4886                if (context instanceof ContextWrapper) {
4887                    context = ((ContextWrapper) context).getBaseContext();
4888                } else {
4889                    // Can't search up the hierarchy, null out and fail.
4890                    context = null;
4891                }
4892            }
4893
4894            final int id = mHostView.getId();
4895            final String idText = id == NO_ID ? "" : " with id '"
4896                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4897            throw new IllegalStateException("Could not find method " + mMethodName
4898                    + "(View) in a parent or ancestor Context for android:onClick "
4899                    + "attribute defined on view " + mHostView.getClass() + idText);
4900        }
4901    }
4902
4903    /**
4904     * Non-public constructor for use in testing
4905     */
4906    View() {
4907        mResources = null;
4908        mRenderNode = RenderNode.create(getClass().getName(), this);
4909    }
4910
4911    final boolean debugDraw() {
4912        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
4913    }
4914
4915    private static SparseArray<String> getAttributeMap() {
4916        if (mAttributeMap == null) {
4917            mAttributeMap = new SparseArray<>();
4918        }
4919        return mAttributeMap;
4920    }
4921
4922    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4923        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4924        final int indexCount = t.getIndexCount();
4925        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4926
4927        int i = 0;
4928
4929        // Store raw XML attributes.
4930        for (int j = 0; j < attrsCount; ++j) {
4931            attributes[i] = attrs.getAttributeName(j);
4932            attributes[i + 1] = attrs.getAttributeValue(j);
4933            i += 2;
4934        }
4935
4936        // Store resolved styleable attributes.
4937        final Resources res = t.getResources();
4938        final SparseArray<String> attributeMap = getAttributeMap();
4939        for (int j = 0; j < indexCount; ++j) {
4940            final int index = t.getIndex(j);
4941            if (!t.hasValueOrEmpty(index)) {
4942                // Value is undefined. Skip it.
4943                continue;
4944            }
4945
4946            final int resourceId = t.getResourceId(index, 0);
4947            if (resourceId == 0) {
4948                // Value is not a reference. Skip it.
4949                continue;
4950            }
4951
4952            String resourceName = attributeMap.get(resourceId);
4953            if (resourceName == null) {
4954                try {
4955                    resourceName = res.getResourceName(resourceId);
4956                } catch (Resources.NotFoundException e) {
4957                    resourceName = "0x" + Integer.toHexString(resourceId);
4958                }
4959                attributeMap.put(resourceId, resourceName);
4960            }
4961
4962            attributes[i] = resourceName;
4963            attributes[i + 1] = t.getString(index);
4964            i += 2;
4965        }
4966
4967        // Trim to fit contents.
4968        final String[] trimmed = new String[i];
4969        System.arraycopy(attributes, 0, trimmed, 0, i);
4970        mAttributes = trimmed;
4971    }
4972
4973    public String toString() {
4974        StringBuilder out = new StringBuilder(128);
4975        out.append(getClass().getName());
4976        out.append('{');
4977        out.append(Integer.toHexString(System.identityHashCode(this)));
4978        out.append(' ');
4979        switch (mViewFlags&VISIBILITY_MASK) {
4980            case VISIBLE: out.append('V'); break;
4981            case INVISIBLE: out.append('I'); break;
4982            case GONE: out.append('G'); break;
4983            default: out.append('.'); break;
4984        }
4985        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4986        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4987        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4988        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4989        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4990        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4991        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4992        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4993        out.append(' ');
4994        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4995        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4996        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4997        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4998            out.append('p');
4999        } else {
5000            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5001        }
5002        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5003        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5004        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5005        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5006        out.append(' ');
5007        out.append(mLeft);
5008        out.append(',');
5009        out.append(mTop);
5010        out.append('-');
5011        out.append(mRight);
5012        out.append(',');
5013        out.append(mBottom);
5014        final int id = getId();
5015        if (id != NO_ID) {
5016            out.append(" #");
5017            out.append(Integer.toHexString(id));
5018            final Resources r = mResources;
5019            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5020                try {
5021                    String pkgname;
5022                    switch (id&0xff000000) {
5023                        case 0x7f000000:
5024                            pkgname="app";
5025                            break;
5026                        case 0x01000000:
5027                            pkgname="android";
5028                            break;
5029                        default:
5030                            pkgname = r.getResourcePackageName(id);
5031                            break;
5032                    }
5033                    String typename = r.getResourceTypeName(id);
5034                    String entryname = r.getResourceEntryName(id);
5035                    out.append(" ");
5036                    out.append(pkgname);
5037                    out.append(":");
5038                    out.append(typename);
5039                    out.append("/");
5040                    out.append(entryname);
5041                } catch (Resources.NotFoundException e) {
5042                }
5043            }
5044        }
5045        out.append("}");
5046        return out.toString();
5047    }
5048
5049    /**
5050     * <p>
5051     * Initializes the fading edges from a given set of styled attributes. This
5052     * method should be called by subclasses that need fading edges and when an
5053     * instance of these subclasses is created programmatically rather than
5054     * being inflated from XML. This method is automatically called when the XML
5055     * is inflated.
5056     * </p>
5057     *
5058     * @param a the styled attributes set to initialize the fading edges from
5059     *
5060     * @removed
5061     */
5062    protected void initializeFadingEdge(TypedArray a) {
5063        // This method probably shouldn't have been included in the SDK to begin with.
5064        // It relies on 'a' having been initialized using an attribute filter array that is
5065        // not publicly available to the SDK. The old method has been renamed
5066        // to initializeFadingEdgeInternal and hidden for framework use only;
5067        // this one initializes using defaults to make it safe to call for apps.
5068
5069        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5070
5071        initializeFadingEdgeInternal(arr);
5072
5073        arr.recycle();
5074    }
5075
5076    /**
5077     * <p>
5078     * Initializes the fading edges from a given set of styled attributes. This
5079     * method should be called by subclasses that need fading edges and when an
5080     * instance of these subclasses is created programmatically rather than
5081     * being inflated from XML. This method is automatically called when the XML
5082     * is inflated.
5083     * </p>
5084     *
5085     * @param a the styled attributes set to initialize the fading edges from
5086     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5087     */
5088    protected void initializeFadingEdgeInternal(TypedArray a) {
5089        initScrollCache();
5090
5091        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5092                R.styleable.View_fadingEdgeLength,
5093                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5094    }
5095
5096    /**
5097     * Returns the size of the vertical faded edges used to indicate that more
5098     * content in this view is visible.
5099     *
5100     * @return The size in pixels of the vertical faded edge or 0 if vertical
5101     *         faded edges are not enabled for this view.
5102     * @attr ref android.R.styleable#View_fadingEdgeLength
5103     */
5104    public int getVerticalFadingEdgeLength() {
5105        if (isVerticalFadingEdgeEnabled()) {
5106            ScrollabilityCache cache = mScrollCache;
5107            if (cache != null) {
5108                return cache.fadingEdgeLength;
5109            }
5110        }
5111        return 0;
5112    }
5113
5114    /**
5115     * Set the size of the faded edge used to indicate that more content in this
5116     * view is available.  Will not change whether the fading edge is enabled; use
5117     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5118     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5119     * for the vertical or horizontal fading edges.
5120     *
5121     * @param length The size in pixels of the faded edge used to indicate that more
5122     *        content in this view is visible.
5123     */
5124    public void setFadingEdgeLength(int length) {
5125        initScrollCache();
5126        mScrollCache.fadingEdgeLength = length;
5127    }
5128
5129    /**
5130     * Returns the size of the horizontal faded edges used to indicate that more
5131     * content in this view is visible.
5132     *
5133     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5134     *         faded edges are not enabled for this view.
5135     * @attr ref android.R.styleable#View_fadingEdgeLength
5136     */
5137    public int getHorizontalFadingEdgeLength() {
5138        if (isHorizontalFadingEdgeEnabled()) {
5139            ScrollabilityCache cache = mScrollCache;
5140            if (cache != null) {
5141                return cache.fadingEdgeLength;
5142            }
5143        }
5144        return 0;
5145    }
5146
5147    /**
5148     * Returns the width of the vertical scrollbar.
5149     *
5150     * @return The width in pixels of the vertical scrollbar or 0 if there
5151     *         is no vertical scrollbar.
5152     */
5153    public int getVerticalScrollbarWidth() {
5154        ScrollabilityCache cache = mScrollCache;
5155        if (cache != null) {
5156            ScrollBarDrawable scrollBar = cache.scrollBar;
5157            if (scrollBar != null) {
5158                int size = scrollBar.getSize(true);
5159                if (size <= 0) {
5160                    size = cache.scrollBarSize;
5161                }
5162                return size;
5163            }
5164            return 0;
5165        }
5166        return 0;
5167    }
5168
5169    /**
5170     * Returns the height of the horizontal scrollbar.
5171     *
5172     * @return The height in pixels of the horizontal scrollbar or 0 if
5173     *         there is no horizontal scrollbar.
5174     */
5175    protected int getHorizontalScrollbarHeight() {
5176        ScrollabilityCache cache = mScrollCache;
5177        if (cache != null) {
5178            ScrollBarDrawable scrollBar = cache.scrollBar;
5179            if (scrollBar != null) {
5180                int size = scrollBar.getSize(false);
5181                if (size <= 0) {
5182                    size = cache.scrollBarSize;
5183                }
5184                return size;
5185            }
5186            return 0;
5187        }
5188        return 0;
5189    }
5190
5191    /**
5192     * <p>
5193     * Initializes the scrollbars from a given set of styled attributes. This
5194     * method should be called by subclasses that need scrollbars and when an
5195     * instance of these subclasses is created programmatically rather than
5196     * being inflated from XML. This method is automatically called when the XML
5197     * is inflated.
5198     * </p>
5199     *
5200     * @param a the styled attributes set to initialize the scrollbars from
5201     *
5202     * @removed
5203     */
5204    protected void initializeScrollbars(TypedArray a) {
5205        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5206        // using the View filter array which is not available to the SDK. As such, internal
5207        // framework usage now uses initializeScrollbarsInternal and we grab a default
5208        // TypedArray with the right filter instead here.
5209        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5210
5211        initializeScrollbarsInternal(arr);
5212
5213        // We ignored the method parameter. Recycle the one we actually did use.
5214        arr.recycle();
5215    }
5216
5217    /**
5218     * <p>
5219     * Initializes the scrollbars from a given set of styled attributes. This
5220     * method should be called by subclasses that need scrollbars and when an
5221     * instance of these subclasses is created programmatically rather than
5222     * being inflated from XML. This method is automatically called when the XML
5223     * is inflated.
5224     * </p>
5225     *
5226     * @param a the styled attributes set to initialize the scrollbars from
5227     * @hide
5228     */
5229    protected void initializeScrollbarsInternal(TypedArray a) {
5230        initScrollCache();
5231
5232        final ScrollabilityCache scrollabilityCache = mScrollCache;
5233
5234        if (scrollabilityCache.scrollBar == null) {
5235            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5236            scrollabilityCache.scrollBar.setState(getDrawableState());
5237            scrollabilityCache.scrollBar.setCallback(this);
5238        }
5239
5240        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5241
5242        if (!fadeScrollbars) {
5243            scrollabilityCache.state = ScrollabilityCache.ON;
5244        }
5245        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5246
5247
5248        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5249                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5250                        .getScrollBarFadeDuration());
5251        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5252                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5253                ViewConfiguration.getScrollDefaultDelay());
5254
5255
5256        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5257                com.android.internal.R.styleable.View_scrollbarSize,
5258                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5259
5260        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5261        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5262
5263        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5264        if (thumb != null) {
5265            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5266        }
5267
5268        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5269                false);
5270        if (alwaysDraw) {
5271            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5272        }
5273
5274        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5275        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5276
5277        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5278        if (thumb != null) {
5279            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5280        }
5281
5282        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5283                false);
5284        if (alwaysDraw) {
5285            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5286        }
5287
5288        // Apply layout direction to the new Drawables if needed
5289        final int layoutDirection = getLayoutDirection();
5290        if (track != null) {
5291            track.setLayoutDirection(layoutDirection);
5292        }
5293        if (thumb != null) {
5294            thumb.setLayoutDirection(layoutDirection);
5295        }
5296
5297        // Re-apply user/background padding so that scrollbar(s) get added
5298        resolvePadding();
5299    }
5300
5301    private void initializeScrollIndicatorsInternal() {
5302        // Some day maybe we'll break this into top/left/start/etc. and let the
5303        // client control it. Until then, you can have any scroll indicator you
5304        // want as long as it's a 1dp foreground-colored rectangle.
5305        if (mScrollIndicatorDrawable == null) {
5306            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5307        }
5308    }
5309
5310    /**
5311     * <p>
5312     * Initalizes the scrollability cache if necessary.
5313     * </p>
5314     */
5315    private void initScrollCache() {
5316        if (mScrollCache == null) {
5317            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5318        }
5319    }
5320
5321    private ScrollabilityCache getScrollCache() {
5322        initScrollCache();
5323        return mScrollCache;
5324    }
5325
5326    /**
5327     * Set the position of the vertical scroll bar. Should be one of
5328     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5329     * {@link #SCROLLBAR_POSITION_RIGHT}.
5330     *
5331     * @param position Where the vertical scroll bar should be positioned.
5332     */
5333    public void setVerticalScrollbarPosition(int position) {
5334        if (mVerticalScrollbarPosition != position) {
5335            mVerticalScrollbarPosition = position;
5336            computeOpaqueFlags();
5337            resolvePadding();
5338        }
5339    }
5340
5341    /**
5342     * @return The position where the vertical scroll bar will show, if applicable.
5343     * @see #setVerticalScrollbarPosition(int)
5344     */
5345    public int getVerticalScrollbarPosition() {
5346        return mVerticalScrollbarPosition;
5347    }
5348
5349    boolean isOnScrollbar(float x, float y) {
5350        if (mScrollCache == null) {
5351            return false;
5352        }
5353        x += getScrollX();
5354        y += getScrollY();
5355        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5356            final Rect bounds = mScrollCache.mScrollBarBounds;
5357            getVerticalScrollBarBounds(bounds);
5358            if (bounds.contains((int)x, (int)y)) {
5359                return true;
5360            }
5361        }
5362        if (isHorizontalScrollBarEnabled()) {
5363            final Rect bounds = mScrollCache.mScrollBarBounds;
5364            getHorizontalScrollBarBounds(bounds);
5365            if (bounds.contains((int)x, (int)y)) {
5366                return true;
5367            }
5368        }
5369        return false;
5370    }
5371
5372    boolean isOnScrollbarThumb(float x, float y) {
5373        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5374    }
5375
5376    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5377        if (mScrollCache == null) {
5378            return false;
5379        }
5380        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5381            x += getScrollX();
5382            y += getScrollY();
5383            final Rect bounds = mScrollCache.mScrollBarBounds;
5384            getVerticalScrollBarBounds(bounds);
5385            final int range = computeVerticalScrollRange();
5386            final int offset = computeVerticalScrollOffset();
5387            final int extent = computeVerticalScrollExtent();
5388            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5389                    extent, range);
5390            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5391                    extent, range, offset);
5392            final int thumbTop = bounds.top + thumbOffset;
5393            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5394                    && y <= thumbTop + thumbLength) {
5395                return true;
5396            }
5397        }
5398        return false;
5399    }
5400
5401    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5402        if (mScrollCache == null) {
5403            return false;
5404        }
5405        if (isHorizontalScrollBarEnabled()) {
5406            x += getScrollX();
5407            y += getScrollY();
5408            final Rect bounds = mScrollCache.mScrollBarBounds;
5409            getHorizontalScrollBarBounds(bounds);
5410            final int range = computeHorizontalScrollRange();
5411            final int offset = computeHorizontalScrollOffset();
5412            final int extent = computeHorizontalScrollExtent();
5413            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5414                    extent, range);
5415            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5416                    extent, range, offset);
5417            final int thumbLeft = bounds.left + thumbOffset;
5418            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5419                    && y <= bounds.bottom) {
5420                return true;
5421            }
5422        }
5423        return false;
5424    }
5425
5426    boolean isDraggingScrollBar() {
5427        return mScrollCache != null
5428                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5429    }
5430
5431    /**
5432     * Sets the state of all scroll indicators.
5433     * <p>
5434     * See {@link #setScrollIndicators(int, int)} for usage information.
5435     *
5436     * @param indicators a bitmask of indicators that should be enabled, or
5437     *                   {@code 0} to disable all indicators
5438     * @see #setScrollIndicators(int, int)
5439     * @see #getScrollIndicators()
5440     * @attr ref android.R.styleable#View_scrollIndicators
5441     */
5442    public void setScrollIndicators(@ScrollIndicators int indicators) {
5443        setScrollIndicators(indicators,
5444                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5445    }
5446
5447    /**
5448     * Sets the state of the scroll indicators specified by the mask. To change
5449     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5450     * <p>
5451     * When a scroll indicator is enabled, it will be displayed if the view
5452     * can scroll in the direction of the indicator.
5453     * <p>
5454     * Multiple indicator types may be enabled or disabled by passing the
5455     * logical OR of the desired types. If multiple types are specified, they
5456     * will all be set to the same enabled state.
5457     * <p>
5458     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5459     *
5460     * @param indicators the indicator direction, or the logical OR of multiple
5461     *             indicator directions. One or more of:
5462     *             <ul>
5463     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5464     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5465     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5466     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5467     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5468     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5469     *             </ul>
5470     * @see #setScrollIndicators(int)
5471     * @see #getScrollIndicators()
5472     * @attr ref android.R.styleable#View_scrollIndicators
5473     */
5474    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5475        // Shift and sanitize mask.
5476        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5477        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5478
5479        // Shift and mask indicators.
5480        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5481        indicators &= mask;
5482
5483        // Merge with non-masked flags.
5484        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5485
5486        if (mPrivateFlags3 != updatedFlags) {
5487            mPrivateFlags3 = updatedFlags;
5488
5489            if (indicators != 0) {
5490                initializeScrollIndicatorsInternal();
5491            }
5492            invalidate();
5493        }
5494    }
5495
5496    /**
5497     * Returns a bitmask representing the enabled scroll indicators.
5498     * <p>
5499     * For example, if the top and left scroll indicators are enabled and all
5500     * other indicators are disabled, the return value will be
5501     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5502     * <p>
5503     * To check whether the bottom scroll indicator is enabled, use the value
5504     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5505     *
5506     * @return a bitmask representing the enabled scroll indicators
5507     */
5508    @ScrollIndicators
5509    public int getScrollIndicators() {
5510        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5511                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5512    }
5513
5514    ListenerInfo getListenerInfo() {
5515        if (mListenerInfo != null) {
5516            return mListenerInfo;
5517        }
5518        mListenerInfo = new ListenerInfo();
5519        return mListenerInfo;
5520    }
5521
5522    /**
5523     * Register a callback to be invoked when the scroll X or Y positions of
5524     * this view change.
5525     * <p>
5526     * <b>Note:</b> Some views handle scrolling independently from View and may
5527     * have their own separate listeners for scroll-type events. For example,
5528     * {@link android.widget.ListView ListView} allows clients to register an
5529     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5530     * to listen for changes in list scroll position.
5531     *
5532     * @param l The listener to notify when the scroll X or Y position changes.
5533     * @see android.view.View#getScrollX()
5534     * @see android.view.View#getScrollY()
5535     */
5536    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5537        getListenerInfo().mOnScrollChangeListener = l;
5538    }
5539
5540    /**
5541     * Register a callback to be invoked when focus of this view changed.
5542     *
5543     * @param l The callback that will run.
5544     */
5545    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5546        getListenerInfo().mOnFocusChangeListener = l;
5547    }
5548
5549    /**
5550     * Add a listener that will be called when the bounds of the view change due to
5551     * layout processing.
5552     *
5553     * @param listener The listener that will be called when layout bounds change.
5554     */
5555    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5556        ListenerInfo li = getListenerInfo();
5557        if (li.mOnLayoutChangeListeners == null) {
5558            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5559        }
5560        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5561            li.mOnLayoutChangeListeners.add(listener);
5562        }
5563    }
5564
5565    /**
5566     * Remove a listener for layout changes.
5567     *
5568     * @param listener The listener for layout bounds change.
5569     */
5570    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5571        ListenerInfo li = mListenerInfo;
5572        if (li == null || li.mOnLayoutChangeListeners == null) {
5573            return;
5574        }
5575        li.mOnLayoutChangeListeners.remove(listener);
5576    }
5577
5578    /**
5579     * Add a listener for attach state changes.
5580     *
5581     * This listener will be called whenever this view is attached or detached
5582     * from a window. Remove the listener using
5583     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5584     *
5585     * @param listener Listener to attach
5586     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5587     */
5588    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5589        ListenerInfo li = getListenerInfo();
5590        if (li.mOnAttachStateChangeListeners == null) {
5591            li.mOnAttachStateChangeListeners
5592                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5593        }
5594        li.mOnAttachStateChangeListeners.add(listener);
5595    }
5596
5597    /**
5598     * Remove a listener for attach state changes. The listener will receive no further
5599     * notification of window attach/detach events.
5600     *
5601     * @param listener Listener to remove
5602     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5603     */
5604    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5605        ListenerInfo li = mListenerInfo;
5606        if (li == null || li.mOnAttachStateChangeListeners == null) {
5607            return;
5608        }
5609        li.mOnAttachStateChangeListeners.remove(listener);
5610    }
5611
5612    /**
5613     * Returns the focus-change callback registered for this view.
5614     *
5615     * @return The callback, or null if one is not registered.
5616     */
5617    public OnFocusChangeListener getOnFocusChangeListener() {
5618        ListenerInfo li = mListenerInfo;
5619        return li != null ? li.mOnFocusChangeListener : null;
5620    }
5621
5622    /**
5623     * Register a callback to be invoked when this view is clicked. If this view is not
5624     * clickable, it becomes clickable.
5625     *
5626     * @param l The callback that will run
5627     *
5628     * @see #setClickable(boolean)
5629     */
5630    public void setOnClickListener(@Nullable OnClickListener l) {
5631        if (!isClickable()) {
5632            setClickable(true);
5633        }
5634        getListenerInfo().mOnClickListener = l;
5635    }
5636
5637    /**
5638     * Return whether this view has an attached OnClickListener.  Returns
5639     * true if there is a listener, false if there is none.
5640     */
5641    public boolean hasOnClickListeners() {
5642        ListenerInfo li = mListenerInfo;
5643        return (li != null && li.mOnClickListener != null);
5644    }
5645
5646    /**
5647     * Register a callback to be invoked when this view is clicked and held. If this view is not
5648     * long clickable, it becomes long clickable.
5649     *
5650     * @param l The callback that will run
5651     *
5652     * @see #setLongClickable(boolean)
5653     */
5654    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5655        if (!isLongClickable()) {
5656            setLongClickable(true);
5657        }
5658        getListenerInfo().mOnLongClickListener = l;
5659    }
5660
5661    /**
5662     * Register a callback to be invoked when this view is context clicked. If the view is not
5663     * context clickable, it becomes context clickable.
5664     *
5665     * @param l The callback that will run
5666     * @see #setContextClickable(boolean)
5667     */
5668    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5669        if (!isContextClickable()) {
5670            setContextClickable(true);
5671        }
5672        getListenerInfo().mOnContextClickListener = l;
5673    }
5674
5675    /**
5676     * Register a callback to be invoked when the context menu for this view is
5677     * being built. If this view is not long clickable, it becomes long clickable.
5678     *
5679     * @param l The callback that will run
5680     *
5681     */
5682    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5683        if (!isLongClickable()) {
5684            setLongClickable(true);
5685        }
5686        getListenerInfo().mOnCreateContextMenuListener = l;
5687    }
5688
5689    /**
5690     * Set an observer to collect stats for each frame rendered for this view.
5691     *
5692     * @hide
5693     */
5694    public void addFrameMetricsListener(Window window,
5695            Window.OnFrameMetricsAvailableListener listener,
5696            Handler handler) {
5697        if (mAttachInfo != null) {
5698            if (mAttachInfo.mThreadedRenderer != null) {
5699                if (mFrameMetricsObservers == null) {
5700                    mFrameMetricsObservers = new ArrayList<>();
5701                }
5702
5703                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5704                        handler.getLooper(), listener);
5705                mFrameMetricsObservers.add(fmo);
5706                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5707            } else {
5708                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5709            }
5710        } else {
5711            if (mFrameMetricsObservers == null) {
5712                mFrameMetricsObservers = new ArrayList<>();
5713            }
5714
5715            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5716                    handler.getLooper(), listener);
5717            mFrameMetricsObservers.add(fmo);
5718        }
5719    }
5720
5721    /**
5722     * Remove observer configured to collect frame stats for this view.
5723     *
5724     * @hide
5725     */
5726    public void removeFrameMetricsListener(
5727            Window.OnFrameMetricsAvailableListener listener) {
5728        ThreadedRenderer renderer = getThreadedRenderer();
5729        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5730        if (fmo == null) {
5731            throw new IllegalArgumentException(
5732                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5733        }
5734
5735        if (mFrameMetricsObservers != null) {
5736            mFrameMetricsObservers.remove(fmo);
5737            if (renderer != null) {
5738                renderer.removeFrameMetricsObserver(fmo);
5739            }
5740        }
5741    }
5742
5743    private void registerPendingFrameMetricsObservers() {
5744        if (mFrameMetricsObservers != null) {
5745            ThreadedRenderer renderer = getThreadedRenderer();
5746            if (renderer != null) {
5747                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5748                    renderer.addFrameMetricsObserver(fmo);
5749                }
5750            } else {
5751                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5752            }
5753        }
5754    }
5755
5756    private FrameMetricsObserver findFrameMetricsObserver(
5757            Window.OnFrameMetricsAvailableListener listener) {
5758        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5759            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5760            if (observer.mListener == listener) {
5761                return observer;
5762            }
5763        }
5764
5765        return null;
5766    }
5767
5768    /**
5769     * Call this view's OnClickListener, if it is defined.  Performs all normal
5770     * actions associated with clicking: reporting accessibility event, playing
5771     * a sound, etc.
5772     *
5773     * @return True there was an assigned OnClickListener that was called, false
5774     *         otherwise is returned.
5775     */
5776    public boolean performClick() {
5777        final boolean result;
5778        final ListenerInfo li = mListenerInfo;
5779        if (li != null && li.mOnClickListener != null) {
5780            playSoundEffect(SoundEffectConstants.CLICK);
5781            li.mOnClickListener.onClick(this);
5782            result = true;
5783        } else {
5784            result = false;
5785        }
5786
5787        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5788        return result;
5789    }
5790
5791    /**
5792     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5793     * this only calls the listener, and does not do any associated clicking
5794     * actions like reporting an accessibility event.
5795     *
5796     * @return True there was an assigned OnClickListener that was called, false
5797     *         otherwise is returned.
5798     */
5799    public boolean callOnClick() {
5800        ListenerInfo li = mListenerInfo;
5801        if (li != null && li.mOnClickListener != null) {
5802            li.mOnClickListener.onClick(this);
5803            return true;
5804        }
5805        return false;
5806    }
5807
5808    /**
5809     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5810     * context menu if the OnLongClickListener did not consume the event.
5811     *
5812     * @return {@code true} if one of the above receivers consumed the event,
5813     *         {@code false} otherwise
5814     */
5815    public boolean performLongClick() {
5816        return performLongClickInternal(mLongClickX, mLongClickY);
5817    }
5818
5819    /**
5820     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5821     * context menu if the OnLongClickListener did not consume the event,
5822     * anchoring it to an (x,y) coordinate.
5823     *
5824     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5825     *          to disable anchoring
5826     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5827     *          to disable anchoring
5828     * @return {@code true} if one of the above receivers consumed the event,
5829     *         {@code false} otherwise
5830     */
5831    public boolean performLongClick(float x, float y) {
5832        mLongClickX = x;
5833        mLongClickY = y;
5834        final boolean handled = performLongClick();
5835        mLongClickX = Float.NaN;
5836        mLongClickY = Float.NaN;
5837        return handled;
5838    }
5839
5840    /**
5841     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5842     * context menu if the OnLongClickListener did not consume the event,
5843     * optionally anchoring it to an (x,y) coordinate.
5844     *
5845     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5846     *          to disable anchoring
5847     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5848     *          to disable anchoring
5849     * @return {@code true} if one of the above receivers consumed the event,
5850     *         {@code false} otherwise
5851     */
5852    private boolean performLongClickInternal(float x, float y) {
5853        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5854
5855        boolean handled = false;
5856        final ListenerInfo li = mListenerInfo;
5857        if (li != null && li.mOnLongClickListener != null) {
5858            handled = li.mOnLongClickListener.onLongClick(View.this);
5859        }
5860        if (!handled) {
5861            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5862            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5863        }
5864        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5865            if (!handled) {
5866                handled = showLongClickTooltip((int) x, (int) y);
5867            }
5868        }
5869        if (handled) {
5870            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5871        }
5872        return handled;
5873    }
5874
5875    /**
5876     * Call this view's OnContextClickListener, if it is defined.
5877     *
5878     * @param x the x coordinate of the context click
5879     * @param y the y coordinate of the context click
5880     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5881     *         otherwise.
5882     */
5883    public boolean performContextClick(float x, float y) {
5884        return performContextClick();
5885    }
5886
5887    /**
5888     * Call this view's OnContextClickListener, if it is defined.
5889     *
5890     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5891     *         otherwise.
5892     */
5893    public boolean performContextClick() {
5894        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5895
5896        boolean handled = false;
5897        ListenerInfo li = mListenerInfo;
5898        if (li != null && li.mOnContextClickListener != null) {
5899            handled = li.mOnContextClickListener.onContextClick(View.this);
5900        }
5901        if (handled) {
5902            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5903        }
5904        return handled;
5905    }
5906
5907    /**
5908     * Performs button-related actions during a touch down event.
5909     *
5910     * @param event The event.
5911     * @return True if the down was consumed.
5912     *
5913     * @hide
5914     */
5915    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5916        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5917            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5918            showContextMenu(event.getX(), event.getY());
5919            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5920            return true;
5921        }
5922        return false;
5923    }
5924
5925    /**
5926     * Shows the context menu for this view.
5927     *
5928     * @return {@code true} if the context menu was shown, {@code false}
5929     *         otherwise
5930     * @see #showContextMenu(float, float)
5931     */
5932    public boolean showContextMenu() {
5933        return getParent().showContextMenuForChild(this);
5934    }
5935
5936    /**
5937     * Shows the context menu for this view anchored to the specified
5938     * view-relative coordinate.
5939     *
5940     * @param x the X coordinate in pixels relative to the view to which the
5941     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5942     * @param y the Y coordinate in pixels relative to the view to which the
5943     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5944     * @return {@code true} if the context menu was shown, {@code false}
5945     *         otherwise
5946     */
5947    public boolean showContextMenu(float x, float y) {
5948        return getParent().showContextMenuForChild(this, x, y);
5949    }
5950
5951    /**
5952     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5953     *
5954     * @param callback Callback that will control the lifecycle of the action mode
5955     * @return The new action mode if it is started, null otherwise
5956     *
5957     * @see ActionMode
5958     * @see #startActionMode(android.view.ActionMode.Callback, int)
5959     */
5960    public ActionMode startActionMode(ActionMode.Callback callback) {
5961        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5962    }
5963
5964    /**
5965     * Start an action mode with the given type.
5966     *
5967     * @param callback Callback that will control the lifecycle of the action mode
5968     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5969     * @return The new action mode if it is started, null otherwise
5970     *
5971     * @see ActionMode
5972     */
5973    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5974        ViewParent parent = getParent();
5975        if (parent == null) return null;
5976        try {
5977            return parent.startActionModeForChild(this, callback, type);
5978        } catch (AbstractMethodError ame) {
5979            // Older implementations of custom views might not implement this.
5980            return parent.startActionModeForChild(this, callback);
5981        }
5982    }
5983
5984    /**
5985     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5986     * Context, creating a unique View identifier to retrieve the result.
5987     *
5988     * @param intent The Intent to be started.
5989     * @param requestCode The request code to use.
5990     * @hide
5991     */
5992    public void startActivityForResult(Intent intent, int requestCode) {
5993        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5994        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5995    }
5996
5997    /**
5998     * If this View corresponds to the calling who, dispatches the activity result.
5999     * @param who The identifier for the targeted View to receive the result.
6000     * @param requestCode The integer request code originally supplied to
6001     *                    startActivityForResult(), allowing you to identify who this
6002     *                    result came from.
6003     * @param resultCode The integer result code returned by the child activity
6004     *                   through its setResult().
6005     * @param data An Intent, which can return result data to the caller
6006     *               (various data can be attached to Intent "extras").
6007     * @return {@code true} if the activity result was dispatched.
6008     * @hide
6009     */
6010    public boolean dispatchActivityResult(
6011            String who, int requestCode, int resultCode, Intent data) {
6012        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6013            onActivityResult(requestCode, resultCode, data);
6014            mStartActivityRequestWho = null;
6015            return true;
6016        }
6017        return false;
6018    }
6019
6020    /**
6021     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6022     *
6023     * @param requestCode The integer request code originally supplied to
6024     *                    startActivityForResult(), allowing you to identify who this
6025     *                    result came from.
6026     * @param resultCode The integer result code returned by the child activity
6027     *                   through its setResult().
6028     * @param data An Intent, which can return result data to the caller
6029     *               (various data can be attached to Intent "extras").
6030     * @hide
6031     */
6032    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6033        // Do nothing.
6034    }
6035
6036    /**
6037     * Register a callback to be invoked when a hardware key is pressed in this view.
6038     * Key presses in software input methods will generally not trigger the methods of
6039     * this listener.
6040     * @param l the key listener to attach to this view
6041     */
6042    public void setOnKeyListener(OnKeyListener l) {
6043        getListenerInfo().mOnKeyListener = l;
6044    }
6045
6046    /**
6047     * Register a callback to be invoked when a touch event is sent to this view.
6048     * @param l the touch listener to attach to this view
6049     */
6050    public void setOnTouchListener(OnTouchListener l) {
6051        getListenerInfo().mOnTouchListener = l;
6052    }
6053
6054    /**
6055     * Register a callback to be invoked when a generic motion event is sent to this view.
6056     * @param l the generic motion listener to attach to this view
6057     */
6058    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6059        getListenerInfo().mOnGenericMotionListener = l;
6060    }
6061
6062    /**
6063     * Register a callback to be invoked when a hover event is sent to this view.
6064     * @param l the hover listener to attach to this view
6065     */
6066    public void setOnHoverListener(OnHoverListener l) {
6067        getListenerInfo().mOnHoverListener = l;
6068    }
6069
6070    /**
6071     * Register a drag event listener callback object for this View. The parameter is
6072     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6073     * View, the system calls the
6074     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6075     * @param l An implementation of {@link android.view.View.OnDragListener}.
6076     */
6077    public void setOnDragListener(OnDragListener l) {
6078        getListenerInfo().mOnDragListener = l;
6079    }
6080
6081    /**
6082     * Give this view focus. This will cause
6083     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6084     *
6085     * Note: this does not check whether this {@link View} should get focus, it just
6086     * gives it focus no matter what.  It should only be called internally by framework
6087     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6088     *
6089     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6090     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6091     *        focus moved when requestFocus() is called. It may not always
6092     *        apply, in which case use the default View.FOCUS_DOWN.
6093     * @param previouslyFocusedRect The rectangle of the view that had focus
6094     *        prior in this View's coordinate system.
6095     */
6096    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6097        if (DBG) {
6098            System.out.println(this + " requestFocus()");
6099        }
6100
6101        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6102            mPrivateFlags |= PFLAG_FOCUSED;
6103
6104            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6105
6106            if (mParent != null) {
6107                mParent.requestChildFocus(this, this);
6108            }
6109
6110            if (mAttachInfo != null) {
6111                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6112            }
6113
6114            onFocusChanged(true, direction, previouslyFocusedRect);
6115            refreshDrawableState();
6116        }
6117    }
6118
6119    /**
6120     * Sets this view's preference for reveal behavior when it gains focus.
6121     *
6122     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6123     * this view would prefer to be brought fully into view when it gains focus.
6124     * For example, a text field that a user is meant to type into. Other views such
6125     * as scrolling containers may prefer to opt-out of this behavior.</p>
6126     *
6127     * <p>The default value for views is true, though subclasses may change this
6128     * based on their preferred behavior.</p>
6129     *
6130     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6131     *
6132     * @see #getRevealOnFocusHint()
6133     */
6134    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6135        if (revealOnFocus) {
6136            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6137        } else {
6138            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6139        }
6140    }
6141
6142    /**
6143     * Returns this view's preference for reveal behavior when it gains focus.
6144     *
6145     * <p>When this method returns true for a child view requesting focus, ancestor
6146     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6147     * should make a best effort to make the newly focused child fully visible to the user.
6148     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6149     * other properties affecting visibility to the user as part of the focus change.</p>
6150     *
6151     * @return true if this view would prefer to become fully visible when it gains focus,
6152     *         false if it would prefer not to disrupt scroll positioning
6153     *
6154     * @see #setRevealOnFocusHint(boolean)
6155     */
6156    public final boolean getRevealOnFocusHint() {
6157        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6158    }
6159
6160    /**
6161     * Populates <code>outRect</code> with the hotspot bounds. By default,
6162     * the hotspot bounds are identical to the screen bounds.
6163     *
6164     * @param outRect rect to populate with hotspot bounds
6165     * @hide Only for internal use by views and widgets.
6166     */
6167    public void getHotspotBounds(Rect outRect) {
6168        final Drawable background = getBackground();
6169        if (background != null) {
6170            background.getHotspotBounds(outRect);
6171        } else {
6172            getBoundsOnScreen(outRect);
6173        }
6174    }
6175
6176    /**
6177     * Request that a rectangle of this view be visible on the screen,
6178     * scrolling if necessary just enough.
6179     *
6180     * <p>A View should call this if it maintains some notion of which part
6181     * of its content is interesting.  For example, a text editing view
6182     * should call this when its cursor moves.
6183     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6184     * It should not be affected by which part of the View is currently visible or its scroll
6185     * position.
6186     *
6187     * @param rectangle The rectangle in the View's content coordinate space
6188     * @return Whether any parent scrolled.
6189     */
6190    public boolean requestRectangleOnScreen(Rect rectangle) {
6191        return requestRectangleOnScreen(rectangle, false);
6192    }
6193
6194    /**
6195     * Request that a rectangle of this view be visible on the screen,
6196     * scrolling if necessary just enough.
6197     *
6198     * <p>A View should call this if it maintains some notion of which part
6199     * of its content is interesting.  For example, a text editing view
6200     * should call this when its cursor moves.
6201     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6202     * It should not be affected by which part of the View is currently visible or its scroll
6203     * position.
6204     * <p>When <code>immediate</code> is set to true, scrolling will not be
6205     * animated.
6206     *
6207     * @param rectangle The rectangle in the View's content coordinate space
6208     * @param immediate True to forbid animated scrolling, false otherwise
6209     * @return Whether any parent scrolled.
6210     */
6211    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6212        if (mParent == null) {
6213            return false;
6214        }
6215
6216        View child = this;
6217
6218        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6219        position.set(rectangle);
6220
6221        ViewParent parent = mParent;
6222        boolean scrolled = false;
6223        while (parent != null) {
6224            rectangle.set((int) position.left, (int) position.top,
6225                    (int) position.right, (int) position.bottom);
6226
6227            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6228
6229            if (!(parent instanceof View)) {
6230                break;
6231            }
6232
6233            // move it from child's content coordinate space to parent's content coordinate space
6234            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6235
6236            child = (View) parent;
6237            parent = child.getParent();
6238        }
6239
6240        return scrolled;
6241    }
6242
6243    /**
6244     * Called when this view wants to give up focus. If focus is cleared
6245     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6246     * <p>
6247     * <strong>Note:</strong> When a View clears focus the framework is trying
6248     * to give focus to the first focusable View from the top. Hence, if this
6249     * View is the first from the top that can take focus, then all callbacks
6250     * related to clearing focus will be invoked after which the framework will
6251     * give focus to this view.
6252     * </p>
6253     */
6254    public void clearFocus() {
6255        if (DBG) {
6256            System.out.println(this + " clearFocus()");
6257        }
6258
6259        clearFocusInternal(null, true, true);
6260    }
6261
6262    /**
6263     * Clears focus from the view, optionally propagating the change up through
6264     * the parent hierarchy and requesting that the root view place new focus.
6265     *
6266     * @param propagate whether to propagate the change up through the parent
6267     *            hierarchy
6268     * @param refocus when propagate is true, specifies whether to request the
6269     *            root view place new focus
6270     */
6271    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6272        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6273            mPrivateFlags &= ~PFLAG_FOCUSED;
6274
6275            if (propagate && mParent != null) {
6276                mParent.clearChildFocus(this);
6277            }
6278
6279            onFocusChanged(false, 0, null);
6280            refreshDrawableState();
6281
6282            if (propagate && (!refocus || !rootViewRequestFocus())) {
6283                notifyGlobalFocusCleared(this);
6284            }
6285        }
6286    }
6287
6288    void notifyGlobalFocusCleared(View oldFocus) {
6289        if (oldFocus != null && mAttachInfo != null) {
6290            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6291        }
6292    }
6293
6294    boolean rootViewRequestFocus() {
6295        final View root = getRootView();
6296        return root != null && root.requestFocus();
6297    }
6298
6299    /**
6300     * Called internally by the view system when a new view is getting focus.
6301     * This is what clears the old focus.
6302     * <p>
6303     * <b>NOTE:</b> The parent view's focused child must be updated manually
6304     * after calling this method. Otherwise, the view hierarchy may be left in
6305     * an inconstent state.
6306     */
6307    void unFocus(View focused) {
6308        if (DBG) {
6309            System.out.println(this + " unFocus()");
6310        }
6311
6312        clearFocusInternal(focused, false, false);
6313    }
6314
6315    /**
6316     * Returns true if this view has focus itself, or is the ancestor of the
6317     * view that has focus.
6318     *
6319     * @return True if this view has or contains focus, false otherwise.
6320     */
6321    @ViewDebug.ExportedProperty(category = "focus")
6322    public boolean hasFocus() {
6323        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6324    }
6325
6326    /**
6327     * Returns true if this view is focusable or if it contains a reachable View
6328     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6329     * is a View whose parents do not block descendants focus.
6330     *
6331     * Only {@link #VISIBLE} views are considered focusable.
6332     *
6333     * @return True if the view is focusable or if the view contains a focusable
6334     *         View, false otherwise.
6335     *
6336     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6337     * @see ViewGroup#getTouchscreenBlocksFocus()
6338     */
6339    public boolean hasFocusable() {
6340        if (!isFocusableInTouchMode()) {
6341            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6342                final ViewGroup g = (ViewGroup) p;
6343                if (g.shouldBlockFocusForTouchscreen()) {
6344                    return false;
6345                }
6346            }
6347        }
6348        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6349    }
6350
6351    /**
6352     * Called by the view system when the focus state of this view changes.
6353     * When the focus change event is caused by directional navigation, direction
6354     * and previouslyFocusedRect provide insight into where the focus is coming from.
6355     * When overriding, be sure to call up through to the super class so that
6356     * the standard focus handling will occur.
6357     *
6358     * @param gainFocus True if the View has focus; false otherwise.
6359     * @param direction The direction focus has moved when requestFocus()
6360     *                  is called to give this view focus. Values are
6361     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6362     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6363     *                  It may not always apply, in which case use the default.
6364     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6365     *        system, of the previously focused view.  If applicable, this will be
6366     *        passed in as finer grained information about where the focus is coming
6367     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6368     */
6369    @CallSuper
6370    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6371            @Nullable Rect previouslyFocusedRect) {
6372        if (gainFocus) {
6373            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6374        } else {
6375            notifyViewAccessibilityStateChangedIfNeeded(
6376                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6377        }
6378
6379        InputMethodManager imm = InputMethodManager.peekInstance();
6380        if (!gainFocus) {
6381            if (isPressed()) {
6382                setPressed(false);
6383            }
6384            if (imm != null && mAttachInfo != null
6385                    && mAttachInfo.mHasWindowFocus) {
6386                imm.focusOut(this);
6387            }
6388            onFocusLost();
6389        } else if (imm != null && mAttachInfo != null
6390                && mAttachInfo.mHasWindowFocus) {
6391            imm.focusIn(this);
6392        }
6393
6394        invalidate(true);
6395        ListenerInfo li = mListenerInfo;
6396        if (li != null && li.mOnFocusChangeListener != null) {
6397            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6398        }
6399
6400        if (mAttachInfo != null) {
6401            mAttachInfo.mKeyDispatchState.reset(this);
6402        }
6403    }
6404
6405    /**
6406     * Sends an accessibility event of the given type. If accessibility is
6407     * not enabled this method has no effect. The default implementation calls
6408     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6409     * to populate information about the event source (this View), then calls
6410     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6411     * populate the text content of the event source including its descendants,
6412     * and last calls
6413     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6414     * on its parent to request sending of the event to interested parties.
6415     * <p>
6416     * If an {@link AccessibilityDelegate} has been specified via calling
6417     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6418     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6419     * responsible for handling this call.
6420     * </p>
6421     *
6422     * @param eventType The type of the event to send, as defined by several types from
6423     * {@link android.view.accessibility.AccessibilityEvent}, such as
6424     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6425     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6426     *
6427     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6428     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6429     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6430     * @see AccessibilityDelegate
6431     */
6432    public void sendAccessibilityEvent(int eventType) {
6433        if (mAccessibilityDelegate != null) {
6434            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6435        } else {
6436            sendAccessibilityEventInternal(eventType);
6437        }
6438    }
6439
6440    /**
6441     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6442     * {@link AccessibilityEvent} to make an announcement which is related to some
6443     * sort of a context change for which none of the events representing UI transitions
6444     * is a good fit. For example, announcing a new page in a book. If accessibility
6445     * is not enabled this method does nothing.
6446     *
6447     * @param text The announcement text.
6448     */
6449    public void announceForAccessibility(CharSequence text) {
6450        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6451            AccessibilityEvent event = AccessibilityEvent.obtain(
6452                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6453            onInitializeAccessibilityEvent(event);
6454            event.getText().add(text);
6455            event.setContentDescription(null);
6456            mParent.requestSendAccessibilityEvent(this, event);
6457        }
6458    }
6459
6460    /**
6461     * @see #sendAccessibilityEvent(int)
6462     *
6463     * Note: Called from the default {@link AccessibilityDelegate}.
6464     *
6465     * @hide
6466     */
6467    public void sendAccessibilityEventInternal(int eventType) {
6468        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6469            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6470        }
6471    }
6472
6473    /**
6474     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6475     * takes as an argument an empty {@link AccessibilityEvent} and does not
6476     * perform a check whether accessibility is enabled.
6477     * <p>
6478     * If an {@link AccessibilityDelegate} has been specified via calling
6479     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6480     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6481     * is responsible for handling this call.
6482     * </p>
6483     *
6484     * @param event The event to send.
6485     *
6486     * @see #sendAccessibilityEvent(int)
6487     */
6488    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6489        if (mAccessibilityDelegate != null) {
6490            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6491        } else {
6492            sendAccessibilityEventUncheckedInternal(event);
6493        }
6494    }
6495
6496    /**
6497     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6498     *
6499     * Note: Called from the default {@link AccessibilityDelegate}.
6500     *
6501     * @hide
6502     */
6503    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6504        if (!isShown()) {
6505            return;
6506        }
6507        onInitializeAccessibilityEvent(event);
6508        // Only a subset of accessibility events populates text content.
6509        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6510            dispatchPopulateAccessibilityEvent(event);
6511        }
6512        // In the beginning we called #isShown(), so we know that getParent() is not null.
6513        getParent().requestSendAccessibilityEvent(this, event);
6514    }
6515
6516    /**
6517     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6518     * to its children for adding their text content to the event. Note that the
6519     * event text is populated in a separate dispatch path since we add to the
6520     * event not only the text of the source but also the text of all its descendants.
6521     * A typical implementation will call
6522     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6523     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6524     * on each child. Override this method if custom population of the event text
6525     * content is required.
6526     * <p>
6527     * If an {@link AccessibilityDelegate} has been specified via calling
6528     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6529     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6530     * is responsible for handling this call.
6531     * </p>
6532     * <p>
6533     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6534     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6535     * </p>
6536     *
6537     * @param event The event.
6538     *
6539     * @return True if the event population was completed.
6540     */
6541    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6542        if (mAccessibilityDelegate != null) {
6543            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6544        } else {
6545            return dispatchPopulateAccessibilityEventInternal(event);
6546        }
6547    }
6548
6549    /**
6550     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6551     *
6552     * Note: Called from the default {@link AccessibilityDelegate}.
6553     *
6554     * @hide
6555     */
6556    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6557        onPopulateAccessibilityEvent(event);
6558        return false;
6559    }
6560
6561    /**
6562     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6563     * giving a chance to this View to populate the accessibility event with its
6564     * text content. While this method is free to modify event
6565     * attributes other than text content, doing so should normally be performed in
6566     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6567     * <p>
6568     * Example: Adding formatted date string to an accessibility event in addition
6569     *          to the text added by the super implementation:
6570     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6571     *     super.onPopulateAccessibilityEvent(event);
6572     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6573     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6574     *         mCurrentDate.getTimeInMillis(), flags);
6575     *     event.getText().add(selectedDateUtterance);
6576     * }</pre>
6577     * <p>
6578     * If an {@link AccessibilityDelegate} has been specified via calling
6579     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6580     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6581     * is responsible for handling this call.
6582     * </p>
6583     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6584     * information to the event, in case the default implementation has basic information to add.
6585     * </p>
6586     *
6587     * @param event The accessibility event which to populate.
6588     *
6589     * @see #sendAccessibilityEvent(int)
6590     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6591     */
6592    @CallSuper
6593    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6594        if (mAccessibilityDelegate != null) {
6595            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6596        } else {
6597            onPopulateAccessibilityEventInternal(event);
6598        }
6599    }
6600
6601    /**
6602     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6603     *
6604     * Note: Called from the default {@link AccessibilityDelegate}.
6605     *
6606     * @hide
6607     */
6608    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6609    }
6610
6611    /**
6612     * Initializes an {@link AccessibilityEvent} with information about
6613     * this View which is the event source. In other words, the source of
6614     * an accessibility event is the view whose state change triggered firing
6615     * the event.
6616     * <p>
6617     * Example: Setting the password property of an event in addition
6618     *          to properties set by the super implementation:
6619     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6620     *     super.onInitializeAccessibilityEvent(event);
6621     *     event.setPassword(true);
6622     * }</pre>
6623     * <p>
6624     * If an {@link AccessibilityDelegate} has been specified via calling
6625     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6626     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6627     * is responsible for handling this call.
6628     * </p>
6629     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6630     * information to the event, in case the default implementation has basic information to add.
6631     * </p>
6632     * @param event The event to initialize.
6633     *
6634     * @see #sendAccessibilityEvent(int)
6635     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6636     */
6637    @CallSuper
6638    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6639        if (mAccessibilityDelegate != null) {
6640            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6641        } else {
6642            onInitializeAccessibilityEventInternal(event);
6643        }
6644    }
6645
6646    /**
6647     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6648     *
6649     * Note: Called from the default {@link AccessibilityDelegate}.
6650     *
6651     * @hide
6652     */
6653    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6654        event.setSource(this);
6655        event.setClassName(getAccessibilityClassName());
6656        event.setPackageName(getContext().getPackageName());
6657        event.setEnabled(isEnabled());
6658        event.setContentDescription(mContentDescription);
6659
6660        switch (event.getEventType()) {
6661            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6662                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6663                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6664                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6665                event.setItemCount(focusablesTempList.size());
6666                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6667                if (mAttachInfo != null) {
6668                    focusablesTempList.clear();
6669                }
6670            } break;
6671            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6672                CharSequence text = getIterableTextForAccessibility();
6673                if (text != null && text.length() > 0) {
6674                    event.setFromIndex(getAccessibilitySelectionStart());
6675                    event.setToIndex(getAccessibilitySelectionEnd());
6676                    event.setItemCount(text.length());
6677                }
6678            } break;
6679        }
6680    }
6681
6682    /**
6683     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6684     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6685     * This method is responsible for obtaining an accessibility node info from a
6686     * pool of reusable instances and calling
6687     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6688     * initialize the former.
6689     * <p>
6690     * Note: The client is responsible for recycling the obtained instance by calling
6691     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6692     * </p>
6693     *
6694     * @return A populated {@link AccessibilityNodeInfo}.
6695     *
6696     * @see AccessibilityNodeInfo
6697     */
6698    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6699        if (mAccessibilityDelegate != null) {
6700            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6701        } else {
6702            return createAccessibilityNodeInfoInternal();
6703        }
6704    }
6705
6706    /**
6707     * @see #createAccessibilityNodeInfo()
6708     *
6709     * @hide
6710     */
6711    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6712        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6713        if (provider != null) {
6714            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6715        } else {
6716            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6717            onInitializeAccessibilityNodeInfo(info);
6718            return info;
6719        }
6720    }
6721
6722    /**
6723     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6724     * The base implementation sets:
6725     * <ul>
6726     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6727     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6728     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6729     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6730     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6731     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6732     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6733     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6734     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6735     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6736     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6737     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6738     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6739     * </ul>
6740     * <p>
6741     * Subclasses should override this method, call the super implementation,
6742     * and set additional attributes.
6743     * </p>
6744     * <p>
6745     * If an {@link AccessibilityDelegate} has been specified via calling
6746     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6747     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6748     * is responsible for handling this call.
6749     * </p>
6750     *
6751     * @param info The instance to initialize.
6752     */
6753    @CallSuper
6754    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6755        if (mAccessibilityDelegate != null) {
6756            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6757        } else {
6758            onInitializeAccessibilityNodeInfoInternal(info);
6759        }
6760    }
6761
6762    /**
6763     * Gets the location of this view in screen coordinates.
6764     *
6765     * @param outRect The output location
6766     * @hide
6767     */
6768    public void getBoundsOnScreen(Rect outRect) {
6769        getBoundsOnScreen(outRect, false);
6770    }
6771
6772    /**
6773     * Gets the location of this view in screen coordinates.
6774     *
6775     * @param outRect The output location
6776     * @param clipToParent Whether to clip child bounds to the parent ones.
6777     * @hide
6778     */
6779    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6780        if (mAttachInfo == null) {
6781            return;
6782        }
6783
6784        RectF position = mAttachInfo.mTmpTransformRect;
6785        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6786
6787        if (!hasIdentityMatrix()) {
6788            getMatrix().mapRect(position);
6789        }
6790
6791        position.offset(mLeft, mTop);
6792
6793        ViewParent parent = mParent;
6794        while (parent instanceof View) {
6795            View parentView = (View) parent;
6796
6797            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6798
6799            if (clipToParent) {
6800                position.left = Math.max(position.left, 0);
6801                position.top = Math.max(position.top, 0);
6802                position.right = Math.min(position.right, parentView.getWidth());
6803                position.bottom = Math.min(position.bottom, parentView.getHeight());
6804            }
6805
6806            if (!parentView.hasIdentityMatrix()) {
6807                parentView.getMatrix().mapRect(position);
6808            }
6809
6810            position.offset(parentView.mLeft, parentView.mTop);
6811
6812            parent = parentView.mParent;
6813        }
6814
6815        if (parent instanceof ViewRootImpl) {
6816            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6817            position.offset(0, -viewRootImpl.mCurScrollY);
6818        }
6819
6820        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6821
6822        outRect.set(Math.round(position.left), Math.round(position.top),
6823                Math.round(position.right), Math.round(position.bottom));
6824    }
6825
6826    /**
6827     * Return the class name of this object to be used for accessibility purposes.
6828     * Subclasses should only override this if they are implementing something that
6829     * should be seen as a completely new class of view when used by accessibility,
6830     * unrelated to the class it is deriving from.  This is used to fill in
6831     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6832     */
6833    public CharSequence getAccessibilityClassName() {
6834        return View.class.getName();
6835    }
6836
6837    /**
6838     * Called when assist structure is being retrieved from a view as part of
6839     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6840     * @param structure Fill in with structured view data.  The default implementation
6841     * fills in all data that can be inferred from the view itself.
6842     *
6843     * @deprecated As of API O sub-classes should override
6844     * {@link #onProvideStructure(ViewStructure, int)} instead.
6845     */
6846    // TODO(b/33197203): set proper API above
6847    @Deprecated
6848    public void onProvideStructure(ViewStructure structure) {
6849        onProvideStructure(structure, 0);
6850    }
6851
6852    /**
6853     * Called when assist structure is being retrieved from a view as part of
6854     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} or as part
6855     * of an auto-fill request.
6856     *
6857     * <p>The default implementation fills in all data that can be inferred from the view itself.
6858     *
6859     * <p>The structure must be filled according to the request type, which is set in the
6860     * {@code flags} parameter - see the documentation on each flag for more details.
6861     *
6862     * @param structure Fill in with structured view data. The default implementation
6863     * fills in all data that can be inferred from the view itself.
6864     * @param flags optional flags (see {@link #ASSIST_FLAG_SANITIZED_TEXT} and
6865     * {@link #ASSIST_FLAG_NON_SANITIZED_TEXT} for more info).
6866     */
6867    public void onProvideStructure(ViewStructure structure, int flags) {
6868        boolean forAutoFill = (flags
6869                & (View.ASSIST_FLAG_SANITIZED_TEXT
6870                        | View.ASSIST_FLAG_NON_SANITIZED_TEXT)) != 0;
6871        final int id = mID;
6872        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6873                && (id&0x0000ffff) != 0) {
6874            String pkg, type, entry;
6875            try {
6876                final Resources res = getResources();
6877                entry = res.getResourceEntryName(id);
6878                type = res.getResourceTypeName(id);
6879                pkg = res.getResourcePackageName(id);
6880            } catch (Resources.NotFoundException e) {
6881                entry = type = pkg = null;
6882            }
6883            structure.setId(id, pkg, type, entry);
6884        } else {
6885            structure.setId(id, null, null, null);
6886        }
6887
6888        if (forAutoFill) {
6889            // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to
6890            // reuse the accessibility id to save space.
6891            structure.setAutoFillId(getAccessibilityViewId());
6892        }
6893
6894        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6895        if (!hasIdentityMatrix()) {
6896            structure.setTransformation(getMatrix());
6897        }
6898        structure.setElevation(getZ());
6899        structure.setVisibility(getVisibility());
6900        structure.setEnabled(isEnabled());
6901        if (isClickable()) {
6902            structure.setClickable(true);
6903        }
6904        if (isFocusable()) {
6905            structure.setFocusable(true);
6906        }
6907        if (isFocused()) {
6908            structure.setFocused(true);
6909        }
6910        if (isAccessibilityFocused()) {
6911            structure.setAccessibilityFocused(true);
6912        }
6913        if (isSelected()) {
6914            structure.setSelected(true);
6915        }
6916        if (isActivated()) {
6917            structure.setActivated(true);
6918        }
6919        if (isLongClickable()) {
6920            structure.setLongClickable(true);
6921        }
6922        if (this instanceof Checkable) {
6923            structure.setCheckable(true);
6924            if (((Checkable)this).isChecked()) {
6925                structure.setChecked(true);
6926            }
6927        }
6928        if (isContextClickable()) {
6929            structure.setContextClickable(true);
6930        }
6931        structure.setClassName(getAccessibilityClassName().toString());
6932        structure.setContentDescription(getContentDescription());
6933    }
6934
6935    /**
6936     * Called when assist structure is being retrieved from a view as part of
6937     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6938     * generate additional virtual structure under this view.  The defaullt implementation
6939     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6940     * view's virtual accessibility nodes, if any.  You can override this for a more
6941     * optimal implementation providing this data.
6942     *
6943     * @deprecated As of API O, sub-classes should override
6944     * {@link #onProvideVirtualStructure(ViewStructure, int)} instead.
6945     */
6946    // TODO(b/33197203): set proper API above
6947    @Deprecated
6948    public void onProvideVirtualStructure(ViewStructure structure) {
6949        onProvideVirtualStructure(structure, 0);
6950    }
6951
6952    /**
6953     * Called when assist structure is being retrieved from a view as part of
6954     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} or as part
6955     * of an auto-fill request to generate additional virtual structure under this view.
6956     *
6957     * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to
6958     * generate this from the view's virtual accessibility nodes, if any.  You can override this
6959     * for a more optimal implementation providing this data.
6960     *
6961     * <p>The structure must be filled according to the request type, which is set in the
6962     * {@code flags} parameter - see the documentation on each flag for more details.
6963     *
6964     * @param structure Fill in with structured view data.
6965     * @param flags optional flags (see {@link #ASSIST_FLAG_SANITIZED_TEXT} and
6966     * {@link #ASSIST_FLAG_NON_SANITIZED_TEXT} for more info).
6967     */
6968    public void onProvideVirtualStructure(ViewStructure structure, int flags) {
6969        boolean sanitize = (flags & View.ASSIST_FLAG_SANITIZED_TEXT) != 0;
6970
6971        if (sanitize) {
6972            // TODO(b/33197203): change populateVirtualStructure so it sanitizes data in this case.
6973            return;
6974        }
6975
6976        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6977        if (provider != null) {
6978            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6979            structure.setChildCount(1);
6980            ViewStructure root = structure.newChild(0);
6981            populateVirtualStructure(root, provider, info, flags);
6982            info.recycle();
6983        }
6984    }
6985
6986    private void populateVirtualStructure(ViewStructure structure,
6987            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) {
6988        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6989                null, null, null);
6990        Rect rect = structure.getTempRect();
6991        info.getBoundsInParent(rect);
6992        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6993        structure.setVisibility(VISIBLE);
6994        structure.setEnabled(info.isEnabled());
6995        if (info.isClickable()) {
6996            structure.setClickable(true);
6997        }
6998        if (info.isFocusable()) {
6999            structure.setFocusable(true);
7000        }
7001        if (info.isFocused()) {
7002            structure.setFocused(true);
7003        }
7004        if (info.isAccessibilityFocused()) {
7005            structure.setAccessibilityFocused(true);
7006        }
7007        if (info.isSelected()) {
7008            structure.setSelected(true);
7009        }
7010        if (info.isLongClickable()) {
7011            structure.setLongClickable(true);
7012        }
7013        if (info.isCheckable()) {
7014            structure.setCheckable(true);
7015            if (info.isChecked()) {
7016                structure.setChecked(true);
7017            }
7018        }
7019        if (info.isContextClickable()) {
7020            structure.setContextClickable(true);
7021        }
7022        CharSequence cname = info.getClassName();
7023        structure.setClassName(cname != null ? cname.toString() : null);
7024        structure.setContentDescription(info.getContentDescription());
7025        if (info.getText() != null || info.getError() != null) {
7026            structure.setText(info.getText(), info.getTextSelectionStart(),
7027                    info.getTextSelectionEnd());
7028        }
7029        final int NCHILDREN = info.getChildCount();
7030        if (NCHILDREN > 0) {
7031            structure.setChildCount(NCHILDREN);
7032            for (int i=0; i<NCHILDREN; i++) {
7033                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7034                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7035                ViewStructure child = structure.newChild(i);
7036                populateVirtualStructure(child, provider, cinfo, flags);
7037                cinfo.recycle();
7038            }
7039        }
7040    }
7041
7042    /**
7043     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7044     * implementation calls {@link #onProvideStructure} and
7045     * {@link #onProvideVirtualStructure}.
7046     *
7047     * @deprecated As of API O,  sub-classes should override
7048     * {@link #dispatchProvideStructure(ViewStructure, int)} instead.
7049     */
7050    // TODO(b/33197203): set proper API above
7051    @Deprecated
7052    public void dispatchProvideStructure(ViewStructure structure) {
7053        dispatchProvideStructure(structure, 0);
7054    }
7055
7056    /**
7057     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7058     *
7059     * <p>The structure must be filled according to the request type, which is set in the
7060     * {@code flags} parameter - see the documentation on each flag for more details.
7061     *
7062     * <p>The default implementation calls {@link #onProvideStructure(ViewStructure, int)} and
7063     * {@link #onProvideVirtualStructure(ViewStructure, int)}.
7064     *
7065     * @param structure Fill in with structured view data.
7066     * @param flags optional flags (see {@link #ASSIST_FLAG_SANITIZED_TEXT} and
7067     * {@link #ASSIST_FLAG_NON_SANITIZED_TEXT} for more info).
7068     */
7069    public void dispatchProvideStructure(ViewStructure structure, int flags) {
7070        boolean forAutoFill = (flags
7071                & (View.ASSIST_FLAG_SANITIZED_TEXT
7072                        | View.ASSIST_FLAG_NON_SANITIZED_TEXT)) != 0;
7073
7074        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7075        if (!blocked) {
7076            onProvideStructure(structure, flags);
7077            onProvideVirtualStructure(structure, flags);
7078        } else {
7079            structure.setClassName(getAccessibilityClassName().toString());
7080            structure.setAssistBlocked(true);
7081        }
7082    }
7083
7084    /**
7085     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7086     *
7087     * Note: Called from the default {@link AccessibilityDelegate}.
7088     *
7089     * @hide
7090     */
7091    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7092        if (mAttachInfo == null) {
7093            return;
7094        }
7095
7096        Rect bounds = mAttachInfo.mTmpInvalRect;
7097
7098        getDrawingRect(bounds);
7099        info.setBoundsInParent(bounds);
7100
7101        getBoundsOnScreen(bounds, true);
7102        info.setBoundsInScreen(bounds);
7103
7104        ViewParent parent = getParentForAccessibility();
7105        if (parent instanceof View) {
7106            info.setParent((View) parent);
7107        }
7108
7109        if (mID != View.NO_ID) {
7110            View rootView = getRootView();
7111            if (rootView == null) {
7112                rootView = this;
7113            }
7114
7115            View label = rootView.findLabelForView(this, mID);
7116            if (label != null) {
7117                info.setLabeledBy(label);
7118            }
7119
7120            if ((mAttachInfo.mAccessibilityFetchFlags
7121                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7122                    && Resources.resourceHasPackage(mID)) {
7123                try {
7124                    String viewId = getResources().getResourceName(mID);
7125                    info.setViewIdResourceName(viewId);
7126                } catch (Resources.NotFoundException nfe) {
7127                    /* ignore */
7128                }
7129            }
7130        }
7131
7132        if (mLabelForId != View.NO_ID) {
7133            View rootView = getRootView();
7134            if (rootView == null) {
7135                rootView = this;
7136            }
7137            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7138            if (labeled != null) {
7139                info.setLabelFor(labeled);
7140            }
7141        }
7142
7143        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7144            View rootView = getRootView();
7145            if (rootView == null) {
7146                rootView = this;
7147            }
7148            View next = rootView.findViewInsideOutShouldExist(this,
7149                    mAccessibilityTraversalBeforeId);
7150            if (next != null && next.includeForAccessibility()) {
7151                info.setTraversalBefore(next);
7152            }
7153        }
7154
7155        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7156            View rootView = getRootView();
7157            if (rootView == null) {
7158                rootView = this;
7159            }
7160            View next = rootView.findViewInsideOutShouldExist(this,
7161                    mAccessibilityTraversalAfterId);
7162            if (next != null && next.includeForAccessibility()) {
7163                info.setTraversalAfter(next);
7164            }
7165        }
7166
7167        info.setVisibleToUser(isVisibleToUser());
7168
7169        info.setImportantForAccessibility(isImportantForAccessibility());
7170        info.setPackageName(mContext.getPackageName());
7171        info.setClassName(getAccessibilityClassName());
7172        info.setContentDescription(getContentDescription());
7173
7174        info.setEnabled(isEnabled());
7175        info.setClickable(isClickable());
7176        info.setFocusable(isFocusable());
7177        info.setFocused(isFocused());
7178        info.setAccessibilityFocused(isAccessibilityFocused());
7179        info.setSelected(isSelected());
7180        info.setLongClickable(isLongClickable());
7181        info.setContextClickable(isContextClickable());
7182        info.setLiveRegion(getAccessibilityLiveRegion());
7183
7184        // TODO: These make sense only if we are in an AdapterView but all
7185        // views can be selected. Maybe from accessibility perspective
7186        // we should report as selectable view in an AdapterView.
7187        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7188        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7189
7190        if (isFocusable()) {
7191            if (isFocused()) {
7192                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7193            } else {
7194                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7195            }
7196        }
7197
7198        if (!isAccessibilityFocused()) {
7199            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7200        } else {
7201            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7202        }
7203
7204        if (isClickable() && isEnabled()) {
7205            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7206        }
7207
7208        if (isLongClickable() && isEnabled()) {
7209            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7210        }
7211
7212        if (isContextClickable() && isEnabled()) {
7213            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7214        }
7215
7216        CharSequence text = getIterableTextForAccessibility();
7217        if (text != null && text.length() > 0) {
7218            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7219
7220            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7221            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7222            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7223            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7224                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7225                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7226        }
7227
7228        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7229        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7230    }
7231
7232    /**
7233     * Determine the order in which this view will be drawn relative to its siblings for a11y
7234     *
7235     * @param info The info whose drawing order should be populated
7236     */
7237    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7238        /*
7239         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7240         * drawing order may not be well-defined, and some Views with custom drawing order may
7241         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7242         */
7243        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7244            info.setDrawingOrder(0);
7245            return;
7246        }
7247        int drawingOrderInParent = 1;
7248        // Iterate up the hierarchy if parents are not important for a11y
7249        View viewAtDrawingLevel = this;
7250        final ViewParent parent = getParentForAccessibility();
7251        while (viewAtDrawingLevel != parent) {
7252            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7253            if (!(currentParent instanceof ViewGroup)) {
7254                // Should only happen for the Decor
7255                drawingOrderInParent = 0;
7256                break;
7257            } else {
7258                final ViewGroup parentGroup = (ViewGroup) currentParent;
7259                final int childCount = parentGroup.getChildCount();
7260                if (childCount > 1) {
7261                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7262                    if (preorderedList != null) {
7263                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7264                        for (int i = 0; i < childDrawIndex; i++) {
7265                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7266                        }
7267                    } else {
7268                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7269                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7270                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7271                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7272                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7273                        if (childDrawIndex != 0) {
7274                            for (int i = 0; i < numChildrenToIterate; i++) {
7275                                final int otherDrawIndex = (customOrder ?
7276                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7277                                if (otherDrawIndex < childDrawIndex) {
7278                                    drawingOrderInParent +=
7279                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7280                                }
7281                            }
7282                        }
7283                    }
7284                }
7285            }
7286            viewAtDrawingLevel = (View) currentParent;
7287        }
7288        info.setDrawingOrder(drawingOrderInParent);
7289    }
7290
7291    private static int numViewsForAccessibility(View view) {
7292        if (view != null) {
7293            if (view.includeForAccessibility()) {
7294                return 1;
7295            } else if (view instanceof ViewGroup) {
7296                return ((ViewGroup) view).getNumChildrenForAccessibility();
7297            }
7298        }
7299        return 0;
7300    }
7301
7302    private View findLabelForView(View view, int labeledId) {
7303        if (mMatchLabelForPredicate == null) {
7304            mMatchLabelForPredicate = new MatchLabelForPredicate();
7305        }
7306        mMatchLabelForPredicate.mLabeledId = labeledId;
7307        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7308    }
7309
7310    /**
7311     * Computes whether this view is visible to the user. Such a view is
7312     * attached, visible, all its predecessors are visible, it is not clipped
7313     * entirely by its predecessors, and has an alpha greater than zero.
7314     *
7315     * @return Whether the view is visible on the screen.
7316     *
7317     * @hide
7318     */
7319    protected boolean isVisibleToUser() {
7320        return isVisibleToUser(null);
7321    }
7322
7323    /**
7324     * Computes whether the given portion of this view is visible to the user.
7325     * Such a view is attached, visible, all its predecessors are visible,
7326     * has an alpha greater than zero, and the specified portion is not
7327     * clipped entirely by its predecessors.
7328     *
7329     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7330     *                    <code>null</code>, and the entire view will be tested in this case.
7331     *                    When <code>true</code> is returned by the function, the actual visible
7332     *                    region will be stored in this parameter; that is, if boundInView is fully
7333     *                    contained within the view, no modification will be made, otherwise regions
7334     *                    outside of the visible area of the view will be clipped.
7335     *
7336     * @return Whether the specified portion of the view is visible on the screen.
7337     *
7338     * @hide
7339     */
7340    protected boolean isVisibleToUser(Rect boundInView) {
7341        if (mAttachInfo != null) {
7342            // Attached to invisible window means this view is not visible.
7343            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7344                return false;
7345            }
7346            // An invisible predecessor or one with alpha zero means
7347            // that this view is not visible to the user.
7348            Object current = this;
7349            while (current instanceof View) {
7350                View view = (View) current;
7351                // We have attach info so this view is attached and there is no
7352                // need to check whether we reach to ViewRootImpl on the way up.
7353                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7354                        view.getVisibility() != VISIBLE) {
7355                    return false;
7356                }
7357                current = view.mParent;
7358            }
7359            // Check if the view is entirely covered by its predecessors.
7360            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7361            Point offset = mAttachInfo.mPoint;
7362            if (!getGlobalVisibleRect(visibleRect, offset)) {
7363                return false;
7364            }
7365            // Check if the visible portion intersects the rectangle of interest.
7366            if (boundInView != null) {
7367                visibleRect.offset(-offset.x, -offset.y);
7368                return boundInView.intersect(visibleRect);
7369            }
7370            return true;
7371        }
7372        return false;
7373    }
7374
7375    /**
7376     * Returns the delegate for implementing accessibility support via
7377     * composition. For more details see {@link AccessibilityDelegate}.
7378     *
7379     * @return The delegate, or null if none set.
7380     *
7381     * @hide
7382     */
7383    public AccessibilityDelegate getAccessibilityDelegate() {
7384        return mAccessibilityDelegate;
7385    }
7386
7387    /**
7388     * Sets a delegate for implementing accessibility support via composition
7389     * (as opposed to inheritance). For more details, see
7390     * {@link AccessibilityDelegate}.
7391     * <p>
7392     * <strong>Note:</strong> On platform versions prior to
7393     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7394     * views in the {@code android.widget.*} package are called <i>before</i>
7395     * host methods. This prevents certain properties such as class name from
7396     * being modified by overriding
7397     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7398     * as any changes will be overwritten by the host class.
7399     * <p>
7400     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7401     * methods are called <i>after</i> host methods, which all properties to be
7402     * modified without being overwritten by the host class.
7403     *
7404     * @param delegate the object to which accessibility method calls should be
7405     *                 delegated
7406     * @see AccessibilityDelegate
7407     */
7408    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7409        mAccessibilityDelegate = delegate;
7410    }
7411
7412    /**
7413     * Gets the provider for managing a virtual view hierarchy rooted at this View
7414     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7415     * that explore the window content.
7416     * <p>
7417     * If this method returns an instance, this instance is responsible for managing
7418     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7419     * View including the one representing the View itself. Similarly the returned
7420     * instance is responsible for performing accessibility actions on any virtual
7421     * view or the root view itself.
7422     * </p>
7423     * <p>
7424     * If an {@link AccessibilityDelegate} has been specified via calling
7425     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7426     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7427     * is responsible for handling this call.
7428     * </p>
7429     *
7430     * @return The provider.
7431     *
7432     * @see AccessibilityNodeProvider
7433     */
7434    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7435        if (mAccessibilityDelegate != null) {
7436            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7437        } else {
7438            return null;
7439        }
7440    }
7441
7442    /**
7443     * Gets the unique identifier of this view on the screen for accessibility purposes.
7444     *
7445     * @return The view accessibility id.
7446     *
7447     * @hide
7448     */
7449    public int getAccessibilityViewId() {
7450        if (mAccessibilityViewId == NO_ID) {
7451            mAccessibilityViewId = sNextAccessibilityViewId++;
7452        }
7453        return mAccessibilityViewId;
7454    }
7455
7456    /**
7457     * Gets the unique identifier of the window in which this View reseides.
7458     *
7459     * @return The window accessibility id.
7460     *
7461     * @hide
7462     */
7463    public int getAccessibilityWindowId() {
7464        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7465                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7466    }
7467
7468    /**
7469     * Returns the {@link View}'s content description.
7470     * <p>
7471     * <strong>Note:</strong> Do not override this method, as it will have no
7472     * effect on the content description presented to accessibility services.
7473     * You must call {@link #setContentDescription(CharSequence)} to modify the
7474     * content description.
7475     *
7476     * @return the content description
7477     * @see #setContentDescription(CharSequence)
7478     * @attr ref android.R.styleable#View_contentDescription
7479     */
7480    @ViewDebug.ExportedProperty(category = "accessibility")
7481    public CharSequence getContentDescription() {
7482        return mContentDescription;
7483    }
7484
7485    /**
7486     * Sets the {@link View}'s content description.
7487     * <p>
7488     * A content description briefly describes the view and is primarily used
7489     * for accessibility support to determine how a view should be presented to
7490     * the user. In the case of a view with no textual representation, such as
7491     * {@link android.widget.ImageButton}, a useful content description
7492     * explains what the view does. For example, an image button with a phone
7493     * icon that is used to place a call may use "Call" as its content
7494     * description. An image of a floppy disk that is used to save a file may
7495     * use "Save".
7496     *
7497     * @param contentDescription The content description.
7498     * @see #getContentDescription()
7499     * @attr ref android.R.styleable#View_contentDescription
7500     */
7501    @RemotableViewMethod
7502    public void setContentDescription(CharSequence contentDescription) {
7503        if (mContentDescription == null) {
7504            if (contentDescription == null) {
7505                return;
7506            }
7507        } else if (mContentDescription.equals(contentDescription)) {
7508            return;
7509        }
7510        mContentDescription = contentDescription;
7511        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7512        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7513            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7514            notifySubtreeAccessibilityStateChangedIfNeeded();
7515        } else {
7516            notifyViewAccessibilityStateChangedIfNeeded(
7517                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7518        }
7519    }
7520
7521    /**
7522     * Sets the id of a view before which this one is visited in accessibility traversal.
7523     * A screen-reader must visit the content of this view before the content of the one
7524     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7525     * will traverse the entire content of B before traversing the entire content of A,
7526     * regardles of what traversal strategy it is using.
7527     * <p>
7528     * Views that do not have specified before/after relationships are traversed in order
7529     * determined by the screen-reader.
7530     * </p>
7531     * <p>
7532     * Setting that this view is before a view that is not important for accessibility
7533     * or if this view is not important for accessibility will have no effect as the
7534     * screen-reader is not aware of unimportant views.
7535     * </p>
7536     *
7537     * @param beforeId The id of a view this one precedes in accessibility traversal.
7538     *
7539     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7540     *
7541     * @see #setImportantForAccessibility(int)
7542     */
7543    @RemotableViewMethod
7544    public void setAccessibilityTraversalBefore(int beforeId) {
7545        if (mAccessibilityTraversalBeforeId == beforeId) {
7546            return;
7547        }
7548        mAccessibilityTraversalBeforeId = beforeId;
7549        notifyViewAccessibilityStateChangedIfNeeded(
7550                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7551    }
7552
7553    /**
7554     * Gets the id of a view before which this one is visited in accessibility traversal.
7555     *
7556     * @return The id of a view this one precedes in accessibility traversal if
7557     *         specified, otherwise {@link #NO_ID}.
7558     *
7559     * @see #setAccessibilityTraversalBefore(int)
7560     */
7561    public int getAccessibilityTraversalBefore() {
7562        return mAccessibilityTraversalBeforeId;
7563    }
7564
7565    /**
7566     * Sets the id of a view after which this one is visited in accessibility traversal.
7567     * A screen-reader must visit the content of the other view before the content of this
7568     * one. For example, if view B is set to be after view A, then a screen-reader
7569     * will traverse the entire content of A before traversing the entire content of B,
7570     * regardles of what traversal strategy it is using.
7571     * <p>
7572     * Views that do not have specified before/after relationships are traversed in order
7573     * determined by the screen-reader.
7574     * </p>
7575     * <p>
7576     * Setting that this view is after a view that is not important for accessibility
7577     * or if this view is not important for accessibility will have no effect as the
7578     * screen-reader is not aware of unimportant views.
7579     * </p>
7580     *
7581     * @param afterId The id of a view this one succedees in accessibility traversal.
7582     *
7583     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7584     *
7585     * @see #setImportantForAccessibility(int)
7586     */
7587    @RemotableViewMethod
7588    public void setAccessibilityTraversalAfter(int afterId) {
7589        if (mAccessibilityTraversalAfterId == afterId) {
7590            return;
7591        }
7592        mAccessibilityTraversalAfterId = afterId;
7593        notifyViewAccessibilityStateChangedIfNeeded(
7594                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7595    }
7596
7597    /**
7598     * Gets the id of a view after which this one is visited in accessibility traversal.
7599     *
7600     * @return The id of a view this one succeedes in accessibility traversal if
7601     *         specified, otherwise {@link #NO_ID}.
7602     *
7603     * @see #setAccessibilityTraversalAfter(int)
7604     */
7605    public int getAccessibilityTraversalAfter() {
7606        return mAccessibilityTraversalAfterId;
7607    }
7608
7609    /**
7610     * Gets the id of a view for which this view serves as a label for
7611     * accessibility purposes.
7612     *
7613     * @return The labeled view id.
7614     */
7615    @ViewDebug.ExportedProperty(category = "accessibility")
7616    public int getLabelFor() {
7617        return mLabelForId;
7618    }
7619
7620    /**
7621     * Sets the id of a view for which this view serves as a label for
7622     * accessibility purposes.
7623     *
7624     * @param id The labeled view id.
7625     */
7626    @RemotableViewMethod
7627    public void setLabelFor(@IdRes int id) {
7628        if (mLabelForId == id) {
7629            return;
7630        }
7631        mLabelForId = id;
7632        if (mLabelForId != View.NO_ID
7633                && mID == View.NO_ID) {
7634            mID = generateViewId();
7635        }
7636        notifyViewAccessibilityStateChangedIfNeeded(
7637                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7638    }
7639
7640    /**
7641     * Invoked whenever this view loses focus, either by losing window focus or by losing
7642     * focus within its window. This method can be used to clear any state tied to the
7643     * focus. For instance, if a button is held pressed with the trackball and the window
7644     * loses focus, this method can be used to cancel the press.
7645     *
7646     * Subclasses of View overriding this method should always call super.onFocusLost().
7647     *
7648     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7649     * @see #onWindowFocusChanged(boolean)
7650     *
7651     * @hide pending API council approval
7652     */
7653    @CallSuper
7654    protected void onFocusLost() {
7655        resetPressedState();
7656    }
7657
7658    private void resetPressedState() {
7659        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7660            return;
7661        }
7662
7663        if (isPressed()) {
7664            setPressed(false);
7665
7666            if (!mHasPerformedLongPress) {
7667                removeLongPressCallback();
7668            }
7669        }
7670    }
7671
7672    /**
7673     * Returns true if this view has focus
7674     *
7675     * @return True if this view has focus, false otherwise.
7676     */
7677    @ViewDebug.ExportedProperty(category = "focus")
7678    public boolean isFocused() {
7679        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7680    }
7681
7682    /**
7683     * Find the view in the hierarchy rooted at this view that currently has
7684     * focus.
7685     *
7686     * @return The view that currently has focus, or null if no focused view can
7687     *         be found.
7688     */
7689    public View findFocus() {
7690        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7691    }
7692
7693    /**
7694     * Indicates whether this view is one of the set of scrollable containers in
7695     * its window.
7696     *
7697     * @return whether this view is one of the set of scrollable containers in
7698     * its window
7699     *
7700     * @attr ref android.R.styleable#View_isScrollContainer
7701     */
7702    public boolean isScrollContainer() {
7703        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7704    }
7705
7706    /**
7707     * Change whether this view is one of the set of scrollable containers in
7708     * its window.  This will be used to determine whether the window can
7709     * resize or must pan when a soft input area is open -- scrollable
7710     * containers allow the window to use resize mode since the container
7711     * will appropriately shrink.
7712     *
7713     * @attr ref android.R.styleable#View_isScrollContainer
7714     */
7715    public void setScrollContainer(boolean isScrollContainer) {
7716        if (isScrollContainer) {
7717            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7718                mAttachInfo.mScrollContainers.add(this);
7719                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7720            }
7721            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7722        } else {
7723            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7724                mAttachInfo.mScrollContainers.remove(this);
7725            }
7726            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7727        }
7728    }
7729
7730    /**
7731     * Returns the quality of the drawing cache.
7732     *
7733     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7734     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7735     *
7736     * @see #setDrawingCacheQuality(int)
7737     * @see #setDrawingCacheEnabled(boolean)
7738     * @see #isDrawingCacheEnabled()
7739     *
7740     * @attr ref android.R.styleable#View_drawingCacheQuality
7741     */
7742    @DrawingCacheQuality
7743    public int getDrawingCacheQuality() {
7744        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7745    }
7746
7747    /**
7748     * Set the drawing cache quality of this view. This value is used only when the
7749     * drawing cache is enabled
7750     *
7751     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7752     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7753     *
7754     * @see #getDrawingCacheQuality()
7755     * @see #setDrawingCacheEnabled(boolean)
7756     * @see #isDrawingCacheEnabled()
7757     *
7758     * @attr ref android.R.styleable#View_drawingCacheQuality
7759     */
7760    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7761        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7762    }
7763
7764    /**
7765     * Returns whether the screen should remain on, corresponding to the current
7766     * value of {@link #KEEP_SCREEN_ON}.
7767     *
7768     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7769     *
7770     * @see #setKeepScreenOn(boolean)
7771     *
7772     * @attr ref android.R.styleable#View_keepScreenOn
7773     */
7774    public boolean getKeepScreenOn() {
7775        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7776    }
7777
7778    /**
7779     * Controls whether the screen should remain on, modifying the
7780     * value of {@link #KEEP_SCREEN_ON}.
7781     *
7782     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7783     *
7784     * @see #getKeepScreenOn()
7785     *
7786     * @attr ref android.R.styleable#View_keepScreenOn
7787     */
7788    public void setKeepScreenOn(boolean keepScreenOn) {
7789        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7790    }
7791
7792    /**
7793     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7794     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7795     *
7796     * @attr ref android.R.styleable#View_nextFocusLeft
7797     */
7798    public int getNextFocusLeftId() {
7799        return mNextFocusLeftId;
7800    }
7801
7802    /**
7803     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7804     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7805     * decide automatically.
7806     *
7807     * @attr ref android.R.styleable#View_nextFocusLeft
7808     */
7809    public void setNextFocusLeftId(int nextFocusLeftId) {
7810        mNextFocusLeftId = nextFocusLeftId;
7811    }
7812
7813    /**
7814     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7815     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7816     *
7817     * @attr ref android.R.styleable#View_nextFocusRight
7818     */
7819    public int getNextFocusRightId() {
7820        return mNextFocusRightId;
7821    }
7822
7823    /**
7824     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7825     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7826     * decide automatically.
7827     *
7828     * @attr ref android.R.styleable#View_nextFocusRight
7829     */
7830    public void setNextFocusRightId(int nextFocusRightId) {
7831        mNextFocusRightId = nextFocusRightId;
7832    }
7833
7834    /**
7835     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7836     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7837     *
7838     * @attr ref android.R.styleable#View_nextFocusUp
7839     */
7840    public int getNextFocusUpId() {
7841        return mNextFocusUpId;
7842    }
7843
7844    /**
7845     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7846     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7847     * decide automatically.
7848     *
7849     * @attr ref android.R.styleable#View_nextFocusUp
7850     */
7851    public void setNextFocusUpId(int nextFocusUpId) {
7852        mNextFocusUpId = nextFocusUpId;
7853    }
7854
7855    /**
7856     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7857     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7858     *
7859     * @attr ref android.R.styleable#View_nextFocusDown
7860     */
7861    public int getNextFocusDownId() {
7862        return mNextFocusDownId;
7863    }
7864
7865    /**
7866     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7867     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7868     * decide automatically.
7869     *
7870     * @attr ref android.R.styleable#View_nextFocusDown
7871     */
7872    public void setNextFocusDownId(int nextFocusDownId) {
7873        mNextFocusDownId = nextFocusDownId;
7874    }
7875
7876    /**
7877     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7878     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7879     *
7880     * @attr ref android.R.styleable#View_nextFocusForward
7881     */
7882    public int getNextFocusForwardId() {
7883        return mNextFocusForwardId;
7884    }
7885
7886    /**
7887     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7888     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7889     * decide automatically.
7890     *
7891     * @attr ref android.R.styleable#View_nextFocusForward
7892     */
7893    public void setNextFocusForwardId(int nextFocusForwardId) {
7894        mNextFocusForwardId = nextFocusForwardId;
7895    }
7896
7897    /**
7898     * Gets the id of the root of the next keyboard navigation cluster.
7899     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
7900     * decide automatically.
7901     *
7902     * @attr ref android.R.styleable#View_nextClusterForward
7903     */
7904    public int getNextClusterForwardId() {
7905        return mNextClusterForwardId;
7906    }
7907
7908    /**
7909     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
7910     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
7911     * decide automatically.
7912     *
7913     * @attr ref android.R.styleable#View_nextClusterForward
7914     */
7915    public void setNextClusterForwardId(int nextClusterForwardId) {
7916        mNextClusterForwardId = nextClusterForwardId;
7917    }
7918
7919    /**
7920     * Gets the id of the root of the next keyboard navigation section.
7921     * @return The next keyboard navigation section ID, or {@link #NO_ID} if the framework should
7922     * decide automatically.
7923     *
7924     * @attr ref android.R.styleable#View_nextSectionForward
7925     */
7926    public int getNextSectionForwardId() {
7927        return mNextSectionForwardId;
7928    }
7929
7930    /**
7931     * Sets the id of the view to use as the root of the next keyboard navigation section.
7932     * @param nextSectionForwardId The next section ID, or {@link #NO_ID} if the framework should
7933     * decide automatically.
7934     *
7935     * @attr ref android.R.styleable#View_nextSectionForward
7936     */
7937    public void setNextSectionForwardId(int nextSectionForwardId) {
7938        mNextSectionForwardId = nextSectionForwardId;
7939    }
7940
7941    /**
7942     * Returns the visibility of this view and all of its ancestors
7943     *
7944     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7945     */
7946    public boolean isShown() {
7947        View current = this;
7948        //noinspection ConstantConditions
7949        do {
7950            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7951                return false;
7952            }
7953            ViewParent parent = current.mParent;
7954            if (parent == null) {
7955                return false; // We are not attached to the view root
7956            }
7957            if (!(parent instanceof View)) {
7958                return true;
7959            }
7960            current = (View) parent;
7961        } while (current != null);
7962
7963        return false;
7964    }
7965
7966    /**
7967     * Called by the view hierarchy when the content insets for a window have
7968     * changed, to allow it to adjust its content to fit within those windows.
7969     * The content insets tell you the space that the status bar, input method,
7970     * and other system windows infringe on the application's window.
7971     *
7972     * <p>You do not normally need to deal with this function, since the default
7973     * window decoration given to applications takes care of applying it to the
7974     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7975     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7976     * and your content can be placed under those system elements.  You can then
7977     * use this method within your view hierarchy if you have parts of your UI
7978     * which you would like to ensure are not being covered.
7979     *
7980     * <p>The default implementation of this method simply applies the content
7981     * insets to the view's padding, consuming that content (modifying the
7982     * insets to be 0), and returning true.  This behavior is off by default, but can
7983     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7984     *
7985     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7986     * insets object is propagated down the hierarchy, so any changes made to it will
7987     * be seen by all following views (including potentially ones above in
7988     * the hierarchy since this is a depth-first traversal).  The first view
7989     * that returns true will abort the entire traversal.
7990     *
7991     * <p>The default implementation works well for a situation where it is
7992     * used with a container that covers the entire window, allowing it to
7993     * apply the appropriate insets to its content on all edges.  If you need
7994     * a more complicated layout (such as two different views fitting system
7995     * windows, one on the top of the window, and one on the bottom),
7996     * you can override the method and handle the insets however you would like.
7997     * Note that the insets provided by the framework are always relative to the
7998     * far edges of the window, not accounting for the location of the called view
7999     * within that window.  (In fact when this method is called you do not yet know
8000     * where the layout will place the view, as it is done before layout happens.)
8001     *
8002     * <p>Note: unlike many View methods, there is no dispatch phase to this
8003     * call.  If you are overriding it in a ViewGroup and want to allow the
8004     * call to continue to your children, you must be sure to call the super
8005     * implementation.
8006     *
8007     * <p>Here is a sample layout that makes use of fitting system windows
8008     * to have controls for a video view placed inside of the window decorations
8009     * that it hides and shows.  This can be used with code like the second
8010     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8011     *
8012     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8013     *
8014     * @param insets Current content insets of the window.  Prior to
8015     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8016     * the insets or else you and Android will be unhappy.
8017     *
8018     * @return {@code true} if this view applied the insets and it should not
8019     * continue propagating further down the hierarchy, {@code false} otherwise.
8020     * @see #getFitsSystemWindows()
8021     * @see #setFitsSystemWindows(boolean)
8022     * @see #setSystemUiVisibility(int)
8023     *
8024     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8025     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8026     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8027     * to implement handling their own insets.
8028     */
8029    @Deprecated
8030    protected boolean fitSystemWindows(Rect insets) {
8031        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8032            if (insets == null) {
8033                // Null insets by definition have already been consumed.
8034                // This call cannot apply insets since there are none to apply,
8035                // so return false.
8036                return false;
8037            }
8038            // If we're not in the process of dispatching the newer apply insets call,
8039            // that means we're not in the compatibility path. Dispatch into the newer
8040            // apply insets path and take things from there.
8041            try {
8042                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8043                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8044            } finally {
8045                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8046            }
8047        } else {
8048            // We're being called from the newer apply insets path.
8049            // Perform the standard fallback behavior.
8050            return fitSystemWindowsInt(insets);
8051        }
8052    }
8053
8054    private boolean fitSystemWindowsInt(Rect insets) {
8055        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8056            mUserPaddingStart = UNDEFINED_PADDING;
8057            mUserPaddingEnd = UNDEFINED_PADDING;
8058            Rect localInsets = sThreadLocal.get();
8059            if (localInsets == null) {
8060                localInsets = new Rect();
8061                sThreadLocal.set(localInsets);
8062            }
8063            boolean res = computeFitSystemWindows(insets, localInsets);
8064            mUserPaddingLeftInitial = localInsets.left;
8065            mUserPaddingRightInitial = localInsets.right;
8066            internalSetPadding(localInsets.left, localInsets.top,
8067                    localInsets.right, localInsets.bottom);
8068            return res;
8069        }
8070        return false;
8071    }
8072
8073    /**
8074     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8075     *
8076     * <p>This method should be overridden by views that wish to apply a policy different from or
8077     * in addition to the default behavior. Clients that wish to force a view subtree
8078     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8079     *
8080     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8081     * it will be called during dispatch instead of this method. The listener may optionally
8082     * call this method from its own implementation if it wishes to apply the view's default
8083     * insets policy in addition to its own.</p>
8084     *
8085     * <p>Implementations of this method should either return the insets parameter unchanged
8086     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8087     * that this view applied itself. This allows new inset types added in future platform
8088     * versions to pass through existing implementations unchanged without being erroneously
8089     * consumed.</p>
8090     *
8091     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8092     * property is set then the view will consume the system window insets and apply them
8093     * as padding for the view.</p>
8094     *
8095     * @param insets Insets to apply
8096     * @return The supplied insets with any applied insets consumed
8097     */
8098    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8099        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8100            // We weren't called from within a direct call to fitSystemWindows,
8101            // call into it as a fallback in case we're in a class that overrides it
8102            // and has logic to perform.
8103            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8104                return insets.consumeSystemWindowInsets();
8105            }
8106        } else {
8107            // We were called from within a direct call to fitSystemWindows.
8108            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8109                return insets.consumeSystemWindowInsets();
8110            }
8111        }
8112        return insets;
8113    }
8114
8115    /**
8116     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8117     * window insets to this view. The listener's
8118     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8119     * method will be called instead of the view's
8120     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8121     *
8122     * @param listener Listener to set
8123     *
8124     * @see #onApplyWindowInsets(WindowInsets)
8125     */
8126    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8127        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8128    }
8129
8130    /**
8131     * Request to apply the given window insets to this view or another view in its subtree.
8132     *
8133     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8134     * obscured by window decorations or overlays. This can include the status and navigation bars,
8135     * action bars, input methods and more. New inset categories may be added in the future.
8136     * The method returns the insets provided minus any that were applied by this view or its
8137     * children.</p>
8138     *
8139     * <p>Clients wishing to provide custom behavior should override the
8140     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8141     * {@link OnApplyWindowInsetsListener} via the
8142     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8143     * method.</p>
8144     *
8145     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8146     * </p>
8147     *
8148     * @param insets Insets to apply
8149     * @return The provided insets minus the insets that were consumed
8150     */
8151    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8152        try {
8153            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8154            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8155                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8156            } else {
8157                return onApplyWindowInsets(insets);
8158            }
8159        } finally {
8160            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8161        }
8162    }
8163
8164    /**
8165     * Compute the view's coordinate within the surface.
8166     *
8167     * <p>Computes the coordinates of this view in its surface. The argument
8168     * must be an array of two integers. After the method returns, the array
8169     * contains the x and y location in that order.</p>
8170     * @hide
8171     * @param location an array of two integers in which to hold the coordinates
8172     */
8173    public void getLocationInSurface(@Size(2) int[] location) {
8174        getLocationInWindow(location);
8175        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8176            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8177            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8178        }
8179    }
8180
8181    /**
8182     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8183     * only available if the view is attached.
8184     *
8185     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8186     */
8187    public WindowInsets getRootWindowInsets() {
8188        if (mAttachInfo != null) {
8189            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8190        }
8191        return null;
8192    }
8193
8194    /**
8195     * @hide Compute the insets that should be consumed by this view and the ones
8196     * that should propagate to those under it.
8197     */
8198    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8199        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8200                || mAttachInfo == null
8201                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8202                        && !mAttachInfo.mOverscanRequested)) {
8203            outLocalInsets.set(inoutInsets);
8204            inoutInsets.set(0, 0, 0, 0);
8205            return true;
8206        } else {
8207            // The application wants to take care of fitting system window for
8208            // the content...  however we still need to take care of any overscan here.
8209            final Rect overscan = mAttachInfo.mOverscanInsets;
8210            outLocalInsets.set(overscan);
8211            inoutInsets.left -= overscan.left;
8212            inoutInsets.top -= overscan.top;
8213            inoutInsets.right -= overscan.right;
8214            inoutInsets.bottom -= overscan.bottom;
8215            return false;
8216        }
8217    }
8218
8219    /**
8220     * Compute insets that should be consumed by this view and the ones that should propagate
8221     * to those under it.
8222     *
8223     * @param in Insets currently being processed by this View, likely received as a parameter
8224     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8225     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8226     *                       by this view
8227     * @return Insets that should be passed along to views under this one
8228     */
8229    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8230        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8231                || mAttachInfo == null
8232                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8233            outLocalInsets.set(in.getSystemWindowInsets());
8234            return in.consumeSystemWindowInsets();
8235        } else {
8236            outLocalInsets.set(0, 0, 0, 0);
8237            return in;
8238        }
8239    }
8240
8241    /**
8242     * Sets whether or not this view should account for system screen decorations
8243     * such as the status bar and inset its content; that is, controlling whether
8244     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8245     * executed.  See that method for more details.
8246     *
8247     * <p>Note that if you are providing your own implementation of
8248     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8249     * flag to true -- your implementation will be overriding the default
8250     * implementation that checks this flag.
8251     *
8252     * @param fitSystemWindows If true, then the default implementation of
8253     * {@link #fitSystemWindows(Rect)} will be executed.
8254     *
8255     * @attr ref android.R.styleable#View_fitsSystemWindows
8256     * @see #getFitsSystemWindows()
8257     * @see #fitSystemWindows(Rect)
8258     * @see #setSystemUiVisibility(int)
8259     */
8260    public void setFitsSystemWindows(boolean fitSystemWindows) {
8261        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8262    }
8263
8264    /**
8265     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8266     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8267     * will be executed.
8268     *
8269     * @return {@code true} if the default implementation of
8270     * {@link #fitSystemWindows(Rect)} will be executed.
8271     *
8272     * @attr ref android.R.styleable#View_fitsSystemWindows
8273     * @see #setFitsSystemWindows(boolean)
8274     * @see #fitSystemWindows(Rect)
8275     * @see #setSystemUiVisibility(int)
8276     */
8277    @ViewDebug.ExportedProperty
8278    public boolean getFitsSystemWindows() {
8279        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8280    }
8281
8282    /** @hide */
8283    public boolean fitsSystemWindows() {
8284        return getFitsSystemWindows();
8285    }
8286
8287    /**
8288     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8289     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8290     */
8291    @Deprecated
8292    public void requestFitSystemWindows() {
8293        if (mParent != null) {
8294            mParent.requestFitSystemWindows();
8295        }
8296    }
8297
8298    /**
8299     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8300     */
8301    public void requestApplyInsets() {
8302        requestFitSystemWindows();
8303    }
8304
8305    /**
8306     * For use by PhoneWindow to make its own system window fitting optional.
8307     * @hide
8308     */
8309    public void makeOptionalFitsSystemWindows() {
8310        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8311    }
8312
8313    /**
8314     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8315     * treat them as such.
8316     * @hide
8317     */
8318    public void getOutsets(Rect outOutsetRect) {
8319        if (mAttachInfo != null) {
8320            outOutsetRect.set(mAttachInfo.mOutsets);
8321        } else {
8322            outOutsetRect.setEmpty();
8323        }
8324    }
8325
8326    /**
8327     * Returns the visibility status for this view.
8328     *
8329     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8330     * @attr ref android.R.styleable#View_visibility
8331     */
8332    @ViewDebug.ExportedProperty(mapping = {
8333        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8334        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8335        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8336    })
8337    @Visibility
8338    public int getVisibility() {
8339        return mViewFlags & VISIBILITY_MASK;
8340    }
8341
8342    /**
8343     * Set the visibility state of this view.
8344     *
8345     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8346     * @attr ref android.R.styleable#View_visibility
8347     */
8348    @RemotableViewMethod
8349    public void setVisibility(@Visibility int visibility) {
8350        setFlags(visibility, VISIBILITY_MASK);
8351    }
8352
8353    /**
8354     * Returns the enabled status for this view. The interpretation of the
8355     * enabled state varies by subclass.
8356     *
8357     * @return True if this view is enabled, false otherwise.
8358     */
8359    @ViewDebug.ExportedProperty
8360    public boolean isEnabled() {
8361        return (mViewFlags & ENABLED_MASK) == ENABLED;
8362    }
8363
8364    /**
8365     * Set the enabled state of this view. The interpretation of the enabled
8366     * state varies by subclass.
8367     *
8368     * @param enabled True if this view is enabled, false otherwise.
8369     */
8370    @RemotableViewMethod
8371    public void setEnabled(boolean enabled) {
8372        if (enabled == isEnabled()) return;
8373
8374        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8375
8376        /*
8377         * The View most likely has to change its appearance, so refresh
8378         * the drawable state.
8379         */
8380        refreshDrawableState();
8381
8382        // Invalidate too, since the default behavior for views is to be
8383        // be drawn at 50% alpha rather than to change the drawable.
8384        invalidate(true);
8385
8386        if (!enabled) {
8387            cancelPendingInputEvents();
8388        }
8389    }
8390
8391    /**
8392     * Set whether this view can receive the focus.
8393     *
8394     * Setting this to false will also ensure that this view is not focusable
8395     * in touch mode.
8396     *
8397     * @param focusable If true, this view can receive the focus.
8398     *
8399     * @see #setFocusableInTouchMode(boolean)
8400     * @attr ref android.R.styleable#View_focusable
8401     */
8402    public void setFocusable(boolean focusable) {
8403        if (!focusable) {
8404            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8405        }
8406        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8407    }
8408
8409    /**
8410     * Set whether this view can receive focus while in touch mode.
8411     *
8412     * Setting this to true will also ensure that this view is focusable.
8413     *
8414     * @param focusableInTouchMode If true, this view can receive the focus while
8415     *   in touch mode.
8416     *
8417     * @see #setFocusable(boolean)
8418     * @attr ref android.R.styleable#View_focusableInTouchMode
8419     */
8420    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8421        // Focusable in touch mode should always be set before the focusable flag
8422        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8423        // which, in touch mode, will not successfully request focus on this view
8424        // because the focusable in touch mode flag is not set
8425        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8426        if (focusableInTouchMode) {
8427            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8428        }
8429    }
8430
8431    /**
8432     * Set whether this view should have sound effects enabled for events such as
8433     * clicking and touching.
8434     *
8435     * <p>You may wish to disable sound effects for a view if you already play sounds,
8436     * for instance, a dial key that plays dtmf tones.
8437     *
8438     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8439     * @see #isSoundEffectsEnabled()
8440     * @see #playSoundEffect(int)
8441     * @attr ref android.R.styleable#View_soundEffectsEnabled
8442     */
8443    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8444        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8445    }
8446
8447    /**
8448     * @return whether this view should have sound effects enabled for events such as
8449     *     clicking and touching.
8450     *
8451     * @see #setSoundEffectsEnabled(boolean)
8452     * @see #playSoundEffect(int)
8453     * @attr ref android.R.styleable#View_soundEffectsEnabled
8454     */
8455    @ViewDebug.ExportedProperty
8456    public boolean isSoundEffectsEnabled() {
8457        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8458    }
8459
8460    /**
8461     * Set whether this view should have haptic feedback for events such as
8462     * long presses.
8463     *
8464     * <p>You may wish to disable haptic feedback if your view already controls
8465     * its own haptic feedback.
8466     *
8467     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8468     * @see #isHapticFeedbackEnabled()
8469     * @see #performHapticFeedback(int)
8470     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8471     */
8472    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8473        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8474    }
8475
8476    /**
8477     * @return whether this view should have haptic feedback enabled for events
8478     * long presses.
8479     *
8480     * @see #setHapticFeedbackEnabled(boolean)
8481     * @see #performHapticFeedback(int)
8482     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8483     */
8484    @ViewDebug.ExportedProperty
8485    public boolean isHapticFeedbackEnabled() {
8486        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8487    }
8488
8489    /**
8490     * Returns the layout direction for this view.
8491     *
8492     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8493     *   {@link #LAYOUT_DIRECTION_RTL},
8494     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8495     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8496     *
8497     * @attr ref android.R.styleable#View_layoutDirection
8498     *
8499     * @hide
8500     */
8501    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8502        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8503        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8504        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8505        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8506    })
8507    @LayoutDir
8508    public int getRawLayoutDirection() {
8509        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8510    }
8511
8512    /**
8513     * Set the layout direction for this view. This will propagate a reset of layout direction
8514     * resolution to the view's children and resolve layout direction for this view.
8515     *
8516     * @param layoutDirection the layout direction to set. Should be one of:
8517     *
8518     * {@link #LAYOUT_DIRECTION_LTR},
8519     * {@link #LAYOUT_DIRECTION_RTL},
8520     * {@link #LAYOUT_DIRECTION_INHERIT},
8521     * {@link #LAYOUT_DIRECTION_LOCALE}.
8522     *
8523     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8524     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8525     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8526     *
8527     * @attr ref android.R.styleable#View_layoutDirection
8528     */
8529    @RemotableViewMethod
8530    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8531        if (getRawLayoutDirection() != layoutDirection) {
8532            // Reset the current layout direction and the resolved one
8533            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8534            resetRtlProperties();
8535            // Set the new layout direction (filtered)
8536            mPrivateFlags2 |=
8537                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8538            // We need to resolve all RTL properties as they all depend on layout direction
8539            resolveRtlPropertiesIfNeeded();
8540            requestLayout();
8541            invalidate(true);
8542        }
8543    }
8544
8545    /**
8546     * Returns the resolved layout direction for this view.
8547     *
8548     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8549     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8550     *
8551     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8552     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8553     *
8554     * @attr ref android.R.styleable#View_layoutDirection
8555     */
8556    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8557        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8558        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8559    })
8560    @ResolvedLayoutDir
8561    public int getLayoutDirection() {
8562        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8563        if (targetSdkVersion < JELLY_BEAN_MR1) {
8564            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8565            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8566        }
8567        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8568                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8569    }
8570
8571    /**
8572     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8573     * layout attribute and/or the inherited value from the parent
8574     *
8575     * @return true if the layout is right-to-left.
8576     *
8577     * @hide
8578     */
8579    @ViewDebug.ExportedProperty(category = "layout")
8580    public boolean isLayoutRtl() {
8581        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8582    }
8583
8584    /**
8585     * Indicates whether the view is currently tracking transient state that the
8586     * app should not need to concern itself with saving and restoring, but that
8587     * the framework should take special note to preserve when possible.
8588     *
8589     * <p>A view with transient state cannot be trivially rebound from an external
8590     * data source, such as an adapter binding item views in a list. This may be
8591     * because the view is performing an animation, tracking user selection
8592     * of content, or similar.</p>
8593     *
8594     * @return true if the view has transient state
8595     */
8596    @ViewDebug.ExportedProperty(category = "layout")
8597    public boolean hasTransientState() {
8598        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8599    }
8600
8601    /**
8602     * Set whether this view is currently tracking transient state that the
8603     * framework should attempt to preserve when possible. This flag is reference counted,
8604     * so every call to setHasTransientState(true) should be paired with a later call
8605     * to setHasTransientState(false).
8606     *
8607     * <p>A view with transient state cannot be trivially rebound from an external
8608     * data source, such as an adapter binding item views in a list. This may be
8609     * because the view is performing an animation, tracking user selection
8610     * of content, or similar.</p>
8611     *
8612     * @param hasTransientState true if this view has transient state
8613     */
8614    public void setHasTransientState(boolean hasTransientState) {
8615        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8616                mTransientStateCount - 1;
8617        if (mTransientStateCount < 0) {
8618            mTransientStateCount = 0;
8619            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8620                    "unmatched pair of setHasTransientState calls");
8621        } else if ((hasTransientState && mTransientStateCount == 1) ||
8622                (!hasTransientState && mTransientStateCount == 0)) {
8623            // update flag if we've just incremented up from 0 or decremented down to 0
8624            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8625                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8626            if (mParent != null) {
8627                try {
8628                    mParent.childHasTransientStateChanged(this, hasTransientState);
8629                } catch (AbstractMethodError e) {
8630                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8631                            " does not fully implement ViewParent", e);
8632                }
8633            }
8634        }
8635    }
8636
8637    /**
8638     * Returns true if this view is currently attached to a window.
8639     */
8640    public boolean isAttachedToWindow() {
8641        return mAttachInfo != null;
8642    }
8643
8644    /**
8645     * Returns true if this view has been through at least one layout since it
8646     * was last attached to or detached from a window.
8647     */
8648    public boolean isLaidOut() {
8649        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8650    }
8651
8652    /**
8653     * If this view doesn't do any drawing on its own, set this flag to
8654     * allow further optimizations. By default, this flag is not set on
8655     * View, but could be set on some View subclasses such as ViewGroup.
8656     *
8657     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8658     * you should clear this flag.
8659     *
8660     * @param willNotDraw whether or not this View draw on its own
8661     */
8662    public void setWillNotDraw(boolean willNotDraw) {
8663        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8664    }
8665
8666    /**
8667     * Returns whether or not this View draws on its own.
8668     *
8669     * @return true if this view has nothing to draw, false otherwise
8670     */
8671    @ViewDebug.ExportedProperty(category = "drawing")
8672    public boolean willNotDraw() {
8673        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8674    }
8675
8676    /**
8677     * When a View's drawing cache is enabled, drawing is redirected to an
8678     * offscreen bitmap. Some views, like an ImageView, must be able to
8679     * bypass this mechanism if they already draw a single bitmap, to avoid
8680     * unnecessary usage of the memory.
8681     *
8682     * @param willNotCacheDrawing true if this view does not cache its
8683     *        drawing, false otherwise
8684     */
8685    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8686        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8687    }
8688
8689    /**
8690     * Returns whether or not this View can cache its drawing or not.
8691     *
8692     * @return true if this view does not cache its drawing, false otherwise
8693     */
8694    @ViewDebug.ExportedProperty(category = "drawing")
8695    public boolean willNotCacheDrawing() {
8696        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8697    }
8698
8699    /**
8700     * Indicates whether this view reacts to click events or not.
8701     *
8702     * @return true if the view is clickable, false otherwise
8703     *
8704     * @see #setClickable(boolean)
8705     * @attr ref android.R.styleable#View_clickable
8706     */
8707    @ViewDebug.ExportedProperty
8708    public boolean isClickable() {
8709        return (mViewFlags & CLICKABLE) == CLICKABLE;
8710    }
8711
8712    /**
8713     * Enables or disables click events for this view. When a view
8714     * is clickable it will change its state to "pressed" on every click.
8715     * Subclasses should set the view clickable to visually react to
8716     * user's clicks.
8717     *
8718     * @param clickable true to make the view clickable, false otherwise
8719     *
8720     * @see #isClickable()
8721     * @attr ref android.R.styleable#View_clickable
8722     */
8723    public void setClickable(boolean clickable) {
8724        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8725    }
8726
8727    /**
8728     * Indicates whether this view reacts to long click events or not.
8729     *
8730     * @return true if the view is long clickable, false otherwise
8731     *
8732     * @see #setLongClickable(boolean)
8733     * @attr ref android.R.styleable#View_longClickable
8734     */
8735    public boolean isLongClickable() {
8736        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8737    }
8738
8739    /**
8740     * Enables or disables long click events for this view. When a view is long
8741     * clickable it reacts to the user holding down the button for a longer
8742     * duration than a tap. This event can either launch the listener or a
8743     * context menu.
8744     *
8745     * @param longClickable true to make the view long clickable, false otherwise
8746     * @see #isLongClickable()
8747     * @attr ref android.R.styleable#View_longClickable
8748     */
8749    public void setLongClickable(boolean longClickable) {
8750        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8751    }
8752
8753    /**
8754     * Indicates whether this view reacts to context clicks or not.
8755     *
8756     * @return true if the view is context clickable, false otherwise
8757     * @see #setContextClickable(boolean)
8758     * @attr ref android.R.styleable#View_contextClickable
8759     */
8760    public boolean isContextClickable() {
8761        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8762    }
8763
8764    /**
8765     * Enables or disables context clicking for this view. This event can launch the listener.
8766     *
8767     * @param contextClickable true to make the view react to a context click, false otherwise
8768     * @see #isContextClickable()
8769     * @attr ref android.R.styleable#View_contextClickable
8770     */
8771    public void setContextClickable(boolean contextClickable) {
8772        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8773    }
8774
8775    /**
8776     * Sets the pressed state for this view and provides a touch coordinate for
8777     * animation hinting.
8778     *
8779     * @param pressed Pass true to set the View's internal state to "pressed",
8780     *            or false to reverts the View's internal state from a
8781     *            previously set "pressed" state.
8782     * @param x The x coordinate of the touch that caused the press
8783     * @param y The y coordinate of the touch that caused the press
8784     */
8785    private void setPressed(boolean pressed, float x, float y) {
8786        if (pressed) {
8787            drawableHotspotChanged(x, y);
8788        }
8789
8790        setPressed(pressed);
8791    }
8792
8793    /**
8794     * Sets the pressed state for this view.
8795     *
8796     * @see #isClickable()
8797     * @see #setClickable(boolean)
8798     *
8799     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8800     *        the View's internal state from a previously set "pressed" state.
8801     */
8802    public void setPressed(boolean pressed) {
8803        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8804
8805        if (pressed) {
8806            mPrivateFlags |= PFLAG_PRESSED;
8807        } else {
8808            mPrivateFlags &= ~PFLAG_PRESSED;
8809        }
8810
8811        if (needsRefresh) {
8812            refreshDrawableState();
8813        }
8814        dispatchSetPressed(pressed);
8815    }
8816
8817    /**
8818     * Dispatch setPressed to all of this View's children.
8819     *
8820     * @see #setPressed(boolean)
8821     *
8822     * @param pressed The new pressed state
8823     */
8824    protected void dispatchSetPressed(boolean pressed) {
8825    }
8826
8827    /**
8828     * Indicates whether the view is currently in pressed state. Unless
8829     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8830     * the pressed state.
8831     *
8832     * @see #setPressed(boolean)
8833     * @see #isClickable()
8834     * @see #setClickable(boolean)
8835     *
8836     * @return true if the view is currently pressed, false otherwise
8837     */
8838    @ViewDebug.ExportedProperty
8839    public boolean isPressed() {
8840        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8841    }
8842
8843    /**
8844     * @hide
8845     * Indicates whether this view will participate in data collection through
8846     * {@link ViewStructure}.  If true, it will not provide any data
8847     * for itself or its children.  If false, the normal data collection will be allowed.
8848     *
8849     * @return Returns false if assist data collection is not blocked, else true.
8850     *
8851     * @see #setAssistBlocked(boolean)
8852     * @attr ref android.R.styleable#View_assistBlocked
8853     */
8854    public boolean isAssistBlocked() {
8855        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8856    }
8857
8858    /**
8859     * @hide
8860     * Indicates whether this view will participate in data collection through
8861     * {@link ViewStructure} for auto-fill purposes.
8862     *
8863     * <p>If {@code true}, it will not provide any data for itself or its children.
8864     * <p>If {@code false}, the normal data collection will be allowed.
8865     *
8866     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
8867     * else {@code true}.
8868     *
8869     * TODO(b/33197203): update / remove javadoc tags below
8870     * @see #setAssistBlocked(boolean)
8871     * @attr ref android.R.styleable#View_assistBlocked
8872     */
8873    public boolean isAutoFillBlocked() {
8874        return false; // TODO(b/33197203): properly implement it
8875    }
8876
8877    /**
8878     * @hide
8879     * Controls whether assist data collection from this view and its children is enabled
8880     * (that is, whether {@link #onProvideStructure} and
8881     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8882     * allowing normal assist collection.  Setting this to false will disable assist collection.
8883     *
8884     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8885     * (the default) to allow it.
8886     *
8887     * @see #isAssistBlocked()
8888     * @see #onProvideStructure
8889     * @see #onProvideVirtualStructure
8890     * @attr ref android.R.styleable#View_assistBlocked
8891     */
8892    public void setAssistBlocked(boolean enabled) {
8893        if (enabled) {
8894            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8895        } else {
8896            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8897        }
8898    }
8899
8900    /**
8901     * Indicates whether this view will save its state (that is,
8902     * whether its {@link #onSaveInstanceState} method will be called).
8903     *
8904     * @return Returns true if the view state saving is enabled, else false.
8905     *
8906     * @see #setSaveEnabled(boolean)
8907     * @attr ref android.R.styleable#View_saveEnabled
8908     */
8909    public boolean isSaveEnabled() {
8910        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8911    }
8912
8913    /**
8914     * Controls whether the saving of this view's state is
8915     * enabled (that is, whether its {@link #onSaveInstanceState} method
8916     * will be called).  Note that even if freezing is enabled, the
8917     * view still must have an id assigned to it (via {@link #setId(int)})
8918     * for its state to be saved.  This flag can only disable the
8919     * saving of this view; any child views may still have their state saved.
8920     *
8921     * @param enabled Set to false to <em>disable</em> state saving, or true
8922     * (the default) to allow it.
8923     *
8924     * @see #isSaveEnabled()
8925     * @see #setId(int)
8926     * @see #onSaveInstanceState()
8927     * @attr ref android.R.styleable#View_saveEnabled
8928     */
8929    public void setSaveEnabled(boolean enabled) {
8930        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8931    }
8932
8933    /**
8934     * Gets whether the framework should discard touches when the view's
8935     * window is obscured by another visible window.
8936     * Refer to the {@link View} security documentation for more details.
8937     *
8938     * @return True if touch filtering is enabled.
8939     *
8940     * @see #setFilterTouchesWhenObscured(boolean)
8941     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8942     */
8943    @ViewDebug.ExportedProperty
8944    public boolean getFilterTouchesWhenObscured() {
8945        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8946    }
8947
8948    /**
8949     * Sets whether the framework should discard touches when the view's
8950     * window is obscured by another visible window.
8951     * Refer to the {@link View} security documentation for more details.
8952     *
8953     * @param enabled True if touch filtering should be enabled.
8954     *
8955     * @see #getFilterTouchesWhenObscured
8956     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8957     */
8958    public void setFilterTouchesWhenObscured(boolean enabled) {
8959        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8960                FILTER_TOUCHES_WHEN_OBSCURED);
8961    }
8962
8963    /**
8964     * Indicates whether the entire hierarchy under this view will save its
8965     * state when a state saving traversal occurs from its parent.  The default
8966     * is true; if false, these views will not be saved unless
8967     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8968     *
8969     * @return Returns true if the view state saving from parent is enabled, else false.
8970     *
8971     * @see #setSaveFromParentEnabled(boolean)
8972     */
8973    public boolean isSaveFromParentEnabled() {
8974        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8975    }
8976
8977    /**
8978     * Controls whether the entire hierarchy under this view will save its
8979     * state when a state saving traversal occurs from its parent.  The default
8980     * is true; if false, these views will not be saved unless
8981     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8982     *
8983     * @param enabled Set to false to <em>disable</em> state saving, or true
8984     * (the default) to allow it.
8985     *
8986     * @see #isSaveFromParentEnabled()
8987     * @see #setId(int)
8988     * @see #onSaveInstanceState()
8989     */
8990    public void setSaveFromParentEnabled(boolean enabled) {
8991        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8992    }
8993
8994
8995    /**
8996     * Returns whether this View is able to take focus.
8997     *
8998     * @return True if this view can take focus, or false otherwise.
8999     * @attr ref android.R.styleable#View_focusable
9000     */
9001    @ViewDebug.ExportedProperty(category = "focus")
9002    public final boolean isFocusable() {
9003        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
9004    }
9005
9006    /**
9007     * When a view is focusable, it may not want to take focus when in touch mode.
9008     * For example, a button would like focus when the user is navigating via a D-pad
9009     * so that the user can click on it, but once the user starts touching the screen,
9010     * the button shouldn't take focus
9011     * @return Whether the view is focusable in touch mode.
9012     * @attr ref android.R.styleable#View_focusableInTouchMode
9013     */
9014    @ViewDebug.ExportedProperty
9015    public final boolean isFocusableInTouchMode() {
9016        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9017    }
9018
9019    /**
9020     * Find the nearest view in the specified direction that can take focus.
9021     * This does not actually give focus to that view.
9022     *
9023     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9024     *
9025     * @return The nearest focusable in the specified direction, or null if none
9026     *         can be found.
9027     */
9028    public View focusSearch(@FocusRealDirection int direction) {
9029        if (mParent != null) {
9030            return mParent.focusSearch(this, direction);
9031        } else {
9032            return null;
9033        }
9034    }
9035
9036    /**
9037     * Returns whether this View is a root of a keyboard navigation cluster.
9038     *
9039     * @return True if this view is a root of a cluster, or false otherwise.
9040     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9041     */
9042    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9043    public final boolean isKeyboardNavigationCluster() {
9044        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9045    }
9046
9047    /**
9048     * Set whether this view is a root of a keyboard navigation cluster.
9049     *
9050     * @param isCluster If true, this view is a root of a cluster.
9051     *
9052     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9053     */
9054    public void setKeyboardNavigationCluster(boolean isCluster) {
9055        if (isCluster) {
9056            mPrivateFlags3 |= PFLAG3_CLUSTER;
9057        } else {
9058            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9059        }
9060    }
9061
9062    /**
9063     * Returns whether this View is a root of a keyboard navigation section.
9064     *
9065     * @return True if this view is a root of a section, or false otherwise.
9066     * @attr ref android.R.styleable#View_keyboardNavigationSection
9067     */
9068    @ViewDebug.ExportedProperty(category = "keyboardNavigationSection")
9069    public final boolean isKeyboardNavigationSection() {
9070        return (mPrivateFlags3 & PFLAG3_SECTION) != 0;
9071    }
9072
9073    /**
9074     * Set whether this view is a root of a keyboard navigation section.
9075     *
9076     * @param isSection If true, this view is a root of a section.
9077     *
9078     * @attr ref android.R.styleable#View_keyboardNavigationSection
9079     */
9080    public void setKeyboardNavigationSection(boolean isSection) {
9081        if (isSection) {
9082            mPrivateFlags3 |= PFLAG3_SECTION;
9083        } else {
9084            mPrivateFlags3 &= ~PFLAG3_SECTION;
9085        }
9086    }
9087
9088    /**
9089     * This method is the last chance for the focused view and its ancestors to
9090     * respond to an arrow key. This is called when the focused view did not
9091     * consume the key internally, nor could the view system find a new view in
9092     * the requested direction to give focus to.
9093     *
9094     * @param focused The currently focused view.
9095     * @param direction The direction focus wants to move. One of FOCUS_UP,
9096     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9097     * @return True if the this view consumed this unhandled move.
9098     */
9099    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9100        return false;
9101    }
9102
9103    /**
9104     * If a user manually specified the next view id for a particular direction,
9105     * use the root to look up the view.
9106     * @param root The root view of the hierarchy containing this view.
9107     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9108     * or FOCUS_BACKWARD.
9109     * @return The user specified next view, or null if there is none.
9110     */
9111    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9112        switch (direction) {
9113            case FOCUS_LEFT:
9114                if (mNextFocusLeftId == View.NO_ID) return null;
9115                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9116            case FOCUS_RIGHT:
9117                if (mNextFocusRightId == View.NO_ID) return null;
9118                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9119            case FOCUS_UP:
9120                if (mNextFocusUpId == View.NO_ID) return null;
9121                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9122            case FOCUS_DOWN:
9123                if (mNextFocusDownId == View.NO_ID) return null;
9124                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9125            case FOCUS_FORWARD:
9126                if (mNextFocusForwardId == View.NO_ID) return null;
9127                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9128            case FOCUS_BACKWARD: {
9129                if (mID == View.NO_ID) return null;
9130                final int id = mID;
9131                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9132                    @Override
9133                    public boolean apply(View t) {
9134                        return t.mNextFocusForwardId == id;
9135                    }
9136                });
9137            }
9138        }
9139        return null;
9140    }
9141
9142    private View findViewInsideOutShouldExist(View root, int id) {
9143        if (mMatchIdPredicate == null) {
9144            mMatchIdPredicate = new MatchIdPredicate();
9145        }
9146        mMatchIdPredicate.mId = id;
9147        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9148        if (result == null) {
9149            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9150        }
9151        return result;
9152    }
9153
9154    /**
9155     * Find and return all focusable views that are descendants of this view,
9156     * possibly including this view if it is focusable itself.
9157     *
9158     * @param direction The direction of the focus
9159     * @return A list of focusable views
9160     */
9161    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9162        ArrayList<View> result = new ArrayList<View>(24);
9163        addFocusables(result, direction);
9164        return result;
9165    }
9166
9167    /**
9168     * Add any focusable views that are descendants of this view (possibly
9169     * including this view if it is focusable itself) to views.  If we are in touch mode,
9170     * only add views that are also focusable in touch mode.
9171     *
9172     * @param views Focusable views found so far
9173     * @param direction The direction of the focus
9174     */
9175    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9176        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9177    }
9178
9179    /**
9180     * Adds any focusable views that are descendants of this view (possibly
9181     * including this view if it is focusable itself) to views. This method
9182     * adds all focusable views regardless if we are in touch mode or
9183     * only views focusable in touch mode if we are in touch mode or
9184     * only views that can take accessibility focus if accessibility is enabled
9185     * depending on the focusable mode parameter.
9186     *
9187     * @param views Focusable views found so far or null if all we are interested is
9188     *        the number of focusables.
9189     * @param direction The direction of the focus.
9190     * @param focusableMode The type of focusables to be added.
9191     *
9192     * @see #FOCUSABLES_ALL
9193     * @see #FOCUSABLES_TOUCH_MODE
9194     */
9195    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9196            @FocusableMode int focusableMode) {
9197        if (views == null) {
9198            return;
9199        }
9200        if (!isFocusable()) {
9201            return;
9202        }
9203        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9204                && !isFocusableInTouchMode()) {
9205            return;
9206        }
9207        views.add(this);
9208    }
9209
9210    /**
9211     * Finds the Views that contain given text. The containment is case insensitive.
9212     * The search is performed by either the text that the View renders or the content
9213     * description that describes the view for accessibility purposes and the view does
9214     * not render or both. Clients can specify how the search is to be performed via
9215     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9216     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9217     *
9218     * @param outViews The output list of matching Views.
9219     * @param searched The text to match against.
9220     *
9221     * @see #FIND_VIEWS_WITH_TEXT
9222     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9223     * @see #setContentDescription(CharSequence)
9224     */
9225    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9226            @FindViewFlags int flags) {
9227        if (getAccessibilityNodeProvider() != null) {
9228            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9229                outViews.add(this);
9230            }
9231        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9232                && (searched != null && searched.length() > 0)
9233                && (mContentDescription != null && mContentDescription.length() > 0)) {
9234            String searchedLowerCase = searched.toString().toLowerCase();
9235            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9236            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9237                outViews.add(this);
9238            }
9239        }
9240    }
9241
9242    /**
9243     * Find and return all touchable views that are descendants of this view,
9244     * possibly including this view if it is touchable itself.
9245     *
9246     * @return A list of touchable views
9247     */
9248    public ArrayList<View> getTouchables() {
9249        ArrayList<View> result = new ArrayList<View>();
9250        addTouchables(result);
9251        return result;
9252    }
9253
9254    /**
9255     * Add any touchable views that are descendants of this view (possibly
9256     * including this view if it is touchable itself) to views.
9257     *
9258     * @param views Touchable views found so far
9259     */
9260    public void addTouchables(ArrayList<View> views) {
9261        final int viewFlags = mViewFlags;
9262
9263        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9264                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9265                && (viewFlags & ENABLED_MASK) == ENABLED) {
9266            views.add(this);
9267        }
9268    }
9269
9270    /**
9271     * Returns whether this View is accessibility focused.
9272     *
9273     * @return True if this View is accessibility focused.
9274     */
9275    public boolean isAccessibilityFocused() {
9276        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9277    }
9278
9279    /**
9280     * Call this to try to give accessibility focus to this view.
9281     *
9282     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9283     * returns false or the view is no visible or the view already has accessibility
9284     * focus.
9285     *
9286     * See also {@link #focusSearch(int)}, which is what you call to say that you
9287     * have focus, and you want your parent to look for the next one.
9288     *
9289     * @return Whether this view actually took accessibility focus.
9290     *
9291     * @hide
9292     */
9293    public boolean requestAccessibilityFocus() {
9294        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9295        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9296            return false;
9297        }
9298        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9299            return false;
9300        }
9301        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9302            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9303            ViewRootImpl viewRootImpl = getViewRootImpl();
9304            if (viewRootImpl != null) {
9305                viewRootImpl.setAccessibilityFocus(this, null);
9306            }
9307            invalidate();
9308            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9309            return true;
9310        }
9311        return false;
9312    }
9313
9314    /**
9315     * Call this to try to clear accessibility focus of this view.
9316     *
9317     * See also {@link #focusSearch(int)}, which is what you call to say that you
9318     * have focus, and you want your parent to look for the next one.
9319     *
9320     * @hide
9321     */
9322    public void clearAccessibilityFocus() {
9323        clearAccessibilityFocusNoCallbacks(0);
9324
9325        // Clear the global reference of accessibility focus if this view or
9326        // any of its descendants had accessibility focus. This will NOT send
9327        // an event or update internal state if focus is cleared from a
9328        // descendant view, which may leave views in inconsistent states.
9329        final ViewRootImpl viewRootImpl = getViewRootImpl();
9330        if (viewRootImpl != null) {
9331            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9332            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9333                viewRootImpl.setAccessibilityFocus(null, null);
9334            }
9335        }
9336    }
9337
9338    private void sendAccessibilityHoverEvent(int eventType) {
9339        // Since we are not delivering to a client accessibility events from not
9340        // important views (unless the clinet request that) we need to fire the
9341        // event from the deepest view exposed to the client. As a consequence if
9342        // the user crosses a not exposed view the client will see enter and exit
9343        // of the exposed predecessor followed by and enter and exit of that same
9344        // predecessor when entering and exiting the not exposed descendant. This
9345        // is fine since the client has a clear idea which view is hovered at the
9346        // price of a couple more events being sent. This is a simple and
9347        // working solution.
9348        View source = this;
9349        while (true) {
9350            if (source.includeForAccessibility()) {
9351                source.sendAccessibilityEvent(eventType);
9352                return;
9353            }
9354            ViewParent parent = source.getParent();
9355            if (parent instanceof View) {
9356                source = (View) parent;
9357            } else {
9358                return;
9359            }
9360        }
9361    }
9362
9363    /**
9364     * Clears accessibility focus without calling any callback methods
9365     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9366     * is used separately from that one for clearing accessibility focus when
9367     * giving this focus to another view.
9368     *
9369     * @param action The action, if any, that led to focus being cleared. Set to
9370     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9371     * the window.
9372     */
9373    void clearAccessibilityFocusNoCallbacks(int action) {
9374        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9375            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9376            invalidate();
9377            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9378                AccessibilityEvent event = AccessibilityEvent.obtain(
9379                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9380                event.setAction(action);
9381                if (mAccessibilityDelegate != null) {
9382                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9383                } else {
9384                    sendAccessibilityEventUnchecked(event);
9385                }
9386            }
9387        }
9388    }
9389
9390    /**
9391     * Call this to try to give focus to a specific view or to one of its
9392     * descendants.
9393     *
9394     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9395     * false), or if it is focusable and it is not focusable in touch mode
9396     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9397     *
9398     * See also {@link #focusSearch(int)}, which is what you call to say that you
9399     * have focus, and you want your parent to look for the next one.
9400     *
9401     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9402     * {@link #FOCUS_DOWN} and <code>null</code>.
9403     *
9404     * @return Whether this view or one of its descendants actually took focus.
9405     */
9406    public final boolean requestFocus() {
9407        return requestFocus(View.FOCUS_DOWN);
9408    }
9409
9410    /**
9411     * Call this to try to give focus to a specific view or to one of its
9412     * descendants and give it a hint about what direction focus is heading.
9413     *
9414     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9415     * false), or if it is focusable and it is not focusable in touch mode
9416     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9417     *
9418     * See also {@link #focusSearch(int)}, which is what you call to say that you
9419     * have focus, and you want your parent to look for the next one.
9420     *
9421     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9422     * <code>null</code> set for the previously focused rectangle.
9423     *
9424     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9425     * @return Whether this view or one of its descendants actually took focus.
9426     */
9427    public final boolean requestFocus(int direction) {
9428        return requestFocus(direction, null);
9429    }
9430
9431    /**
9432     * Call this to try to give focus to a specific view or to one of its descendants
9433     * and give it hints about the direction and a specific rectangle that the focus
9434     * is coming from.  The rectangle can help give larger views a finer grained hint
9435     * about where focus is coming from, and therefore, where to show selection, or
9436     * forward focus change internally.
9437     *
9438     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9439     * false), or if it is focusable and it is not focusable in touch mode
9440     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9441     *
9442     * A View will not take focus if it is not visible.
9443     *
9444     * A View will not take focus if one of its parents has
9445     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9446     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9447     *
9448     * See also {@link #focusSearch(int)}, which is what you call to say that you
9449     * have focus, and you want your parent to look for the next one.
9450     *
9451     * You may wish to override this method if your custom {@link View} has an internal
9452     * {@link View} that it wishes to forward the request to.
9453     *
9454     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9455     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9456     *        to give a finer grained hint about where focus is coming from.  May be null
9457     *        if there is no hint.
9458     * @return Whether this view or one of its descendants actually took focus.
9459     */
9460    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9461        return requestFocusNoSearch(direction, previouslyFocusedRect);
9462    }
9463
9464    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9465        // need to be focusable
9466        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9467                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9468            return false;
9469        }
9470
9471        // need to be focusable in touch mode if in touch mode
9472        if (isInTouchMode() &&
9473            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9474               return false;
9475        }
9476
9477        // need to not have any parents blocking us
9478        if (hasAncestorThatBlocksDescendantFocus()) {
9479            return false;
9480        }
9481
9482        handleFocusGainInternal(direction, previouslyFocusedRect);
9483        return true;
9484    }
9485
9486    /**
9487     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9488     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9489     * touch mode to request focus when they are touched.
9490     *
9491     * @return Whether this view or one of its descendants actually took focus.
9492     *
9493     * @see #isInTouchMode()
9494     *
9495     */
9496    public final boolean requestFocusFromTouch() {
9497        // Leave touch mode if we need to
9498        if (isInTouchMode()) {
9499            ViewRootImpl viewRoot = getViewRootImpl();
9500            if (viewRoot != null) {
9501                viewRoot.ensureTouchMode(false);
9502            }
9503        }
9504        return requestFocus(View.FOCUS_DOWN);
9505    }
9506
9507    /**
9508     * @return Whether any ancestor of this view blocks descendant focus.
9509     */
9510    private boolean hasAncestorThatBlocksDescendantFocus() {
9511        final boolean focusableInTouchMode = isFocusableInTouchMode();
9512        ViewParent ancestor = mParent;
9513        while (ancestor instanceof ViewGroup) {
9514            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9515            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9516                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9517                return true;
9518            } else {
9519                ancestor = vgAncestor.getParent();
9520            }
9521        }
9522        return false;
9523    }
9524
9525    /**
9526     * Gets the mode for determining whether this View is important for accessibility.
9527     * A view is important for accessibility if it fires accessibility events and if it
9528     * is reported to accessibility services that query the screen.
9529     *
9530     * @return The mode for determining whether a view is important for accessibility, one
9531     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9532     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9533     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9534     *
9535     * @attr ref android.R.styleable#View_importantForAccessibility
9536     *
9537     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9538     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9539     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9540     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9541     */
9542    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9543            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9544            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9545            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9546            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9547                    to = "noHideDescendants")
9548        })
9549    public int getImportantForAccessibility() {
9550        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9551                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9552    }
9553
9554    /**
9555     * Sets the live region mode for this view. This indicates to accessibility
9556     * services whether they should automatically notify the user about changes
9557     * to the view's content description or text, or to the content descriptions
9558     * or text of the view's children (where applicable).
9559     * <p>
9560     * For example, in a login screen with a TextView that displays an "incorrect
9561     * password" notification, that view should be marked as a live region with
9562     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9563     * <p>
9564     * To disable change notifications for this view, use
9565     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9566     * mode for most views.
9567     * <p>
9568     * To indicate that the user should be notified of changes, use
9569     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9570     * <p>
9571     * If the view's changes should interrupt ongoing speech and notify the user
9572     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9573     *
9574     * @param mode The live region mode for this view, one of:
9575     *        <ul>
9576     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9577     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9578     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9579     *        </ul>
9580     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9581     */
9582    public void setAccessibilityLiveRegion(int mode) {
9583        if (mode != getAccessibilityLiveRegion()) {
9584            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9585            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9586                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9587            notifyViewAccessibilityStateChangedIfNeeded(
9588                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9589        }
9590    }
9591
9592    /**
9593     * Gets the live region mode for this View.
9594     *
9595     * @return The live region mode for the view.
9596     *
9597     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9598     *
9599     * @see #setAccessibilityLiveRegion(int)
9600     */
9601    public int getAccessibilityLiveRegion() {
9602        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9603                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9604    }
9605
9606    /**
9607     * Sets how to determine whether this view is important for accessibility
9608     * which is if it fires accessibility events and if it is reported to
9609     * accessibility services that query the screen.
9610     *
9611     * @param mode How to determine whether this view is important for accessibility.
9612     *
9613     * @attr ref android.R.styleable#View_importantForAccessibility
9614     *
9615     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9616     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9617     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9618     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9619     */
9620    public void setImportantForAccessibility(int mode) {
9621        final int oldMode = getImportantForAccessibility();
9622        if (mode != oldMode) {
9623            final boolean hideDescendants =
9624                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9625
9626            // If this node or its descendants are no longer important, try to
9627            // clear accessibility focus.
9628            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9629                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9630                if (focusHost != null) {
9631                    focusHost.clearAccessibilityFocus();
9632                }
9633            }
9634
9635            // If we're moving between AUTO and another state, we might not need
9636            // to send a subtree changed notification. We'll store the computed
9637            // importance, since we'll need to check it later to make sure.
9638            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9639                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9640            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9641            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9642            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9643                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9644            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9645                notifySubtreeAccessibilityStateChangedIfNeeded();
9646            } else {
9647                notifyViewAccessibilityStateChangedIfNeeded(
9648                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9649            }
9650        }
9651    }
9652
9653    /**
9654     * Returns the view within this view's hierarchy that is hosting
9655     * accessibility focus.
9656     *
9657     * @param searchDescendants whether to search for focus in descendant views
9658     * @return the view hosting accessibility focus, or {@code null}
9659     */
9660    private View findAccessibilityFocusHost(boolean searchDescendants) {
9661        if (isAccessibilityFocusedViewOrHost()) {
9662            return this;
9663        }
9664
9665        if (searchDescendants) {
9666            final ViewRootImpl viewRoot = getViewRootImpl();
9667            if (viewRoot != null) {
9668                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9669                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9670                    return focusHost;
9671                }
9672            }
9673        }
9674
9675        return null;
9676    }
9677
9678    /**
9679     * Computes whether this view should be exposed for accessibility. In
9680     * general, views that are interactive or provide information are exposed
9681     * while views that serve only as containers are hidden.
9682     * <p>
9683     * If an ancestor of this view has importance
9684     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9685     * returns <code>false</code>.
9686     * <p>
9687     * Otherwise, the value is computed according to the view's
9688     * {@link #getImportantForAccessibility()} value:
9689     * <ol>
9690     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9691     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9692     * </code>
9693     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9694     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9695     * view satisfies any of the following:
9696     * <ul>
9697     * <li>Is actionable, e.g. {@link #isClickable()},
9698     * {@link #isLongClickable()}, or {@link #isFocusable()}
9699     * <li>Has an {@link AccessibilityDelegate}
9700     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9701     * {@link OnKeyListener}, etc.
9702     * <li>Is an accessibility live region, e.g.
9703     * {@link #getAccessibilityLiveRegion()} is not
9704     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9705     * </ul>
9706     * </ol>
9707     *
9708     * @return Whether the view is exposed for accessibility.
9709     * @see #setImportantForAccessibility(int)
9710     * @see #getImportantForAccessibility()
9711     */
9712    public boolean isImportantForAccessibility() {
9713        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9714                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9715        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9716                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9717            return false;
9718        }
9719
9720        // Check parent mode to ensure we're not hidden.
9721        ViewParent parent = mParent;
9722        while (parent instanceof View) {
9723            if (((View) parent).getImportantForAccessibility()
9724                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9725                return false;
9726            }
9727            parent = parent.getParent();
9728        }
9729
9730        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9731                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9732                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9733    }
9734
9735    /**
9736     * Gets the parent for accessibility purposes. Note that the parent for
9737     * accessibility is not necessary the immediate parent. It is the first
9738     * predecessor that is important for accessibility.
9739     *
9740     * @return The parent for accessibility purposes.
9741     */
9742    public ViewParent getParentForAccessibility() {
9743        if (mParent instanceof View) {
9744            View parentView = (View) mParent;
9745            if (parentView.includeForAccessibility()) {
9746                return mParent;
9747            } else {
9748                return mParent.getParentForAccessibility();
9749            }
9750        }
9751        return null;
9752    }
9753
9754    /**
9755     * Adds the children of this View relevant for accessibility to the given list
9756     * as output. Since some Views are not important for accessibility the added
9757     * child views are not necessarily direct children of this view, rather they are
9758     * the first level of descendants important for accessibility.
9759     *
9760     * @param outChildren The output list that will receive children for accessibility.
9761     */
9762    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9763
9764    }
9765
9766    /**
9767     * Whether to regard this view for accessibility. A view is regarded for
9768     * accessibility if it is important for accessibility or the querying
9769     * accessibility service has explicitly requested that view not
9770     * important for accessibility are regarded.
9771     *
9772     * @return Whether to regard the view for accessibility.
9773     *
9774     * @hide
9775     */
9776    public boolean includeForAccessibility() {
9777        if (mAttachInfo != null) {
9778            return (mAttachInfo.mAccessibilityFetchFlags
9779                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9780                    || isImportantForAccessibility();
9781        }
9782        return false;
9783    }
9784
9785    /**
9786     * Returns whether the View is considered actionable from
9787     * accessibility perspective. Such view are important for
9788     * accessibility.
9789     *
9790     * @return True if the view is actionable for accessibility.
9791     *
9792     * @hide
9793     */
9794    public boolean isActionableForAccessibility() {
9795        return (isClickable() || isLongClickable() || isFocusable());
9796    }
9797
9798    /**
9799     * Returns whether the View has registered callbacks which makes it
9800     * important for accessibility.
9801     *
9802     * @return True if the view is actionable for accessibility.
9803     */
9804    private boolean hasListenersForAccessibility() {
9805        ListenerInfo info = getListenerInfo();
9806        return mTouchDelegate != null || info.mOnKeyListener != null
9807                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9808                || info.mOnHoverListener != null || info.mOnDragListener != null;
9809    }
9810
9811    /**
9812     * Notifies that the accessibility state of this view changed. The change
9813     * is local to this view and does not represent structural changes such
9814     * as children and parent. For example, the view became focusable. The
9815     * notification is at at most once every
9816     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9817     * to avoid unnecessary load to the system. Also once a view has a pending
9818     * notification this method is a NOP until the notification has been sent.
9819     *
9820     * @hide
9821     */
9822    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9823        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9824            return;
9825        }
9826        if (mSendViewStateChangedAccessibilityEvent == null) {
9827            mSendViewStateChangedAccessibilityEvent =
9828                    new SendViewStateChangedAccessibilityEvent();
9829        }
9830        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9831    }
9832
9833    /**
9834     * Notifies that the accessibility state of this view changed. The change
9835     * is *not* local to this view and does represent structural changes such
9836     * as children and parent. For example, the view size changed. The
9837     * notification is at at most once every
9838     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9839     * to avoid unnecessary load to the system. Also once a view has a pending
9840     * notification this method is a NOP until the notification has been sent.
9841     *
9842     * @hide
9843     */
9844    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9845        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9846            return;
9847        }
9848        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9849            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9850            if (mParent != null) {
9851                try {
9852                    mParent.notifySubtreeAccessibilityStateChanged(
9853                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9854                } catch (AbstractMethodError e) {
9855                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9856                            " does not fully implement ViewParent", e);
9857                }
9858            }
9859        }
9860    }
9861
9862    /**
9863     * Change the visibility of the View without triggering any other changes. This is
9864     * important for transitions, where visibility changes should not adjust focus or
9865     * trigger a new layout. This is only used when the visibility has already been changed
9866     * and we need a transient value during an animation. When the animation completes,
9867     * the original visibility value is always restored.
9868     *
9869     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9870     * @hide
9871     */
9872    public void setTransitionVisibility(@Visibility int visibility) {
9873        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9874    }
9875
9876    /**
9877     * Reset the flag indicating the accessibility state of the subtree rooted
9878     * at this view changed.
9879     */
9880    void resetSubtreeAccessibilityStateChanged() {
9881        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9882    }
9883
9884    /**
9885     * Report an accessibility action to this view's parents for delegated processing.
9886     *
9887     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9888     * call this method to delegate an accessibility action to a supporting parent. If the parent
9889     * returns true from its
9890     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9891     * method this method will return true to signify that the action was consumed.</p>
9892     *
9893     * <p>This method is useful for implementing nested scrolling child views. If
9894     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9895     * a custom view implementation may invoke this method to allow a parent to consume the
9896     * scroll first. If this method returns true the custom view should skip its own scrolling
9897     * behavior.</p>
9898     *
9899     * @param action Accessibility action to delegate
9900     * @param arguments Optional action arguments
9901     * @return true if the action was consumed by a parent
9902     */
9903    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9904        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9905            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9906                return true;
9907            }
9908        }
9909        return false;
9910    }
9911
9912    /**
9913     * Performs the specified accessibility action on the view. For
9914     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9915     * <p>
9916     * If an {@link AccessibilityDelegate} has been specified via calling
9917     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9918     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9919     * is responsible for handling this call.
9920     * </p>
9921     *
9922     * <p>The default implementation will delegate
9923     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9924     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9925     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9926     *
9927     * @param action The action to perform.
9928     * @param arguments Optional action arguments.
9929     * @return Whether the action was performed.
9930     */
9931    public boolean performAccessibilityAction(int action, Bundle arguments) {
9932      if (mAccessibilityDelegate != null) {
9933          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9934      } else {
9935          return performAccessibilityActionInternal(action, arguments);
9936      }
9937    }
9938
9939   /**
9940    * @see #performAccessibilityAction(int, Bundle)
9941    *
9942    * Note: Called from the default {@link AccessibilityDelegate}.
9943    *
9944    * @hide
9945    */
9946    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9947        if (isNestedScrollingEnabled()
9948                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9949                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9950                || action == R.id.accessibilityActionScrollUp
9951                || action == R.id.accessibilityActionScrollLeft
9952                || action == R.id.accessibilityActionScrollDown
9953                || action == R.id.accessibilityActionScrollRight)) {
9954            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9955                return true;
9956            }
9957        }
9958
9959        switch (action) {
9960            case AccessibilityNodeInfo.ACTION_CLICK: {
9961                if (isClickable()) {
9962                    performClick();
9963                    return true;
9964                }
9965            } break;
9966            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9967                if (isLongClickable()) {
9968                    performLongClick();
9969                    return true;
9970                }
9971            } break;
9972            case AccessibilityNodeInfo.ACTION_FOCUS: {
9973                if (!hasFocus()) {
9974                    // Get out of touch mode since accessibility
9975                    // wants to move focus around.
9976                    getViewRootImpl().ensureTouchMode(false);
9977                    return requestFocus();
9978                }
9979            } break;
9980            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9981                if (hasFocus()) {
9982                    clearFocus();
9983                    return !isFocused();
9984                }
9985            } break;
9986            case AccessibilityNodeInfo.ACTION_SELECT: {
9987                if (!isSelected()) {
9988                    setSelected(true);
9989                    return isSelected();
9990                }
9991            } break;
9992            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9993                if (isSelected()) {
9994                    setSelected(false);
9995                    return !isSelected();
9996                }
9997            } break;
9998            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9999                if (!isAccessibilityFocused()) {
10000                    return requestAccessibilityFocus();
10001                }
10002            } break;
10003            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10004                if (isAccessibilityFocused()) {
10005                    clearAccessibilityFocus();
10006                    return true;
10007                }
10008            } break;
10009            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10010                if (arguments != null) {
10011                    final int granularity = arguments.getInt(
10012                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10013                    final boolean extendSelection = arguments.getBoolean(
10014                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10015                    return traverseAtGranularity(granularity, true, extendSelection);
10016                }
10017            } break;
10018            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10019                if (arguments != null) {
10020                    final int granularity = arguments.getInt(
10021                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10022                    final boolean extendSelection = arguments.getBoolean(
10023                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10024                    return traverseAtGranularity(granularity, false, extendSelection);
10025                }
10026            } break;
10027            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10028                CharSequence text = getIterableTextForAccessibility();
10029                if (text == null) {
10030                    return false;
10031                }
10032                final int start = (arguments != null) ? arguments.getInt(
10033                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10034                final int end = (arguments != null) ? arguments.getInt(
10035                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10036                // Only cursor position can be specified (selection length == 0)
10037                if ((getAccessibilitySelectionStart() != start
10038                        || getAccessibilitySelectionEnd() != end)
10039                        && (start == end)) {
10040                    setAccessibilitySelection(start, end);
10041                    notifyViewAccessibilityStateChangedIfNeeded(
10042                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10043                    return true;
10044                }
10045            } break;
10046            case R.id.accessibilityActionShowOnScreen: {
10047                if (mAttachInfo != null) {
10048                    final Rect r = mAttachInfo.mTmpInvalRect;
10049                    getDrawingRect(r);
10050                    return requestRectangleOnScreen(r, true);
10051                }
10052            } break;
10053            case R.id.accessibilityActionContextClick: {
10054                if (isContextClickable()) {
10055                    performContextClick();
10056                    return true;
10057                }
10058            } break;
10059        }
10060        return false;
10061    }
10062
10063    private boolean traverseAtGranularity(int granularity, boolean forward,
10064            boolean extendSelection) {
10065        CharSequence text = getIterableTextForAccessibility();
10066        if (text == null || text.length() == 0) {
10067            return false;
10068        }
10069        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10070        if (iterator == null) {
10071            return false;
10072        }
10073        int current = getAccessibilitySelectionEnd();
10074        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10075            current = forward ? 0 : text.length();
10076        }
10077        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10078        if (range == null) {
10079            return false;
10080        }
10081        final int segmentStart = range[0];
10082        final int segmentEnd = range[1];
10083        int selectionStart;
10084        int selectionEnd;
10085        if (extendSelection && isAccessibilitySelectionExtendable()) {
10086            selectionStart = getAccessibilitySelectionStart();
10087            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10088                selectionStart = forward ? segmentStart : segmentEnd;
10089            }
10090            selectionEnd = forward ? segmentEnd : segmentStart;
10091        } else {
10092            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10093        }
10094        setAccessibilitySelection(selectionStart, selectionEnd);
10095        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10096                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10097        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10098        return true;
10099    }
10100
10101    /**
10102     * Gets the text reported for accessibility purposes.
10103     *
10104     * @return The accessibility text.
10105     *
10106     * @hide
10107     */
10108    public CharSequence getIterableTextForAccessibility() {
10109        return getContentDescription();
10110    }
10111
10112    /**
10113     * Gets whether accessibility selection can be extended.
10114     *
10115     * @return If selection is extensible.
10116     *
10117     * @hide
10118     */
10119    public boolean isAccessibilitySelectionExtendable() {
10120        return false;
10121    }
10122
10123    /**
10124     * @hide
10125     */
10126    public int getAccessibilitySelectionStart() {
10127        return mAccessibilityCursorPosition;
10128    }
10129
10130    /**
10131     * @hide
10132     */
10133    public int getAccessibilitySelectionEnd() {
10134        return getAccessibilitySelectionStart();
10135    }
10136
10137    /**
10138     * @hide
10139     */
10140    public void setAccessibilitySelection(int start, int end) {
10141        if (start ==  end && end == mAccessibilityCursorPosition) {
10142            return;
10143        }
10144        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10145            mAccessibilityCursorPosition = start;
10146        } else {
10147            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10148        }
10149        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10150    }
10151
10152    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10153            int fromIndex, int toIndex) {
10154        if (mParent == null) {
10155            return;
10156        }
10157        AccessibilityEvent event = AccessibilityEvent.obtain(
10158                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10159        onInitializeAccessibilityEvent(event);
10160        onPopulateAccessibilityEvent(event);
10161        event.setFromIndex(fromIndex);
10162        event.setToIndex(toIndex);
10163        event.setAction(action);
10164        event.setMovementGranularity(granularity);
10165        mParent.requestSendAccessibilityEvent(this, event);
10166    }
10167
10168    /**
10169     * @hide
10170     */
10171    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10172        switch (granularity) {
10173            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10174                CharSequence text = getIterableTextForAccessibility();
10175                if (text != null && text.length() > 0) {
10176                    CharacterTextSegmentIterator iterator =
10177                        CharacterTextSegmentIterator.getInstance(
10178                                mContext.getResources().getConfiguration().locale);
10179                    iterator.initialize(text.toString());
10180                    return iterator;
10181                }
10182            } break;
10183            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10184                CharSequence text = getIterableTextForAccessibility();
10185                if (text != null && text.length() > 0) {
10186                    WordTextSegmentIterator iterator =
10187                        WordTextSegmentIterator.getInstance(
10188                                mContext.getResources().getConfiguration().locale);
10189                    iterator.initialize(text.toString());
10190                    return iterator;
10191                }
10192            } break;
10193            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10194                CharSequence text = getIterableTextForAccessibility();
10195                if (text != null && text.length() > 0) {
10196                    ParagraphTextSegmentIterator iterator =
10197                        ParagraphTextSegmentIterator.getInstance();
10198                    iterator.initialize(text.toString());
10199                    return iterator;
10200                }
10201            } break;
10202        }
10203        return null;
10204    }
10205
10206    /**
10207     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10208     * and {@link #onFinishTemporaryDetach()}.
10209     *
10210     * <p>This method always returns {@code true} when called directly or indirectly from
10211     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10212     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10213     * <ul>
10214     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10215     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10216     * </ul>
10217     * </p>
10218     *
10219     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10220     * and {@link #onFinishTemporaryDetach()}.
10221     */
10222    public final boolean isTemporarilyDetached() {
10223        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10224    }
10225
10226    /**
10227     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10228     * a container View.
10229     */
10230    @CallSuper
10231    public void dispatchStartTemporaryDetach() {
10232        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10233        onStartTemporaryDetach();
10234    }
10235
10236    /**
10237     * This is called when a container is going to temporarily detach a child, with
10238     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10239     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10240     * {@link #onDetachedFromWindow()} when the container is done.
10241     */
10242    public void onStartTemporaryDetach() {
10243        removeUnsetPressCallback();
10244        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10245    }
10246
10247    /**
10248     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10249     * a container View.
10250     */
10251    @CallSuper
10252    public void dispatchFinishTemporaryDetach() {
10253        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10254        onFinishTemporaryDetach();
10255        if (hasWindowFocus() && hasFocus()) {
10256            InputMethodManager.getInstance().focusIn(this);
10257        }
10258    }
10259
10260    /**
10261     * Called after {@link #onStartTemporaryDetach} when the container is done
10262     * changing the view.
10263     */
10264    public void onFinishTemporaryDetach() {
10265    }
10266
10267    /**
10268     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10269     * for this view's window.  Returns null if the view is not currently attached
10270     * to the window.  Normally you will not need to use this directly, but
10271     * just use the standard high-level event callbacks like
10272     * {@link #onKeyDown(int, KeyEvent)}.
10273     */
10274    public KeyEvent.DispatcherState getKeyDispatcherState() {
10275        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10276    }
10277
10278    /**
10279     * Dispatch a key event before it is processed by any input method
10280     * associated with the view hierarchy.  This can be used to intercept
10281     * key events in special situations before the IME consumes them; a
10282     * typical example would be handling the BACK key to update the application's
10283     * UI instead of allowing the IME to see it and close itself.
10284     *
10285     * @param event The key event to be dispatched.
10286     * @return True if the event was handled, false otherwise.
10287     */
10288    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10289        return onKeyPreIme(event.getKeyCode(), event);
10290    }
10291
10292    /**
10293     * Dispatch a key event to the next view on the focus path. This path runs
10294     * from the top of the view tree down to the currently focused view. If this
10295     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10296     * the next node down the focus path. This method also fires any key
10297     * listeners.
10298     *
10299     * @param event The key event to be dispatched.
10300     * @return True if the event was handled, false otherwise.
10301     */
10302    public boolean dispatchKeyEvent(KeyEvent event) {
10303        if (mInputEventConsistencyVerifier != null) {
10304            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10305        }
10306
10307        // Give any attached key listener a first crack at the event.
10308        //noinspection SimplifiableIfStatement
10309        ListenerInfo li = mListenerInfo;
10310        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10311                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10312            return true;
10313        }
10314
10315        if (event.dispatch(this, mAttachInfo != null
10316                ? mAttachInfo.mKeyDispatchState : null, this)) {
10317            return true;
10318        }
10319
10320        if (mInputEventConsistencyVerifier != null) {
10321            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10322        }
10323        return false;
10324    }
10325
10326    /**
10327     * Dispatches a key shortcut event.
10328     *
10329     * @param event The key event to be dispatched.
10330     * @return True if the event was handled by the view, false otherwise.
10331     */
10332    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10333        return onKeyShortcut(event.getKeyCode(), event);
10334    }
10335
10336    /**
10337     * Pass the touch screen motion event down to the target view, or this
10338     * view if it is the target.
10339     *
10340     * @param event The motion event to be dispatched.
10341     * @return True if the event was handled by the view, false otherwise.
10342     */
10343    public boolean dispatchTouchEvent(MotionEvent event) {
10344        // If the event should be handled by accessibility focus first.
10345        if (event.isTargetAccessibilityFocus()) {
10346            // We don't have focus or no virtual descendant has it, do not handle the event.
10347            if (!isAccessibilityFocusedViewOrHost()) {
10348                return false;
10349            }
10350            // We have focus and got the event, then use normal event dispatch.
10351            event.setTargetAccessibilityFocus(false);
10352        }
10353
10354        boolean result = false;
10355
10356        if (mInputEventConsistencyVerifier != null) {
10357            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10358        }
10359
10360        final int actionMasked = event.getActionMasked();
10361        if (actionMasked == MotionEvent.ACTION_DOWN) {
10362            // Defensive cleanup for new gesture
10363            stopNestedScroll();
10364        }
10365
10366        if (onFilterTouchEventForSecurity(event)) {
10367            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10368                result = true;
10369            }
10370            //noinspection SimplifiableIfStatement
10371            ListenerInfo li = mListenerInfo;
10372            if (li != null && li.mOnTouchListener != null
10373                    && (mViewFlags & ENABLED_MASK) == ENABLED
10374                    && li.mOnTouchListener.onTouch(this, event)) {
10375                result = true;
10376            }
10377
10378            if (!result && onTouchEvent(event)) {
10379                result = true;
10380            }
10381        }
10382
10383        if (!result && mInputEventConsistencyVerifier != null) {
10384            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10385        }
10386
10387        // Clean up after nested scrolls if this is the end of a gesture;
10388        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10389        // of the gesture.
10390        if (actionMasked == MotionEvent.ACTION_UP ||
10391                actionMasked == MotionEvent.ACTION_CANCEL ||
10392                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10393            stopNestedScroll();
10394        }
10395
10396        return result;
10397    }
10398
10399    boolean isAccessibilityFocusedViewOrHost() {
10400        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10401                .getAccessibilityFocusedHost() == this);
10402    }
10403
10404    /**
10405     * Filter the touch event to apply security policies.
10406     *
10407     * @param event The motion event to be filtered.
10408     * @return True if the event should be dispatched, false if the event should be dropped.
10409     *
10410     * @see #getFilterTouchesWhenObscured
10411     */
10412    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10413        //noinspection RedundantIfStatement
10414        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10415                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10416            // Window is obscured, drop this touch.
10417            return false;
10418        }
10419        return true;
10420    }
10421
10422    /**
10423     * Pass a trackball motion event down to the focused view.
10424     *
10425     * @param event The motion event to be dispatched.
10426     * @return True if the event was handled by the view, false otherwise.
10427     */
10428    public boolean dispatchTrackballEvent(MotionEvent event) {
10429        if (mInputEventConsistencyVerifier != null) {
10430            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10431        }
10432
10433        return onTrackballEvent(event);
10434    }
10435
10436    /**
10437     * Dispatch a generic motion event.
10438     * <p>
10439     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10440     * are delivered to the view under the pointer.  All other generic motion events are
10441     * delivered to the focused view.  Hover events are handled specially and are delivered
10442     * to {@link #onHoverEvent(MotionEvent)}.
10443     * </p>
10444     *
10445     * @param event The motion event to be dispatched.
10446     * @return True if the event was handled by the view, false otherwise.
10447     */
10448    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10449        if (mInputEventConsistencyVerifier != null) {
10450            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10451        }
10452
10453        final int source = event.getSource();
10454        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10455            final int action = event.getAction();
10456            if (action == MotionEvent.ACTION_HOVER_ENTER
10457                    || action == MotionEvent.ACTION_HOVER_MOVE
10458                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10459                if (dispatchHoverEvent(event)) {
10460                    return true;
10461                }
10462            } else if (dispatchGenericPointerEvent(event)) {
10463                return true;
10464            }
10465        } else if (dispatchGenericFocusedEvent(event)) {
10466            return true;
10467        }
10468
10469        if (dispatchGenericMotionEventInternal(event)) {
10470            return true;
10471        }
10472
10473        if (mInputEventConsistencyVerifier != null) {
10474            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10475        }
10476        return false;
10477    }
10478
10479    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10480        //noinspection SimplifiableIfStatement
10481        ListenerInfo li = mListenerInfo;
10482        if (li != null && li.mOnGenericMotionListener != null
10483                && (mViewFlags & ENABLED_MASK) == ENABLED
10484                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10485            return true;
10486        }
10487
10488        if (onGenericMotionEvent(event)) {
10489            return true;
10490        }
10491
10492        final int actionButton = event.getActionButton();
10493        switch (event.getActionMasked()) {
10494            case MotionEvent.ACTION_BUTTON_PRESS:
10495                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10496                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10497                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10498                    if (performContextClick(event.getX(), event.getY())) {
10499                        mInContextButtonPress = true;
10500                        setPressed(true, event.getX(), event.getY());
10501                        removeTapCallback();
10502                        removeLongPressCallback();
10503                        return true;
10504                    }
10505                }
10506                break;
10507
10508            case MotionEvent.ACTION_BUTTON_RELEASE:
10509                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10510                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10511                    mInContextButtonPress = false;
10512                    mIgnoreNextUpEvent = true;
10513                }
10514                break;
10515        }
10516
10517        if (mInputEventConsistencyVerifier != null) {
10518            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10519        }
10520        return false;
10521    }
10522
10523    /**
10524     * Dispatch a hover event.
10525     * <p>
10526     * Do not call this method directly.
10527     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10528     * </p>
10529     *
10530     * @param event The motion event to be dispatched.
10531     * @return True if the event was handled by the view, false otherwise.
10532     */
10533    protected boolean dispatchHoverEvent(MotionEvent event) {
10534        ListenerInfo li = mListenerInfo;
10535        //noinspection SimplifiableIfStatement
10536        if (li != null && li.mOnHoverListener != null
10537                && (mViewFlags & ENABLED_MASK) == ENABLED
10538                && li.mOnHoverListener.onHover(this, event)) {
10539            return true;
10540        }
10541
10542        return onHoverEvent(event);
10543    }
10544
10545    /**
10546     * Returns true if the view has a child to which it has recently sent
10547     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10548     * it does not have a hovered child, then it must be the innermost hovered view.
10549     * @hide
10550     */
10551    protected boolean hasHoveredChild() {
10552        return false;
10553    }
10554
10555    /**
10556     * Dispatch a generic motion event to the view under the first pointer.
10557     * <p>
10558     * Do not call this method directly.
10559     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10560     * </p>
10561     *
10562     * @param event The motion event to be dispatched.
10563     * @return True if the event was handled by the view, false otherwise.
10564     */
10565    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10566        return false;
10567    }
10568
10569    /**
10570     * Dispatch a generic motion event to the currently focused view.
10571     * <p>
10572     * Do not call this method directly.
10573     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10574     * </p>
10575     *
10576     * @param event The motion event to be dispatched.
10577     * @return True if the event was handled by the view, false otherwise.
10578     */
10579    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10580        return false;
10581    }
10582
10583    /**
10584     * Dispatch a pointer event.
10585     * <p>
10586     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10587     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10588     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10589     * and should not be expected to handle other pointing device features.
10590     * </p>
10591     *
10592     * @param event The motion event to be dispatched.
10593     * @return True if the event was handled by the view, false otherwise.
10594     * @hide
10595     */
10596    public final boolean dispatchPointerEvent(MotionEvent event) {
10597        if (event.isTouchEvent()) {
10598            return dispatchTouchEvent(event);
10599        } else {
10600            return dispatchGenericMotionEvent(event);
10601        }
10602    }
10603
10604    /**
10605     * Called when the window containing this view gains or loses window focus.
10606     * ViewGroups should override to route to their children.
10607     *
10608     * @param hasFocus True if the window containing this view now has focus,
10609     *        false otherwise.
10610     */
10611    public void dispatchWindowFocusChanged(boolean hasFocus) {
10612        onWindowFocusChanged(hasFocus);
10613    }
10614
10615    /**
10616     * Called when the window containing this view gains or loses focus.  Note
10617     * that this is separate from view focus: to receive key events, both
10618     * your view and its window must have focus.  If a window is displayed
10619     * on top of yours that takes input focus, then your own window will lose
10620     * focus but the view focus will remain unchanged.
10621     *
10622     * @param hasWindowFocus True if the window containing this view now has
10623     *        focus, false otherwise.
10624     */
10625    public void onWindowFocusChanged(boolean hasWindowFocus) {
10626        InputMethodManager imm = InputMethodManager.peekInstance();
10627        if (!hasWindowFocus) {
10628            if (isPressed()) {
10629                setPressed(false);
10630            }
10631            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10632                imm.focusOut(this);
10633            }
10634            removeLongPressCallback();
10635            removeTapCallback();
10636            onFocusLost();
10637        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10638            imm.focusIn(this);
10639        }
10640        refreshDrawableState();
10641    }
10642
10643    /**
10644     * Returns true if this view is in a window that currently has window focus.
10645     * Note that this is not the same as the view itself having focus.
10646     *
10647     * @return True if this view is in a window that currently has window focus.
10648     */
10649    public boolean hasWindowFocus() {
10650        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10651    }
10652
10653    /**
10654     * Dispatch a view visibility change down the view hierarchy.
10655     * ViewGroups should override to route to their children.
10656     * @param changedView The view whose visibility changed. Could be 'this' or
10657     * an ancestor view.
10658     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10659     * {@link #INVISIBLE} or {@link #GONE}.
10660     */
10661    protected void dispatchVisibilityChanged(@NonNull View changedView,
10662            @Visibility int visibility) {
10663        onVisibilityChanged(changedView, visibility);
10664    }
10665
10666    /**
10667     * Called when the visibility of the view or an ancestor of the view has
10668     * changed.
10669     *
10670     * @param changedView The view whose visibility changed. May be
10671     *                    {@code this} or an ancestor view.
10672     * @param visibility The new visibility, one of {@link #VISIBLE},
10673     *                   {@link #INVISIBLE} or {@link #GONE}.
10674     */
10675    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10676    }
10677
10678    /**
10679     * Dispatch a hint about whether this view is displayed. For instance, when
10680     * a View moves out of the screen, it might receives a display hint indicating
10681     * the view is not displayed. Applications should not <em>rely</em> on this hint
10682     * as there is no guarantee that they will receive one.
10683     *
10684     * @param hint A hint about whether or not this view is displayed:
10685     * {@link #VISIBLE} or {@link #INVISIBLE}.
10686     */
10687    public void dispatchDisplayHint(@Visibility int hint) {
10688        onDisplayHint(hint);
10689    }
10690
10691    /**
10692     * Gives this view a hint about whether is displayed or not. For instance, when
10693     * a View moves out of the screen, it might receives a display hint indicating
10694     * the view is not displayed. Applications should not <em>rely</em> on this hint
10695     * as there is no guarantee that they will receive one.
10696     *
10697     * @param hint A hint about whether or not this view is displayed:
10698     * {@link #VISIBLE} or {@link #INVISIBLE}.
10699     */
10700    protected void onDisplayHint(@Visibility int hint) {
10701    }
10702
10703    /**
10704     * Dispatch a window visibility change down the view hierarchy.
10705     * ViewGroups should override to route to their children.
10706     *
10707     * @param visibility The new visibility of the window.
10708     *
10709     * @see #onWindowVisibilityChanged(int)
10710     */
10711    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10712        onWindowVisibilityChanged(visibility);
10713    }
10714
10715    /**
10716     * Called when the window containing has change its visibility
10717     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10718     * that this tells you whether or not your window is being made visible
10719     * to the window manager; this does <em>not</em> tell you whether or not
10720     * your window is obscured by other windows on the screen, even if it
10721     * is itself visible.
10722     *
10723     * @param visibility The new visibility of the window.
10724     */
10725    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10726        if (visibility == VISIBLE) {
10727            initialAwakenScrollBars();
10728        }
10729    }
10730
10731    /**
10732     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10733     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10734     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10735     *
10736     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10737     *                  ancestors or by window visibility
10738     * @return true if this view is visible to the user, not counting clipping or overlapping
10739     */
10740    boolean dispatchVisibilityAggregated(boolean isVisible) {
10741        final boolean thisVisible = getVisibility() == VISIBLE;
10742        // If we're not visible but something is telling us we are, ignore it.
10743        if (thisVisible || !isVisible) {
10744            onVisibilityAggregated(isVisible);
10745        }
10746        return thisVisible && isVisible;
10747    }
10748
10749    /**
10750     * Called when the user-visibility of this View is potentially affected by a change
10751     * to this view itself, an ancestor view or the window this view is attached to.
10752     *
10753     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10754     *                  and this view's window is also visible
10755     */
10756    @CallSuper
10757    public void onVisibilityAggregated(boolean isVisible) {
10758        if (isVisible && mAttachInfo != null) {
10759            initialAwakenScrollBars();
10760        }
10761
10762        final Drawable dr = mBackground;
10763        if (dr != null && isVisible != dr.isVisible()) {
10764            dr.setVisible(isVisible, false);
10765        }
10766        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10767        if (fg != null && isVisible != fg.isVisible()) {
10768            fg.setVisible(isVisible, false);
10769        }
10770    }
10771
10772    /**
10773     * Returns the current visibility of the window this view is attached to
10774     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10775     *
10776     * @return Returns the current visibility of the view's window.
10777     */
10778    @Visibility
10779    public int getWindowVisibility() {
10780        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10781    }
10782
10783    /**
10784     * Retrieve the overall visible display size in which the window this view is
10785     * attached to has been positioned in.  This takes into account screen
10786     * decorations above the window, for both cases where the window itself
10787     * is being position inside of them or the window is being placed under
10788     * then and covered insets are used for the window to position its content
10789     * inside.  In effect, this tells you the available area where content can
10790     * be placed and remain visible to users.
10791     *
10792     * <p>This function requires an IPC back to the window manager to retrieve
10793     * the requested information, so should not be used in performance critical
10794     * code like drawing.
10795     *
10796     * @param outRect Filled in with the visible display frame.  If the view
10797     * is not attached to a window, this is simply the raw display size.
10798     */
10799    public void getWindowVisibleDisplayFrame(Rect outRect) {
10800        if (mAttachInfo != null) {
10801            try {
10802                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10803            } catch (RemoteException e) {
10804                return;
10805            }
10806            // XXX This is really broken, and probably all needs to be done
10807            // in the window manager, and we need to know more about whether
10808            // we want the area behind or in front of the IME.
10809            final Rect insets = mAttachInfo.mVisibleInsets;
10810            outRect.left += insets.left;
10811            outRect.top += insets.top;
10812            outRect.right -= insets.right;
10813            outRect.bottom -= insets.bottom;
10814            return;
10815        }
10816        // The view is not attached to a display so we don't have a context.
10817        // Make a best guess about the display size.
10818        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10819        d.getRectSize(outRect);
10820    }
10821
10822    /**
10823     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10824     * is currently in without any insets.
10825     *
10826     * @hide
10827     */
10828    public void getWindowDisplayFrame(Rect outRect) {
10829        if (mAttachInfo != null) {
10830            try {
10831                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10832            } catch (RemoteException e) {
10833                return;
10834            }
10835            return;
10836        }
10837        // The view is not attached to a display so we don't have a context.
10838        // Make a best guess about the display size.
10839        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10840        d.getRectSize(outRect);
10841    }
10842
10843    /**
10844     * Dispatch a notification about a resource configuration change down
10845     * the view hierarchy.
10846     * ViewGroups should override to route to their children.
10847     *
10848     * @param newConfig The new resource configuration.
10849     *
10850     * @see #onConfigurationChanged(android.content.res.Configuration)
10851     */
10852    public void dispatchConfigurationChanged(Configuration newConfig) {
10853        onConfigurationChanged(newConfig);
10854    }
10855
10856    /**
10857     * Called when the current configuration of the resources being used
10858     * by the application have changed.  You can use this to decide when
10859     * to reload resources that can changed based on orientation and other
10860     * configuration characteristics.  You only need to use this if you are
10861     * not relying on the normal {@link android.app.Activity} mechanism of
10862     * recreating the activity instance upon a configuration change.
10863     *
10864     * @param newConfig The new resource configuration.
10865     */
10866    protected void onConfigurationChanged(Configuration newConfig) {
10867    }
10868
10869    /**
10870     * Private function to aggregate all per-view attributes in to the view
10871     * root.
10872     */
10873    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10874        performCollectViewAttributes(attachInfo, visibility);
10875    }
10876
10877    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10878        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10879            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10880                attachInfo.mKeepScreenOn = true;
10881            }
10882            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10883            ListenerInfo li = mListenerInfo;
10884            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10885                attachInfo.mHasSystemUiListeners = true;
10886            }
10887        }
10888    }
10889
10890    void needGlobalAttributesUpdate(boolean force) {
10891        final AttachInfo ai = mAttachInfo;
10892        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10893            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10894                    || ai.mHasSystemUiListeners) {
10895                ai.mRecomputeGlobalAttributes = true;
10896            }
10897        }
10898    }
10899
10900    /**
10901     * Returns whether the device is currently in touch mode.  Touch mode is entered
10902     * once the user begins interacting with the device by touch, and affects various
10903     * things like whether focus is always visible to the user.
10904     *
10905     * @return Whether the device is in touch mode.
10906     */
10907    @ViewDebug.ExportedProperty
10908    public boolean isInTouchMode() {
10909        if (mAttachInfo != null) {
10910            return mAttachInfo.mInTouchMode;
10911        } else {
10912            return ViewRootImpl.isInTouchMode();
10913        }
10914    }
10915
10916    /**
10917     * Returns the context the view is running in, through which it can
10918     * access the current theme, resources, etc.
10919     *
10920     * @return The view's Context.
10921     */
10922    @ViewDebug.CapturedViewProperty
10923    public final Context getContext() {
10924        return mContext;
10925    }
10926
10927    /**
10928     * Handle a key event before it is processed by any input method
10929     * associated with the view hierarchy.  This can be used to intercept
10930     * key events in special situations before the IME consumes them; a
10931     * typical example would be handling the BACK key to update the application's
10932     * UI instead of allowing the IME to see it and close itself.
10933     *
10934     * @param keyCode The value in event.getKeyCode().
10935     * @param event Description of the key event.
10936     * @return If you handled the event, return true. If you want to allow the
10937     *         event to be handled by the next receiver, return false.
10938     */
10939    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10940        return false;
10941    }
10942
10943    /**
10944     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10945     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10946     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10947     * is released, if the view is enabled and clickable.
10948     * <p>
10949     * Key presses in software keyboards will generally NOT trigger this
10950     * listener, although some may elect to do so in some situations. Do not
10951     * rely on this to catch software key presses.
10952     *
10953     * @param keyCode a key code that represents the button pressed, from
10954     *                {@link android.view.KeyEvent}
10955     * @param event the KeyEvent object that defines the button action
10956     */
10957    public boolean onKeyDown(int keyCode, KeyEvent event) {
10958        if (KeyEvent.isConfirmKey(keyCode)) {
10959            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10960                return true;
10961            }
10962
10963            if (event.getRepeatCount() == 0) {
10964                // Long clickable items don't necessarily have to be clickable.
10965                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
10966                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
10967                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
10968                    // For the purposes of menu anchoring and drawable hotspots,
10969                    // key events are considered to be at the center of the view.
10970                    final float x = getWidth() / 2f;
10971                    final float y = getHeight() / 2f;
10972                    if (clickable) {
10973                        setPressed(true, x, y);
10974                    }
10975                    checkForLongClick(0, x, y);
10976                    return true;
10977                }
10978            }
10979        }
10980
10981        return false;
10982    }
10983
10984    /**
10985     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10986     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10987     * the event).
10988     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10989     * although some may elect to do so in some situations. Do not rely on this to
10990     * catch software key presses.
10991     */
10992    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10993        return false;
10994    }
10995
10996    /**
10997     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10998     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10999     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11000     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11001     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11002     * although some may elect to do so in some situations. Do not rely on this to
11003     * catch software key presses.
11004     *
11005     * @param keyCode A key code that represents the button pressed, from
11006     *                {@link android.view.KeyEvent}.
11007     * @param event   The KeyEvent object that defines the button action.
11008     */
11009    public boolean onKeyUp(int keyCode, KeyEvent event) {
11010        if (KeyEvent.isConfirmKey(keyCode)) {
11011            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11012                return true;
11013            }
11014            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11015                setPressed(false);
11016
11017                if (!mHasPerformedLongPress) {
11018                    // This is a tap, so remove the longpress check
11019                    removeLongPressCallback();
11020                    return performClick();
11021                }
11022            }
11023        }
11024        return false;
11025    }
11026
11027    /**
11028     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11029     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11030     * the event).
11031     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11032     * although some may elect to do so in some situations. Do not rely on this to
11033     * catch software key presses.
11034     *
11035     * @param keyCode     A key code that represents the button pressed, from
11036     *                    {@link android.view.KeyEvent}.
11037     * @param repeatCount The number of times the action was made.
11038     * @param event       The KeyEvent object that defines the button action.
11039     */
11040    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11041        return false;
11042    }
11043
11044    /**
11045     * Called on the focused view when a key shortcut event is not handled.
11046     * Override this method to implement local key shortcuts for the View.
11047     * Key shortcuts can also be implemented by setting the
11048     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11049     *
11050     * @param keyCode The value in event.getKeyCode().
11051     * @param event Description of the key event.
11052     * @return If you handled the event, return true. If you want to allow the
11053     *         event to be handled by the next receiver, return false.
11054     */
11055    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11056        return false;
11057    }
11058
11059    /**
11060     * Check whether the called view is a text editor, in which case it
11061     * would make sense to automatically display a soft input window for
11062     * it.  Subclasses should override this if they implement
11063     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11064     * a call on that method would return a non-null InputConnection, and
11065     * they are really a first-class editor that the user would normally
11066     * start typing on when the go into a window containing your view.
11067     *
11068     * <p>The default implementation always returns false.  This does
11069     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11070     * will not be called or the user can not otherwise perform edits on your
11071     * view; it is just a hint to the system that this is not the primary
11072     * purpose of this view.
11073     *
11074     * @return Returns true if this view is a text editor, else false.
11075     */
11076    public boolean onCheckIsTextEditor() {
11077        return false;
11078    }
11079
11080    /**
11081     * Create a new InputConnection for an InputMethod to interact
11082     * with the view.  The default implementation returns null, since it doesn't
11083     * support input methods.  You can override this to implement such support.
11084     * This is only needed for views that take focus and text input.
11085     *
11086     * <p>When implementing this, you probably also want to implement
11087     * {@link #onCheckIsTextEditor()} to indicate you will return a
11088     * non-null InputConnection.</p>
11089     *
11090     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11091     * object correctly and in its entirety, so that the connected IME can rely
11092     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11093     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11094     * must be filled in with the correct cursor position for IMEs to work correctly
11095     * with your application.</p>
11096     *
11097     * @param outAttrs Fill in with attribute information about the connection.
11098     */
11099    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11100        return null;
11101    }
11102
11103    /**
11104     * Called by the {@link android.view.inputmethod.InputMethodManager}
11105     * when a view who is not the current
11106     * input connection target is trying to make a call on the manager.  The
11107     * default implementation returns false; you can override this to return
11108     * true for certain views if you are performing InputConnection proxying
11109     * to them.
11110     * @param view The View that is making the InputMethodManager call.
11111     * @return Return true to allow the call, false to reject.
11112     */
11113    public boolean checkInputConnectionProxy(View view) {
11114        return false;
11115    }
11116
11117    /**
11118     * Show the context menu for this view. It is not safe to hold on to the
11119     * menu after returning from this method.
11120     *
11121     * You should normally not overload this method. Overload
11122     * {@link #onCreateContextMenu(ContextMenu)} or define an
11123     * {@link OnCreateContextMenuListener} to add items to the context menu.
11124     *
11125     * @param menu The context menu to populate
11126     */
11127    public void createContextMenu(ContextMenu menu) {
11128        ContextMenuInfo menuInfo = getContextMenuInfo();
11129
11130        // Sets the current menu info so all items added to menu will have
11131        // my extra info set.
11132        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11133
11134        onCreateContextMenu(menu);
11135        ListenerInfo li = mListenerInfo;
11136        if (li != null && li.mOnCreateContextMenuListener != null) {
11137            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11138        }
11139
11140        // Clear the extra information so subsequent items that aren't mine don't
11141        // have my extra info.
11142        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11143
11144        if (mParent != null) {
11145            mParent.createContextMenu(menu);
11146        }
11147    }
11148
11149    /**
11150     * Views should implement this if they have extra information to associate
11151     * with the context menu. The return result is supplied as a parameter to
11152     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11153     * callback.
11154     *
11155     * @return Extra information about the item for which the context menu
11156     *         should be shown. This information will vary across different
11157     *         subclasses of View.
11158     */
11159    protected ContextMenuInfo getContextMenuInfo() {
11160        return null;
11161    }
11162
11163    /**
11164     * Views should implement this if the view itself is going to add items to
11165     * the context menu.
11166     *
11167     * @param menu the context menu to populate
11168     */
11169    protected void onCreateContextMenu(ContextMenu menu) {
11170    }
11171
11172    /**
11173     * Implement this method to handle trackball motion events.  The
11174     * <em>relative</em> movement of the trackball since the last event
11175     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11176     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11177     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11178     * they will often be fractional values, representing the more fine-grained
11179     * movement information available from a trackball).
11180     *
11181     * @param event The motion event.
11182     * @return True if the event was handled, false otherwise.
11183     */
11184    public boolean onTrackballEvent(MotionEvent event) {
11185        return false;
11186    }
11187
11188    /**
11189     * Implement this method to handle generic motion events.
11190     * <p>
11191     * Generic motion events describe joystick movements, mouse hovers, track pad
11192     * touches, scroll wheel movements and other input events.  The
11193     * {@link MotionEvent#getSource() source} of the motion event specifies
11194     * the class of input that was received.  Implementations of this method
11195     * must examine the bits in the source before processing the event.
11196     * The following code example shows how this is done.
11197     * </p><p>
11198     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11199     * are delivered to the view under the pointer.  All other generic motion events are
11200     * delivered to the focused view.
11201     * </p>
11202     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11203     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11204     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11205     *             // process the joystick movement...
11206     *             return true;
11207     *         }
11208     *     }
11209     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11210     *         switch (event.getAction()) {
11211     *             case MotionEvent.ACTION_HOVER_MOVE:
11212     *                 // process the mouse hover movement...
11213     *                 return true;
11214     *             case MotionEvent.ACTION_SCROLL:
11215     *                 // process the scroll wheel movement...
11216     *                 return true;
11217     *         }
11218     *     }
11219     *     return super.onGenericMotionEvent(event);
11220     * }</pre>
11221     *
11222     * @param event The generic motion event being processed.
11223     * @return True if the event was handled, false otherwise.
11224     */
11225    public boolean onGenericMotionEvent(MotionEvent event) {
11226        return false;
11227    }
11228
11229    /**
11230     * Implement this method to handle hover events.
11231     * <p>
11232     * This method is called whenever a pointer is hovering into, over, or out of the
11233     * bounds of a view and the view is not currently being touched.
11234     * Hover events are represented as pointer events with action
11235     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11236     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11237     * </p>
11238     * <ul>
11239     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11240     * when the pointer enters the bounds of the view.</li>
11241     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11242     * when the pointer has already entered the bounds of the view and has moved.</li>
11243     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11244     * when the pointer has exited the bounds of the view or when the pointer is
11245     * about to go down due to a button click, tap, or similar user action that
11246     * causes the view to be touched.</li>
11247     * </ul>
11248     * <p>
11249     * The view should implement this method to return true to indicate that it is
11250     * handling the hover event, such as by changing its drawable state.
11251     * </p><p>
11252     * The default implementation calls {@link #setHovered} to update the hovered state
11253     * of the view when a hover enter or hover exit event is received, if the view
11254     * is enabled and is clickable.  The default implementation also sends hover
11255     * accessibility events.
11256     * </p>
11257     *
11258     * @param event The motion event that describes the hover.
11259     * @return True if the view handled the hover event.
11260     *
11261     * @see #isHovered
11262     * @see #setHovered
11263     * @see #onHoverChanged
11264     */
11265    public boolean onHoverEvent(MotionEvent event) {
11266        // The root view may receive hover (or touch) events that are outside the bounds of
11267        // the window.  This code ensures that we only send accessibility events for
11268        // hovers that are actually within the bounds of the root view.
11269        final int action = event.getActionMasked();
11270        if (!mSendingHoverAccessibilityEvents) {
11271            if ((action == MotionEvent.ACTION_HOVER_ENTER
11272                    || action == MotionEvent.ACTION_HOVER_MOVE)
11273                    && !hasHoveredChild()
11274                    && pointInView(event.getX(), event.getY())) {
11275                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11276                mSendingHoverAccessibilityEvents = true;
11277            }
11278        } else {
11279            if (action == MotionEvent.ACTION_HOVER_EXIT
11280                    || (action == MotionEvent.ACTION_MOVE
11281                            && !pointInView(event.getX(), event.getY()))) {
11282                mSendingHoverAccessibilityEvents = false;
11283                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11284            }
11285        }
11286
11287        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11288                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11289                && isOnScrollbar(event.getX(), event.getY())) {
11290            awakenScrollBars();
11291        }
11292        if (isHoverable()) {
11293            switch (action) {
11294                case MotionEvent.ACTION_HOVER_ENTER:
11295                    setHovered(true);
11296                    break;
11297                case MotionEvent.ACTION_HOVER_EXIT:
11298                    setHovered(false);
11299                    break;
11300            }
11301
11302            // Dispatch the event to onGenericMotionEvent before returning true.
11303            // This is to provide compatibility with existing applications that
11304            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11305            // break because of the new default handling for hoverable views
11306            // in onHoverEvent.
11307            // Note that onGenericMotionEvent will be called by default when
11308            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11309            dispatchGenericMotionEventInternal(event);
11310            // The event was already handled by calling setHovered(), so always
11311            // return true.
11312            return true;
11313        }
11314
11315        return false;
11316    }
11317
11318    /**
11319     * Returns true if the view should handle {@link #onHoverEvent}
11320     * by calling {@link #setHovered} to change its hovered state.
11321     *
11322     * @return True if the view is hoverable.
11323     */
11324    private boolean isHoverable() {
11325        final int viewFlags = mViewFlags;
11326        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11327            return false;
11328        }
11329
11330        return (viewFlags & CLICKABLE) == CLICKABLE
11331                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11332                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11333    }
11334
11335    /**
11336     * Returns true if the view is currently hovered.
11337     *
11338     * @return True if the view is currently hovered.
11339     *
11340     * @see #setHovered
11341     * @see #onHoverChanged
11342     */
11343    @ViewDebug.ExportedProperty
11344    public boolean isHovered() {
11345        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11346    }
11347
11348    /**
11349     * Sets whether the view is currently hovered.
11350     * <p>
11351     * Calling this method also changes the drawable state of the view.  This
11352     * enables the view to react to hover by using different drawable resources
11353     * to change its appearance.
11354     * </p><p>
11355     * The {@link #onHoverChanged} method is called when the hovered state changes.
11356     * </p>
11357     *
11358     * @param hovered True if the view is hovered.
11359     *
11360     * @see #isHovered
11361     * @see #onHoverChanged
11362     */
11363    public void setHovered(boolean hovered) {
11364        if (hovered) {
11365            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11366                mPrivateFlags |= PFLAG_HOVERED;
11367                refreshDrawableState();
11368                onHoverChanged(true);
11369            }
11370        } else {
11371            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11372                mPrivateFlags &= ~PFLAG_HOVERED;
11373                refreshDrawableState();
11374                onHoverChanged(false);
11375            }
11376        }
11377    }
11378
11379    /**
11380     * Implement this method to handle hover state changes.
11381     * <p>
11382     * This method is called whenever the hover state changes as a result of a
11383     * call to {@link #setHovered}.
11384     * </p>
11385     *
11386     * @param hovered The current hover state, as returned by {@link #isHovered}.
11387     *
11388     * @see #isHovered
11389     * @see #setHovered
11390     */
11391    public void onHoverChanged(boolean hovered) {
11392    }
11393
11394    /**
11395     * Handles scroll bar dragging by mouse input.
11396     *
11397     * @hide
11398     * @param event The motion event.
11399     *
11400     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11401     */
11402    protected boolean handleScrollBarDragging(MotionEvent event) {
11403        if (mScrollCache == null) {
11404            return false;
11405        }
11406        final float x = event.getX();
11407        final float y = event.getY();
11408        final int action = event.getAction();
11409        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11410                && action != MotionEvent.ACTION_DOWN)
11411                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11412                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11413            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11414            return false;
11415        }
11416
11417        switch (action) {
11418            case MotionEvent.ACTION_MOVE:
11419                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11420                    return false;
11421                }
11422                if (mScrollCache.mScrollBarDraggingState
11423                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11424                    final Rect bounds = mScrollCache.mScrollBarBounds;
11425                    getVerticalScrollBarBounds(bounds);
11426                    final int range = computeVerticalScrollRange();
11427                    final int offset = computeVerticalScrollOffset();
11428                    final int extent = computeVerticalScrollExtent();
11429
11430                    final int thumbLength = ScrollBarUtils.getThumbLength(
11431                            bounds.height(), bounds.width(), extent, range);
11432                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11433                            bounds.height(), thumbLength, extent, range, offset);
11434
11435                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11436                    final float maxThumbOffset = bounds.height() - thumbLength;
11437                    final float newThumbOffset =
11438                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11439                    final int height = getHeight();
11440                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11441                            && height > 0 && extent > 0) {
11442                        final int newY = Math.round((range - extent)
11443                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11444                        if (newY != getScrollY()) {
11445                            mScrollCache.mScrollBarDraggingPos = y;
11446                            setScrollY(newY);
11447                        }
11448                    }
11449                    return true;
11450                }
11451                if (mScrollCache.mScrollBarDraggingState
11452                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11453                    final Rect bounds = mScrollCache.mScrollBarBounds;
11454                    getHorizontalScrollBarBounds(bounds);
11455                    final int range = computeHorizontalScrollRange();
11456                    final int offset = computeHorizontalScrollOffset();
11457                    final int extent = computeHorizontalScrollExtent();
11458
11459                    final int thumbLength = ScrollBarUtils.getThumbLength(
11460                            bounds.width(), bounds.height(), extent, range);
11461                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11462                            bounds.width(), thumbLength, extent, range, offset);
11463
11464                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11465                    final float maxThumbOffset = bounds.width() - thumbLength;
11466                    final float newThumbOffset =
11467                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11468                    final int width = getWidth();
11469                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11470                            && width > 0 && extent > 0) {
11471                        final int newX = Math.round((range - extent)
11472                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11473                        if (newX != getScrollX()) {
11474                            mScrollCache.mScrollBarDraggingPos = x;
11475                            setScrollX(newX);
11476                        }
11477                    }
11478                    return true;
11479                }
11480            case MotionEvent.ACTION_DOWN:
11481                if (mScrollCache.state == ScrollabilityCache.OFF) {
11482                    return false;
11483                }
11484                if (isOnVerticalScrollbarThumb(x, y)) {
11485                    mScrollCache.mScrollBarDraggingState =
11486                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11487                    mScrollCache.mScrollBarDraggingPos = y;
11488                    return true;
11489                }
11490                if (isOnHorizontalScrollbarThumb(x, y)) {
11491                    mScrollCache.mScrollBarDraggingState =
11492                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11493                    mScrollCache.mScrollBarDraggingPos = x;
11494                    return true;
11495                }
11496        }
11497        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11498        return false;
11499    }
11500
11501    /**
11502     * Implement this method to handle touch screen motion events.
11503     * <p>
11504     * If this method is used to detect click actions, it is recommended that
11505     * the actions be performed by implementing and calling
11506     * {@link #performClick()}. This will ensure consistent system behavior,
11507     * including:
11508     * <ul>
11509     * <li>obeying click sound preferences
11510     * <li>dispatching OnClickListener calls
11511     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11512     * accessibility features are enabled
11513     * </ul>
11514     *
11515     * @param event The motion event.
11516     * @return True if the event was handled, false otherwise.
11517     */
11518    public boolean onTouchEvent(MotionEvent event) {
11519        final float x = event.getX();
11520        final float y = event.getY();
11521        final int viewFlags = mViewFlags;
11522        final int action = event.getAction();
11523
11524        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11525                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11526                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11527
11528        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11529            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11530                setPressed(false);
11531            }
11532            // A disabled view that is clickable still consumes the touch
11533            // events, it just doesn't respond to them.
11534            return clickable;
11535        }
11536        if (mTouchDelegate != null) {
11537            if (mTouchDelegate.onTouchEvent(event)) {
11538                return true;
11539            }
11540        }
11541
11542        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11543            switch (action) {
11544                case MotionEvent.ACTION_UP:
11545                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11546                        handleTooltipUp();
11547                    }
11548                    if (!clickable) {
11549                        removeTapCallback();
11550                        removeLongPressCallback();
11551                        mInContextButtonPress = false;
11552                        mHasPerformedLongPress = false;
11553                        mIgnoreNextUpEvent = false;
11554                        break;
11555                    }
11556                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11557                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11558                        // take focus if we don't have it already and we should in
11559                        // touch mode.
11560                        boolean focusTaken = false;
11561                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11562                            focusTaken = requestFocus();
11563                        }
11564
11565                        if (prepressed) {
11566                            // The button is being released before we actually
11567                            // showed it as pressed.  Make it show the pressed
11568                            // state now (before scheduling the click) to ensure
11569                            // the user sees it.
11570                            setPressed(true, x, y);
11571                        }
11572
11573                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11574                            // This is a tap, so remove the longpress check
11575                            removeLongPressCallback();
11576
11577                            // Only perform take click actions if we were in the pressed state
11578                            if (!focusTaken) {
11579                                // Use a Runnable and post this rather than calling
11580                                // performClick directly. This lets other visual state
11581                                // of the view update before click actions start.
11582                                if (mPerformClick == null) {
11583                                    mPerformClick = new PerformClick();
11584                                }
11585                                if (!post(mPerformClick)) {
11586                                    performClick();
11587                                }
11588                            }
11589                        }
11590
11591                        if (mUnsetPressedState == null) {
11592                            mUnsetPressedState = new UnsetPressedState();
11593                        }
11594
11595                        if (prepressed) {
11596                            postDelayed(mUnsetPressedState,
11597                                    ViewConfiguration.getPressedStateDuration());
11598                        } else if (!post(mUnsetPressedState)) {
11599                            // If the post failed, unpress right now
11600                            mUnsetPressedState.run();
11601                        }
11602
11603                        removeTapCallback();
11604                    }
11605                    mIgnoreNextUpEvent = false;
11606                    break;
11607
11608                case MotionEvent.ACTION_DOWN:
11609                    mHasPerformedLongPress = false;
11610
11611                    if (!clickable) {
11612                        checkForLongClick(0, x, y);
11613                        break;
11614                    }
11615
11616                    if (performButtonActionOnTouchDown(event)) {
11617                        break;
11618                    }
11619
11620                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11621                    boolean isInScrollingContainer = isInScrollingContainer();
11622
11623                    // For views inside a scrolling container, delay the pressed feedback for
11624                    // a short period in case this is a scroll.
11625                    if (isInScrollingContainer) {
11626                        mPrivateFlags |= PFLAG_PREPRESSED;
11627                        if (mPendingCheckForTap == null) {
11628                            mPendingCheckForTap = new CheckForTap();
11629                        }
11630                        mPendingCheckForTap.x = event.getX();
11631                        mPendingCheckForTap.y = event.getY();
11632                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11633                    } else {
11634                        // Not inside a scrolling container, so show the feedback right away
11635                        setPressed(true, x, y);
11636                        checkForLongClick(0, x, y);
11637                    }
11638                    break;
11639
11640                case MotionEvent.ACTION_CANCEL:
11641                    if (clickable) {
11642                        setPressed(false);
11643                    }
11644                    removeTapCallback();
11645                    removeLongPressCallback();
11646                    mInContextButtonPress = false;
11647                    mHasPerformedLongPress = false;
11648                    mIgnoreNextUpEvent = false;
11649                    break;
11650
11651                case MotionEvent.ACTION_MOVE:
11652                    if (clickable) {
11653                        drawableHotspotChanged(x, y);
11654                    }
11655
11656                    // Be lenient about moving outside of buttons
11657                    if (!pointInView(x, y, mTouchSlop)) {
11658                        // Outside button
11659                        // Remove any future long press/tap checks
11660                        removeTapCallback();
11661                        removeLongPressCallback();
11662                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11663                            setPressed(false);
11664                        }
11665                    }
11666                    break;
11667            }
11668
11669            return true;
11670        }
11671
11672        return false;
11673    }
11674
11675    /**
11676     * @hide
11677     */
11678    public boolean isInScrollingContainer() {
11679        ViewParent p = getParent();
11680        while (p != null && p instanceof ViewGroup) {
11681            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11682                return true;
11683            }
11684            p = p.getParent();
11685        }
11686        return false;
11687    }
11688
11689    /**
11690     * Remove the longpress detection timer.
11691     */
11692    private void removeLongPressCallback() {
11693        if (mPendingCheckForLongPress != null) {
11694            removeCallbacks(mPendingCheckForLongPress);
11695        }
11696    }
11697
11698    /**
11699     * Remove the pending click action
11700     */
11701    private void removePerformClickCallback() {
11702        if (mPerformClick != null) {
11703            removeCallbacks(mPerformClick);
11704        }
11705    }
11706
11707    /**
11708     * Remove the prepress detection timer.
11709     */
11710    private void removeUnsetPressCallback() {
11711        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11712            setPressed(false);
11713            removeCallbacks(mUnsetPressedState);
11714        }
11715    }
11716
11717    /**
11718     * Remove the tap detection timer.
11719     */
11720    private void removeTapCallback() {
11721        if (mPendingCheckForTap != null) {
11722            mPrivateFlags &= ~PFLAG_PREPRESSED;
11723            removeCallbacks(mPendingCheckForTap);
11724        }
11725    }
11726
11727    /**
11728     * Cancels a pending long press.  Your subclass can use this if you
11729     * want the context menu to come up if the user presses and holds
11730     * at the same place, but you don't want it to come up if they press
11731     * and then move around enough to cause scrolling.
11732     */
11733    public void cancelLongPress() {
11734        removeLongPressCallback();
11735
11736        /*
11737         * The prepressed state handled by the tap callback is a display
11738         * construct, but the tap callback will post a long press callback
11739         * less its own timeout. Remove it here.
11740         */
11741        removeTapCallback();
11742    }
11743
11744    /**
11745     * Remove the pending callback for sending a
11746     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11747     */
11748    private void removeSendViewScrolledAccessibilityEventCallback() {
11749        if (mSendViewScrolledAccessibilityEvent != null) {
11750            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11751            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11752        }
11753    }
11754
11755    /**
11756     * Sets the TouchDelegate for this View.
11757     */
11758    public void setTouchDelegate(TouchDelegate delegate) {
11759        mTouchDelegate = delegate;
11760    }
11761
11762    /**
11763     * Gets the TouchDelegate for this View.
11764     */
11765    public TouchDelegate getTouchDelegate() {
11766        return mTouchDelegate;
11767    }
11768
11769    /**
11770     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11771     *
11772     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11773     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11774     * available. This method should only be called for touch events.
11775     *
11776     * <p class="note">This api is not intended for most applications. Buffered dispatch
11777     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11778     * streams will not improve your input latency. Side effects include: increased latency,
11779     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11780     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11781     * you.</p>
11782     */
11783    public final void requestUnbufferedDispatch(MotionEvent event) {
11784        final int action = event.getAction();
11785        if (mAttachInfo == null
11786                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11787                || !event.isTouchEvent()) {
11788            return;
11789        }
11790        mAttachInfo.mUnbufferedDispatchRequested = true;
11791    }
11792
11793    /**
11794     * Set flags controlling behavior of this view.
11795     *
11796     * @param flags Constant indicating the value which should be set
11797     * @param mask Constant indicating the bit range that should be changed
11798     */
11799    void setFlags(int flags, int mask) {
11800        final boolean accessibilityEnabled =
11801                AccessibilityManager.getInstance(mContext).isEnabled();
11802        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11803
11804        int old = mViewFlags;
11805        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11806
11807        int changed = mViewFlags ^ old;
11808        if (changed == 0) {
11809            return;
11810        }
11811        int privateFlags = mPrivateFlags;
11812
11813        /* Check if the FOCUSABLE bit has changed */
11814        if (((changed & FOCUSABLE_MASK) != 0) &&
11815                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11816            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11817                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11818                /* Give up focus if we are no longer focusable */
11819                clearFocus();
11820            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11821                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11822                /*
11823                 * Tell the view system that we are now available to take focus
11824                 * if no one else already has it.
11825                 */
11826                if (mParent != null) mParent.focusableViewAvailable(this);
11827            }
11828        }
11829
11830        final int newVisibility = flags & VISIBILITY_MASK;
11831        if (newVisibility == VISIBLE) {
11832            if ((changed & VISIBILITY_MASK) != 0) {
11833                /*
11834                 * If this view is becoming visible, invalidate it in case it changed while
11835                 * it was not visible. Marking it drawn ensures that the invalidation will
11836                 * go through.
11837                 */
11838                mPrivateFlags |= PFLAG_DRAWN;
11839                invalidate(true);
11840
11841                needGlobalAttributesUpdate(true);
11842
11843                // a view becoming visible is worth notifying the parent
11844                // about in case nothing has focus.  even if this specific view
11845                // isn't focusable, it may contain something that is, so let
11846                // the root view try to give this focus if nothing else does.
11847                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11848                    mParent.focusableViewAvailable(this);
11849                }
11850            }
11851        }
11852
11853        /* Check if the GONE bit has changed */
11854        if ((changed & GONE) != 0) {
11855            needGlobalAttributesUpdate(false);
11856            requestLayout();
11857
11858            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11859                if (hasFocus()) clearFocus();
11860                clearAccessibilityFocus();
11861                destroyDrawingCache();
11862                if (mParent instanceof View) {
11863                    // GONE views noop invalidation, so invalidate the parent
11864                    ((View) mParent).invalidate(true);
11865                }
11866                // Mark the view drawn to ensure that it gets invalidated properly the next
11867                // time it is visible and gets invalidated
11868                mPrivateFlags |= PFLAG_DRAWN;
11869            }
11870            if (mAttachInfo != null) {
11871                mAttachInfo.mViewVisibilityChanged = true;
11872            }
11873        }
11874
11875        /* Check if the VISIBLE bit has changed */
11876        if ((changed & INVISIBLE) != 0) {
11877            needGlobalAttributesUpdate(false);
11878            /*
11879             * If this view is becoming invisible, set the DRAWN flag so that
11880             * the next invalidate() will not be skipped.
11881             */
11882            mPrivateFlags |= PFLAG_DRAWN;
11883
11884            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11885                // root view becoming invisible shouldn't clear focus and accessibility focus
11886                if (getRootView() != this) {
11887                    if (hasFocus()) clearFocus();
11888                    clearAccessibilityFocus();
11889                }
11890            }
11891            if (mAttachInfo != null) {
11892                mAttachInfo.mViewVisibilityChanged = true;
11893            }
11894        }
11895
11896        if ((changed & VISIBILITY_MASK) != 0) {
11897            // If the view is invisible, cleanup its display list to free up resources
11898            if (newVisibility != VISIBLE && mAttachInfo != null) {
11899                cleanupDraw();
11900            }
11901
11902            if (mParent instanceof ViewGroup) {
11903                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11904                        (changed & VISIBILITY_MASK), newVisibility);
11905                ((View) mParent).invalidate(true);
11906            } else if (mParent != null) {
11907                mParent.invalidateChild(this, null);
11908            }
11909
11910            if (mAttachInfo != null) {
11911                dispatchVisibilityChanged(this, newVisibility);
11912
11913                // Aggregated visibility changes are dispatched to attached views
11914                // in visible windows where the parent is currently shown/drawn
11915                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11916                // discounting clipping or overlapping. This makes it a good place
11917                // to change animation states.
11918                if (mParent != null && getWindowVisibility() == VISIBLE &&
11919                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11920                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11921                }
11922                notifySubtreeAccessibilityStateChangedIfNeeded();
11923            }
11924        }
11925
11926        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11927            destroyDrawingCache();
11928        }
11929
11930        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11931            destroyDrawingCache();
11932            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11933            invalidateParentCaches();
11934        }
11935
11936        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11937            destroyDrawingCache();
11938            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11939        }
11940
11941        if ((changed & DRAW_MASK) != 0) {
11942            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11943                if (mBackground != null
11944                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11945                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11946                } else {
11947                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11948                }
11949            } else {
11950                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11951            }
11952            requestLayout();
11953            invalidate(true);
11954        }
11955
11956        if ((changed & KEEP_SCREEN_ON) != 0) {
11957            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11958                mParent.recomputeViewAttributes(this);
11959            }
11960        }
11961
11962        if (accessibilityEnabled) {
11963            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11964                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11965                    || (changed & CONTEXT_CLICKABLE) != 0) {
11966                if (oldIncludeForAccessibility != includeForAccessibility()) {
11967                    notifySubtreeAccessibilityStateChangedIfNeeded();
11968                } else {
11969                    notifyViewAccessibilityStateChangedIfNeeded(
11970                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11971                }
11972            } else if ((changed & ENABLED_MASK) != 0) {
11973                notifyViewAccessibilityStateChangedIfNeeded(
11974                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11975            }
11976        }
11977    }
11978
11979    /**
11980     * Change the view's z order in the tree, so it's on top of other sibling
11981     * views. This ordering change may affect layout, if the parent container
11982     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11983     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11984     * method should be followed by calls to {@link #requestLayout()} and
11985     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11986     * with the new child ordering.
11987     *
11988     * @see ViewGroup#bringChildToFront(View)
11989     */
11990    public void bringToFront() {
11991        if (mParent != null) {
11992            mParent.bringChildToFront(this);
11993        }
11994    }
11995
11996    /**
11997     * This is called in response to an internal scroll in this view (i.e., the
11998     * view scrolled its own contents). This is typically as a result of
11999     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12000     * called.
12001     *
12002     * @param l Current horizontal scroll origin.
12003     * @param t Current vertical scroll origin.
12004     * @param oldl Previous horizontal scroll origin.
12005     * @param oldt Previous vertical scroll origin.
12006     */
12007    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12008        notifySubtreeAccessibilityStateChangedIfNeeded();
12009
12010        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12011            postSendViewScrolledAccessibilityEventCallback();
12012        }
12013
12014        mBackgroundSizeChanged = true;
12015        if (mForegroundInfo != null) {
12016            mForegroundInfo.mBoundsChanged = true;
12017        }
12018
12019        final AttachInfo ai = mAttachInfo;
12020        if (ai != null) {
12021            ai.mViewScrollChanged = true;
12022        }
12023
12024        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12025            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12026        }
12027    }
12028
12029    /**
12030     * Interface definition for a callback to be invoked when the scroll
12031     * X or Y positions of a view change.
12032     * <p>
12033     * <b>Note:</b> Some views handle scrolling independently from View and may
12034     * have their own separate listeners for scroll-type events. For example,
12035     * {@link android.widget.ListView ListView} allows clients to register an
12036     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12037     * to listen for changes in list scroll position.
12038     *
12039     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12040     */
12041    public interface OnScrollChangeListener {
12042        /**
12043         * Called when the scroll position of a view changes.
12044         *
12045         * @param v The view whose scroll position has changed.
12046         * @param scrollX Current horizontal scroll origin.
12047         * @param scrollY Current vertical scroll origin.
12048         * @param oldScrollX Previous horizontal scroll origin.
12049         * @param oldScrollY Previous vertical scroll origin.
12050         */
12051        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12052    }
12053
12054    /**
12055     * Interface definition for a callback to be invoked when the layout bounds of a view
12056     * changes due to layout processing.
12057     */
12058    public interface OnLayoutChangeListener {
12059        /**
12060         * Called when the layout bounds of a view changes due to layout processing.
12061         *
12062         * @param v The view whose bounds have changed.
12063         * @param left The new value of the view's left property.
12064         * @param top The new value of the view's top property.
12065         * @param right The new value of the view's right property.
12066         * @param bottom The new value of the view's bottom property.
12067         * @param oldLeft The previous value of the view's left property.
12068         * @param oldTop The previous value of the view's top property.
12069         * @param oldRight The previous value of the view's right property.
12070         * @param oldBottom The previous value of the view's bottom property.
12071         */
12072        void onLayoutChange(View v, int left, int top, int right, int bottom,
12073            int oldLeft, int oldTop, int oldRight, int oldBottom);
12074    }
12075
12076    /**
12077     * This is called during layout when the size of this view has changed. If
12078     * you were just added to the view hierarchy, you're called with the old
12079     * values of 0.
12080     *
12081     * @param w Current width of this view.
12082     * @param h Current height of this view.
12083     * @param oldw Old width of this view.
12084     * @param oldh Old height of this view.
12085     */
12086    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12087    }
12088
12089    /**
12090     * Called by draw to draw the child views. This may be overridden
12091     * by derived classes to gain control just before its children are drawn
12092     * (but after its own view has been drawn).
12093     * @param canvas the canvas on which to draw the view
12094     */
12095    protected void dispatchDraw(Canvas canvas) {
12096
12097    }
12098
12099    /**
12100     * Gets the parent of this view. Note that the parent is a
12101     * ViewParent and not necessarily a View.
12102     *
12103     * @return Parent of this view.
12104     */
12105    public final ViewParent getParent() {
12106        return mParent;
12107    }
12108
12109    /**
12110     * Set the horizontal scrolled position of your view. This will cause a call to
12111     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12112     * invalidated.
12113     * @param value the x position to scroll to
12114     */
12115    public void setScrollX(int value) {
12116        scrollTo(value, mScrollY);
12117    }
12118
12119    /**
12120     * Set the vertical scrolled position of your view. This will cause a call to
12121     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12122     * invalidated.
12123     * @param value the y position to scroll to
12124     */
12125    public void setScrollY(int value) {
12126        scrollTo(mScrollX, value);
12127    }
12128
12129    /**
12130     * Return the scrolled left position of this view. This is the left edge of
12131     * the displayed part of your view. You do not need to draw any pixels
12132     * farther left, since those are outside of the frame of your view on
12133     * screen.
12134     *
12135     * @return The left edge of the displayed part of your view, in pixels.
12136     */
12137    public final int getScrollX() {
12138        return mScrollX;
12139    }
12140
12141    /**
12142     * Return the scrolled top position of this view. This is the top edge of
12143     * the displayed part of your view. You do not need to draw any pixels above
12144     * it, since those are outside of the frame of your view on screen.
12145     *
12146     * @return The top edge of the displayed part of your view, in pixels.
12147     */
12148    public final int getScrollY() {
12149        return mScrollY;
12150    }
12151
12152    /**
12153     * Return the width of the your view.
12154     *
12155     * @return The width of your view, in pixels.
12156     */
12157    @ViewDebug.ExportedProperty(category = "layout")
12158    public final int getWidth() {
12159        return mRight - mLeft;
12160    }
12161
12162    /**
12163     * Return the height of your view.
12164     *
12165     * @return The height of your view, in pixels.
12166     */
12167    @ViewDebug.ExportedProperty(category = "layout")
12168    public final int getHeight() {
12169        return mBottom - mTop;
12170    }
12171
12172    /**
12173     * Return the visible drawing bounds of your view. Fills in the output
12174     * rectangle with the values from getScrollX(), getScrollY(),
12175     * getWidth(), and getHeight(). These bounds do not account for any
12176     * transformation properties currently set on the view, such as
12177     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12178     *
12179     * @param outRect The (scrolled) drawing bounds of the view.
12180     */
12181    public void getDrawingRect(Rect outRect) {
12182        outRect.left = mScrollX;
12183        outRect.top = mScrollY;
12184        outRect.right = mScrollX + (mRight - mLeft);
12185        outRect.bottom = mScrollY + (mBottom - mTop);
12186    }
12187
12188    /**
12189     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12190     * raw width component (that is the result is masked by
12191     * {@link #MEASURED_SIZE_MASK}).
12192     *
12193     * @return The raw measured width of this view.
12194     */
12195    public final int getMeasuredWidth() {
12196        return mMeasuredWidth & MEASURED_SIZE_MASK;
12197    }
12198
12199    /**
12200     * Return the full width measurement information for this view as computed
12201     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12202     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12203     * This should be used during measurement and layout calculations only. Use
12204     * {@link #getWidth()} to see how wide a view is after layout.
12205     *
12206     * @return The measured width of this view as a bit mask.
12207     */
12208    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12209            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12210                    name = "MEASURED_STATE_TOO_SMALL"),
12211    })
12212    public final int getMeasuredWidthAndState() {
12213        return mMeasuredWidth;
12214    }
12215
12216    /**
12217     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12218     * raw height component (that is the result is masked by
12219     * {@link #MEASURED_SIZE_MASK}).
12220     *
12221     * @return The raw measured height of this view.
12222     */
12223    public final int getMeasuredHeight() {
12224        return mMeasuredHeight & MEASURED_SIZE_MASK;
12225    }
12226
12227    /**
12228     * Return the full height measurement information for this view as computed
12229     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12230     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12231     * This should be used during measurement and layout calculations only. Use
12232     * {@link #getHeight()} to see how wide a view is after layout.
12233     *
12234     * @return The measured height of this view as a bit mask.
12235     */
12236    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12237            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12238                    name = "MEASURED_STATE_TOO_SMALL"),
12239    })
12240    public final int getMeasuredHeightAndState() {
12241        return mMeasuredHeight;
12242    }
12243
12244    /**
12245     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12246     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12247     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12248     * and the height component is at the shifted bits
12249     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12250     */
12251    public final int getMeasuredState() {
12252        return (mMeasuredWidth&MEASURED_STATE_MASK)
12253                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12254                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12255    }
12256
12257    /**
12258     * The transform matrix of this view, which is calculated based on the current
12259     * rotation, scale, and pivot properties.
12260     *
12261     * @see #getRotation()
12262     * @see #getScaleX()
12263     * @see #getScaleY()
12264     * @see #getPivotX()
12265     * @see #getPivotY()
12266     * @return The current transform matrix for the view
12267     */
12268    public Matrix getMatrix() {
12269        ensureTransformationInfo();
12270        final Matrix matrix = mTransformationInfo.mMatrix;
12271        mRenderNode.getMatrix(matrix);
12272        return matrix;
12273    }
12274
12275    /**
12276     * Returns true if the transform matrix is the identity matrix.
12277     * Recomputes the matrix if necessary.
12278     *
12279     * @return True if the transform matrix is the identity matrix, false otherwise.
12280     */
12281    final boolean hasIdentityMatrix() {
12282        return mRenderNode.hasIdentityMatrix();
12283    }
12284
12285    void ensureTransformationInfo() {
12286        if (mTransformationInfo == null) {
12287            mTransformationInfo = new TransformationInfo();
12288        }
12289    }
12290
12291    /**
12292     * Utility method to retrieve the inverse of the current mMatrix property.
12293     * We cache the matrix to avoid recalculating it when transform properties
12294     * have not changed.
12295     *
12296     * @return The inverse of the current matrix of this view.
12297     * @hide
12298     */
12299    public final Matrix getInverseMatrix() {
12300        ensureTransformationInfo();
12301        if (mTransformationInfo.mInverseMatrix == null) {
12302            mTransformationInfo.mInverseMatrix = new Matrix();
12303        }
12304        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12305        mRenderNode.getInverseMatrix(matrix);
12306        return matrix;
12307    }
12308
12309    /**
12310     * Gets the distance along the Z axis from the camera to this view.
12311     *
12312     * @see #setCameraDistance(float)
12313     *
12314     * @return The distance along the Z axis.
12315     */
12316    public float getCameraDistance() {
12317        final float dpi = mResources.getDisplayMetrics().densityDpi;
12318        return -(mRenderNode.getCameraDistance() * dpi);
12319    }
12320
12321    /**
12322     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12323     * views are drawn) from the camera to this view. The camera's distance
12324     * affects 3D transformations, for instance rotations around the X and Y
12325     * axis. If the rotationX or rotationY properties are changed and this view is
12326     * large (more than half the size of the screen), it is recommended to always
12327     * use a camera distance that's greater than the height (X axis rotation) or
12328     * the width (Y axis rotation) of this view.</p>
12329     *
12330     * <p>The distance of the camera from the view plane can have an affect on the
12331     * perspective distortion of the view when it is rotated around the x or y axis.
12332     * For example, a large distance will result in a large viewing angle, and there
12333     * will not be much perspective distortion of the view as it rotates. A short
12334     * distance may cause much more perspective distortion upon rotation, and can
12335     * also result in some drawing artifacts if the rotated view ends up partially
12336     * behind the camera (which is why the recommendation is to use a distance at
12337     * least as far as the size of the view, if the view is to be rotated.)</p>
12338     *
12339     * <p>The distance is expressed in "depth pixels." The default distance depends
12340     * on the screen density. For instance, on a medium density display, the
12341     * default distance is 1280. On a high density display, the default distance
12342     * is 1920.</p>
12343     *
12344     * <p>If you want to specify a distance that leads to visually consistent
12345     * results across various densities, use the following formula:</p>
12346     * <pre>
12347     * float scale = context.getResources().getDisplayMetrics().density;
12348     * view.setCameraDistance(distance * scale);
12349     * </pre>
12350     *
12351     * <p>The density scale factor of a high density display is 1.5,
12352     * and 1920 = 1280 * 1.5.</p>
12353     *
12354     * @param distance The distance in "depth pixels", if negative the opposite
12355     *        value is used
12356     *
12357     * @see #setRotationX(float)
12358     * @see #setRotationY(float)
12359     */
12360    public void setCameraDistance(float distance) {
12361        final float dpi = mResources.getDisplayMetrics().densityDpi;
12362
12363        invalidateViewProperty(true, false);
12364        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12365        invalidateViewProperty(false, false);
12366
12367        invalidateParentIfNeededAndWasQuickRejected();
12368    }
12369
12370    /**
12371     * The degrees that the view is rotated around the pivot point.
12372     *
12373     * @see #setRotation(float)
12374     * @see #getPivotX()
12375     * @see #getPivotY()
12376     *
12377     * @return The degrees of rotation.
12378     */
12379    @ViewDebug.ExportedProperty(category = "drawing")
12380    public float getRotation() {
12381        return mRenderNode.getRotation();
12382    }
12383
12384    /**
12385     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12386     * result in clockwise rotation.
12387     *
12388     * @param rotation The degrees of rotation.
12389     *
12390     * @see #getRotation()
12391     * @see #getPivotX()
12392     * @see #getPivotY()
12393     * @see #setRotationX(float)
12394     * @see #setRotationY(float)
12395     *
12396     * @attr ref android.R.styleable#View_rotation
12397     */
12398    public void setRotation(float rotation) {
12399        if (rotation != getRotation()) {
12400            // Double-invalidation is necessary to capture view's old and new areas
12401            invalidateViewProperty(true, false);
12402            mRenderNode.setRotation(rotation);
12403            invalidateViewProperty(false, true);
12404
12405            invalidateParentIfNeededAndWasQuickRejected();
12406            notifySubtreeAccessibilityStateChangedIfNeeded();
12407        }
12408    }
12409
12410    /**
12411     * The degrees that the view is rotated around the vertical axis through the pivot point.
12412     *
12413     * @see #getPivotX()
12414     * @see #getPivotY()
12415     * @see #setRotationY(float)
12416     *
12417     * @return The degrees of Y rotation.
12418     */
12419    @ViewDebug.ExportedProperty(category = "drawing")
12420    public float getRotationY() {
12421        return mRenderNode.getRotationY();
12422    }
12423
12424    /**
12425     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12426     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12427     * down the y axis.
12428     *
12429     * When rotating large views, it is recommended to adjust the camera distance
12430     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12431     *
12432     * @param rotationY The degrees of Y rotation.
12433     *
12434     * @see #getRotationY()
12435     * @see #getPivotX()
12436     * @see #getPivotY()
12437     * @see #setRotation(float)
12438     * @see #setRotationX(float)
12439     * @see #setCameraDistance(float)
12440     *
12441     * @attr ref android.R.styleable#View_rotationY
12442     */
12443    public void setRotationY(float rotationY) {
12444        if (rotationY != getRotationY()) {
12445            invalidateViewProperty(true, false);
12446            mRenderNode.setRotationY(rotationY);
12447            invalidateViewProperty(false, true);
12448
12449            invalidateParentIfNeededAndWasQuickRejected();
12450            notifySubtreeAccessibilityStateChangedIfNeeded();
12451        }
12452    }
12453
12454    /**
12455     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12456     *
12457     * @see #getPivotX()
12458     * @see #getPivotY()
12459     * @see #setRotationX(float)
12460     *
12461     * @return The degrees of X rotation.
12462     */
12463    @ViewDebug.ExportedProperty(category = "drawing")
12464    public float getRotationX() {
12465        return mRenderNode.getRotationX();
12466    }
12467
12468    /**
12469     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12470     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12471     * x axis.
12472     *
12473     * When rotating large views, it is recommended to adjust the camera distance
12474     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12475     *
12476     * @param rotationX The degrees of X rotation.
12477     *
12478     * @see #getRotationX()
12479     * @see #getPivotX()
12480     * @see #getPivotY()
12481     * @see #setRotation(float)
12482     * @see #setRotationY(float)
12483     * @see #setCameraDistance(float)
12484     *
12485     * @attr ref android.R.styleable#View_rotationX
12486     */
12487    public void setRotationX(float rotationX) {
12488        if (rotationX != getRotationX()) {
12489            invalidateViewProperty(true, false);
12490            mRenderNode.setRotationX(rotationX);
12491            invalidateViewProperty(false, true);
12492
12493            invalidateParentIfNeededAndWasQuickRejected();
12494            notifySubtreeAccessibilityStateChangedIfNeeded();
12495        }
12496    }
12497
12498    /**
12499     * The amount that the view is scaled in x around the pivot point, as a proportion of
12500     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12501     *
12502     * <p>By default, this is 1.0f.
12503     *
12504     * @see #getPivotX()
12505     * @see #getPivotY()
12506     * @return The scaling factor.
12507     */
12508    @ViewDebug.ExportedProperty(category = "drawing")
12509    public float getScaleX() {
12510        return mRenderNode.getScaleX();
12511    }
12512
12513    /**
12514     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12515     * the view's unscaled width. A value of 1 means that no scaling is applied.
12516     *
12517     * @param scaleX The scaling factor.
12518     * @see #getPivotX()
12519     * @see #getPivotY()
12520     *
12521     * @attr ref android.R.styleable#View_scaleX
12522     */
12523    public void setScaleX(float scaleX) {
12524        if (scaleX != getScaleX()) {
12525            invalidateViewProperty(true, false);
12526            mRenderNode.setScaleX(scaleX);
12527            invalidateViewProperty(false, true);
12528
12529            invalidateParentIfNeededAndWasQuickRejected();
12530            notifySubtreeAccessibilityStateChangedIfNeeded();
12531        }
12532    }
12533
12534    /**
12535     * The amount that the view is scaled in y around the pivot point, as a proportion of
12536     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12537     *
12538     * <p>By default, this is 1.0f.
12539     *
12540     * @see #getPivotX()
12541     * @see #getPivotY()
12542     * @return The scaling factor.
12543     */
12544    @ViewDebug.ExportedProperty(category = "drawing")
12545    public float getScaleY() {
12546        return mRenderNode.getScaleY();
12547    }
12548
12549    /**
12550     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12551     * the view's unscaled width. A value of 1 means that no scaling is applied.
12552     *
12553     * @param scaleY The scaling factor.
12554     * @see #getPivotX()
12555     * @see #getPivotY()
12556     *
12557     * @attr ref android.R.styleable#View_scaleY
12558     */
12559    public void setScaleY(float scaleY) {
12560        if (scaleY != getScaleY()) {
12561            invalidateViewProperty(true, false);
12562            mRenderNode.setScaleY(scaleY);
12563            invalidateViewProperty(false, true);
12564
12565            invalidateParentIfNeededAndWasQuickRejected();
12566            notifySubtreeAccessibilityStateChangedIfNeeded();
12567        }
12568    }
12569
12570    /**
12571     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12572     * and {@link #setScaleX(float) scaled}.
12573     *
12574     * @see #getRotation()
12575     * @see #getScaleX()
12576     * @see #getScaleY()
12577     * @see #getPivotY()
12578     * @return The x location of the pivot point.
12579     *
12580     * @attr ref android.R.styleable#View_transformPivotX
12581     */
12582    @ViewDebug.ExportedProperty(category = "drawing")
12583    public float getPivotX() {
12584        return mRenderNode.getPivotX();
12585    }
12586
12587    /**
12588     * Sets the x location of the point around which the view is
12589     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12590     * By default, the pivot point is centered on the object.
12591     * Setting this property disables this behavior and causes the view to use only the
12592     * explicitly set pivotX and pivotY values.
12593     *
12594     * @param pivotX The x location of the pivot point.
12595     * @see #getRotation()
12596     * @see #getScaleX()
12597     * @see #getScaleY()
12598     * @see #getPivotY()
12599     *
12600     * @attr ref android.R.styleable#View_transformPivotX
12601     */
12602    public void setPivotX(float pivotX) {
12603        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12604            invalidateViewProperty(true, false);
12605            mRenderNode.setPivotX(pivotX);
12606            invalidateViewProperty(false, true);
12607
12608            invalidateParentIfNeededAndWasQuickRejected();
12609        }
12610    }
12611
12612    /**
12613     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12614     * and {@link #setScaleY(float) scaled}.
12615     *
12616     * @see #getRotation()
12617     * @see #getScaleX()
12618     * @see #getScaleY()
12619     * @see #getPivotY()
12620     * @return The y location of the pivot point.
12621     *
12622     * @attr ref android.R.styleable#View_transformPivotY
12623     */
12624    @ViewDebug.ExportedProperty(category = "drawing")
12625    public float getPivotY() {
12626        return mRenderNode.getPivotY();
12627    }
12628
12629    /**
12630     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12631     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12632     * Setting this property disables this behavior and causes the view to use only the
12633     * explicitly set pivotX and pivotY values.
12634     *
12635     * @param pivotY The y location of the pivot point.
12636     * @see #getRotation()
12637     * @see #getScaleX()
12638     * @see #getScaleY()
12639     * @see #getPivotY()
12640     *
12641     * @attr ref android.R.styleable#View_transformPivotY
12642     */
12643    public void setPivotY(float pivotY) {
12644        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12645            invalidateViewProperty(true, false);
12646            mRenderNode.setPivotY(pivotY);
12647            invalidateViewProperty(false, true);
12648
12649            invalidateParentIfNeededAndWasQuickRejected();
12650        }
12651    }
12652
12653    /**
12654     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12655     * completely transparent and 1 means the view is completely opaque.
12656     *
12657     * <p>By default this is 1.0f.
12658     * @return The opacity of the view.
12659     */
12660    @ViewDebug.ExportedProperty(category = "drawing")
12661    public float getAlpha() {
12662        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12663    }
12664
12665    /**
12666     * Sets the behavior for overlapping rendering for this view (see {@link
12667     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12668     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12669     * providing the value which is then used internally. That is, when {@link
12670     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12671     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12672     * instead.
12673     *
12674     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12675     * instead of that returned by {@link #hasOverlappingRendering()}.
12676     *
12677     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12678     */
12679    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12680        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12681        if (hasOverlappingRendering) {
12682            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12683        } else {
12684            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12685        }
12686    }
12687
12688    /**
12689     * Returns the value for overlapping rendering that is used internally. This is either
12690     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12691     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12692     *
12693     * @return The value for overlapping rendering being used internally.
12694     */
12695    public final boolean getHasOverlappingRendering() {
12696        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12697                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12698                hasOverlappingRendering();
12699    }
12700
12701    /**
12702     * Returns whether this View has content which overlaps.
12703     *
12704     * <p>This function, intended to be overridden by specific View types, is an optimization when
12705     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12706     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12707     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12708     * directly. An example of overlapping rendering is a TextView with a background image, such as
12709     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12710     * ImageView with only the foreground image. The default implementation returns true; subclasses
12711     * should override if they have cases which can be optimized.</p>
12712     *
12713     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12714     * necessitates that a View return true if it uses the methods internally without passing the
12715     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12716     *
12717     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12718     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12719     *
12720     * @return true if the content in this view might overlap, false otherwise.
12721     */
12722    @ViewDebug.ExportedProperty(category = "drawing")
12723    public boolean hasOverlappingRendering() {
12724        return true;
12725    }
12726
12727    /**
12728     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12729     * completely transparent and 1 means the view is completely opaque.
12730     *
12731     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12732     * can have significant performance implications, especially for large views. It is best to use
12733     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12734     *
12735     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12736     * strongly recommended for performance reasons to either override
12737     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12738     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12739     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12740     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12741     * of rendering cost, even for simple or small views. Starting with
12742     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12743     * applied to the view at the rendering level.</p>
12744     *
12745     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12746     * responsible for applying the opacity itself.</p>
12747     *
12748     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12749     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12750     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12751     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12752     *
12753     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12754     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12755     * {@link #hasOverlappingRendering}.</p>
12756     *
12757     * @param alpha The opacity of the view.
12758     *
12759     * @see #hasOverlappingRendering()
12760     * @see #setLayerType(int, android.graphics.Paint)
12761     *
12762     * @attr ref android.R.styleable#View_alpha
12763     */
12764    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12765        ensureTransformationInfo();
12766        if (mTransformationInfo.mAlpha != alpha) {
12767            // Report visibility changes, which can affect children, to accessibility
12768            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
12769                notifySubtreeAccessibilityStateChangedIfNeeded();
12770            }
12771            mTransformationInfo.mAlpha = alpha;
12772            if (onSetAlpha((int) (alpha * 255))) {
12773                mPrivateFlags |= PFLAG_ALPHA_SET;
12774                // subclass is handling alpha - don't optimize rendering cache invalidation
12775                invalidateParentCaches();
12776                invalidate(true);
12777            } else {
12778                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12779                invalidateViewProperty(true, false);
12780                mRenderNode.setAlpha(getFinalAlpha());
12781            }
12782        }
12783    }
12784
12785    /**
12786     * Faster version of setAlpha() which performs the same steps except there are
12787     * no calls to invalidate(). The caller of this function should perform proper invalidation
12788     * on the parent and this object. The return value indicates whether the subclass handles
12789     * alpha (the return value for onSetAlpha()).
12790     *
12791     * @param alpha The new value for the alpha property
12792     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12793     *         the new value for the alpha property is different from the old value
12794     */
12795    boolean setAlphaNoInvalidation(float alpha) {
12796        ensureTransformationInfo();
12797        if (mTransformationInfo.mAlpha != alpha) {
12798            mTransformationInfo.mAlpha = alpha;
12799            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12800            if (subclassHandlesAlpha) {
12801                mPrivateFlags |= PFLAG_ALPHA_SET;
12802                return true;
12803            } else {
12804                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12805                mRenderNode.setAlpha(getFinalAlpha());
12806            }
12807        }
12808        return false;
12809    }
12810
12811    /**
12812     * This property is hidden and intended only for use by the Fade transition, which
12813     * animates it to produce a visual translucency that does not side-effect (or get
12814     * affected by) the real alpha property. This value is composited with the other
12815     * alpha value (and the AlphaAnimation value, when that is present) to produce
12816     * a final visual translucency result, which is what is passed into the DisplayList.
12817     *
12818     * @hide
12819     */
12820    public void setTransitionAlpha(float alpha) {
12821        ensureTransformationInfo();
12822        if (mTransformationInfo.mTransitionAlpha != alpha) {
12823            mTransformationInfo.mTransitionAlpha = alpha;
12824            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12825            invalidateViewProperty(true, false);
12826            mRenderNode.setAlpha(getFinalAlpha());
12827        }
12828    }
12829
12830    /**
12831     * Calculates the visual alpha of this view, which is a combination of the actual
12832     * alpha value and the transitionAlpha value (if set).
12833     */
12834    private float getFinalAlpha() {
12835        if (mTransformationInfo != null) {
12836            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12837        }
12838        return 1;
12839    }
12840
12841    /**
12842     * This property is hidden and intended only for use by the Fade transition, which
12843     * animates it to produce a visual translucency that does not side-effect (or get
12844     * affected by) the real alpha property. This value is composited with the other
12845     * alpha value (and the AlphaAnimation value, when that is present) to produce
12846     * a final visual translucency result, which is what is passed into the DisplayList.
12847     *
12848     * @hide
12849     */
12850    @ViewDebug.ExportedProperty(category = "drawing")
12851    public float getTransitionAlpha() {
12852        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12853    }
12854
12855    /**
12856     * Top position of this view relative to its parent.
12857     *
12858     * @return The top of this view, in pixels.
12859     */
12860    @ViewDebug.CapturedViewProperty
12861    public final int getTop() {
12862        return mTop;
12863    }
12864
12865    /**
12866     * Sets the top position of this view relative to its parent. This method is meant to be called
12867     * by the layout system and should not generally be called otherwise, because the property
12868     * may be changed at any time by the layout.
12869     *
12870     * @param top The top of this view, in pixels.
12871     */
12872    public final void setTop(int top) {
12873        if (top != mTop) {
12874            final boolean matrixIsIdentity = hasIdentityMatrix();
12875            if (matrixIsIdentity) {
12876                if (mAttachInfo != null) {
12877                    int minTop;
12878                    int yLoc;
12879                    if (top < mTop) {
12880                        minTop = top;
12881                        yLoc = top - mTop;
12882                    } else {
12883                        minTop = mTop;
12884                        yLoc = 0;
12885                    }
12886                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12887                }
12888            } else {
12889                // Double-invalidation is necessary to capture view's old and new areas
12890                invalidate(true);
12891            }
12892
12893            int width = mRight - mLeft;
12894            int oldHeight = mBottom - mTop;
12895
12896            mTop = top;
12897            mRenderNode.setTop(mTop);
12898
12899            sizeChange(width, mBottom - mTop, width, oldHeight);
12900
12901            if (!matrixIsIdentity) {
12902                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12903                invalidate(true);
12904            }
12905            mBackgroundSizeChanged = true;
12906            if (mForegroundInfo != null) {
12907                mForegroundInfo.mBoundsChanged = true;
12908            }
12909            invalidateParentIfNeeded();
12910            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12911                // View was rejected last time it was drawn by its parent; this may have changed
12912                invalidateParentIfNeeded();
12913            }
12914        }
12915    }
12916
12917    /**
12918     * Bottom position of this view relative to its parent.
12919     *
12920     * @return The bottom of this view, in pixels.
12921     */
12922    @ViewDebug.CapturedViewProperty
12923    public final int getBottom() {
12924        return mBottom;
12925    }
12926
12927    /**
12928     * True if this view has changed since the last time being drawn.
12929     *
12930     * @return The dirty state of this view.
12931     */
12932    public boolean isDirty() {
12933        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12934    }
12935
12936    /**
12937     * Sets the bottom position of this view relative to its parent. This method is meant to be
12938     * called by the layout system and should not generally be called otherwise, because the
12939     * property may be changed at any time by the layout.
12940     *
12941     * @param bottom The bottom of this view, in pixels.
12942     */
12943    public final void setBottom(int bottom) {
12944        if (bottom != mBottom) {
12945            final boolean matrixIsIdentity = hasIdentityMatrix();
12946            if (matrixIsIdentity) {
12947                if (mAttachInfo != null) {
12948                    int maxBottom;
12949                    if (bottom < mBottom) {
12950                        maxBottom = mBottom;
12951                    } else {
12952                        maxBottom = bottom;
12953                    }
12954                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12955                }
12956            } else {
12957                // Double-invalidation is necessary to capture view's old and new areas
12958                invalidate(true);
12959            }
12960
12961            int width = mRight - mLeft;
12962            int oldHeight = mBottom - mTop;
12963
12964            mBottom = bottom;
12965            mRenderNode.setBottom(mBottom);
12966
12967            sizeChange(width, mBottom - mTop, width, oldHeight);
12968
12969            if (!matrixIsIdentity) {
12970                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12971                invalidate(true);
12972            }
12973            mBackgroundSizeChanged = true;
12974            if (mForegroundInfo != null) {
12975                mForegroundInfo.mBoundsChanged = true;
12976            }
12977            invalidateParentIfNeeded();
12978            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12979                // View was rejected last time it was drawn by its parent; this may have changed
12980                invalidateParentIfNeeded();
12981            }
12982        }
12983    }
12984
12985    /**
12986     * Left position of this view relative to its parent.
12987     *
12988     * @return The left edge of this view, in pixels.
12989     */
12990    @ViewDebug.CapturedViewProperty
12991    public final int getLeft() {
12992        return mLeft;
12993    }
12994
12995    /**
12996     * Sets the left position of this view relative to its parent. This method is meant to be called
12997     * by the layout system and should not generally be called otherwise, because the property
12998     * may be changed at any time by the layout.
12999     *
13000     * @param left The left of this view, in pixels.
13001     */
13002    public final void setLeft(int left) {
13003        if (left != mLeft) {
13004            final boolean matrixIsIdentity = hasIdentityMatrix();
13005            if (matrixIsIdentity) {
13006                if (mAttachInfo != null) {
13007                    int minLeft;
13008                    int xLoc;
13009                    if (left < mLeft) {
13010                        minLeft = left;
13011                        xLoc = left - mLeft;
13012                    } else {
13013                        minLeft = mLeft;
13014                        xLoc = 0;
13015                    }
13016                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13017                }
13018            } else {
13019                // Double-invalidation is necessary to capture view's old and new areas
13020                invalidate(true);
13021            }
13022
13023            int oldWidth = mRight - mLeft;
13024            int height = mBottom - mTop;
13025
13026            mLeft = left;
13027            mRenderNode.setLeft(left);
13028
13029            sizeChange(mRight - mLeft, height, oldWidth, height);
13030
13031            if (!matrixIsIdentity) {
13032                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13033                invalidate(true);
13034            }
13035            mBackgroundSizeChanged = true;
13036            if (mForegroundInfo != null) {
13037                mForegroundInfo.mBoundsChanged = true;
13038            }
13039            invalidateParentIfNeeded();
13040            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13041                // View was rejected last time it was drawn by its parent; this may have changed
13042                invalidateParentIfNeeded();
13043            }
13044        }
13045    }
13046
13047    /**
13048     * Right position of this view relative to its parent.
13049     *
13050     * @return The right edge of this view, in pixels.
13051     */
13052    @ViewDebug.CapturedViewProperty
13053    public final int getRight() {
13054        return mRight;
13055    }
13056
13057    /**
13058     * Sets the right position of this view relative to its parent. This method is meant to be called
13059     * by the layout system and should not generally be called otherwise, because the property
13060     * may be changed at any time by the layout.
13061     *
13062     * @param right The right of this view, in pixels.
13063     */
13064    public final void setRight(int right) {
13065        if (right != mRight) {
13066            final boolean matrixIsIdentity = hasIdentityMatrix();
13067            if (matrixIsIdentity) {
13068                if (mAttachInfo != null) {
13069                    int maxRight;
13070                    if (right < mRight) {
13071                        maxRight = mRight;
13072                    } else {
13073                        maxRight = right;
13074                    }
13075                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13076                }
13077            } else {
13078                // Double-invalidation is necessary to capture view's old and new areas
13079                invalidate(true);
13080            }
13081
13082            int oldWidth = mRight - mLeft;
13083            int height = mBottom - mTop;
13084
13085            mRight = right;
13086            mRenderNode.setRight(mRight);
13087
13088            sizeChange(mRight - mLeft, height, oldWidth, height);
13089
13090            if (!matrixIsIdentity) {
13091                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13092                invalidate(true);
13093            }
13094            mBackgroundSizeChanged = true;
13095            if (mForegroundInfo != null) {
13096                mForegroundInfo.mBoundsChanged = true;
13097            }
13098            invalidateParentIfNeeded();
13099            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13100                // View was rejected last time it was drawn by its parent; this may have changed
13101                invalidateParentIfNeeded();
13102            }
13103        }
13104    }
13105
13106    /**
13107     * The visual x position of this view, in pixels. This is equivalent to the
13108     * {@link #setTranslationX(float) translationX} property plus the current
13109     * {@link #getLeft() left} property.
13110     *
13111     * @return The visual x position of this view, in pixels.
13112     */
13113    @ViewDebug.ExportedProperty(category = "drawing")
13114    public float getX() {
13115        return mLeft + getTranslationX();
13116    }
13117
13118    /**
13119     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13120     * {@link #setTranslationX(float) translationX} property to be the difference between
13121     * the x value passed in and the current {@link #getLeft() left} property.
13122     *
13123     * @param x The visual x position of this view, in pixels.
13124     */
13125    public void setX(float x) {
13126        setTranslationX(x - mLeft);
13127    }
13128
13129    /**
13130     * The visual y position of this view, in pixels. This is equivalent to the
13131     * {@link #setTranslationY(float) translationY} property plus the current
13132     * {@link #getTop() top} property.
13133     *
13134     * @return The visual y position of this view, in pixels.
13135     */
13136    @ViewDebug.ExportedProperty(category = "drawing")
13137    public float getY() {
13138        return mTop + getTranslationY();
13139    }
13140
13141    /**
13142     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13143     * {@link #setTranslationY(float) translationY} property to be the difference between
13144     * the y value passed in and the current {@link #getTop() top} property.
13145     *
13146     * @param y The visual y position of this view, in pixels.
13147     */
13148    public void setY(float y) {
13149        setTranslationY(y - mTop);
13150    }
13151
13152    /**
13153     * The visual z position of this view, in pixels. This is equivalent to the
13154     * {@link #setTranslationZ(float) translationZ} property plus the current
13155     * {@link #getElevation() elevation} property.
13156     *
13157     * @return The visual z position of this view, in pixels.
13158     */
13159    @ViewDebug.ExportedProperty(category = "drawing")
13160    public float getZ() {
13161        return getElevation() + getTranslationZ();
13162    }
13163
13164    /**
13165     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13166     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13167     * the x value passed in and the current {@link #getElevation() elevation} property.
13168     *
13169     * @param z The visual z position of this view, in pixels.
13170     */
13171    public void setZ(float z) {
13172        setTranslationZ(z - getElevation());
13173    }
13174
13175    /**
13176     * The base elevation of this view relative to its parent, in pixels.
13177     *
13178     * @return The base depth position of the view, in pixels.
13179     */
13180    @ViewDebug.ExportedProperty(category = "drawing")
13181    public float getElevation() {
13182        return mRenderNode.getElevation();
13183    }
13184
13185    /**
13186     * Sets the base elevation of this view, in pixels.
13187     *
13188     * @attr ref android.R.styleable#View_elevation
13189     */
13190    public void setElevation(float elevation) {
13191        if (elevation != getElevation()) {
13192            invalidateViewProperty(true, false);
13193            mRenderNode.setElevation(elevation);
13194            invalidateViewProperty(false, true);
13195
13196            invalidateParentIfNeededAndWasQuickRejected();
13197        }
13198    }
13199
13200    /**
13201     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13202     * This position is post-layout, in addition to wherever the object's
13203     * layout placed it.
13204     *
13205     * @return The horizontal position of this view relative to its left position, in pixels.
13206     */
13207    @ViewDebug.ExportedProperty(category = "drawing")
13208    public float getTranslationX() {
13209        return mRenderNode.getTranslationX();
13210    }
13211
13212    /**
13213     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13214     * This effectively positions the object post-layout, in addition to wherever the object's
13215     * layout placed it.
13216     *
13217     * @param translationX The horizontal position of this view relative to its left position,
13218     * in pixels.
13219     *
13220     * @attr ref android.R.styleable#View_translationX
13221     */
13222    public void setTranslationX(float translationX) {
13223        if (translationX != getTranslationX()) {
13224            invalidateViewProperty(true, false);
13225            mRenderNode.setTranslationX(translationX);
13226            invalidateViewProperty(false, true);
13227
13228            invalidateParentIfNeededAndWasQuickRejected();
13229            notifySubtreeAccessibilityStateChangedIfNeeded();
13230        }
13231    }
13232
13233    /**
13234     * The vertical location of this view relative to its {@link #getTop() top} position.
13235     * This position is post-layout, in addition to wherever the object's
13236     * layout placed it.
13237     *
13238     * @return The vertical position of this view relative to its top position,
13239     * in pixels.
13240     */
13241    @ViewDebug.ExportedProperty(category = "drawing")
13242    public float getTranslationY() {
13243        return mRenderNode.getTranslationY();
13244    }
13245
13246    /**
13247     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13248     * This effectively positions the object post-layout, in addition to wherever the object's
13249     * layout placed it.
13250     *
13251     * @param translationY The vertical position of this view relative to its top position,
13252     * in pixels.
13253     *
13254     * @attr ref android.R.styleable#View_translationY
13255     */
13256    public void setTranslationY(float translationY) {
13257        if (translationY != getTranslationY()) {
13258            invalidateViewProperty(true, false);
13259            mRenderNode.setTranslationY(translationY);
13260            invalidateViewProperty(false, true);
13261
13262            invalidateParentIfNeededAndWasQuickRejected();
13263            notifySubtreeAccessibilityStateChangedIfNeeded();
13264        }
13265    }
13266
13267    /**
13268     * The depth location of this view relative to its {@link #getElevation() elevation}.
13269     *
13270     * @return The depth of this view relative to its elevation.
13271     */
13272    @ViewDebug.ExportedProperty(category = "drawing")
13273    public float getTranslationZ() {
13274        return mRenderNode.getTranslationZ();
13275    }
13276
13277    /**
13278     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13279     *
13280     * @attr ref android.R.styleable#View_translationZ
13281     */
13282    public void setTranslationZ(float translationZ) {
13283        if (translationZ != getTranslationZ()) {
13284            invalidateViewProperty(true, false);
13285            mRenderNode.setTranslationZ(translationZ);
13286            invalidateViewProperty(false, true);
13287
13288            invalidateParentIfNeededAndWasQuickRejected();
13289        }
13290    }
13291
13292    /** @hide */
13293    public void setAnimationMatrix(Matrix matrix) {
13294        invalidateViewProperty(true, false);
13295        mRenderNode.setAnimationMatrix(matrix);
13296        invalidateViewProperty(false, true);
13297
13298        invalidateParentIfNeededAndWasQuickRejected();
13299    }
13300
13301    /**
13302     * Returns the current StateListAnimator if exists.
13303     *
13304     * @return StateListAnimator or null if it does not exists
13305     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13306     */
13307    public StateListAnimator getStateListAnimator() {
13308        return mStateListAnimator;
13309    }
13310
13311    /**
13312     * Attaches the provided StateListAnimator to this View.
13313     * <p>
13314     * Any previously attached StateListAnimator will be detached.
13315     *
13316     * @param stateListAnimator The StateListAnimator to update the view
13317     * @see {@link android.animation.StateListAnimator}
13318     */
13319    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13320        if (mStateListAnimator == stateListAnimator) {
13321            return;
13322        }
13323        if (mStateListAnimator != null) {
13324            mStateListAnimator.setTarget(null);
13325        }
13326        mStateListAnimator = stateListAnimator;
13327        if (stateListAnimator != null) {
13328            stateListAnimator.setTarget(this);
13329            if (isAttachedToWindow()) {
13330                stateListAnimator.setState(getDrawableState());
13331            }
13332        }
13333    }
13334
13335    /**
13336     * Returns whether the Outline should be used to clip the contents of the View.
13337     * <p>
13338     * Note that this flag will only be respected if the View's Outline returns true from
13339     * {@link Outline#canClip()}.
13340     *
13341     * @see #setOutlineProvider(ViewOutlineProvider)
13342     * @see #setClipToOutline(boolean)
13343     */
13344    public final boolean getClipToOutline() {
13345        return mRenderNode.getClipToOutline();
13346    }
13347
13348    /**
13349     * Sets whether the View's Outline should be used to clip the contents of the View.
13350     * <p>
13351     * Only a single non-rectangular clip can be applied on a View at any time.
13352     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13353     * circular reveal} animation take priority over Outline clipping, and
13354     * child Outline clipping takes priority over Outline clipping done by a
13355     * parent.
13356     * <p>
13357     * Note that this flag will only be respected if the View's Outline returns true from
13358     * {@link Outline#canClip()}.
13359     *
13360     * @see #setOutlineProvider(ViewOutlineProvider)
13361     * @see #getClipToOutline()
13362     */
13363    public void setClipToOutline(boolean clipToOutline) {
13364        damageInParent();
13365        if (getClipToOutline() != clipToOutline) {
13366            mRenderNode.setClipToOutline(clipToOutline);
13367        }
13368    }
13369
13370    // correspond to the enum values of View_outlineProvider
13371    private static final int PROVIDER_BACKGROUND = 0;
13372    private static final int PROVIDER_NONE = 1;
13373    private static final int PROVIDER_BOUNDS = 2;
13374    private static final int PROVIDER_PADDED_BOUNDS = 3;
13375    private void setOutlineProviderFromAttribute(int providerInt) {
13376        switch (providerInt) {
13377            case PROVIDER_BACKGROUND:
13378                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13379                break;
13380            case PROVIDER_NONE:
13381                setOutlineProvider(null);
13382                break;
13383            case PROVIDER_BOUNDS:
13384                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13385                break;
13386            case PROVIDER_PADDED_BOUNDS:
13387                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13388                break;
13389        }
13390    }
13391
13392    /**
13393     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13394     * the shape of the shadow it casts, and enables outline clipping.
13395     * <p>
13396     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13397     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13398     * outline provider with this method allows this behavior to be overridden.
13399     * <p>
13400     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13401     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13402     * <p>
13403     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13404     *
13405     * @see #setClipToOutline(boolean)
13406     * @see #getClipToOutline()
13407     * @see #getOutlineProvider()
13408     */
13409    public void setOutlineProvider(ViewOutlineProvider provider) {
13410        mOutlineProvider = provider;
13411        invalidateOutline();
13412    }
13413
13414    /**
13415     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13416     * that defines the shape of the shadow it casts, and enables outline clipping.
13417     *
13418     * @see #setOutlineProvider(ViewOutlineProvider)
13419     */
13420    public ViewOutlineProvider getOutlineProvider() {
13421        return mOutlineProvider;
13422    }
13423
13424    /**
13425     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13426     *
13427     * @see #setOutlineProvider(ViewOutlineProvider)
13428     */
13429    public void invalidateOutline() {
13430        rebuildOutline();
13431
13432        notifySubtreeAccessibilityStateChangedIfNeeded();
13433        invalidateViewProperty(false, false);
13434    }
13435
13436    /**
13437     * Internal version of {@link #invalidateOutline()} which invalidates the
13438     * outline without invalidating the view itself. This is intended to be called from
13439     * within methods in the View class itself which are the result of the view being
13440     * invalidated already. For example, when we are drawing the background of a View,
13441     * we invalidate the outline in case it changed in the meantime, but we do not
13442     * need to invalidate the view because we're already drawing the background as part
13443     * of drawing the view in response to an earlier invalidation of the view.
13444     */
13445    private void rebuildOutline() {
13446        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13447        if (mAttachInfo == null) return;
13448
13449        if (mOutlineProvider == null) {
13450            // no provider, remove outline
13451            mRenderNode.setOutline(null);
13452        } else {
13453            final Outline outline = mAttachInfo.mTmpOutline;
13454            outline.setEmpty();
13455            outline.setAlpha(1.0f);
13456
13457            mOutlineProvider.getOutline(this, outline);
13458            mRenderNode.setOutline(outline);
13459        }
13460    }
13461
13462    /**
13463     * HierarchyViewer only
13464     *
13465     * @hide
13466     */
13467    @ViewDebug.ExportedProperty(category = "drawing")
13468    public boolean hasShadow() {
13469        return mRenderNode.hasShadow();
13470    }
13471
13472
13473    /** @hide */
13474    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13475        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13476        invalidateViewProperty(false, false);
13477    }
13478
13479    /**
13480     * Hit rectangle in parent's coordinates
13481     *
13482     * @param outRect The hit rectangle of the view.
13483     */
13484    public void getHitRect(Rect outRect) {
13485        if (hasIdentityMatrix() || mAttachInfo == null) {
13486            outRect.set(mLeft, mTop, mRight, mBottom);
13487        } else {
13488            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13489            tmpRect.set(0, 0, getWidth(), getHeight());
13490            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13491            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13492                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13493        }
13494    }
13495
13496    /**
13497     * Determines whether the given point, in local coordinates is inside the view.
13498     */
13499    /*package*/ final boolean pointInView(float localX, float localY) {
13500        return pointInView(localX, localY, 0);
13501    }
13502
13503    /**
13504     * Utility method to determine whether the given point, in local coordinates,
13505     * is inside the view, where the area of the view is expanded by the slop factor.
13506     * This method is called while processing touch-move events to determine if the event
13507     * is still within the view.
13508     *
13509     * @hide
13510     */
13511    public boolean pointInView(float localX, float localY, float slop) {
13512        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13513                localY < ((mBottom - mTop) + slop);
13514    }
13515
13516    /**
13517     * When a view has focus and the user navigates away from it, the next view is searched for
13518     * starting from the rectangle filled in by this method.
13519     *
13520     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13521     * of the view.  However, if your view maintains some idea of internal selection,
13522     * such as a cursor, or a selected row or column, you should override this method and
13523     * fill in a more specific rectangle.
13524     *
13525     * @param r The rectangle to fill in, in this view's coordinates.
13526     */
13527    public void getFocusedRect(Rect r) {
13528        getDrawingRect(r);
13529    }
13530
13531    /**
13532     * If some part of this view is not clipped by any of its parents, then
13533     * return that area in r in global (root) coordinates. To convert r to local
13534     * coordinates (without taking possible View rotations into account), offset
13535     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13536     * If the view is completely clipped or translated out, return false.
13537     *
13538     * @param r If true is returned, r holds the global coordinates of the
13539     *        visible portion of this view.
13540     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13541     *        between this view and its root. globalOffet may be null.
13542     * @return true if r is non-empty (i.e. part of the view is visible at the
13543     *         root level.
13544     */
13545    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13546        int width = mRight - mLeft;
13547        int height = mBottom - mTop;
13548        if (width > 0 && height > 0) {
13549            r.set(0, 0, width, height);
13550            if (globalOffset != null) {
13551                globalOffset.set(-mScrollX, -mScrollY);
13552            }
13553            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13554        }
13555        return false;
13556    }
13557
13558    public final boolean getGlobalVisibleRect(Rect r) {
13559        return getGlobalVisibleRect(r, null);
13560    }
13561
13562    public final boolean getLocalVisibleRect(Rect r) {
13563        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13564        if (getGlobalVisibleRect(r, offset)) {
13565            r.offset(-offset.x, -offset.y); // make r local
13566            return true;
13567        }
13568        return false;
13569    }
13570
13571    /**
13572     * Offset this view's vertical location by the specified number of pixels.
13573     *
13574     * @param offset the number of pixels to offset the view by
13575     */
13576    public void offsetTopAndBottom(int offset) {
13577        if (offset != 0) {
13578            final boolean matrixIsIdentity = hasIdentityMatrix();
13579            if (matrixIsIdentity) {
13580                if (isHardwareAccelerated()) {
13581                    invalidateViewProperty(false, false);
13582                } else {
13583                    final ViewParent p = mParent;
13584                    if (p != null && mAttachInfo != null) {
13585                        final Rect r = mAttachInfo.mTmpInvalRect;
13586                        int minTop;
13587                        int maxBottom;
13588                        int yLoc;
13589                        if (offset < 0) {
13590                            minTop = mTop + offset;
13591                            maxBottom = mBottom;
13592                            yLoc = offset;
13593                        } else {
13594                            minTop = mTop;
13595                            maxBottom = mBottom + offset;
13596                            yLoc = 0;
13597                        }
13598                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13599                        p.invalidateChild(this, r);
13600                    }
13601                }
13602            } else {
13603                invalidateViewProperty(false, false);
13604            }
13605
13606            mTop += offset;
13607            mBottom += offset;
13608            mRenderNode.offsetTopAndBottom(offset);
13609            if (isHardwareAccelerated()) {
13610                invalidateViewProperty(false, false);
13611                invalidateParentIfNeededAndWasQuickRejected();
13612            } else {
13613                if (!matrixIsIdentity) {
13614                    invalidateViewProperty(false, true);
13615                }
13616                invalidateParentIfNeeded();
13617            }
13618            notifySubtreeAccessibilityStateChangedIfNeeded();
13619        }
13620    }
13621
13622    /**
13623     * Offset this view's horizontal location by the specified amount of pixels.
13624     *
13625     * @param offset the number of pixels to offset the view by
13626     */
13627    public void offsetLeftAndRight(int offset) {
13628        if (offset != 0) {
13629            final boolean matrixIsIdentity = hasIdentityMatrix();
13630            if (matrixIsIdentity) {
13631                if (isHardwareAccelerated()) {
13632                    invalidateViewProperty(false, false);
13633                } else {
13634                    final ViewParent p = mParent;
13635                    if (p != null && mAttachInfo != null) {
13636                        final Rect r = mAttachInfo.mTmpInvalRect;
13637                        int minLeft;
13638                        int maxRight;
13639                        if (offset < 0) {
13640                            minLeft = mLeft + offset;
13641                            maxRight = mRight;
13642                        } else {
13643                            minLeft = mLeft;
13644                            maxRight = mRight + offset;
13645                        }
13646                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13647                        p.invalidateChild(this, r);
13648                    }
13649                }
13650            } else {
13651                invalidateViewProperty(false, false);
13652            }
13653
13654            mLeft += offset;
13655            mRight += offset;
13656            mRenderNode.offsetLeftAndRight(offset);
13657            if (isHardwareAccelerated()) {
13658                invalidateViewProperty(false, false);
13659                invalidateParentIfNeededAndWasQuickRejected();
13660            } else {
13661                if (!matrixIsIdentity) {
13662                    invalidateViewProperty(false, true);
13663                }
13664                invalidateParentIfNeeded();
13665            }
13666            notifySubtreeAccessibilityStateChangedIfNeeded();
13667        }
13668    }
13669
13670    /**
13671     * Get the LayoutParams associated with this view. All views should have
13672     * layout parameters. These supply parameters to the <i>parent</i> of this
13673     * view specifying how it should be arranged. There are many subclasses of
13674     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13675     * of ViewGroup that are responsible for arranging their children.
13676     *
13677     * This method may return null if this View is not attached to a parent
13678     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13679     * was not invoked successfully. When a View is attached to a parent
13680     * ViewGroup, this method must not return null.
13681     *
13682     * @return The LayoutParams associated with this view, or null if no
13683     *         parameters have been set yet
13684     */
13685    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13686    public ViewGroup.LayoutParams getLayoutParams() {
13687        return mLayoutParams;
13688    }
13689
13690    /**
13691     * Set the layout parameters associated with this view. These supply
13692     * parameters to the <i>parent</i> of this view specifying how it should be
13693     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13694     * correspond to the different subclasses of ViewGroup that are responsible
13695     * for arranging their children.
13696     *
13697     * @param params The layout parameters for this view, cannot be null
13698     */
13699    public void setLayoutParams(ViewGroup.LayoutParams params) {
13700        if (params == null) {
13701            throw new NullPointerException("Layout parameters cannot be null");
13702        }
13703        mLayoutParams = params;
13704        resolveLayoutParams();
13705        if (mParent instanceof ViewGroup) {
13706            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13707        }
13708        requestLayout();
13709    }
13710
13711    /**
13712     * Resolve the layout parameters depending on the resolved layout direction
13713     *
13714     * @hide
13715     */
13716    public void resolveLayoutParams() {
13717        if (mLayoutParams != null) {
13718            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13719        }
13720    }
13721
13722    /**
13723     * Set the scrolled position of your view. This will cause a call to
13724     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13725     * invalidated.
13726     * @param x the x position to scroll to
13727     * @param y the y position to scroll to
13728     */
13729    public void scrollTo(int x, int y) {
13730        if (mScrollX != x || mScrollY != y) {
13731            int oldX = mScrollX;
13732            int oldY = mScrollY;
13733            mScrollX = x;
13734            mScrollY = y;
13735            invalidateParentCaches();
13736            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13737            if (!awakenScrollBars()) {
13738                postInvalidateOnAnimation();
13739            }
13740        }
13741    }
13742
13743    /**
13744     * Move the scrolled position of your view. This will cause a call to
13745     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13746     * invalidated.
13747     * @param x the amount of pixels to scroll by horizontally
13748     * @param y the amount of pixels to scroll by vertically
13749     */
13750    public void scrollBy(int x, int y) {
13751        scrollTo(mScrollX + x, mScrollY + y);
13752    }
13753
13754    /**
13755     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13756     * animation to fade the scrollbars out after a default delay. If a subclass
13757     * provides animated scrolling, the start delay should equal the duration
13758     * of the scrolling animation.</p>
13759     *
13760     * <p>The animation starts only if at least one of the scrollbars is
13761     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13762     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13763     * this method returns true, and false otherwise. If the animation is
13764     * started, this method calls {@link #invalidate()}; in that case the
13765     * caller should not call {@link #invalidate()}.</p>
13766     *
13767     * <p>This method should be invoked every time a subclass directly updates
13768     * the scroll parameters.</p>
13769     *
13770     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13771     * and {@link #scrollTo(int, int)}.</p>
13772     *
13773     * @return true if the animation is played, false otherwise
13774     *
13775     * @see #awakenScrollBars(int)
13776     * @see #scrollBy(int, int)
13777     * @see #scrollTo(int, int)
13778     * @see #isHorizontalScrollBarEnabled()
13779     * @see #isVerticalScrollBarEnabled()
13780     * @see #setHorizontalScrollBarEnabled(boolean)
13781     * @see #setVerticalScrollBarEnabled(boolean)
13782     */
13783    protected boolean awakenScrollBars() {
13784        return mScrollCache != null &&
13785                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13786    }
13787
13788    /**
13789     * Trigger the scrollbars to draw.
13790     * This method differs from awakenScrollBars() only in its default duration.
13791     * initialAwakenScrollBars() will show the scroll bars for longer than
13792     * usual to give the user more of a chance to notice them.
13793     *
13794     * @return true if the animation is played, false otherwise.
13795     */
13796    private boolean initialAwakenScrollBars() {
13797        return mScrollCache != null &&
13798                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13799    }
13800
13801    /**
13802     * <p>
13803     * Trigger the scrollbars to draw. When invoked this method starts an
13804     * animation to fade the scrollbars out after a fixed delay. If a subclass
13805     * provides animated scrolling, the start delay should equal the duration of
13806     * the scrolling animation.
13807     * </p>
13808     *
13809     * <p>
13810     * The animation starts only if at least one of the scrollbars is enabled,
13811     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13812     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13813     * this method returns true, and false otherwise. If the animation is
13814     * started, this method calls {@link #invalidate()}; in that case the caller
13815     * should not call {@link #invalidate()}.
13816     * </p>
13817     *
13818     * <p>
13819     * This method should be invoked every time a subclass directly updates the
13820     * scroll parameters.
13821     * </p>
13822     *
13823     * @param startDelay the delay, in milliseconds, after which the animation
13824     *        should start; when the delay is 0, the animation starts
13825     *        immediately
13826     * @return true if the animation is played, false otherwise
13827     *
13828     * @see #scrollBy(int, int)
13829     * @see #scrollTo(int, int)
13830     * @see #isHorizontalScrollBarEnabled()
13831     * @see #isVerticalScrollBarEnabled()
13832     * @see #setHorizontalScrollBarEnabled(boolean)
13833     * @see #setVerticalScrollBarEnabled(boolean)
13834     */
13835    protected boolean awakenScrollBars(int startDelay) {
13836        return awakenScrollBars(startDelay, true);
13837    }
13838
13839    /**
13840     * <p>
13841     * Trigger the scrollbars to draw. When invoked this method starts an
13842     * animation to fade the scrollbars out after a fixed delay. If a subclass
13843     * provides animated scrolling, the start delay should equal the duration of
13844     * the scrolling animation.
13845     * </p>
13846     *
13847     * <p>
13848     * The animation starts only if at least one of the scrollbars is enabled,
13849     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13850     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13851     * this method returns true, and false otherwise. If the animation is
13852     * started, this method calls {@link #invalidate()} if the invalidate parameter
13853     * is set to true; in that case the caller
13854     * should not call {@link #invalidate()}.
13855     * </p>
13856     *
13857     * <p>
13858     * This method should be invoked every time a subclass directly updates the
13859     * scroll parameters.
13860     * </p>
13861     *
13862     * @param startDelay the delay, in milliseconds, after which the animation
13863     *        should start; when the delay is 0, the animation starts
13864     *        immediately
13865     *
13866     * @param invalidate Whether this method should call invalidate
13867     *
13868     * @return true if the animation is played, false otherwise
13869     *
13870     * @see #scrollBy(int, int)
13871     * @see #scrollTo(int, int)
13872     * @see #isHorizontalScrollBarEnabled()
13873     * @see #isVerticalScrollBarEnabled()
13874     * @see #setHorizontalScrollBarEnabled(boolean)
13875     * @see #setVerticalScrollBarEnabled(boolean)
13876     */
13877    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13878        final ScrollabilityCache scrollCache = mScrollCache;
13879
13880        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13881            return false;
13882        }
13883
13884        if (scrollCache.scrollBar == null) {
13885            scrollCache.scrollBar = new ScrollBarDrawable();
13886            scrollCache.scrollBar.setState(getDrawableState());
13887            scrollCache.scrollBar.setCallback(this);
13888        }
13889
13890        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13891
13892            if (invalidate) {
13893                // Invalidate to show the scrollbars
13894                postInvalidateOnAnimation();
13895            }
13896
13897            if (scrollCache.state == ScrollabilityCache.OFF) {
13898                // FIXME: this is copied from WindowManagerService.
13899                // We should get this value from the system when it
13900                // is possible to do so.
13901                final int KEY_REPEAT_FIRST_DELAY = 750;
13902                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13903            }
13904
13905            // Tell mScrollCache when we should start fading. This may
13906            // extend the fade start time if one was already scheduled
13907            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13908            scrollCache.fadeStartTime = fadeStartTime;
13909            scrollCache.state = ScrollabilityCache.ON;
13910
13911            // Schedule our fader to run, unscheduling any old ones first
13912            if (mAttachInfo != null) {
13913                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13914                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13915            }
13916
13917            return true;
13918        }
13919
13920        return false;
13921    }
13922
13923    /**
13924     * Do not invalidate views which are not visible and which are not running an animation. They
13925     * will not get drawn and they should not set dirty flags as if they will be drawn
13926     */
13927    private boolean skipInvalidate() {
13928        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13929                (!(mParent instanceof ViewGroup) ||
13930                        !((ViewGroup) mParent).isViewTransitioning(this));
13931    }
13932
13933    /**
13934     * Mark the area defined by dirty as needing to be drawn. If the view is
13935     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13936     * point in the future.
13937     * <p>
13938     * This must be called from a UI thread. To call from a non-UI thread, call
13939     * {@link #postInvalidate()}.
13940     * <p>
13941     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13942     * {@code dirty}.
13943     *
13944     * @param dirty the rectangle representing the bounds of the dirty region
13945     */
13946    public void invalidate(Rect dirty) {
13947        final int scrollX = mScrollX;
13948        final int scrollY = mScrollY;
13949        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13950                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13951    }
13952
13953    /**
13954     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13955     * coordinates of the dirty rect are relative to the view. If the view is
13956     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13957     * point in the future.
13958     * <p>
13959     * This must be called from a UI thread. To call from a non-UI thread, call
13960     * {@link #postInvalidate()}.
13961     *
13962     * @param l the left position of the dirty region
13963     * @param t the top position of the dirty region
13964     * @param r the right position of the dirty region
13965     * @param b the bottom position of the dirty region
13966     */
13967    public void invalidate(int l, int t, int r, int b) {
13968        final int scrollX = mScrollX;
13969        final int scrollY = mScrollY;
13970        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13971    }
13972
13973    /**
13974     * Invalidate the whole view. If the view is visible,
13975     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13976     * the future.
13977     * <p>
13978     * This must be called from a UI thread. To call from a non-UI thread, call
13979     * {@link #postInvalidate()}.
13980     */
13981    public void invalidate() {
13982        invalidate(true);
13983    }
13984
13985    /**
13986     * This is where the invalidate() work actually happens. A full invalidate()
13987     * causes the drawing cache to be invalidated, but this function can be
13988     * called with invalidateCache set to false to skip that invalidation step
13989     * for cases that do not need it (for example, a component that remains at
13990     * the same dimensions with the same content).
13991     *
13992     * @param invalidateCache Whether the drawing cache for this view should be
13993     *            invalidated as well. This is usually true for a full
13994     *            invalidate, but may be set to false if the View's contents or
13995     *            dimensions have not changed.
13996     */
13997    void invalidate(boolean invalidateCache) {
13998        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13999    }
14000
14001    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14002            boolean fullInvalidate) {
14003        if (mGhostView != null) {
14004            mGhostView.invalidate(true);
14005            return;
14006        }
14007
14008        if (skipInvalidate()) {
14009            return;
14010        }
14011
14012        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14013                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14014                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14015                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14016            if (fullInvalidate) {
14017                mLastIsOpaque = isOpaque();
14018                mPrivateFlags &= ~PFLAG_DRAWN;
14019            }
14020
14021            mPrivateFlags |= PFLAG_DIRTY;
14022
14023            if (invalidateCache) {
14024                mPrivateFlags |= PFLAG_INVALIDATED;
14025                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14026            }
14027
14028            // Propagate the damage rectangle to the parent view.
14029            final AttachInfo ai = mAttachInfo;
14030            final ViewParent p = mParent;
14031            if (p != null && ai != null && l < r && t < b) {
14032                final Rect damage = ai.mTmpInvalRect;
14033                damage.set(l, t, r, b);
14034                p.invalidateChild(this, damage);
14035            }
14036
14037            // Damage the entire projection receiver, if necessary.
14038            if (mBackground != null && mBackground.isProjected()) {
14039                final View receiver = getProjectionReceiver();
14040                if (receiver != null) {
14041                    receiver.damageInParent();
14042                }
14043            }
14044        }
14045    }
14046
14047    /**
14048     * @return this view's projection receiver, or {@code null} if none exists
14049     */
14050    private View getProjectionReceiver() {
14051        ViewParent p = getParent();
14052        while (p != null && p instanceof View) {
14053            final View v = (View) p;
14054            if (v.isProjectionReceiver()) {
14055                return v;
14056            }
14057            p = p.getParent();
14058        }
14059
14060        return null;
14061    }
14062
14063    /**
14064     * @return whether the view is a projection receiver
14065     */
14066    private boolean isProjectionReceiver() {
14067        return mBackground != null;
14068    }
14069
14070    /**
14071     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14072     * set any flags or handle all of the cases handled by the default invalidation methods.
14073     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14074     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14075     * walk up the hierarchy, transforming the dirty rect as necessary.
14076     *
14077     * The method also handles normal invalidation logic if display list properties are not
14078     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14079     * backup approach, to handle these cases used in the various property-setting methods.
14080     *
14081     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14082     * are not being used in this view
14083     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14084     * list properties are not being used in this view
14085     */
14086    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14087        if (!isHardwareAccelerated()
14088                || !mRenderNode.isValid()
14089                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14090            if (invalidateParent) {
14091                invalidateParentCaches();
14092            }
14093            if (forceRedraw) {
14094                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14095            }
14096            invalidate(false);
14097        } else {
14098            damageInParent();
14099        }
14100    }
14101
14102    /**
14103     * Tells the parent view to damage this view's bounds.
14104     *
14105     * @hide
14106     */
14107    protected void damageInParent() {
14108        final AttachInfo ai = mAttachInfo;
14109        final ViewParent p = mParent;
14110        if (p != null && ai != null) {
14111            final Rect r = ai.mTmpInvalRect;
14112            r.set(0, 0, mRight - mLeft, mBottom - mTop);
14113            if (mParent instanceof ViewGroup) {
14114                ((ViewGroup) mParent).damageChild(this, r);
14115            } else {
14116                mParent.invalidateChild(this, r);
14117            }
14118        }
14119    }
14120
14121    /**
14122     * Utility method to transform a given Rect by the current matrix of this view.
14123     */
14124    void transformRect(final Rect rect) {
14125        if (!getMatrix().isIdentity()) {
14126            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14127            boundingRect.set(rect);
14128            getMatrix().mapRect(boundingRect);
14129            rect.set((int) Math.floor(boundingRect.left),
14130                    (int) Math.floor(boundingRect.top),
14131                    (int) Math.ceil(boundingRect.right),
14132                    (int) Math.ceil(boundingRect.bottom));
14133        }
14134    }
14135
14136    /**
14137     * Used to indicate that the parent of this view should clear its caches. This functionality
14138     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14139     * which is necessary when various parent-managed properties of the view change, such as
14140     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14141     * clears the parent caches and does not causes an invalidate event.
14142     *
14143     * @hide
14144     */
14145    protected void invalidateParentCaches() {
14146        if (mParent instanceof View) {
14147            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14148        }
14149    }
14150
14151    /**
14152     * Used to indicate that the parent of this view should be invalidated. This functionality
14153     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14154     * which is necessary when various parent-managed properties of the view change, such as
14155     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14156     * an invalidation event to the parent.
14157     *
14158     * @hide
14159     */
14160    protected void invalidateParentIfNeeded() {
14161        if (isHardwareAccelerated() && mParent instanceof View) {
14162            ((View) mParent).invalidate(true);
14163        }
14164    }
14165
14166    /**
14167     * @hide
14168     */
14169    protected void invalidateParentIfNeededAndWasQuickRejected() {
14170        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14171            // View was rejected last time it was drawn by its parent; this may have changed
14172            invalidateParentIfNeeded();
14173        }
14174    }
14175
14176    /**
14177     * Indicates whether this View is opaque. An opaque View guarantees that it will
14178     * draw all the pixels overlapping its bounds using a fully opaque color.
14179     *
14180     * Subclasses of View should override this method whenever possible to indicate
14181     * whether an instance is opaque. Opaque Views are treated in a special way by
14182     * the View hierarchy, possibly allowing it to perform optimizations during
14183     * invalidate/draw passes.
14184     *
14185     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14186     */
14187    @ViewDebug.ExportedProperty(category = "drawing")
14188    public boolean isOpaque() {
14189        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14190                getFinalAlpha() >= 1.0f;
14191    }
14192
14193    /**
14194     * @hide
14195     */
14196    protected void computeOpaqueFlags() {
14197        // Opaque if:
14198        //   - Has a background
14199        //   - Background is opaque
14200        //   - Doesn't have scrollbars or scrollbars overlay
14201
14202        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14203            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14204        } else {
14205            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14206        }
14207
14208        final int flags = mViewFlags;
14209        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14210                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14211                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14212            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14213        } else {
14214            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14215        }
14216    }
14217
14218    /**
14219     * @hide
14220     */
14221    protected boolean hasOpaqueScrollbars() {
14222        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14223    }
14224
14225    /**
14226     * @return A handler associated with the thread running the View. This
14227     * handler can be used to pump events in the UI events queue.
14228     */
14229    public Handler getHandler() {
14230        final AttachInfo attachInfo = mAttachInfo;
14231        if (attachInfo != null) {
14232            return attachInfo.mHandler;
14233        }
14234        return null;
14235    }
14236
14237    /**
14238     * Returns the queue of runnable for this view.
14239     *
14240     * @return the queue of runnables for this view
14241     */
14242    private HandlerActionQueue getRunQueue() {
14243        if (mRunQueue == null) {
14244            mRunQueue = new HandlerActionQueue();
14245        }
14246        return mRunQueue;
14247    }
14248
14249    /**
14250     * Gets the view root associated with the View.
14251     * @return The view root, or null if none.
14252     * @hide
14253     */
14254    public ViewRootImpl getViewRootImpl() {
14255        if (mAttachInfo != null) {
14256            return mAttachInfo.mViewRootImpl;
14257        }
14258        return null;
14259    }
14260
14261    /**
14262     * @hide
14263     */
14264    public ThreadedRenderer getThreadedRenderer() {
14265        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14266    }
14267
14268    /**
14269     * <p>Causes the Runnable to be added to the message queue.
14270     * The runnable will be run on the user interface thread.</p>
14271     *
14272     * @param action The Runnable that will be executed.
14273     *
14274     * @return Returns true if the Runnable was successfully placed in to the
14275     *         message queue.  Returns false on failure, usually because the
14276     *         looper processing the message queue is exiting.
14277     *
14278     * @see #postDelayed
14279     * @see #removeCallbacks
14280     */
14281    public boolean post(Runnable action) {
14282        final AttachInfo attachInfo = mAttachInfo;
14283        if (attachInfo != null) {
14284            return attachInfo.mHandler.post(action);
14285        }
14286
14287        // Postpone the runnable until we know on which thread it needs to run.
14288        // Assume that the runnable will be successfully placed after attach.
14289        getRunQueue().post(action);
14290        return true;
14291    }
14292
14293    /**
14294     * <p>Causes the Runnable to be added to the message queue, to be run
14295     * after the specified amount of time elapses.
14296     * The runnable will be run on the user interface thread.</p>
14297     *
14298     * @param action The Runnable that will be executed.
14299     * @param delayMillis The delay (in milliseconds) until the Runnable
14300     *        will be executed.
14301     *
14302     * @return true if the Runnable was successfully placed in to the
14303     *         message queue.  Returns false on failure, usually because the
14304     *         looper processing the message queue is exiting.  Note that a
14305     *         result of true does not mean the Runnable will be processed --
14306     *         if the looper is quit before the delivery time of the message
14307     *         occurs then the message will be dropped.
14308     *
14309     * @see #post
14310     * @see #removeCallbacks
14311     */
14312    public boolean postDelayed(Runnable action, long delayMillis) {
14313        final AttachInfo attachInfo = mAttachInfo;
14314        if (attachInfo != null) {
14315            return attachInfo.mHandler.postDelayed(action, delayMillis);
14316        }
14317
14318        // Postpone the runnable until we know on which thread it needs to run.
14319        // Assume that the runnable will be successfully placed after attach.
14320        getRunQueue().postDelayed(action, delayMillis);
14321        return true;
14322    }
14323
14324    /**
14325     * <p>Causes the Runnable to execute on the next animation time step.
14326     * The runnable will be run on the user interface thread.</p>
14327     *
14328     * @param action The Runnable that will be executed.
14329     *
14330     * @see #postOnAnimationDelayed
14331     * @see #removeCallbacks
14332     */
14333    public void postOnAnimation(Runnable action) {
14334        final AttachInfo attachInfo = mAttachInfo;
14335        if (attachInfo != null) {
14336            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14337                    Choreographer.CALLBACK_ANIMATION, action, null);
14338        } else {
14339            // Postpone the runnable until we know
14340            // on which thread it needs to run.
14341            getRunQueue().post(action);
14342        }
14343    }
14344
14345    /**
14346     * <p>Causes the Runnable to execute on the next animation time step,
14347     * after the specified amount of time elapses.
14348     * The runnable will be run on the user interface thread.</p>
14349     *
14350     * @param action The Runnable that will be executed.
14351     * @param delayMillis The delay (in milliseconds) until the Runnable
14352     *        will be executed.
14353     *
14354     * @see #postOnAnimation
14355     * @see #removeCallbacks
14356     */
14357    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14358        final AttachInfo attachInfo = mAttachInfo;
14359        if (attachInfo != null) {
14360            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14361                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14362        } else {
14363            // Postpone the runnable until we know
14364            // on which thread it needs to run.
14365            getRunQueue().postDelayed(action, delayMillis);
14366        }
14367    }
14368
14369    /**
14370     * <p>Removes the specified Runnable from the message queue.</p>
14371     *
14372     * @param action The Runnable to remove from the message handling queue
14373     *
14374     * @return true if this view could ask the Handler to remove the Runnable,
14375     *         false otherwise. When the returned value is true, the Runnable
14376     *         may or may not have been actually removed from the message queue
14377     *         (for instance, if the Runnable was not in the queue already.)
14378     *
14379     * @see #post
14380     * @see #postDelayed
14381     * @see #postOnAnimation
14382     * @see #postOnAnimationDelayed
14383     */
14384    public boolean removeCallbacks(Runnable action) {
14385        if (action != null) {
14386            final AttachInfo attachInfo = mAttachInfo;
14387            if (attachInfo != null) {
14388                attachInfo.mHandler.removeCallbacks(action);
14389                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14390                        Choreographer.CALLBACK_ANIMATION, action, null);
14391            }
14392            getRunQueue().removeCallbacks(action);
14393        }
14394        return true;
14395    }
14396
14397    /**
14398     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14399     * Use this to invalidate the View from a non-UI thread.</p>
14400     *
14401     * <p>This method can be invoked from outside of the UI thread
14402     * only when this View is attached to a window.</p>
14403     *
14404     * @see #invalidate()
14405     * @see #postInvalidateDelayed(long)
14406     */
14407    public void postInvalidate() {
14408        postInvalidateDelayed(0);
14409    }
14410
14411    /**
14412     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14413     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14414     *
14415     * <p>This method can be invoked from outside of the UI thread
14416     * only when this View is attached to a window.</p>
14417     *
14418     * @param left The left coordinate of the rectangle to invalidate.
14419     * @param top The top coordinate of the rectangle to invalidate.
14420     * @param right The right coordinate of the rectangle to invalidate.
14421     * @param bottom The bottom coordinate of the rectangle to invalidate.
14422     *
14423     * @see #invalidate(int, int, int, int)
14424     * @see #invalidate(Rect)
14425     * @see #postInvalidateDelayed(long, int, int, int, int)
14426     */
14427    public void postInvalidate(int left, int top, int right, int bottom) {
14428        postInvalidateDelayed(0, left, top, right, bottom);
14429    }
14430
14431    /**
14432     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14433     * loop. Waits for the specified amount of time.</p>
14434     *
14435     * <p>This method can be invoked from outside of the UI thread
14436     * only when this View is attached to a window.</p>
14437     *
14438     * @param delayMilliseconds the duration in milliseconds to delay the
14439     *         invalidation by
14440     *
14441     * @see #invalidate()
14442     * @see #postInvalidate()
14443     */
14444    public void postInvalidateDelayed(long delayMilliseconds) {
14445        // We try only with the AttachInfo because there's no point in invalidating
14446        // if we are not attached to our window
14447        final AttachInfo attachInfo = mAttachInfo;
14448        if (attachInfo != null) {
14449            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14450        }
14451    }
14452
14453    /**
14454     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14455     * through the event loop. Waits for the specified amount of time.</p>
14456     *
14457     * <p>This method can be invoked from outside of the UI thread
14458     * only when this View is attached to a window.</p>
14459     *
14460     * @param delayMilliseconds the duration in milliseconds to delay the
14461     *         invalidation by
14462     * @param left The left coordinate of the rectangle to invalidate.
14463     * @param top The top coordinate of the rectangle to invalidate.
14464     * @param right The right coordinate of the rectangle to invalidate.
14465     * @param bottom The bottom coordinate of the rectangle to invalidate.
14466     *
14467     * @see #invalidate(int, int, int, int)
14468     * @see #invalidate(Rect)
14469     * @see #postInvalidate(int, int, int, int)
14470     */
14471    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14472            int right, int bottom) {
14473
14474        // We try only with the AttachInfo because there's no point in invalidating
14475        // if we are not attached to our window
14476        final AttachInfo attachInfo = mAttachInfo;
14477        if (attachInfo != null) {
14478            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14479            info.target = this;
14480            info.left = left;
14481            info.top = top;
14482            info.right = right;
14483            info.bottom = bottom;
14484
14485            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14486        }
14487    }
14488
14489    /**
14490     * <p>Cause an invalidate to happen on the next animation time step, typically the
14491     * next display frame.</p>
14492     *
14493     * <p>This method can be invoked from outside of the UI thread
14494     * only when this View is attached to a window.</p>
14495     *
14496     * @see #invalidate()
14497     */
14498    public void postInvalidateOnAnimation() {
14499        // We try only with the AttachInfo because there's no point in invalidating
14500        // if we are not attached to our window
14501        final AttachInfo attachInfo = mAttachInfo;
14502        if (attachInfo != null) {
14503            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14504        }
14505    }
14506
14507    /**
14508     * <p>Cause an invalidate of the specified area to happen on the next animation
14509     * time step, typically the next display frame.</p>
14510     *
14511     * <p>This method can be invoked from outside of the UI thread
14512     * only when this View is attached to a window.</p>
14513     *
14514     * @param left The left coordinate of the rectangle to invalidate.
14515     * @param top The top coordinate of the rectangle to invalidate.
14516     * @param right The right coordinate of the rectangle to invalidate.
14517     * @param bottom The bottom coordinate of the rectangle to invalidate.
14518     *
14519     * @see #invalidate(int, int, int, int)
14520     * @see #invalidate(Rect)
14521     */
14522    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14523        // We try only with the AttachInfo because there's no point in invalidating
14524        // if we are not attached to our window
14525        final AttachInfo attachInfo = mAttachInfo;
14526        if (attachInfo != null) {
14527            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14528            info.target = this;
14529            info.left = left;
14530            info.top = top;
14531            info.right = right;
14532            info.bottom = bottom;
14533
14534            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14535        }
14536    }
14537
14538    /**
14539     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14540     * This event is sent at most once every
14541     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14542     */
14543    private void postSendViewScrolledAccessibilityEventCallback() {
14544        if (mSendViewScrolledAccessibilityEvent == null) {
14545            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14546        }
14547        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14548            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14549            postDelayed(mSendViewScrolledAccessibilityEvent,
14550                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14551        }
14552    }
14553
14554    /**
14555     * Called by a parent to request that a child update its values for mScrollX
14556     * and mScrollY if necessary. This will typically be done if the child is
14557     * animating a scroll using a {@link android.widget.Scroller Scroller}
14558     * object.
14559     */
14560    public void computeScroll() {
14561    }
14562
14563    /**
14564     * <p>Indicate whether the horizontal edges are faded when the view is
14565     * scrolled horizontally.</p>
14566     *
14567     * @return true if the horizontal edges should are faded on scroll, false
14568     *         otherwise
14569     *
14570     * @see #setHorizontalFadingEdgeEnabled(boolean)
14571     *
14572     * @attr ref android.R.styleable#View_requiresFadingEdge
14573     */
14574    public boolean isHorizontalFadingEdgeEnabled() {
14575        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14576    }
14577
14578    /**
14579     * <p>Define whether the horizontal edges should be faded when this view
14580     * is scrolled horizontally.</p>
14581     *
14582     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14583     *                                    be faded when the view is scrolled
14584     *                                    horizontally
14585     *
14586     * @see #isHorizontalFadingEdgeEnabled()
14587     *
14588     * @attr ref android.R.styleable#View_requiresFadingEdge
14589     */
14590    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14591        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14592            if (horizontalFadingEdgeEnabled) {
14593                initScrollCache();
14594            }
14595
14596            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14597        }
14598    }
14599
14600    /**
14601     * <p>Indicate whether the vertical edges are faded when the view is
14602     * scrolled horizontally.</p>
14603     *
14604     * @return true if the vertical edges should are faded on scroll, false
14605     *         otherwise
14606     *
14607     * @see #setVerticalFadingEdgeEnabled(boolean)
14608     *
14609     * @attr ref android.R.styleable#View_requiresFadingEdge
14610     */
14611    public boolean isVerticalFadingEdgeEnabled() {
14612        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14613    }
14614
14615    /**
14616     * <p>Define whether the vertical edges should be faded when this view
14617     * is scrolled vertically.</p>
14618     *
14619     * @param verticalFadingEdgeEnabled true if the vertical edges should
14620     *                                  be faded when the view is scrolled
14621     *                                  vertically
14622     *
14623     * @see #isVerticalFadingEdgeEnabled()
14624     *
14625     * @attr ref android.R.styleable#View_requiresFadingEdge
14626     */
14627    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14628        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14629            if (verticalFadingEdgeEnabled) {
14630                initScrollCache();
14631            }
14632
14633            mViewFlags ^= FADING_EDGE_VERTICAL;
14634        }
14635    }
14636
14637    /**
14638     * Returns the strength, or intensity, of the top faded edge. The strength is
14639     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14640     * returns 0.0 or 1.0 but no value in between.
14641     *
14642     * Subclasses should override this method to provide a smoother fade transition
14643     * when scrolling occurs.
14644     *
14645     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14646     */
14647    protected float getTopFadingEdgeStrength() {
14648        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14649    }
14650
14651    /**
14652     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14653     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14654     * returns 0.0 or 1.0 but no value in between.
14655     *
14656     * Subclasses should override this method to provide a smoother fade transition
14657     * when scrolling occurs.
14658     *
14659     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14660     */
14661    protected float getBottomFadingEdgeStrength() {
14662        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14663                computeVerticalScrollRange() ? 1.0f : 0.0f;
14664    }
14665
14666    /**
14667     * Returns the strength, or intensity, of the left faded edge. The strength is
14668     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14669     * returns 0.0 or 1.0 but no value in between.
14670     *
14671     * Subclasses should override this method to provide a smoother fade transition
14672     * when scrolling occurs.
14673     *
14674     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14675     */
14676    protected float getLeftFadingEdgeStrength() {
14677        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14678    }
14679
14680    /**
14681     * Returns the strength, or intensity, of the right faded edge. The strength is
14682     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14683     * returns 0.0 or 1.0 but no value in between.
14684     *
14685     * Subclasses should override this method to provide a smoother fade transition
14686     * when scrolling occurs.
14687     *
14688     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14689     */
14690    protected float getRightFadingEdgeStrength() {
14691        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14692                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14693    }
14694
14695    /**
14696     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14697     * scrollbar is not drawn by default.</p>
14698     *
14699     * @return true if the horizontal scrollbar should be painted, false
14700     *         otherwise
14701     *
14702     * @see #setHorizontalScrollBarEnabled(boolean)
14703     */
14704    public boolean isHorizontalScrollBarEnabled() {
14705        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14706    }
14707
14708    /**
14709     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14710     * scrollbar is not drawn by default.</p>
14711     *
14712     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14713     *                                   be painted
14714     *
14715     * @see #isHorizontalScrollBarEnabled()
14716     */
14717    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14718        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14719            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14720            computeOpaqueFlags();
14721            resolvePadding();
14722        }
14723    }
14724
14725    /**
14726     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14727     * scrollbar is not drawn by default.</p>
14728     *
14729     * @return true if the vertical scrollbar should be painted, false
14730     *         otherwise
14731     *
14732     * @see #setVerticalScrollBarEnabled(boolean)
14733     */
14734    public boolean isVerticalScrollBarEnabled() {
14735        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14736    }
14737
14738    /**
14739     * <p>Define whether the vertical scrollbar should be drawn or not. The
14740     * scrollbar is not drawn by default.</p>
14741     *
14742     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14743     *                                 be painted
14744     *
14745     * @see #isVerticalScrollBarEnabled()
14746     */
14747    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14748        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14749            mViewFlags ^= SCROLLBARS_VERTICAL;
14750            computeOpaqueFlags();
14751            resolvePadding();
14752        }
14753    }
14754
14755    /**
14756     * @hide
14757     */
14758    protected void recomputePadding() {
14759        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14760    }
14761
14762    /**
14763     * Define whether scrollbars will fade when the view is not scrolling.
14764     *
14765     * @param fadeScrollbars whether to enable fading
14766     *
14767     * @attr ref android.R.styleable#View_fadeScrollbars
14768     */
14769    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14770        initScrollCache();
14771        final ScrollabilityCache scrollabilityCache = mScrollCache;
14772        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14773        if (fadeScrollbars) {
14774            scrollabilityCache.state = ScrollabilityCache.OFF;
14775        } else {
14776            scrollabilityCache.state = ScrollabilityCache.ON;
14777        }
14778    }
14779
14780    /**
14781     *
14782     * Returns true if scrollbars will fade when this view is not scrolling
14783     *
14784     * @return true if scrollbar fading is enabled
14785     *
14786     * @attr ref android.R.styleable#View_fadeScrollbars
14787     */
14788    public boolean isScrollbarFadingEnabled() {
14789        return mScrollCache != null && mScrollCache.fadeScrollBars;
14790    }
14791
14792    /**
14793     *
14794     * Returns the delay before scrollbars fade.
14795     *
14796     * @return the delay before scrollbars fade
14797     *
14798     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14799     */
14800    public int getScrollBarDefaultDelayBeforeFade() {
14801        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14802                mScrollCache.scrollBarDefaultDelayBeforeFade;
14803    }
14804
14805    /**
14806     * Define the delay before scrollbars fade.
14807     *
14808     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14809     *
14810     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14811     */
14812    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14813        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14814    }
14815
14816    /**
14817     *
14818     * Returns the scrollbar fade duration.
14819     *
14820     * @return the scrollbar fade duration, in milliseconds
14821     *
14822     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14823     */
14824    public int getScrollBarFadeDuration() {
14825        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14826                mScrollCache.scrollBarFadeDuration;
14827    }
14828
14829    /**
14830     * Define the scrollbar fade duration.
14831     *
14832     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
14833     *
14834     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14835     */
14836    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14837        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14838    }
14839
14840    /**
14841     *
14842     * Returns the scrollbar size.
14843     *
14844     * @return the scrollbar size
14845     *
14846     * @attr ref android.R.styleable#View_scrollbarSize
14847     */
14848    public int getScrollBarSize() {
14849        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14850                mScrollCache.scrollBarSize;
14851    }
14852
14853    /**
14854     * Define the scrollbar size.
14855     *
14856     * @param scrollBarSize - the scrollbar size
14857     *
14858     * @attr ref android.R.styleable#View_scrollbarSize
14859     */
14860    public void setScrollBarSize(int scrollBarSize) {
14861        getScrollCache().scrollBarSize = scrollBarSize;
14862    }
14863
14864    /**
14865     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14866     * inset. When inset, they add to the padding of the view. And the scrollbars
14867     * can be drawn inside the padding area or on the edge of the view. For example,
14868     * if a view has a background drawable and you want to draw the scrollbars
14869     * inside the padding specified by the drawable, you can use
14870     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14871     * appear at the edge of the view, ignoring the padding, then you can use
14872     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14873     * @param style the style of the scrollbars. Should be one of
14874     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14875     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14876     * @see #SCROLLBARS_INSIDE_OVERLAY
14877     * @see #SCROLLBARS_INSIDE_INSET
14878     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14879     * @see #SCROLLBARS_OUTSIDE_INSET
14880     *
14881     * @attr ref android.R.styleable#View_scrollbarStyle
14882     */
14883    public void setScrollBarStyle(@ScrollBarStyle int style) {
14884        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14885            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14886            computeOpaqueFlags();
14887            resolvePadding();
14888        }
14889    }
14890
14891    /**
14892     * <p>Returns the current scrollbar style.</p>
14893     * @return the current scrollbar style
14894     * @see #SCROLLBARS_INSIDE_OVERLAY
14895     * @see #SCROLLBARS_INSIDE_INSET
14896     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14897     * @see #SCROLLBARS_OUTSIDE_INSET
14898     *
14899     * @attr ref android.R.styleable#View_scrollbarStyle
14900     */
14901    @ViewDebug.ExportedProperty(mapping = {
14902            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14903            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14904            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14905            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14906    })
14907    @ScrollBarStyle
14908    public int getScrollBarStyle() {
14909        return mViewFlags & SCROLLBARS_STYLE_MASK;
14910    }
14911
14912    /**
14913     * <p>Compute the horizontal range that the horizontal scrollbar
14914     * represents.</p>
14915     *
14916     * <p>The range is expressed in arbitrary units that must be the same as the
14917     * units used by {@link #computeHorizontalScrollExtent()} and
14918     * {@link #computeHorizontalScrollOffset()}.</p>
14919     *
14920     * <p>The default range is the drawing width of this view.</p>
14921     *
14922     * @return the total horizontal range represented by the horizontal
14923     *         scrollbar
14924     *
14925     * @see #computeHorizontalScrollExtent()
14926     * @see #computeHorizontalScrollOffset()
14927     * @see android.widget.ScrollBarDrawable
14928     */
14929    protected int computeHorizontalScrollRange() {
14930        return getWidth();
14931    }
14932
14933    /**
14934     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14935     * within the horizontal range. This value is used to compute the position
14936     * of the thumb within the scrollbar's track.</p>
14937     *
14938     * <p>The range is expressed in arbitrary units that must be the same as the
14939     * units used by {@link #computeHorizontalScrollRange()} and
14940     * {@link #computeHorizontalScrollExtent()}.</p>
14941     *
14942     * <p>The default offset is the scroll offset of this view.</p>
14943     *
14944     * @return the horizontal offset of the scrollbar's thumb
14945     *
14946     * @see #computeHorizontalScrollRange()
14947     * @see #computeHorizontalScrollExtent()
14948     * @see android.widget.ScrollBarDrawable
14949     */
14950    protected int computeHorizontalScrollOffset() {
14951        return mScrollX;
14952    }
14953
14954    /**
14955     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14956     * within the horizontal range. This value is used to compute the length
14957     * of the thumb within the scrollbar's track.</p>
14958     *
14959     * <p>The range is expressed in arbitrary units that must be the same as the
14960     * units used by {@link #computeHorizontalScrollRange()} and
14961     * {@link #computeHorizontalScrollOffset()}.</p>
14962     *
14963     * <p>The default extent is the drawing width of this view.</p>
14964     *
14965     * @return the horizontal extent of the scrollbar's thumb
14966     *
14967     * @see #computeHorizontalScrollRange()
14968     * @see #computeHorizontalScrollOffset()
14969     * @see android.widget.ScrollBarDrawable
14970     */
14971    protected int computeHorizontalScrollExtent() {
14972        return getWidth();
14973    }
14974
14975    /**
14976     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14977     *
14978     * <p>The range is expressed in arbitrary units that must be the same as the
14979     * units used by {@link #computeVerticalScrollExtent()} and
14980     * {@link #computeVerticalScrollOffset()}.</p>
14981     *
14982     * @return the total vertical range represented by the vertical scrollbar
14983     *
14984     * <p>The default range is the drawing height of this view.</p>
14985     *
14986     * @see #computeVerticalScrollExtent()
14987     * @see #computeVerticalScrollOffset()
14988     * @see android.widget.ScrollBarDrawable
14989     */
14990    protected int computeVerticalScrollRange() {
14991        return getHeight();
14992    }
14993
14994    /**
14995     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14996     * within the horizontal range. This value is used to compute the position
14997     * of the thumb within the scrollbar's track.</p>
14998     *
14999     * <p>The range is expressed in arbitrary units that must be the same as the
15000     * units used by {@link #computeVerticalScrollRange()} and
15001     * {@link #computeVerticalScrollExtent()}.</p>
15002     *
15003     * <p>The default offset is the scroll offset of this view.</p>
15004     *
15005     * @return the vertical offset of the scrollbar's thumb
15006     *
15007     * @see #computeVerticalScrollRange()
15008     * @see #computeVerticalScrollExtent()
15009     * @see android.widget.ScrollBarDrawable
15010     */
15011    protected int computeVerticalScrollOffset() {
15012        return mScrollY;
15013    }
15014
15015    /**
15016     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15017     * within the vertical range. This value is used to compute the length
15018     * of the thumb within the scrollbar's track.</p>
15019     *
15020     * <p>The range is expressed in arbitrary units that must be the same as the
15021     * units used by {@link #computeVerticalScrollRange()} and
15022     * {@link #computeVerticalScrollOffset()}.</p>
15023     *
15024     * <p>The default extent is the drawing height of this view.</p>
15025     *
15026     * @return the vertical extent of the scrollbar's thumb
15027     *
15028     * @see #computeVerticalScrollRange()
15029     * @see #computeVerticalScrollOffset()
15030     * @see android.widget.ScrollBarDrawable
15031     */
15032    protected int computeVerticalScrollExtent() {
15033        return getHeight();
15034    }
15035
15036    /**
15037     * Check if this view can be scrolled horizontally in a certain direction.
15038     *
15039     * @param direction Negative to check scrolling left, positive to check scrolling right.
15040     * @return true if this view can be scrolled in the specified direction, false otherwise.
15041     */
15042    public boolean canScrollHorizontally(int direction) {
15043        final int offset = computeHorizontalScrollOffset();
15044        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15045        if (range == 0) return false;
15046        if (direction < 0) {
15047            return offset > 0;
15048        } else {
15049            return offset < range - 1;
15050        }
15051    }
15052
15053    /**
15054     * Check if this view can be scrolled vertically in a certain direction.
15055     *
15056     * @param direction Negative to check scrolling up, positive to check scrolling down.
15057     * @return true if this view can be scrolled in the specified direction, false otherwise.
15058     */
15059    public boolean canScrollVertically(int direction) {
15060        final int offset = computeVerticalScrollOffset();
15061        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15062        if (range == 0) return false;
15063        if (direction < 0) {
15064            return offset > 0;
15065        } else {
15066            return offset < range - 1;
15067        }
15068    }
15069
15070    void getScrollIndicatorBounds(@NonNull Rect out) {
15071        out.left = mScrollX;
15072        out.right = mScrollX + mRight - mLeft;
15073        out.top = mScrollY;
15074        out.bottom = mScrollY + mBottom - mTop;
15075    }
15076
15077    private void onDrawScrollIndicators(Canvas c) {
15078        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15079            // No scroll indicators enabled.
15080            return;
15081        }
15082
15083        final Drawable dr = mScrollIndicatorDrawable;
15084        if (dr == null) {
15085            // Scroll indicators aren't supported here.
15086            return;
15087        }
15088
15089        final int h = dr.getIntrinsicHeight();
15090        final int w = dr.getIntrinsicWidth();
15091        final Rect rect = mAttachInfo.mTmpInvalRect;
15092        getScrollIndicatorBounds(rect);
15093
15094        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15095            final boolean canScrollUp = canScrollVertically(-1);
15096            if (canScrollUp) {
15097                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15098                dr.draw(c);
15099            }
15100        }
15101
15102        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15103            final boolean canScrollDown = canScrollVertically(1);
15104            if (canScrollDown) {
15105                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15106                dr.draw(c);
15107            }
15108        }
15109
15110        final int leftRtl;
15111        final int rightRtl;
15112        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15113            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15114            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15115        } else {
15116            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15117            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15118        }
15119
15120        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15121        if ((mPrivateFlags3 & leftMask) != 0) {
15122            final boolean canScrollLeft = canScrollHorizontally(-1);
15123            if (canScrollLeft) {
15124                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15125                dr.draw(c);
15126            }
15127        }
15128
15129        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15130        if ((mPrivateFlags3 & rightMask) != 0) {
15131            final boolean canScrollRight = canScrollHorizontally(1);
15132            if (canScrollRight) {
15133                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15134                dr.draw(c);
15135            }
15136        }
15137    }
15138
15139    private void getHorizontalScrollBarBounds(Rect bounds) {
15140        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15141        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15142                && !isVerticalScrollBarHidden();
15143        final int size = getHorizontalScrollbarHeight();
15144        final int verticalScrollBarGap = drawVerticalScrollBar ?
15145                getVerticalScrollbarWidth() : 0;
15146        final int width = mRight - mLeft;
15147        final int height = mBottom - mTop;
15148        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15149        bounds.left = mScrollX + (mPaddingLeft & inside);
15150        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15151        bounds.bottom = bounds.top + size;
15152    }
15153
15154    private void getVerticalScrollBarBounds(Rect bounds) {
15155        if (mRoundScrollbarRenderer == null) {
15156            getStraightVerticalScrollBarBounds(bounds);
15157        } else {
15158            getRoundVerticalScrollBarBounds(bounds);
15159        }
15160    }
15161
15162    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15163        final int width = mRight - mLeft;
15164        final int height = mBottom - mTop;
15165        // Do not take padding into account as we always want the scrollbars
15166        // to hug the screen for round wearable devices.
15167        bounds.left = mScrollX;
15168        bounds.top = mScrollY;
15169        bounds.right = bounds.left + width;
15170        bounds.bottom = mScrollY + height;
15171    }
15172
15173    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15174        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15175        final int size = getVerticalScrollbarWidth();
15176        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15177        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15178            verticalScrollbarPosition = isLayoutRtl() ?
15179                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15180        }
15181        final int width = mRight - mLeft;
15182        final int height = mBottom - mTop;
15183        switch (verticalScrollbarPosition) {
15184            default:
15185            case SCROLLBAR_POSITION_RIGHT:
15186                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15187                break;
15188            case SCROLLBAR_POSITION_LEFT:
15189                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15190                break;
15191        }
15192        bounds.top = mScrollY + (mPaddingTop & inside);
15193        bounds.right = bounds.left + size;
15194        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15195    }
15196
15197    /**
15198     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15199     * scrollbars are painted only if they have been awakened first.</p>
15200     *
15201     * @param canvas the canvas on which to draw the scrollbars
15202     *
15203     * @see #awakenScrollBars(int)
15204     */
15205    protected final void onDrawScrollBars(Canvas canvas) {
15206        // scrollbars are drawn only when the animation is running
15207        final ScrollabilityCache cache = mScrollCache;
15208
15209        if (cache != null) {
15210
15211            int state = cache.state;
15212
15213            if (state == ScrollabilityCache.OFF) {
15214                return;
15215            }
15216
15217            boolean invalidate = false;
15218
15219            if (state == ScrollabilityCache.FADING) {
15220                // We're fading -- get our fade interpolation
15221                if (cache.interpolatorValues == null) {
15222                    cache.interpolatorValues = new float[1];
15223                }
15224
15225                float[] values = cache.interpolatorValues;
15226
15227                // Stops the animation if we're done
15228                if (cache.scrollBarInterpolator.timeToValues(values) ==
15229                        Interpolator.Result.FREEZE_END) {
15230                    cache.state = ScrollabilityCache.OFF;
15231                } else {
15232                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15233                }
15234
15235                // This will make the scroll bars inval themselves after
15236                // drawing. We only want this when we're fading so that
15237                // we prevent excessive redraws
15238                invalidate = true;
15239            } else {
15240                // We're just on -- but we may have been fading before so
15241                // reset alpha
15242                cache.scrollBar.mutate().setAlpha(255);
15243            }
15244
15245            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15246            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15247                    && !isVerticalScrollBarHidden();
15248
15249            // Fork out the scroll bar drawing for round wearable devices.
15250            if (mRoundScrollbarRenderer != null) {
15251                if (drawVerticalScrollBar) {
15252                    final Rect bounds = cache.mScrollBarBounds;
15253                    getVerticalScrollBarBounds(bounds);
15254                    mRoundScrollbarRenderer.drawRoundScrollbars(
15255                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15256                    if (invalidate) {
15257                        invalidate();
15258                    }
15259                }
15260                // Do not draw horizontal scroll bars for round wearable devices.
15261            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15262                final ScrollBarDrawable scrollBar = cache.scrollBar;
15263
15264                if (drawHorizontalScrollBar) {
15265                    scrollBar.setParameters(computeHorizontalScrollRange(),
15266                            computeHorizontalScrollOffset(),
15267                            computeHorizontalScrollExtent(), false);
15268                    final Rect bounds = cache.mScrollBarBounds;
15269                    getHorizontalScrollBarBounds(bounds);
15270                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15271                            bounds.right, bounds.bottom);
15272                    if (invalidate) {
15273                        invalidate(bounds);
15274                    }
15275                }
15276
15277                if (drawVerticalScrollBar) {
15278                    scrollBar.setParameters(computeVerticalScrollRange(),
15279                            computeVerticalScrollOffset(),
15280                            computeVerticalScrollExtent(), true);
15281                    final Rect bounds = cache.mScrollBarBounds;
15282                    getVerticalScrollBarBounds(bounds);
15283                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15284                            bounds.right, bounds.bottom);
15285                    if (invalidate) {
15286                        invalidate(bounds);
15287                    }
15288                }
15289            }
15290        }
15291    }
15292
15293    /**
15294     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15295     * FastScroller is visible.
15296     * @return whether to temporarily hide the vertical scrollbar
15297     * @hide
15298     */
15299    protected boolean isVerticalScrollBarHidden() {
15300        return false;
15301    }
15302
15303    /**
15304     * <p>Draw the horizontal scrollbar if
15305     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15306     *
15307     * @param canvas the canvas on which to draw the scrollbar
15308     * @param scrollBar the scrollbar's drawable
15309     *
15310     * @see #isHorizontalScrollBarEnabled()
15311     * @see #computeHorizontalScrollRange()
15312     * @see #computeHorizontalScrollExtent()
15313     * @see #computeHorizontalScrollOffset()
15314     * @see android.widget.ScrollBarDrawable
15315     * @hide
15316     */
15317    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15318            int l, int t, int r, int b) {
15319        scrollBar.setBounds(l, t, r, b);
15320        scrollBar.draw(canvas);
15321    }
15322
15323    /**
15324     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15325     * returns true.</p>
15326     *
15327     * @param canvas the canvas on which to draw the scrollbar
15328     * @param scrollBar the scrollbar's drawable
15329     *
15330     * @see #isVerticalScrollBarEnabled()
15331     * @see #computeVerticalScrollRange()
15332     * @see #computeVerticalScrollExtent()
15333     * @see #computeVerticalScrollOffset()
15334     * @see android.widget.ScrollBarDrawable
15335     * @hide
15336     */
15337    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15338            int l, int t, int r, int b) {
15339        scrollBar.setBounds(l, t, r, b);
15340        scrollBar.draw(canvas);
15341    }
15342
15343    /**
15344     * Implement this to do your drawing.
15345     *
15346     * @param canvas the canvas on which the background will be drawn
15347     */
15348    protected void onDraw(Canvas canvas) {
15349    }
15350
15351    /*
15352     * Caller is responsible for calling requestLayout if necessary.
15353     * (This allows addViewInLayout to not request a new layout.)
15354     */
15355    void assignParent(ViewParent parent) {
15356        if (mParent == null) {
15357            mParent = parent;
15358        } else if (parent == null) {
15359            mParent = null;
15360        } else {
15361            throw new RuntimeException("view " + this + " being added, but"
15362                    + " it already has a parent");
15363        }
15364    }
15365
15366    /**
15367     * This is called when the view is attached to a window.  At this point it
15368     * has a Surface and will start drawing.  Note that this function is
15369     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15370     * however it may be called any time before the first onDraw -- including
15371     * before or after {@link #onMeasure(int, int)}.
15372     *
15373     * @see #onDetachedFromWindow()
15374     */
15375    @CallSuper
15376    protected void onAttachedToWindow() {
15377        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15378            mParent.requestTransparentRegion(this);
15379        }
15380
15381        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15382
15383        jumpDrawablesToCurrentState();
15384
15385        resetSubtreeAccessibilityStateChanged();
15386
15387        // rebuild, since Outline not maintained while View is detached
15388        rebuildOutline();
15389
15390        if (isFocused()) {
15391            InputMethodManager imm = InputMethodManager.peekInstance();
15392            if (imm != null) {
15393                imm.focusIn(this);
15394            }
15395        }
15396    }
15397
15398    /**
15399     * Resolve all RTL related properties.
15400     *
15401     * @return true if resolution of RTL properties has been done
15402     *
15403     * @hide
15404     */
15405    public boolean resolveRtlPropertiesIfNeeded() {
15406        if (!needRtlPropertiesResolution()) return false;
15407
15408        // Order is important here: LayoutDirection MUST be resolved first
15409        if (!isLayoutDirectionResolved()) {
15410            resolveLayoutDirection();
15411            resolveLayoutParams();
15412        }
15413        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15414        if (!isTextDirectionResolved()) {
15415            resolveTextDirection();
15416        }
15417        if (!isTextAlignmentResolved()) {
15418            resolveTextAlignment();
15419        }
15420        // Should resolve Drawables before Padding because we need the layout direction of the
15421        // Drawable to correctly resolve Padding.
15422        if (!areDrawablesResolved()) {
15423            resolveDrawables();
15424        }
15425        if (!isPaddingResolved()) {
15426            resolvePadding();
15427        }
15428        onRtlPropertiesChanged(getLayoutDirection());
15429        return true;
15430    }
15431
15432    /**
15433     * Reset resolution of all RTL related properties.
15434     *
15435     * @hide
15436     */
15437    public void resetRtlProperties() {
15438        resetResolvedLayoutDirection();
15439        resetResolvedTextDirection();
15440        resetResolvedTextAlignment();
15441        resetResolvedPadding();
15442        resetResolvedDrawables();
15443    }
15444
15445    /**
15446     * @see #onScreenStateChanged(int)
15447     */
15448    void dispatchScreenStateChanged(int screenState) {
15449        onScreenStateChanged(screenState);
15450    }
15451
15452    /**
15453     * This method is called whenever the state of the screen this view is
15454     * attached to changes. A state change will usually occurs when the screen
15455     * turns on or off (whether it happens automatically or the user does it
15456     * manually.)
15457     *
15458     * @param screenState The new state of the screen. Can be either
15459     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15460     */
15461    public void onScreenStateChanged(int screenState) {
15462    }
15463
15464    /**
15465     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15466     */
15467    private boolean hasRtlSupport() {
15468        return mContext.getApplicationInfo().hasRtlSupport();
15469    }
15470
15471    /**
15472     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15473     * RTL not supported)
15474     */
15475    private boolean isRtlCompatibilityMode() {
15476        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15477        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15478    }
15479
15480    /**
15481     * @return true if RTL properties need resolution.
15482     *
15483     */
15484    private boolean needRtlPropertiesResolution() {
15485        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15486    }
15487
15488    /**
15489     * Called when any RTL property (layout direction or text direction or text alignment) has
15490     * been changed.
15491     *
15492     * Subclasses need to override this method to take care of cached information that depends on the
15493     * resolved layout direction, or to inform child views that inherit their layout direction.
15494     *
15495     * The default implementation does nothing.
15496     *
15497     * @param layoutDirection the direction of the layout
15498     *
15499     * @see #LAYOUT_DIRECTION_LTR
15500     * @see #LAYOUT_DIRECTION_RTL
15501     */
15502    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15503    }
15504
15505    /**
15506     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15507     * that the parent directionality can and will be resolved before its children.
15508     *
15509     * @return true if resolution has been done, false otherwise.
15510     *
15511     * @hide
15512     */
15513    public boolean resolveLayoutDirection() {
15514        // Clear any previous layout direction resolution
15515        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15516
15517        if (hasRtlSupport()) {
15518            // Set resolved depending on layout direction
15519            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15520                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15521                case LAYOUT_DIRECTION_INHERIT:
15522                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15523                    // later to get the correct resolved value
15524                    if (!canResolveLayoutDirection()) return false;
15525
15526                    // Parent has not yet resolved, LTR is still the default
15527                    try {
15528                        if (!mParent.isLayoutDirectionResolved()) return false;
15529
15530                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15531                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15532                        }
15533                    } catch (AbstractMethodError e) {
15534                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15535                                " does not fully implement ViewParent", e);
15536                    }
15537                    break;
15538                case LAYOUT_DIRECTION_RTL:
15539                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15540                    break;
15541                case LAYOUT_DIRECTION_LOCALE:
15542                    if((LAYOUT_DIRECTION_RTL ==
15543                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15544                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15545                    }
15546                    break;
15547                default:
15548                    // Nothing to do, LTR by default
15549            }
15550        }
15551
15552        // Set to resolved
15553        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15554        return true;
15555    }
15556
15557    /**
15558     * Check if layout direction resolution can be done.
15559     *
15560     * @return true if layout direction resolution can be done otherwise return false.
15561     */
15562    public boolean canResolveLayoutDirection() {
15563        switch (getRawLayoutDirection()) {
15564            case LAYOUT_DIRECTION_INHERIT:
15565                if (mParent != null) {
15566                    try {
15567                        return mParent.canResolveLayoutDirection();
15568                    } catch (AbstractMethodError e) {
15569                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15570                                " does not fully implement ViewParent", e);
15571                    }
15572                }
15573                return false;
15574
15575            default:
15576                return true;
15577        }
15578    }
15579
15580    /**
15581     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15582     * {@link #onMeasure(int, int)}.
15583     *
15584     * @hide
15585     */
15586    public void resetResolvedLayoutDirection() {
15587        // Reset the current resolved bits
15588        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15589    }
15590
15591    /**
15592     * @return true if the layout direction is inherited.
15593     *
15594     * @hide
15595     */
15596    public boolean isLayoutDirectionInherited() {
15597        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15598    }
15599
15600    /**
15601     * @return true if layout direction has been resolved.
15602     */
15603    public boolean isLayoutDirectionResolved() {
15604        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15605    }
15606
15607    /**
15608     * Return if padding has been resolved
15609     *
15610     * @hide
15611     */
15612    boolean isPaddingResolved() {
15613        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15614    }
15615
15616    /**
15617     * Resolves padding depending on layout direction, if applicable, and
15618     * recomputes internal padding values to adjust for scroll bars.
15619     *
15620     * @hide
15621     */
15622    public void resolvePadding() {
15623        final int resolvedLayoutDirection = getLayoutDirection();
15624
15625        if (!isRtlCompatibilityMode()) {
15626            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15627            // If start / end padding are defined, they will be resolved (hence overriding) to
15628            // left / right or right / left depending on the resolved layout direction.
15629            // If start / end padding are not defined, use the left / right ones.
15630            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15631                Rect padding = sThreadLocal.get();
15632                if (padding == null) {
15633                    padding = new Rect();
15634                    sThreadLocal.set(padding);
15635                }
15636                mBackground.getPadding(padding);
15637                if (!mLeftPaddingDefined) {
15638                    mUserPaddingLeftInitial = padding.left;
15639                }
15640                if (!mRightPaddingDefined) {
15641                    mUserPaddingRightInitial = padding.right;
15642                }
15643            }
15644            switch (resolvedLayoutDirection) {
15645                case LAYOUT_DIRECTION_RTL:
15646                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15647                        mUserPaddingRight = mUserPaddingStart;
15648                    } else {
15649                        mUserPaddingRight = mUserPaddingRightInitial;
15650                    }
15651                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15652                        mUserPaddingLeft = mUserPaddingEnd;
15653                    } else {
15654                        mUserPaddingLeft = mUserPaddingLeftInitial;
15655                    }
15656                    break;
15657                case LAYOUT_DIRECTION_LTR:
15658                default:
15659                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15660                        mUserPaddingLeft = mUserPaddingStart;
15661                    } else {
15662                        mUserPaddingLeft = mUserPaddingLeftInitial;
15663                    }
15664                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15665                        mUserPaddingRight = mUserPaddingEnd;
15666                    } else {
15667                        mUserPaddingRight = mUserPaddingRightInitial;
15668                    }
15669            }
15670
15671            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15672        }
15673
15674        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15675        onRtlPropertiesChanged(resolvedLayoutDirection);
15676
15677        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15678    }
15679
15680    /**
15681     * Reset the resolved layout direction.
15682     *
15683     * @hide
15684     */
15685    public void resetResolvedPadding() {
15686        resetResolvedPaddingInternal();
15687    }
15688
15689    /**
15690     * Used when we only want to reset *this* view's padding and not trigger overrides
15691     * in ViewGroup that reset children too.
15692     */
15693    void resetResolvedPaddingInternal() {
15694        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15695    }
15696
15697    /**
15698     * This is called when the view is detached from a window.  At this point it
15699     * no longer has a surface for drawing.
15700     *
15701     * @see #onAttachedToWindow()
15702     */
15703    @CallSuper
15704    protected void onDetachedFromWindow() {
15705    }
15706
15707    /**
15708     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15709     * after onDetachedFromWindow().
15710     *
15711     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15712     * The super method should be called at the end of the overridden method to ensure
15713     * subclasses are destroyed first
15714     *
15715     * @hide
15716     */
15717    @CallSuper
15718    protected void onDetachedFromWindowInternal() {
15719        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15720        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15721        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15722
15723        removeUnsetPressCallback();
15724        removeLongPressCallback();
15725        removePerformClickCallback();
15726        removeSendViewScrolledAccessibilityEventCallback();
15727        stopNestedScroll();
15728
15729        // Anything that started animating right before detach should already
15730        // be in its final state when re-attached.
15731        jumpDrawablesToCurrentState();
15732
15733        destroyDrawingCache();
15734
15735        cleanupDraw();
15736        mCurrentAnimation = null;
15737
15738        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
15739            hideTooltip();
15740        }
15741    }
15742
15743    private void cleanupDraw() {
15744        resetDisplayList();
15745        if (mAttachInfo != null) {
15746            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15747        }
15748    }
15749
15750    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15751    }
15752
15753    /**
15754     * @return The number of times this view has been attached to a window
15755     */
15756    protected int getWindowAttachCount() {
15757        return mWindowAttachCount;
15758    }
15759
15760    /**
15761     * Retrieve a unique token identifying the window this view is attached to.
15762     * @return Return the window's token for use in
15763     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15764     */
15765    public IBinder getWindowToken() {
15766        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15767    }
15768
15769    /**
15770     * Retrieve the {@link WindowId} for the window this view is
15771     * currently attached to.
15772     */
15773    public WindowId getWindowId() {
15774        if (mAttachInfo == null) {
15775            return null;
15776        }
15777        if (mAttachInfo.mWindowId == null) {
15778            try {
15779                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15780                        mAttachInfo.mWindowToken);
15781                mAttachInfo.mWindowId = new WindowId(
15782                        mAttachInfo.mIWindowId);
15783            } catch (RemoteException e) {
15784            }
15785        }
15786        return mAttachInfo.mWindowId;
15787    }
15788
15789    /**
15790     * Retrieve a unique token identifying the top-level "real" window of
15791     * the window that this view is attached to.  That is, this is like
15792     * {@link #getWindowToken}, except if the window this view in is a panel
15793     * window (attached to another containing window), then the token of
15794     * the containing window is returned instead.
15795     *
15796     * @return Returns the associated window token, either
15797     * {@link #getWindowToken()} or the containing window's token.
15798     */
15799    public IBinder getApplicationWindowToken() {
15800        AttachInfo ai = mAttachInfo;
15801        if (ai != null) {
15802            IBinder appWindowToken = ai.mPanelParentWindowToken;
15803            if (appWindowToken == null) {
15804                appWindowToken = ai.mWindowToken;
15805            }
15806            return appWindowToken;
15807        }
15808        return null;
15809    }
15810
15811    /**
15812     * Gets the logical display to which the view's window has been attached.
15813     *
15814     * @return The logical display, or null if the view is not currently attached to a window.
15815     */
15816    public Display getDisplay() {
15817        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15818    }
15819
15820    /**
15821     * Retrieve private session object this view hierarchy is using to
15822     * communicate with the window manager.
15823     * @return the session object to communicate with the window manager
15824     */
15825    /*package*/ IWindowSession getWindowSession() {
15826        return mAttachInfo != null ? mAttachInfo.mSession : null;
15827    }
15828
15829    /**
15830     * Return the visibility value of the least visible component passed.
15831     */
15832    int combineVisibility(int vis1, int vis2) {
15833        // This works because VISIBLE < INVISIBLE < GONE.
15834        return Math.max(vis1, vis2);
15835    }
15836
15837    /**
15838     * @param info the {@link android.view.View.AttachInfo} to associated with
15839     *        this view
15840     */
15841    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15842        mAttachInfo = info;
15843        if (mOverlay != null) {
15844            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15845        }
15846        mWindowAttachCount++;
15847        // We will need to evaluate the drawable state at least once.
15848        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15849        if (mFloatingTreeObserver != null) {
15850            info.mTreeObserver.merge(mFloatingTreeObserver);
15851            mFloatingTreeObserver = null;
15852        }
15853
15854        registerPendingFrameMetricsObservers();
15855
15856        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15857            mAttachInfo.mScrollContainers.add(this);
15858            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15859        }
15860        // Transfer all pending runnables.
15861        if (mRunQueue != null) {
15862            mRunQueue.executeActions(info.mHandler);
15863            mRunQueue = null;
15864        }
15865        performCollectViewAttributes(mAttachInfo, visibility);
15866        onAttachedToWindow();
15867
15868        ListenerInfo li = mListenerInfo;
15869        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15870                li != null ? li.mOnAttachStateChangeListeners : null;
15871        if (listeners != null && listeners.size() > 0) {
15872            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15873            // perform the dispatching. The iterator is a safe guard against listeners that
15874            // could mutate the list by calling the various add/remove methods. This prevents
15875            // the array from being modified while we iterate it.
15876            for (OnAttachStateChangeListener listener : listeners) {
15877                listener.onViewAttachedToWindow(this);
15878            }
15879        }
15880
15881        int vis = info.mWindowVisibility;
15882        if (vis != GONE) {
15883            onWindowVisibilityChanged(vis);
15884            if (isShown()) {
15885                // Calling onVisibilityAggregated directly here since the subtree will also
15886                // receive dispatchAttachedToWindow and this same call
15887                onVisibilityAggregated(vis == VISIBLE);
15888            }
15889        }
15890
15891        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15892        // As all views in the subtree will already receive dispatchAttachedToWindow
15893        // traversing the subtree again here is not desired.
15894        onVisibilityChanged(this, visibility);
15895
15896        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15897            // If nobody has evaluated the drawable state yet, then do it now.
15898            refreshDrawableState();
15899        }
15900        needGlobalAttributesUpdate(false);
15901    }
15902
15903    void dispatchDetachedFromWindow() {
15904        AttachInfo info = mAttachInfo;
15905        if (info != null) {
15906            int vis = info.mWindowVisibility;
15907            if (vis != GONE) {
15908                onWindowVisibilityChanged(GONE);
15909                if (isShown()) {
15910                    // Invoking onVisibilityAggregated directly here since the subtree
15911                    // will also receive detached from window
15912                    onVisibilityAggregated(false);
15913                }
15914            }
15915        }
15916
15917        onDetachedFromWindow();
15918        onDetachedFromWindowInternal();
15919
15920        InputMethodManager imm = InputMethodManager.peekInstance();
15921        if (imm != null) {
15922            imm.onViewDetachedFromWindow(this);
15923        }
15924
15925        ListenerInfo li = mListenerInfo;
15926        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15927                li != null ? li.mOnAttachStateChangeListeners : null;
15928        if (listeners != null && listeners.size() > 0) {
15929            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15930            // perform the dispatching. The iterator is a safe guard against listeners that
15931            // could mutate the list by calling the various add/remove methods. This prevents
15932            // the array from being modified while we iterate it.
15933            for (OnAttachStateChangeListener listener : listeners) {
15934                listener.onViewDetachedFromWindow(this);
15935            }
15936        }
15937
15938        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15939            mAttachInfo.mScrollContainers.remove(this);
15940            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15941        }
15942
15943        mAttachInfo = null;
15944        if (mOverlay != null) {
15945            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15946        }
15947    }
15948
15949    /**
15950     * Cancel any deferred high-level input events that were previously posted to the event queue.
15951     *
15952     * <p>Many views post high-level events such as click handlers to the event queue
15953     * to run deferred in order to preserve a desired user experience - clearing visible
15954     * pressed states before executing, etc. This method will abort any events of this nature
15955     * that are currently in flight.</p>
15956     *
15957     * <p>Custom views that generate their own high-level deferred input events should override
15958     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15959     *
15960     * <p>This will also cancel pending input events for any child views.</p>
15961     *
15962     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15963     * This will not impact newer events posted after this call that may occur as a result of
15964     * lower-level input events still waiting in the queue. If you are trying to prevent
15965     * double-submitted  events for the duration of some sort of asynchronous transaction
15966     * you should also take other steps to protect against unexpected double inputs e.g. calling
15967     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15968     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15969     */
15970    public final void cancelPendingInputEvents() {
15971        dispatchCancelPendingInputEvents();
15972    }
15973
15974    /**
15975     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15976     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15977     */
15978    void dispatchCancelPendingInputEvents() {
15979        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15980        onCancelPendingInputEvents();
15981        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15982            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15983                    " did not call through to super.onCancelPendingInputEvents()");
15984        }
15985    }
15986
15987    /**
15988     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15989     * a parent view.
15990     *
15991     * <p>This method is responsible for removing any pending high-level input events that were
15992     * posted to the event queue to run later. Custom view classes that post their own deferred
15993     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15994     * {@link android.os.Handler} should override this method, call
15995     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15996     * </p>
15997     */
15998    public void onCancelPendingInputEvents() {
15999        removePerformClickCallback();
16000        cancelLongPress();
16001        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16002    }
16003
16004    /**
16005     * Store this view hierarchy's frozen state into the given container.
16006     *
16007     * @param container The SparseArray in which to save the view's state.
16008     *
16009     * @see #restoreHierarchyState(android.util.SparseArray)
16010     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16011     * @see #onSaveInstanceState()
16012     */
16013    public void saveHierarchyState(SparseArray<Parcelable> container) {
16014        dispatchSaveInstanceState(container);
16015    }
16016
16017    /**
16018     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16019     * this view and its children. May be overridden to modify how freezing happens to a
16020     * view's children; for example, some views may want to not store state for their children.
16021     *
16022     * @param container The SparseArray in which to save the view's state.
16023     *
16024     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16025     * @see #saveHierarchyState(android.util.SparseArray)
16026     * @see #onSaveInstanceState()
16027     */
16028    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16029        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16030            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16031            Parcelable state = onSaveInstanceState();
16032            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16033                throw new IllegalStateException(
16034                        "Derived class did not call super.onSaveInstanceState()");
16035            }
16036            if (state != null) {
16037                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16038                // + ": " + state);
16039                container.put(mID, state);
16040            }
16041        }
16042    }
16043
16044    /**
16045     * Hook allowing a view to generate a representation of its internal state
16046     * that can later be used to create a new instance with that same state.
16047     * This state should only contain information that is not persistent or can
16048     * not be reconstructed later. For example, you will never store your
16049     * current position on screen because that will be computed again when a
16050     * new instance of the view is placed in its view hierarchy.
16051     * <p>
16052     * Some examples of things you may store here: the current cursor position
16053     * in a text view (but usually not the text itself since that is stored in a
16054     * content provider or other persistent storage), the currently selected
16055     * item in a list view.
16056     *
16057     * @return Returns a Parcelable object containing the view's current dynamic
16058     *         state, or null if there is nothing interesting to save. The
16059     *         default implementation returns null.
16060     * @see #onRestoreInstanceState(android.os.Parcelable)
16061     * @see #saveHierarchyState(android.util.SparseArray)
16062     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16063     * @see #setSaveEnabled(boolean)
16064     */
16065    @CallSuper
16066    protected Parcelable onSaveInstanceState() {
16067        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16068        if (mStartActivityRequestWho != null) {
16069            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16070            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16071            return state;
16072        }
16073        return BaseSavedState.EMPTY_STATE;
16074    }
16075
16076    /**
16077     * Restore this view hierarchy's frozen state from the given container.
16078     *
16079     * @param container The SparseArray which holds previously frozen states.
16080     *
16081     * @see #saveHierarchyState(android.util.SparseArray)
16082     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16083     * @see #onRestoreInstanceState(android.os.Parcelable)
16084     */
16085    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16086        dispatchRestoreInstanceState(container);
16087    }
16088
16089    /**
16090     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16091     * state for this view and its children. May be overridden to modify how restoring
16092     * happens to a view's children; for example, some views may want to not store state
16093     * for their children.
16094     *
16095     * @param container The SparseArray which holds previously saved state.
16096     *
16097     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16098     * @see #restoreHierarchyState(android.util.SparseArray)
16099     * @see #onRestoreInstanceState(android.os.Parcelable)
16100     */
16101    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16102        if (mID != NO_ID) {
16103            Parcelable state = container.get(mID);
16104            if (state != null) {
16105                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16106                // + ": " + state);
16107                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16108                onRestoreInstanceState(state);
16109                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16110                    throw new IllegalStateException(
16111                            "Derived class did not call super.onRestoreInstanceState()");
16112                }
16113            }
16114        }
16115    }
16116
16117    /**
16118     * Hook allowing a view to re-apply a representation of its internal state that had previously
16119     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16120     * null state.
16121     *
16122     * @param state The frozen state that had previously been returned by
16123     *        {@link #onSaveInstanceState}.
16124     *
16125     * @see #onSaveInstanceState()
16126     * @see #restoreHierarchyState(android.util.SparseArray)
16127     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16128     */
16129    @CallSuper
16130    protected void onRestoreInstanceState(Parcelable state) {
16131        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16132        if (state != null && !(state instanceof AbsSavedState)) {
16133            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16134                    + "received " + state.getClass().toString() + " instead. This usually happens "
16135                    + "when two views of different type have the same id in the same hierarchy. "
16136                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16137                    + "other views do not use the same id.");
16138        }
16139        if (state != null && state instanceof BaseSavedState) {
16140            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16141        }
16142    }
16143
16144    /**
16145     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16146     *
16147     * @return the drawing start time in milliseconds
16148     */
16149    public long getDrawingTime() {
16150        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16151    }
16152
16153    /**
16154     * <p>Enables or disables the duplication of the parent's state into this view. When
16155     * duplication is enabled, this view gets its drawable state from its parent rather
16156     * than from its own internal properties.</p>
16157     *
16158     * <p>Note: in the current implementation, setting this property to true after the
16159     * view was added to a ViewGroup might have no effect at all. This property should
16160     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16161     *
16162     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16163     * property is enabled, an exception will be thrown.</p>
16164     *
16165     * <p>Note: if the child view uses and updates additional states which are unknown to the
16166     * parent, these states should not be affected by this method.</p>
16167     *
16168     * @param enabled True to enable duplication of the parent's drawable state, false
16169     *                to disable it.
16170     *
16171     * @see #getDrawableState()
16172     * @see #isDuplicateParentStateEnabled()
16173     */
16174    public void setDuplicateParentStateEnabled(boolean enabled) {
16175        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16176    }
16177
16178    /**
16179     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16180     *
16181     * @return True if this view's drawable state is duplicated from the parent,
16182     *         false otherwise
16183     *
16184     * @see #getDrawableState()
16185     * @see #setDuplicateParentStateEnabled(boolean)
16186     */
16187    public boolean isDuplicateParentStateEnabled() {
16188        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16189    }
16190
16191    /**
16192     * <p>Specifies the type of layer backing this view. The layer can be
16193     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16194     * {@link #LAYER_TYPE_HARDWARE}.</p>
16195     *
16196     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16197     * instance that controls how the layer is composed on screen. The following
16198     * properties of the paint are taken into account when composing the layer:</p>
16199     * <ul>
16200     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16201     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16202     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16203     * </ul>
16204     *
16205     * <p>If this view has an alpha value set to < 1.0 by calling
16206     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16207     * by this view's alpha value.</p>
16208     *
16209     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16210     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16211     * for more information on when and how to use layers.</p>
16212     *
16213     * @param layerType The type of layer to use with this view, must be one of
16214     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16215     *        {@link #LAYER_TYPE_HARDWARE}
16216     * @param paint The paint used to compose the layer. This argument is optional
16217     *        and can be null. It is ignored when the layer type is
16218     *        {@link #LAYER_TYPE_NONE}
16219     *
16220     * @see #getLayerType()
16221     * @see #LAYER_TYPE_NONE
16222     * @see #LAYER_TYPE_SOFTWARE
16223     * @see #LAYER_TYPE_HARDWARE
16224     * @see #setAlpha(float)
16225     *
16226     * @attr ref android.R.styleable#View_layerType
16227     */
16228    public void setLayerType(int layerType, @Nullable Paint paint) {
16229        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16230            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16231                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16232        }
16233
16234        boolean typeChanged = mRenderNode.setLayerType(layerType);
16235
16236        if (!typeChanged) {
16237            setLayerPaint(paint);
16238            return;
16239        }
16240
16241        if (layerType != LAYER_TYPE_SOFTWARE) {
16242            // Destroy any previous software drawing cache if present
16243            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16244            // drawing cache created in View#draw when drawing to a SW canvas.
16245            destroyDrawingCache();
16246        }
16247
16248        mLayerType = layerType;
16249        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16250        mRenderNode.setLayerPaint(mLayerPaint);
16251
16252        // draw() behaves differently if we are on a layer, so we need to
16253        // invalidate() here
16254        invalidateParentCaches();
16255        invalidate(true);
16256    }
16257
16258    /**
16259     * Updates the {@link Paint} object used with the current layer (used only if the current
16260     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16261     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16262     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16263     * ensure that the view gets redrawn immediately.
16264     *
16265     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16266     * instance that controls how the layer is composed on screen. The following
16267     * properties of the paint are taken into account when composing the layer:</p>
16268     * <ul>
16269     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16270     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16271     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16272     * </ul>
16273     *
16274     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16275     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16276     *
16277     * @param paint The paint used to compose the layer. This argument is optional
16278     *        and can be null. It is ignored when the layer type is
16279     *        {@link #LAYER_TYPE_NONE}
16280     *
16281     * @see #setLayerType(int, android.graphics.Paint)
16282     */
16283    public void setLayerPaint(@Nullable Paint paint) {
16284        int layerType = getLayerType();
16285        if (layerType != LAYER_TYPE_NONE) {
16286            mLayerPaint = paint;
16287            if (layerType == LAYER_TYPE_HARDWARE) {
16288                if (mRenderNode.setLayerPaint(paint)) {
16289                    invalidateViewProperty(false, false);
16290                }
16291            } else {
16292                invalidate();
16293            }
16294        }
16295    }
16296
16297    /**
16298     * Indicates what type of layer is currently associated with this view. By default
16299     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16300     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16301     * for more information on the different types of layers.
16302     *
16303     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16304     *         {@link #LAYER_TYPE_HARDWARE}
16305     *
16306     * @see #setLayerType(int, android.graphics.Paint)
16307     * @see #buildLayer()
16308     * @see #LAYER_TYPE_NONE
16309     * @see #LAYER_TYPE_SOFTWARE
16310     * @see #LAYER_TYPE_HARDWARE
16311     */
16312    public int getLayerType() {
16313        return mLayerType;
16314    }
16315
16316    /**
16317     * Forces this view's layer to be created and this view to be rendered
16318     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16319     * invoking this method will have no effect.
16320     *
16321     * This method can for instance be used to render a view into its layer before
16322     * starting an animation. If this view is complex, rendering into the layer
16323     * before starting the animation will avoid skipping frames.
16324     *
16325     * @throws IllegalStateException If this view is not attached to a window
16326     *
16327     * @see #setLayerType(int, android.graphics.Paint)
16328     */
16329    public void buildLayer() {
16330        if (mLayerType == LAYER_TYPE_NONE) return;
16331
16332        final AttachInfo attachInfo = mAttachInfo;
16333        if (attachInfo == null) {
16334            throw new IllegalStateException("This view must be attached to a window first");
16335        }
16336
16337        if (getWidth() == 0 || getHeight() == 0) {
16338            return;
16339        }
16340
16341        switch (mLayerType) {
16342            case LAYER_TYPE_HARDWARE:
16343                updateDisplayListIfDirty();
16344                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16345                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16346                }
16347                break;
16348            case LAYER_TYPE_SOFTWARE:
16349                buildDrawingCache(true);
16350                break;
16351        }
16352    }
16353
16354    /**
16355     * Destroys all hardware rendering resources. This method is invoked
16356     * when the system needs to reclaim resources. Upon execution of this
16357     * method, you should free any OpenGL resources created by the view.
16358     *
16359     * Note: you <strong>must</strong> call
16360     * <code>super.destroyHardwareResources()</code> when overriding
16361     * this method.
16362     *
16363     * @hide
16364     */
16365    @CallSuper
16366    protected void destroyHardwareResources() {
16367        // Although the Layer will be destroyed by RenderNode, we want to release
16368        // the staging display list, which is also a signal to RenderNode that it's
16369        // safe to free its copy of the display list as it knows that we will
16370        // push an updated DisplayList if we try to draw again
16371        resetDisplayList();
16372    }
16373
16374    /**
16375     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16376     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16377     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16378     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16379     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16380     * null.</p>
16381     *
16382     * <p>Enabling the drawing cache is similar to
16383     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16384     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16385     * drawing cache has no effect on rendering because the system uses a different mechanism
16386     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16387     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16388     * for information on how to enable software and hardware layers.</p>
16389     *
16390     * <p>This API can be used to manually generate
16391     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16392     * {@link #getDrawingCache()}.</p>
16393     *
16394     * @param enabled true to enable the drawing cache, false otherwise
16395     *
16396     * @see #isDrawingCacheEnabled()
16397     * @see #getDrawingCache()
16398     * @see #buildDrawingCache()
16399     * @see #setLayerType(int, android.graphics.Paint)
16400     */
16401    public void setDrawingCacheEnabled(boolean enabled) {
16402        mCachingFailed = false;
16403        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16404    }
16405
16406    /**
16407     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16408     *
16409     * @return true if the drawing cache is enabled
16410     *
16411     * @see #setDrawingCacheEnabled(boolean)
16412     * @see #getDrawingCache()
16413     */
16414    @ViewDebug.ExportedProperty(category = "drawing")
16415    public boolean isDrawingCacheEnabled() {
16416        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16417    }
16418
16419    /**
16420     * Debugging utility which recursively outputs the dirty state of a view and its
16421     * descendants.
16422     *
16423     * @hide
16424     */
16425    @SuppressWarnings({"UnusedDeclaration"})
16426    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16427        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16428                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16429                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16430                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16431        if (clear) {
16432            mPrivateFlags &= clearMask;
16433        }
16434        if (this instanceof ViewGroup) {
16435            ViewGroup parent = (ViewGroup) this;
16436            final int count = parent.getChildCount();
16437            for (int i = 0; i < count; i++) {
16438                final View child = parent.getChildAt(i);
16439                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16440            }
16441        }
16442    }
16443
16444    /**
16445     * This method is used by ViewGroup to cause its children to restore or recreate their
16446     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16447     * to recreate its own display list, which would happen if it went through the normal
16448     * draw/dispatchDraw mechanisms.
16449     *
16450     * @hide
16451     */
16452    protected void dispatchGetDisplayList() {}
16453
16454    /**
16455     * A view that is not attached or hardware accelerated cannot create a display list.
16456     * This method checks these conditions and returns the appropriate result.
16457     *
16458     * @return true if view has the ability to create a display list, false otherwise.
16459     *
16460     * @hide
16461     */
16462    public boolean canHaveDisplayList() {
16463        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16464    }
16465
16466    /**
16467     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16468     * @hide
16469     */
16470    @NonNull
16471    public RenderNode updateDisplayListIfDirty() {
16472        final RenderNode renderNode = mRenderNode;
16473        if (!canHaveDisplayList()) {
16474            // can't populate RenderNode, don't try
16475            return renderNode;
16476        }
16477
16478        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16479                || !renderNode.isValid()
16480                || (mRecreateDisplayList)) {
16481            // Don't need to recreate the display list, just need to tell our
16482            // children to restore/recreate theirs
16483            if (renderNode.isValid()
16484                    && !mRecreateDisplayList) {
16485                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16486                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16487                dispatchGetDisplayList();
16488
16489                return renderNode; // no work needed
16490            }
16491
16492            // If we got here, we're recreating it. Mark it as such to ensure that
16493            // we copy in child display lists into ours in drawChild()
16494            mRecreateDisplayList = true;
16495
16496            int width = mRight - mLeft;
16497            int height = mBottom - mTop;
16498            int layerType = getLayerType();
16499
16500            final DisplayListCanvas canvas = renderNode.start(width, height);
16501            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16502
16503            try {
16504                if (layerType == LAYER_TYPE_SOFTWARE) {
16505                    buildDrawingCache(true);
16506                    Bitmap cache = getDrawingCache(true);
16507                    if (cache != null) {
16508                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16509                    }
16510                } else {
16511                    computeScroll();
16512
16513                    canvas.translate(-mScrollX, -mScrollY);
16514                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16515                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16516
16517                    // Fast path for layouts with no backgrounds
16518                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16519                        dispatchDraw(canvas);
16520                        if (mOverlay != null && !mOverlay.isEmpty()) {
16521                            mOverlay.getOverlayView().draw(canvas);
16522                        }
16523                        if (debugDraw()) {
16524                            debugDrawFocus(canvas);
16525                        }
16526                    } else {
16527                        draw(canvas);
16528                    }
16529                }
16530            } finally {
16531                renderNode.end(canvas);
16532                setDisplayListProperties(renderNode);
16533            }
16534        } else {
16535            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16536            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16537        }
16538        return renderNode;
16539    }
16540
16541    private void resetDisplayList() {
16542        if (mRenderNode.isValid()) {
16543            mRenderNode.discardDisplayList();
16544        }
16545
16546        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16547            mBackgroundRenderNode.discardDisplayList();
16548        }
16549    }
16550
16551    /**
16552     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16553     *
16554     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16555     *
16556     * @see #getDrawingCache(boolean)
16557     */
16558    public Bitmap getDrawingCache() {
16559        return getDrawingCache(false);
16560    }
16561
16562    /**
16563     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16564     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16565     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16566     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16567     * request the drawing cache by calling this method and draw it on screen if the
16568     * returned bitmap is not null.</p>
16569     *
16570     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16571     * this method will create a bitmap of the same size as this view. Because this bitmap
16572     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16573     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16574     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16575     * size than the view. This implies that your application must be able to handle this
16576     * size.</p>
16577     *
16578     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16579     *        the current density of the screen when the application is in compatibility
16580     *        mode.
16581     *
16582     * @return A bitmap representing this view or null if cache is disabled.
16583     *
16584     * @see #setDrawingCacheEnabled(boolean)
16585     * @see #isDrawingCacheEnabled()
16586     * @see #buildDrawingCache(boolean)
16587     * @see #destroyDrawingCache()
16588     */
16589    public Bitmap getDrawingCache(boolean autoScale) {
16590        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16591            return null;
16592        }
16593        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16594            buildDrawingCache(autoScale);
16595        }
16596        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16597    }
16598
16599    /**
16600     * <p>Frees the resources used by the drawing cache. If you call
16601     * {@link #buildDrawingCache()} manually without calling
16602     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16603     * should cleanup the cache with this method afterwards.</p>
16604     *
16605     * @see #setDrawingCacheEnabled(boolean)
16606     * @see #buildDrawingCache()
16607     * @see #getDrawingCache()
16608     */
16609    public void destroyDrawingCache() {
16610        if (mDrawingCache != null) {
16611            mDrawingCache.recycle();
16612            mDrawingCache = null;
16613        }
16614        if (mUnscaledDrawingCache != null) {
16615            mUnscaledDrawingCache.recycle();
16616            mUnscaledDrawingCache = null;
16617        }
16618    }
16619
16620    /**
16621     * Setting a solid background color for the drawing cache's bitmaps will improve
16622     * performance and memory usage. Note, though that this should only be used if this
16623     * view will always be drawn on top of a solid color.
16624     *
16625     * @param color The background color to use for the drawing cache's bitmap
16626     *
16627     * @see #setDrawingCacheEnabled(boolean)
16628     * @see #buildDrawingCache()
16629     * @see #getDrawingCache()
16630     */
16631    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16632        if (color != mDrawingCacheBackgroundColor) {
16633            mDrawingCacheBackgroundColor = color;
16634            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16635        }
16636    }
16637
16638    /**
16639     * @see #setDrawingCacheBackgroundColor(int)
16640     *
16641     * @return The background color to used for the drawing cache's bitmap
16642     */
16643    @ColorInt
16644    public int getDrawingCacheBackgroundColor() {
16645        return mDrawingCacheBackgroundColor;
16646    }
16647
16648    /**
16649     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16650     *
16651     * @see #buildDrawingCache(boolean)
16652     */
16653    public void buildDrawingCache() {
16654        buildDrawingCache(false);
16655    }
16656
16657    /**
16658     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16659     *
16660     * <p>If you call {@link #buildDrawingCache()} manually without calling
16661     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16662     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16663     *
16664     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16665     * this method will create a bitmap of the same size as this view. Because this bitmap
16666     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16667     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16668     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16669     * size than the view. This implies that your application must be able to handle this
16670     * size.</p>
16671     *
16672     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16673     * you do not need the drawing cache bitmap, calling this method will increase memory
16674     * usage and cause the view to be rendered in software once, thus negatively impacting
16675     * performance.</p>
16676     *
16677     * @see #getDrawingCache()
16678     * @see #destroyDrawingCache()
16679     */
16680    public void buildDrawingCache(boolean autoScale) {
16681        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16682                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16683            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16684                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16685                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16686            }
16687            try {
16688                buildDrawingCacheImpl(autoScale);
16689            } finally {
16690                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16691            }
16692        }
16693    }
16694
16695    /**
16696     * private, internal implementation of buildDrawingCache, used to enable tracing
16697     */
16698    private void buildDrawingCacheImpl(boolean autoScale) {
16699        mCachingFailed = false;
16700
16701        int width = mRight - mLeft;
16702        int height = mBottom - mTop;
16703
16704        final AttachInfo attachInfo = mAttachInfo;
16705        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16706
16707        if (autoScale && scalingRequired) {
16708            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16709            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16710        }
16711
16712        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16713        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16714        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16715
16716        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16717        final long drawingCacheSize =
16718                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16719        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16720            if (width > 0 && height > 0) {
16721                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16722                        + " too large to fit into a software layer (or drawing cache), needs "
16723                        + projectedBitmapSize + " bytes, only "
16724                        + drawingCacheSize + " available");
16725            }
16726            destroyDrawingCache();
16727            mCachingFailed = true;
16728            return;
16729        }
16730
16731        boolean clear = true;
16732        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16733
16734        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16735            Bitmap.Config quality;
16736            if (!opaque) {
16737                // Never pick ARGB_4444 because it looks awful
16738                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16739                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16740                    case DRAWING_CACHE_QUALITY_AUTO:
16741                    case DRAWING_CACHE_QUALITY_LOW:
16742                    case DRAWING_CACHE_QUALITY_HIGH:
16743                    default:
16744                        quality = Bitmap.Config.ARGB_8888;
16745                        break;
16746                }
16747            } else {
16748                // Optimization for translucent windows
16749                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16750                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16751            }
16752
16753            // Try to cleanup memory
16754            if (bitmap != null) bitmap.recycle();
16755
16756            try {
16757                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16758                        width, height, quality);
16759                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16760                if (autoScale) {
16761                    mDrawingCache = bitmap;
16762                } else {
16763                    mUnscaledDrawingCache = bitmap;
16764                }
16765                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16766            } catch (OutOfMemoryError e) {
16767                // If there is not enough memory to create the bitmap cache, just
16768                // ignore the issue as bitmap caches are not required to draw the
16769                // view hierarchy
16770                if (autoScale) {
16771                    mDrawingCache = null;
16772                } else {
16773                    mUnscaledDrawingCache = null;
16774                }
16775                mCachingFailed = true;
16776                return;
16777            }
16778
16779            clear = drawingCacheBackgroundColor != 0;
16780        }
16781
16782        Canvas canvas;
16783        if (attachInfo != null) {
16784            canvas = attachInfo.mCanvas;
16785            if (canvas == null) {
16786                canvas = new Canvas();
16787            }
16788            canvas.setBitmap(bitmap);
16789            // Temporarily clobber the cached Canvas in case one of our children
16790            // is also using a drawing cache. Without this, the children would
16791            // steal the canvas by attaching their own bitmap to it and bad, bad
16792            // thing would happen (invisible views, corrupted drawings, etc.)
16793            attachInfo.mCanvas = null;
16794        } else {
16795            // This case should hopefully never or seldom happen
16796            canvas = new Canvas(bitmap);
16797        }
16798
16799        if (clear) {
16800            bitmap.eraseColor(drawingCacheBackgroundColor);
16801        }
16802
16803        computeScroll();
16804        final int restoreCount = canvas.save();
16805
16806        if (autoScale && scalingRequired) {
16807            final float scale = attachInfo.mApplicationScale;
16808            canvas.scale(scale, scale);
16809        }
16810
16811        canvas.translate(-mScrollX, -mScrollY);
16812
16813        mPrivateFlags |= PFLAG_DRAWN;
16814        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16815                mLayerType != LAYER_TYPE_NONE) {
16816            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16817        }
16818
16819        // Fast path for layouts with no backgrounds
16820        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16821            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16822            dispatchDraw(canvas);
16823            if (mOverlay != null && !mOverlay.isEmpty()) {
16824                mOverlay.getOverlayView().draw(canvas);
16825            }
16826        } else {
16827            draw(canvas);
16828        }
16829
16830        canvas.restoreToCount(restoreCount);
16831        canvas.setBitmap(null);
16832
16833        if (attachInfo != null) {
16834            // Restore the cached Canvas for our siblings
16835            attachInfo.mCanvas = canvas;
16836        }
16837    }
16838
16839    /**
16840     * Create a snapshot of the view into a bitmap.  We should probably make
16841     * some form of this public, but should think about the API.
16842     *
16843     * @hide
16844     */
16845    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16846        int width = mRight - mLeft;
16847        int height = mBottom - mTop;
16848
16849        final AttachInfo attachInfo = mAttachInfo;
16850        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16851        width = (int) ((width * scale) + 0.5f);
16852        height = (int) ((height * scale) + 0.5f);
16853
16854        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16855                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16856        if (bitmap == null) {
16857            throw new OutOfMemoryError();
16858        }
16859
16860        Resources resources = getResources();
16861        if (resources != null) {
16862            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16863        }
16864
16865        Canvas canvas;
16866        if (attachInfo != null) {
16867            canvas = attachInfo.mCanvas;
16868            if (canvas == null) {
16869                canvas = new Canvas();
16870            }
16871            canvas.setBitmap(bitmap);
16872            // Temporarily clobber the cached Canvas in case one of our children
16873            // is also using a drawing cache. Without this, the children would
16874            // steal the canvas by attaching their own bitmap to it and bad, bad
16875            // things would happen (invisible views, corrupted drawings, etc.)
16876            attachInfo.mCanvas = null;
16877        } else {
16878            // This case should hopefully never or seldom happen
16879            canvas = new Canvas(bitmap);
16880        }
16881
16882        if ((backgroundColor & 0xff000000) != 0) {
16883            bitmap.eraseColor(backgroundColor);
16884        }
16885
16886        computeScroll();
16887        final int restoreCount = canvas.save();
16888        canvas.scale(scale, scale);
16889        canvas.translate(-mScrollX, -mScrollY);
16890
16891        // Temporarily remove the dirty mask
16892        int flags = mPrivateFlags;
16893        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16894
16895        // Fast path for layouts with no backgrounds
16896        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16897            dispatchDraw(canvas);
16898            if (mOverlay != null && !mOverlay.isEmpty()) {
16899                mOverlay.getOverlayView().draw(canvas);
16900            }
16901        } else {
16902            draw(canvas);
16903        }
16904
16905        mPrivateFlags = flags;
16906
16907        canvas.restoreToCount(restoreCount);
16908        canvas.setBitmap(null);
16909
16910        if (attachInfo != null) {
16911            // Restore the cached Canvas for our siblings
16912            attachInfo.mCanvas = canvas;
16913        }
16914
16915        return bitmap;
16916    }
16917
16918    /**
16919     * Indicates whether this View is currently in edit mode. A View is usually
16920     * in edit mode when displayed within a developer tool. For instance, if
16921     * this View is being drawn by a visual user interface builder, this method
16922     * should return true.
16923     *
16924     * Subclasses should check the return value of this method to provide
16925     * different behaviors if their normal behavior might interfere with the
16926     * host environment. For instance: the class spawns a thread in its
16927     * constructor, the drawing code relies on device-specific features, etc.
16928     *
16929     * This method is usually checked in the drawing code of custom widgets.
16930     *
16931     * @return True if this View is in edit mode, false otherwise.
16932     */
16933    public boolean isInEditMode() {
16934        return false;
16935    }
16936
16937    /**
16938     * If the View draws content inside its padding and enables fading edges,
16939     * it needs to support padding offsets. Padding offsets are added to the
16940     * fading edges to extend the length of the fade so that it covers pixels
16941     * drawn inside the padding.
16942     *
16943     * Subclasses of this class should override this method if they need
16944     * to draw content inside the padding.
16945     *
16946     * @return True if padding offset must be applied, false otherwise.
16947     *
16948     * @see #getLeftPaddingOffset()
16949     * @see #getRightPaddingOffset()
16950     * @see #getTopPaddingOffset()
16951     * @see #getBottomPaddingOffset()
16952     *
16953     * @since CURRENT
16954     */
16955    protected boolean isPaddingOffsetRequired() {
16956        return false;
16957    }
16958
16959    /**
16960     * Amount by which to extend the left fading region. Called only when
16961     * {@link #isPaddingOffsetRequired()} returns true.
16962     *
16963     * @return The left padding offset in pixels.
16964     *
16965     * @see #isPaddingOffsetRequired()
16966     *
16967     * @since CURRENT
16968     */
16969    protected int getLeftPaddingOffset() {
16970        return 0;
16971    }
16972
16973    /**
16974     * Amount by which to extend the right fading region. Called only when
16975     * {@link #isPaddingOffsetRequired()} returns true.
16976     *
16977     * @return The right padding offset in pixels.
16978     *
16979     * @see #isPaddingOffsetRequired()
16980     *
16981     * @since CURRENT
16982     */
16983    protected int getRightPaddingOffset() {
16984        return 0;
16985    }
16986
16987    /**
16988     * Amount by which to extend the top fading region. Called only when
16989     * {@link #isPaddingOffsetRequired()} returns true.
16990     *
16991     * @return The top padding offset in pixels.
16992     *
16993     * @see #isPaddingOffsetRequired()
16994     *
16995     * @since CURRENT
16996     */
16997    protected int getTopPaddingOffset() {
16998        return 0;
16999    }
17000
17001    /**
17002     * Amount by which to extend the bottom fading region. Called only when
17003     * {@link #isPaddingOffsetRequired()} returns true.
17004     *
17005     * @return The bottom padding offset in pixels.
17006     *
17007     * @see #isPaddingOffsetRequired()
17008     *
17009     * @since CURRENT
17010     */
17011    protected int getBottomPaddingOffset() {
17012        return 0;
17013    }
17014
17015    /**
17016     * @hide
17017     * @param offsetRequired
17018     */
17019    protected int getFadeTop(boolean offsetRequired) {
17020        int top = mPaddingTop;
17021        if (offsetRequired) top += getTopPaddingOffset();
17022        return top;
17023    }
17024
17025    /**
17026     * @hide
17027     * @param offsetRequired
17028     */
17029    protected int getFadeHeight(boolean offsetRequired) {
17030        int padding = mPaddingTop;
17031        if (offsetRequired) padding += getTopPaddingOffset();
17032        return mBottom - mTop - mPaddingBottom - padding;
17033    }
17034
17035    /**
17036     * <p>Indicates whether this view is attached to a hardware accelerated
17037     * window or not.</p>
17038     *
17039     * <p>Even if this method returns true, it does not mean that every call
17040     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17041     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17042     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17043     * window is hardware accelerated,
17044     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17045     * return false, and this method will return true.</p>
17046     *
17047     * @return True if the view is attached to a window and the window is
17048     *         hardware accelerated; false in any other case.
17049     */
17050    @ViewDebug.ExportedProperty(category = "drawing")
17051    public boolean isHardwareAccelerated() {
17052        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17053    }
17054
17055    /**
17056     * Sets a rectangular area on this view to which the view will be clipped
17057     * when it is drawn. Setting the value to null will remove the clip bounds
17058     * and the view will draw normally, using its full bounds.
17059     *
17060     * @param clipBounds The rectangular area, in the local coordinates of
17061     * this view, to which future drawing operations will be clipped.
17062     */
17063    public void setClipBounds(Rect clipBounds) {
17064        if (clipBounds == mClipBounds
17065                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17066            return;
17067        }
17068        if (clipBounds != null) {
17069            if (mClipBounds == null) {
17070                mClipBounds = new Rect(clipBounds);
17071            } else {
17072                mClipBounds.set(clipBounds);
17073            }
17074        } else {
17075            mClipBounds = null;
17076        }
17077        mRenderNode.setClipBounds(mClipBounds);
17078        invalidateViewProperty(false, false);
17079    }
17080
17081    /**
17082     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17083     *
17084     * @return A copy of the current clip bounds if clip bounds are set,
17085     * otherwise null.
17086     */
17087    public Rect getClipBounds() {
17088        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17089    }
17090
17091
17092    /**
17093     * Populates an output rectangle with the clip bounds of the view,
17094     * returning {@code true} if successful or {@code false} if the view's
17095     * clip bounds are {@code null}.
17096     *
17097     * @param outRect rectangle in which to place the clip bounds of the view
17098     * @return {@code true} if successful or {@code false} if the view's
17099     *         clip bounds are {@code null}
17100     */
17101    public boolean getClipBounds(Rect outRect) {
17102        if (mClipBounds != null) {
17103            outRect.set(mClipBounds);
17104            return true;
17105        }
17106        return false;
17107    }
17108
17109    /**
17110     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17111     * case of an active Animation being run on the view.
17112     */
17113    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17114            Animation a, boolean scalingRequired) {
17115        Transformation invalidationTransform;
17116        final int flags = parent.mGroupFlags;
17117        final boolean initialized = a.isInitialized();
17118        if (!initialized) {
17119            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17120            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17121            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17122            onAnimationStart();
17123        }
17124
17125        final Transformation t = parent.getChildTransformation();
17126        boolean more = a.getTransformation(drawingTime, t, 1f);
17127        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17128            if (parent.mInvalidationTransformation == null) {
17129                parent.mInvalidationTransformation = new Transformation();
17130            }
17131            invalidationTransform = parent.mInvalidationTransformation;
17132            a.getTransformation(drawingTime, invalidationTransform, 1f);
17133        } else {
17134            invalidationTransform = t;
17135        }
17136
17137        if (more) {
17138            if (!a.willChangeBounds()) {
17139                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17140                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17141                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17142                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17143                    // The child need to draw an animation, potentially offscreen, so
17144                    // make sure we do not cancel invalidate requests
17145                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17146                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17147                }
17148            } else {
17149                if (parent.mInvalidateRegion == null) {
17150                    parent.mInvalidateRegion = new RectF();
17151                }
17152                final RectF region = parent.mInvalidateRegion;
17153                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17154                        invalidationTransform);
17155
17156                // The child need to draw an animation, potentially offscreen, so
17157                // make sure we do not cancel invalidate requests
17158                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17159
17160                final int left = mLeft + (int) region.left;
17161                final int top = mTop + (int) region.top;
17162                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17163                        top + (int) (region.height() + .5f));
17164            }
17165        }
17166        return more;
17167    }
17168
17169    /**
17170     * This method is called by getDisplayList() when a display list is recorded for a View.
17171     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17172     */
17173    void setDisplayListProperties(RenderNode renderNode) {
17174        if (renderNode != null) {
17175            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17176            renderNode.setClipToBounds(mParent instanceof ViewGroup
17177                    && ((ViewGroup) mParent).getClipChildren());
17178
17179            float alpha = 1;
17180            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17181                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17182                ViewGroup parentVG = (ViewGroup) mParent;
17183                final Transformation t = parentVG.getChildTransformation();
17184                if (parentVG.getChildStaticTransformation(this, t)) {
17185                    final int transformType = t.getTransformationType();
17186                    if (transformType != Transformation.TYPE_IDENTITY) {
17187                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17188                            alpha = t.getAlpha();
17189                        }
17190                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17191                            renderNode.setStaticMatrix(t.getMatrix());
17192                        }
17193                    }
17194                }
17195            }
17196            if (mTransformationInfo != null) {
17197                alpha *= getFinalAlpha();
17198                if (alpha < 1) {
17199                    final int multipliedAlpha = (int) (255 * alpha);
17200                    if (onSetAlpha(multipliedAlpha)) {
17201                        alpha = 1;
17202                    }
17203                }
17204                renderNode.setAlpha(alpha);
17205            } else if (alpha < 1) {
17206                renderNode.setAlpha(alpha);
17207            }
17208        }
17209    }
17210
17211    /**
17212     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17213     *
17214     * This is where the View specializes rendering behavior based on layer type,
17215     * and hardware acceleration.
17216     */
17217    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17218        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17219        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17220         *
17221         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17222         * HW accelerated, it can't handle drawing RenderNodes.
17223         */
17224        boolean drawingWithRenderNode = mAttachInfo != null
17225                && mAttachInfo.mHardwareAccelerated
17226                && hardwareAcceleratedCanvas;
17227
17228        boolean more = false;
17229        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17230        final int parentFlags = parent.mGroupFlags;
17231
17232        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17233            parent.getChildTransformation().clear();
17234            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17235        }
17236
17237        Transformation transformToApply = null;
17238        boolean concatMatrix = false;
17239        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17240        final Animation a = getAnimation();
17241        if (a != null) {
17242            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17243            concatMatrix = a.willChangeTransformationMatrix();
17244            if (concatMatrix) {
17245                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17246            }
17247            transformToApply = parent.getChildTransformation();
17248        } else {
17249            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17250                // No longer animating: clear out old animation matrix
17251                mRenderNode.setAnimationMatrix(null);
17252                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17253            }
17254            if (!drawingWithRenderNode
17255                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17256                final Transformation t = parent.getChildTransformation();
17257                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17258                if (hasTransform) {
17259                    final int transformType = t.getTransformationType();
17260                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17261                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17262                }
17263            }
17264        }
17265
17266        concatMatrix |= !childHasIdentityMatrix;
17267
17268        // Sets the flag as early as possible to allow draw() implementations
17269        // to call invalidate() successfully when doing animations
17270        mPrivateFlags |= PFLAG_DRAWN;
17271
17272        if (!concatMatrix &&
17273                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17274                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17275                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17276                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17277            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17278            return more;
17279        }
17280        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17281
17282        if (hardwareAcceleratedCanvas) {
17283            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17284            // retain the flag's value temporarily in the mRecreateDisplayList flag
17285            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17286            mPrivateFlags &= ~PFLAG_INVALIDATED;
17287        }
17288
17289        RenderNode renderNode = null;
17290        Bitmap cache = null;
17291        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17292        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17293             if (layerType != LAYER_TYPE_NONE) {
17294                 // If not drawing with RenderNode, treat HW layers as SW
17295                 layerType = LAYER_TYPE_SOFTWARE;
17296                 buildDrawingCache(true);
17297            }
17298            cache = getDrawingCache(true);
17299        }
17300
17301        if (drawingWithRenderNode) {
17302            // Delay getting the display list until animation-driven alpha values are
17303            // set up and possibly passed on to the view
17304            renderNode = updateDisplayListIfDirty();
17305            if (!renderNode.isValid()) {
17306                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17307                // to getDisplayList(), the display list will be marked invalid and we should not
17308                // try to use it again.
17309                renderNode = null;
17310                drawingWithRenderNode = false;
17311            }
17312        }
17313
17314        int sx = 0;
17315        int sy = 0;
17316        if (!drawingWithRenderNode) {
17317            computeScroll();
17318            sx = mScrollX;
17319            sy = mScrollY;
17320        }
17321
17322        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17323        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17324
17325        int restoreTo = -1;
17326        if (!drawingWithRenderNode || transformToApply != null) {
17327            restoreTo = canvas.save();
17328        }
17329        if (offsetForScroll) {
17330            canvas.translate(mLeft - sx, mTop - sy);
17331        } else {
17332            if (!drawingWithRenderNode) {
17333                canvas.translate(mLeft, mTop);
17334            }
17335            if (scalingRequired) {
17336                if (drawingWithRenderNode) {
17337                    // TODO: Might not need this if we put everything inside the DL
17338                    restoreTo = canvas.save();
17339                }
17340                // mAttachInfo cannot be null, otherwise scalingRequired == false
17341                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17342                canvas.scale(scale, scale);
17343            }
17344        }
17345
17346        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17347        if (transformToApply != null
17348                || alpha < 1
17349                || !hasIdentityMatrix()
17350                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17351            if (transformToApply != null || !childHasIdentityMatrix) {
17352                int transX = 0;
17353                int transY = 0;
17354
17355                if (offsetForScroll) {
17356                    transX = -sx;
17357                    transY = -sy;
17358                }
17359
17360                if (transformToApply != null) {
17361                    if (concatMatrix) {
17362                        if (drawingWithRenderNode) {
17363                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17364                        } else {
17365                            // Undo the scroll translation, apply the transformation matrix,
17366                            // then redo the scroll translate to get the correct result.
17367                            canvas.translate(-transX, -transY);
17368                            canvas.concat(transformToApply.getMatrix());
17369                            canvas.translate(transX, transY);
17370                        }
17371                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17372                    }
17373
17374                    float transformAlpha = transformToApply.getAlpha();
17375                    if (transformAlpha < 1) {
17376                        alpha *= transformAlpha;
17377                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17378                    }
17379                }
17380
17381                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17382                    canvas.translate(-transX, -transY);
17383                    canvas.concat(getMatrix());
17384                    canvas.translate(transX, transY);
17385                }
17386            }
17387
17388            // Deal with alpha if it is or used to be <1
17389            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17390                if (alpha < 1) {
17391                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17392                } else {
17393                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17394                }
17395                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17396                if (!drawingWithDrawingCache) {
17397                    final int multipliedAlpha = (int) (255 * alpha);
17398                    if (!onSetAlpha(multipliedAlpha)) {
17399                        if (drawingWithRenderNode) {
17400                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17401                        } else if (layerType == LAYER_TYPE_NONE) {
17402                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17403                                    multipliedAlpha);
17404                        }
17405                    } else {
17406                        // Alpha is handled by the child directly, clobber the layer's alpha
17407                        mPrivateFlags |= PFLAG_ALPHA_SET;
17408                    }
17409                }
17410            }
17411        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17412            onSetAlpha(255);
17413            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17414        }
17415
17416        if (!drawingWithRenderNode) {
17417            // apply clips directly, since RenderNode won't do it for this draw
17418            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17419                if (offsetForScroll) {
17420                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17421                } else {
17422                    if (!scalingRequired || cache == null) {
17423                        canvas.clipRect(0, 0, getWidth(), getHeight());
17424                    } else {
17425                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17426                    }
17427                }
17428            }
17429
17430            if (mClipBounds != null) {
17431                // clip bounds ignore scroll
17432                canvas.clipRect(mClipBounds);
17433            }
17434        }
17435
17436        if (!drawingWithDrawingCache) {
17437            if (drawingWithRenderNode) {
17438                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17439                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17440            } else {
17441                // Fast path for layouts with no backgrounds
17442                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17443                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17444                    dispatchDraw(canvas);
17445                } else {
17446                    draw(canvas);
17447                }
17448            }
17449        } else if (cache != null) {
17450            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17451            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17452                // no layer paint, use temporary paint to draw bitmap
17453                Paint cachePaint = parent.mCachePaint;
17454                if (cachePaint == null) {
17455                    cachePaint = new Paint();
17456                    cachePaint.setDither(false);
17457                    parent.mCachePaint = cachePaint;
17458                }
17459                cachePaint.setAlpha((int) (alpha * 255));
17460                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17461            } else {
17462                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17463                int layerPaintAlpha = mLayerPaint.getAlpha();
17464                if (alpha < 1) {
17465                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17466                }
17467                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17468                if (alpha < 1) {
17469                    mLayerPaint.setAlpha(layerPaintAlpha);
17470                }
17471            }
17472        }
17473
17474        if (restoreTo >= 0) {
17475            canvas.restoreToCount(restoreTo);
17476        }
17477
17478        if (a != null && !more) {
17479            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17480                onSetAlpha(255);
17481            }
17482            parent.finishAnimatingView(this, a);
17483        }
17484
17485        if (more && hardwareAcceleratedCanvas) {
17486            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17487                // alpha animations should cause the child to recreate its display list
17488                invalidate(true);
17489            }
17490        }
17491
17492        mRecreateDisplayList = false;
17493
17494        return more;
17495    }
17496
17497    static Paint getDebugPaint() {
17498        if (sDebugPaint == null) {
17499            sDebugPaint = new Paint();
17500            sDebugPaint.setAntiAlias(false);
17501        }
17502        return sDebugPaint;
17503    }
17504
17505    final int dipsToPixels(int dips) {
17506        float scale = getContext().getResources().getDisplayMetrics().density;
17507        return (int) (dips * scale + 0.5f);
17508    }
17509
17510    final private void debugDrawFocus(Canvas canvas) {
17511        if (isFocused()) {
17512            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17513            final int l = mScrollX;
17514            final int r = l + mRight - mLeft;
17515            final int t = mScrollY;
17516            final int b = t + mBottom - mTop;
17517
17518            final Paint paint = getDebugPaint();
17519            paint.setColor(DEBUG_CORNERS_COLOR);
17520
17521            // Draw squares in corners.
17522            paint.setStyle(Paint.Style.FILL);
17523            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17524            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17525            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17526            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17527
17528            // Draw big X across the view.
17529            paint.setStyle(Paint.Style.STROKE);
17530            canvas.drawLine(l, t, r, b, paint);
17531            canvas.drawLine(l, b, r, t, paint);
17532        }
17533    }
17534
17535    /**
17536     * Manually render this view (and all of its children) to the given Canvas.
17537     * The view must have already done a full layout before this function is
17538     * called.  When implementing a view, implement
17539     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17540     * If you do need to override this method, call the superclass version.
17541     *
17542     * @param canvas The Canvas to which the View is rendered.
17543     */
17544    @CallSuper
17545    public void draw(Canvas canvas) {
17546        final int privateFlags = mPrivateFlags;
17547        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17548                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17549        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17550
17551        /*
17552         * Draw traversal performs several drawing steps which must be executed
17553         * in the appropriate order:
17554         *
17555         *      1. Draw the background
17556         *      2. If necessary, save the canvas' layers to prepare for fading
17557         *      3. Draw view's content
17558         *      4. Draw children
17559         *      5. If necessary, draw the fading edges and restore layers
17560         *      6. Draw decorations (scrollbars for instance)
17561         */
17562
17563        // Step 1, draw the background, if needed
17564        int saveCount;
17565
17566        if (!dirtyOpaque) {
17567            drawBackground(canvas);
17568        }
17569
17570        // skip step 2 & 5 if possible (common case)
17571        final int viewFlags = mViewFlags;
17572        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17573        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17574        if (!verticalEdges && !horizontalEdges) {
17575            // Step 3, draw the content
17576            if (!dirtyOpaque) onDraw(canvas);
17577
17578            // Step 4, draw the children
17579            dispatchDraw(canvas);
17580
17581            // Overlay is part of the content and draws beneath Foreground
17582            if (mOverlay != null && !mOverlay.isEmpty()) {
17583                mOverlay.getOverlayView().dispatchDraw(canvas);
17584            }
17585
17586            // Step 6, draw decorations (foreground, scrollbars)
17587            onDrawForeground(canvas);
17588
17589            if (debugDraw()) {
17590                debugDrawFocus(canvas);
17591            }
17592
17593            // we're done...
17594            return;
17595        }
17596
17597        /*
17598         * Here we do the full fledged routine...
17599         * (this is an uncommon case where speed matters less,
17600         * this is why we repeat some of the tests that have been
17601         * done above)
17602         */
17603
17604        boolean drawTop = false;
17605        boolean drawBottom = false;
17606        boolean drawLeft = false;
17607        boolean drawRight = false;
17608
17609        float topFadeStrength = 0.0f;
17610        float bottomFadeStrength = 0.0f;
17611        float leftFadeStrength = 0.0f;
17612        float rightFadeStrength = 0.0f;
17613
17614        // Step 2, save the canvas' layers
17615        int paddingLeft = mPaddingLeft;
17616
17617        final boolean offsetRequired = isPaddingOffsetRequired();
17618        if (offsetRequired) {
17619            paddingLeft += getLeftPaddingOffset();
17620        }
17621
17622        int left = mScrollX + paddingLeft;
17623        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17624        int top = mScrollY + getFadeTop(offsetRequired);
17625        int bottom = top + getFadeHeight(offsetRequired);
17626
17627        if (offsetRequired) {
17628            right += getRightPaddingOffset();
17629            bottom += getBottomPaddingOffset();
17630        }
17631
17632        final ScrollabilityCache scrollabilityCache = mScrollCache;
17633        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17634        int length = (int) fadeHeight;
17635
17636        // clip the fade length if top and bottom fades overlap
17637        // overlapping fades produce odd-looking artifacts
17638        if (verticalEdges && (top + length > bottom - length)) {
17639            length = (bottom - top) / 2;
17640        }
17641
17642        // also clip horizontal fades if necessary
17643        if (horizontalEdges && (left + length > right - length)) {
17644            length = (right - left) / 2;
17645        }
17646
17647        if (verticalEdges) {
17648            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17649            drawTop = topFadeStrength * fadeHeight > 1.0f;
17650            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17651            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17652        }
17653
17654        if (horizontalEdges) {
17655            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17656            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17657            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17658            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17659        }
17660
17661        saveCount = canvas.getSaveCount();
17662
17663        int solidColor = getSolidColor();
17664        if (solidColor == 0) {
17665            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17666
17667            if (drawTop) {
17668                canvas.saveLayer(left, top, right, top + length, null, flags);
17669            }
17670
17671            if (drawBottom) {
17672                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17673            }
17674
17675            if (drawLeft) {
17676                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17677            }
17678
17679            if (drawRight) {
17680                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17681            }
17682        } else {
17683            scrollabilityCache.setFadeColor(solidColor);
17684        }
17685
17686        // Step 3, draw the content
17687        if (!dirtyOpaque) onDraw(canvas);
17688
17689        // Step 4, draw the children
17690        dispatchDraw(canvas);
17691
17692        // Step 5, draw the fade effect and restore layers
17693        final Paint p = scrollabilityCache.paint;
17694        final Matrix matrix = scrollabilityCache.matrix;
17695        final Shader fade = scrollabilityCache.shader;
17696
17697        if (drawTop) {
17698            matrix.setScale(1, fadeHeight * topFadeStrength);
17699            matrix.postTranslate(left, top);
17700            fade.setLocalMatrix(matrix);
17701            p.setShader(fade);
17702            canvas.drawRect(left, top, right, top + length, p);
17703        }
17704
17705        if (drawBottom) {
17706            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17707            matrix.postRotate(180);
17708            matrix.postTranslate(left, bottom);
17709            fade.setLocalMatrix(matrix);
17710            p.setShader(fade);
17711            canvas.drawRect(left, bottom - length, right, bottom, p);
17712        }
17713
17714        if (drawLeft) {
17715            matrix.setScale(1, fadeHeight * leftFadeStrength);
17716            matrix.postRotate(-90);
17717            matrix.postTranslate(left, top);
17718            fade.setLocalMatrix(matrix);
17719            p.setShader(fade);
17720            canvas.drawRect(left, top, left + length, bottom, p);
17721        }
17722
17723        if (drawRight) {
17724            matrix.setScale(1, fadeHeight * rightFadeStrength);
17725            matrix.postRotate(90);
17726            matrix.postTranslate(right, top);
17727            fade.setLocalMatrix(matrix);
17728            p.setShader(fade);
17729            canvas.drawRect(right - length, top, right, bottom, p);
17730        }
17731
17732        canvas.restoreToCount(saveCount);
17733
17734        // Overlay is part of the content and draws beneath Foreground
17735        if (mOverlay != null && !mOverlay.isEmpty()) {
17736            mOverlay.getOverlayView().dispatchDraw(canvas);
17737        }
17738
17739        // Step 6, draw decorations (foreground, scrollbars)
17740        onDrawForeground(canvas);
17741
17742        if (debugDraw()) {
17743            debugDrawFocus(canvas);
17744        }
17745    }
17746
17747    /**
17748     * Draws the background onto the specified canvas.
17749     *
17750     * @param canvas Canvas on which to draw the background
17751     */
17752    private void drawBackground(Canvas canvas) {
17753        final Drawable background = mBackground;
17754        if (background == null) {
17755            return;
17756        }
17757
17758        setBackgroundBounds();
17759
17760        // Attempt to use a display list if requested.
17761        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17762                && mAttachInfo.mThreadedRenderer != null) {
17763            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17764
17765            final RenderNode renderNode = mBackgroundRenderNode;
17766            if (renderNode != null && renderNode.isValid()) {
17767                setBackgroundRenderNodeProperties(renderNode);
17768                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17769                return;
17770            }
17771        }
17772
17773        final int scrollX = mScrollX;
17774        final int scrollY = mScrollY;
17775        if ((scrollX | scrollY) == 0) {
17776            background.draw(canvas);
17777        } else {
17778            canvas.translate(scrollX, scrollY);
17779            background.draw(canvas);
17780            canvas.translate(-scrollX, -scrollY);
17781        }
17782    }
17783
17784    /**
17785     * Sets the correct background bounds and rebuilds the outline, if needed.
17786     * <p/>
17787     * This is called by LayoutLib.
17788     */
17789    void setBackgroundBounds() {
17790        if (mBackgroundSizeChanged && mBackground != null) {
17791            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17792            mBackgroundSizeChanged = false;
17793            rebuildOutline();
17794        }
17795    }
17796
17797    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17798        renderNode.setTranslationX(mScrollX);
17799        renderNode.setTranslationY(mScrollY);
17800    }
17801
17802    /**
17803     * Creates a new display list or updates the existing display list for the
17804     * specified Drawable.
17805     *
17806     * @param drawable Drawable for which to create a display list
17807     * @param renderNode Existing RenderNode, or {@code null}
17808     * @return A valid display list for the specified drawable
17809     */
17810    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17811        if (renderNode == null) {
17812            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17813        }
17814
17815        final Rect bounds = drawable.getBounds();
17816        final int width = bounds.width();
17817        final int height = bounds.height();
17818        final DisplayListCanvas canvas = renderNode.start(width, height);
17819
17820        // Reverse left/top translation done by drawable canvas, which will
17821        // instead be applied by rendernode's LTRB bounds below. This way, the
17822        // drawable's bounds match with its rendernode bounds and its content
17823        // will lie within those bounds in the rendernode tree.
17824        canvas.translate(-bounds.left, -bounds.top);
17825
17826        try {
17827            drawable.draw(canvas);
17828        } finally {
17829            renderNode.end(canvas);
17830        }
17831
17832        // Set up drawable properties that are view-independent.
17833        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17834        renderNode.setProjectBackwards(drawable.isProjected());
17835        renderNode.setProjectionReceiver(true);
17836        renderNode.setClipToBounds(false);
17837        return renderNode;
17838    }
17839
17840    /**
17841     * Returns the overlay for this view, creating it if it does not yet exist.
17842     * Adding drawables to the overlay will cause them to be displayed whenever
17843     * the view itself is redrawn. Objects in the overlay should be actively
17844     * managed: remove them when they should not be displayed anymore. The
17845     * overlay will always have the same size as its host view.
17846     *
17847     * <p>Note: Overlays do not currently work correctly with {@link
17848     * SurfaceView} or {@link TextureView}; contents in overlays for these
17849     * types of views may not display correctly.</p>
17850     *
17851     * @return The ViewOverlay object for this view.
17852     * @see ViewOverlay
17853     */
17854    public ViewOverlay getOverlay() {
17855        if (mOverlay == null) {
17856            mOverlay = new ViewOverlay(mContext, this);
17857        }
17858        return mOverlay;
17859    }
17860
17861    /**
17862     * Override this if your view is known to always be drawn on top of a solid color background,
17863     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17864     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17865     * should be set to 0xFF.
17866     *
17867     * @see #setVerticalFadingEdgeEnabled(boolean)
17868     * @see #setHorizontalFadingEdgeEnabled(boolean)
17869     *
17870     * @return The known solid color background for this view, or 0 if the color may vary
17871     */
17872    @ViewDebug.ExportedProperty(category = "drawing")
17873    @ColorInt
17874    public int getSolidColor() {
17875        return 0;
17876    }
17877
17878    /**
17879     * Build a human readable string representation of the specified view flags.
17880     *
17881     * @param flags the view flags to convert to a string
17882     * @return a String representing the supplied flags
17883     */
17884    private static String printFlags(int flags) {
17885        String output = "";
17886        int numFlags = 0;
17887        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17888            output += "TAKES_FOCUS";
17889            numFlags++;
17890        }
17891
17892        switch (flags & VISIBILITY_MASK) {
17893        case INVISIBLE:
17894            if (numFlags > 0) {
17895                output += " ";
17896            }
17897            output += "INVISIBLE";
17898            // USELESS HERE numFlags++;
17899            break;
17900        case GONE:
17901            if (numFlags > 0) {
17902                output += " ";
17903            }
17904            output += "GONE";
17905            // USELESS HERE numFlags++;
17906            break;
17907        default:
17908            break;
17909        }
17910        return output;
17911    }
17912
17913    /**
17914     * Build a human readable string representation of the specified private
17915     * view flags.
17916     *
17917     * @param privateFlags the private view flags to convert to a string
17918     * @return a String representing the supplied flags
17919     */
17920    private static String printPrivateFlags(int privateFlags) {
17921        String output = "";
17922        int numFlags = 0;
17923
17924        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17925            output += "WANTS_FOCUS";
17926            numFlags++;
17927        }
17928
17929        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17930            if (numFlags > 0) {
17931                output += " ";
17932            }
17933            output += "FOCUSED";
17934            numFlags++;
17935        }
17936
17937        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17938            if (numFlags > 0) {
17939                output += " ";
17940            }
17941            output += "SELECTED";
17942            numFlags++;
17943        }
17944
17945        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17946            if (numFlags > 0) {
17947                output += " ";
17948            }
17949            output += "IS_ROOT_NAMESPACE";
17950            numFlags++;
17951        }
17952
17953        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17954            if (numFlags > 0) {
17955                output += " ";
17956            }
17957            output += "HAS_BOUNDS";
17958            numFlags++;
17959        }
17960
17961        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17962            if (numFlags > 0) {
17963                output += " ";
17964            }
17965            output += "DRAWN";
17966            // USELESS HERE numFlags++;
17967        }
17968        return output;
17969    }
17970
17971    /**
17972     * <p>Indicates whether or not this view's layout will be requested during
17973     * the next hierarchy layout pass.</p>
17974     *
17975     * @return true if the layout will be forced during next layout pass
17976     */
17977    public boolean isLayoutRequested() {
17978        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17979    }
17980
17981    /**
17982     * Return true if o is a ViewGroup that is laying out using optical bounds.
17983     * @hide
17984     */
17985    public static boolean isLayoutModeOptical(Object o) {
17986        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17987    }
17988
17989    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17990        Insets parentInsets = mParent instanceof View ?
17991                ((View) mParent).getOpticalInsets() : Insets.NONE;
17992        Insets childInsets = getOpticalInsets();
17993        return setFrame(
17994                left   + parentInsets.left - childInsets.left,
17995                top    + parentInsets.top  - childInsets.top,
17996                right  + parentInsets.left + childInsets.right,
17997                bottom + parentInsets.top  + childInsets.bottom);
17998    }
17999
18000    /**
18001     * Assign a size and position to a view and all of its
18002     * descendants
18003     *
18004     * <p>This is the second phase of the layout mechanism.
18005     * (The first is measuring). In this phase, each parent calls
18006     * layout on all of its children to position them.
18007     * This is typically done using the child measurements
18008     * that were stored in the measure pass().</p>
18009     *
18010     * <p>Derived classes should not override this method.
18011     * Derived classes with children should override
18012     * onLayout. In that method, they should
18013     * call layout on each of their children.</p>
18014     *
18015     * @param l Left position, relative to parent
18016     * @param t Top position, relative to parent
18017     * @param r Right position, relative to parent
18018     * @param b Bottom position, relative to parent
18019     */
18020    @SuppressWarnings({"unchecked"})
18021    public void layout(int l, int t, int r, int b) {
18022        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18023            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18024            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18025        }
18026
18027        int oldL = mLeft;
18028        int oldT = mTop;
18029        int oldB = mBottom;
18030        int oldR = mRight;
18031
18032        boolean changed = isLayoutModeOptical(mParent) ?
18033                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18034
18035        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18036            onLayout(changed, l, t, r, b);
18037
18038            if (shouldDrawRoundScrollbar()) {
18039                if(mRoundScrollbarRenderer == null) {
18040                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18041                }
18042            } else {
18043                mRoundScrollbarRenderer = null;
18044            }
18045
18046            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18047
18048            ListenerInfo li = mListenerInfo;
18049            if (li != null && li.mOnLayoutChangeListeners != null) {
18050                ArrayList<OnLayoutChangeListener> listenersCopy =
18051                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18052                int numListeners = listenersCopy.size();
18053                for (int i = 0; i < numListeners; ++i) {
18054                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18055                }
18056            }
18057        }
18058
18059        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18060        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18061    }
18062
18063    /**
18064     * Called from layout when this view should
18065     * assign a size and position to each of its children.
18066     *
18067     * Derived classes with children should override
18068     * this method and call layout on each of
18069     * their children.
18070     * @param changed This is a new size or position for this view
18071     * @param left Left position, relative to parent
18072     * @param top Top position, relative to parent
18073     * @param right Right position, relative to parent
18074     * @param bottom Bottom position, relative to parent
18075     */
18076    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18077    }
18078
18079    /**
18080     * Assign a size and position to this view.
18081     *
18082     * This is called from layout.
18083     *
18084     * @param left Left position, relative to parent
18085     * @param top Top position, relative to parent
18086     * @param right Right position, relative to parent
18087     * @param bottom Bottom position, relative to parent
18088     * @return true if the new size and position are different than the
18089     *         previous ones
18090     * {@hide}
18091     */
18092    protected boolean setFrame(int left, int top, int right, int bottom) {
18093        boolean changed = false;
18094
18095        if (DBG) {
18096            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18097                    + right + "," + bottom + ")");
18098        }
18099
18100        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18101            changed = true;
18102
18103            // Remember our drawn bit
18104            int drawn = mPrivateFlags & PFLAG_DRAWN;
18105
18106            int oldWidth = mRight - mLeft;
18107            int oldHeight = mBottom - mTop;
18108            int newWidth = right - left;
18109            int newHeight = bottom - top;
18110            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18111
18112            // Invalidate our old position
18113            invalidate(sizeChanged);
18114
18115            mLeft = left;
18116            mTop = top;
18117            mRight = right;
18118            mBottom = bottom;
18119            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18120
18121            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18122
18123
18124            if (sizeChanged) {
18125                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18126            }
18127
18128            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18129                // If we are visible, force the DRAWN bit to on so that
18130                // this invalidate will go through (at least to our parent).
18131                // This is because someone may have invalidated this view
18132                // before this call to setFrame came in, thereby clearing
18133                // the DRAWN bit.
18134                mPrivateFlags |= PFLAG_DRAWN;
18135                invalidate(sizeChanged);
18136                // parent display list may need to be recreated based on a change in the bounds
18137                // of any child
18138                invalidateParentCaches();
18139            }
18140
18141            // Reset drawn bit to original value (invalidate turns it off)
18142            mPrivateFlags |= drawn;
18143
18144            mBackgroundSizeChanged = true;
18145            if (mForegroundInfo != null) {
18146                mForegroundInfo.mBoundsChanged = true;
18147            }
18148
18149            notifySubtreeAccessibilityStateChangedIfNeeded();
18150        }
18151        return changed;
18152    }
18153
18154    /**
18155     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18156     * @hide
18157     */
18158    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18159        setFrame(left, top, right, bottom);
18160    }
18161
18162    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18163        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18164        if (mOverlay != null) {
18165            mOverlay.getOverlayView().setRight(newWidth);
18166            mOverlay.getOverlayView().setBottom(newHeight);
18167        }
18168        rebuildOutline();
18169    }
18170
18171    /**
18172     * Finalize inflating a view from XML.  This is called as the last phase
18173     * of inflation, after all child views have been added.
18174     *
18175     * <p>Even if the subclass overrides onFinishInflate, they should always be
18176     * sure to call the super method, so that we get called.
18177     */
18178    @CallSuper
18179    protected void onFinishInflate() {
18180    }
18181
18182    /**
18183     * Returns the resources associated with this view.
18184     *
18185     * @return Resources object.
18186     */
18187    public Resources getResources() {
18188        return mResources;
18189    }
18190
18191    /**
18192     * Invalidates the specified Drawable.
18193     *
18194     * @param drawable the drawable to invalidate
18195     */
18196    @Override
18197    public void invalidateDrawable(@NonNull Drawable drawable) {
18198        if (verifyDrawable(drawable)) {
18199            final Rect dirty = drawable.getDirtyBounds();
18200            final int scrollX = mScrollX;
18201            final int scrollY = mScrollY;
18202
18203            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18204                    dirty.right + scrollX, dirty.bottom + scrollY);
18205            rebuildOutline();
18206        }
18207    }
18208
18209    /**
18210     * Schedules an action on a drawable to occur at a specified time.
18211     *
18212     * @param who the recipient of the action
18213     * @param what the action to run on the drawable
18214     * @param when the time at which the action must occur. Uses the
18215     *        {@link SystemClock#uptimeMillis} timebase.
18216     */
18217    @Override
18218    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18219        if (verifyDrawable(who) && what != null) {
18220            final long delay = when - SystemClock.uptimeMillis();
18221            if (mAttachInfo != null) {
18222                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18223                        Choreographer.CALLBACK_ANIMATION, what, who,
18224                        Choreographer.subtractFrameDelay(delay));
18225            } else {
18226                // Postpone the runnable until we know
18227                // on which thread it needs to run.
18228                getRunQueue().postDelayed(what, delay);
18229            }
18230        }
18231    }
18232
18233    /**
18234     * Cancels a scheduled action on a drawable.
18235     *
18236     * @param who the recipient of the action
18237     * @param what the action to cancel
18238     */
18239    @Override
18240    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18241        if (verifyDrawable(who) && what != null) {
18242            if (mAttachInfo != null) {
18243                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18244                        Choreographer.CALLBACK_ANIMATION, what, who);
18245            }
18246            getRunQueue().removeCallbacks(what);
18247        }
18248    }
18249
18250    /**
18251     * Unschedule any events associated with the given Drawable.  This can be
18252     * used when selecting a new Drawable into a view, so that the previous
18253     * one is completely unscheduled.
18254     *
18255     * @param who The Drawable to unschedule.
18256     *
18257     * @see #drawableStateChanged
18258     */
18259    public void unscheduleDrawable(Drawable who) {
18260        if (mAttachInfo != null && who != null) {
18261            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18262                    Choreographer.CALLBACK_ANIMATION, null, who);
18263        }
18264    }
18265
18266    /**
18267     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18268     * that the View directionality can and will be resolved before its Drawables.
18269     *
18270     * Will call {@link View#onResolveDrawables} when resolution is done.
18271     *
18272     * @hide
18273     */
18274    protected void resolveDrawables() {
18275        // Drawables resolution may need to happen before resolving the layout direction (which is
18276        // done only during the measure() call).
18277        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18278        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18279        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18280        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18281        // direction to be resolved as its resolved value will be the same as its raw value.
18282        if (!isLayoutDirectionResolved() &&
18283                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18284            return;
18285        }
18286
18287        final int layoutDirection = isLayoutDirectionResolved() ?
18288                getLayoutDirection() : getRawLayoutDirection();
18289
18290        if (mBackground != null) {
18291            mBackground.setLayoutDirection(layoutDirection);
18292        }
18293        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18294            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18295        }
18296        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18297        onResolveDrawables(layoutDirection);
18298    }
18299
18300    boolean areDrawablesResolved() {
18301        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18302    }
18303
18304    /**
18305     * Called when layout direction has been resolved.
18306     *
18307     * The default implementation does nothing.
18308     *
18309     * @param layoutDirection The resolved layout direction.
18310     *
18311     * @see #LAYOUT_DIRECTION_LTR
18312     * @see #LAYOUT_DIRECTION_RTL
18313     *
18314     * @hide
18315     */
18316    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18317    }
18318
18319    /**
18320     * @hide
18321     */
18322    protected void resetResolvedDrawables() {
18323        resetResolvedDrawablesInternal();
18324    }
18325
18326    void resetResolvedDrawablesInternal() {
18327        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18328    }
18329
18330    /**
18331     * If your view subclass is displaying its own Drawable objects, it should
18332     * override this function and return true for any Drawable it is
18333     * displaying.  This allows animations for those drawables to be
18334     * scheduled.
18335     *
18336     * <p>Be sure to call through to the super class when overriding this
18337     * function.
18338     *
18339     * @param who The Drawable to verify.  Return true if it is one you are
18340     *            displaying, else return the result of calling through to the
18341     *            super class.
18342     *
18343     * @return boolean If true than the Drawable is being displayed in the
18344     *         view; else false and it is not allowed to animate.
18345     *
18346     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18347     * @see #drawableStateChanged()
18348     */
18349    @CallSuper
18350    protected boolean verifyDrawable(@NonNull Drawable who) {
18351        // Avoid verifying the scroll bar drawable so that we don't end up in
18352        // an invalidation loop. This effectively prevents the scroll bar
18353        // drawable from triggering invalidations and scheduling runnables.
18354        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18355    }
18356
18357    /**
18358     * This function is called whenever the state of the view changes in such
18359     * a way that it impacts the state of drawables being shown.
18360     * <p>
18361     * If the View has a StateListAnimator, it will also be called to run necessary state
18362     * change animations.
18363     * <p>
18364     * Be sure to call through to the superclass when overriding this function.
18365     *
18366     * @see Drawable#setState(int[])
18367     */
18368    @CallSuper
18369    protected void drawableStateChanged() {
18370        final int[] state = getDrawableState();
18371        boolean changed = false;
18372
18373        final Drawable bg = mBackground;
18374        if (bg != null && bg.isStateful()) {
18375            changed |= bg.setState(state);
18376        }
18377
18378        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18379        if (fg != null && fg.isStateful()) {
18380            changed |= fg.setState(state);
18381        }
18382
18383        if (mScrollCache != null) {
18384            final Drawable scrollBar = mScrollCache.scrollBar;
18385            if (scrollBar != null && scrollBar.isStateful()) {
18386                changed |= scrollBar.setState(state)
18387                        && mScrollCache.state != ScrollabilityCache.OFF;
18388            }
18389        }
18390
18391        if (mStateListAnimator != null) {
18392            mStateListAnimator.setState(state);
18393        }
18394
18395        if (changed) {
18396            invalidate();
18397        }
18398    }
18399
18400    /**
18401     * This function is called whenever the view hotspot changes and needs to
18402     * be propagated to drawables or child views managed by the view.
18403     * <p>
18404     * Dispatching to child views is handled by
18405     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18406     * <p>
18407     * Be sure to call through to the superclass when overriding this function.
18408     *
18409     * @param x hotspot x coordinate
18410     * @param y hotspot y coordinate
18411     */
18412    @CallSuper
18413    public void drawableHotspotChanged(float x, float y) {
18414        if (mBackground != null) {
18415            mBackground.setHotspot(x, y);
18416        }
18417        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18418            mForegroundInfo.mDrawable.setHotspot(x, y);
18419        }
18420
18421        dispatchDrawableHotspotChanged(x, y);
18422    }
18423
18424    /**
18425     * Dispatches drawableHotspotChanged to all of this View's children.
18426     *
18427     * @param x hotspot x coordinate
18428     * @param y hotspot y coordinate
18429     * @see #drawableHotspotChanged(float, float)
18430     */
18431    public void dispatchDrawableHotspotChanged(float x, float y) {
18432    }
18433
18434    /**
18435     * Call this to force a view to update its drawable state. This will cause
18436     * drawableStateChanged to be called on this view. Views that are interested
18437     * in the new state should call getDrawableState.
18438     *
18439     * @see #drawableStateChanged
18440     * @see #getDrawableState
18441     */
18442    public void refreshDrawableState() {
18443        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18444        drawableStateChanged();
18445
18446        ViewParent parent = mParent;
18447        if (parent != null) {
18448            parent.childDrawableStateChanged(this);
18449        }
18450    }
18451
18452    /**
18453     * Return an array of resource IDs of the drawable states representing the
18454     * current state of the view.
18455     *
18456     * @return The current drawable state
18457     *
18458     * @see Drawable#setState(int[])
18459     * @see #drawableStateChanged()
18460     * @see #onCreateDrawableState(int)
18461     */
18462    public final int[] getDrawableState() {
18463        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18464            return mDrawableState;
18465        } else {
18466            mDrawableState = onCreateDrawableState(0);
18467            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18468            return mDrawableState;
18469        }
18470    }
18471
18472    /**
18473     * Generate the new {@link android.graphics.drawable.Drawable} state for
18474     * this view. This is called by the view
18475     * system when the cached Drawable state is determined to be invalid.  To
18476     * retrieve the current state, you should use {@link #getDrawableState}.
18477     *
18478     * @param extraSpace if non-zero, this is the number of extra entries you
18479     * would like in the returned array in which you can place your own
18480     * states.
18481     *
18482     * @return Returns an array holding the current {@link Drawable} state of
18483     * the view.
18484     *
18485     * @see #mergeDrawableStates(int[], int[])
18486     */
18487    protected int[] onCreateDrawableState(int extraSpace) {
18488        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18489                mParent instanceof View) {
18490            return ((View) mParent).onCreateDrawableState(extraSpace);
18491        }
18492
18493        int[] drawableState;
18494
18495        int privateFlags = mPrivateFlags;
18496
18497        int viewStateIndex = 0;
18498        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18499        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18500        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18501        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18502        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18503        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18504        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18505                ThreadedRenderer.isAvailable()) {
18506            // This is set if HW acceleration is requested, even if the current
18507            // process doesn't allow it.  This is just to allow app preview
18508            // windows to better match their app.
18509            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18510        }
18511        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18512
18513        final int privateFlags2 = mPrivateFlags2;
18514        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18515            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18516        }
18517        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18518            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18519        }
18520
18521        drawableState = StateSet.get(viewStateIndex);
18522
18523        //noinspection ConstantIfStatement
18524        if (false) {
18525            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18526            Log.i("View", toString()
18527                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18528                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18529                    + " fo=" + hasFocus()
18530                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18531                    + " wf=" + hasWindowFocus()
18532                    + ": " + Arrays.toString(drawableState));
18533        }
18534
18535        if (extraSpace == 0) {
18536            return drawableState;
18537        }
18538
18539        final int[] fullState;
18540        if (drawableState != null) {
18541            fullState = new int[drawableState.length + extraSpace];
18542            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18543        } else {
18544            fullState = new int[extraSpace];
18545        }
18546
18547        return fullState;
18548    }
18549
18550    /**
18551     * Merge your own state values in <var>additionalState</var> into the base
18552     * state values <var>baseState</var> that were returned by
18553     * {@link #onCreateDrawableState(int)}.
18554     *
18555     * @param baseState The base state values returned by
18556     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18557     * own additional state values.
18558     *
18559     * @param additionalState The additional state values you would like
18560     * added to <var>baseState</var>; this array is not modified.
18561     *
18562     * @return As a convenience, the <var>baseState</var> array you originally
18563     * passed into the function is returned.
18564     *
18565     * @see #onCreateDrawableState(int)
18566     */
18567    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18568        final int N = baseState.length;
18569        int i = N - 1;
18570        while (i >= 0 && baseState[i] == 0) {
18571            i--;
18572        }
18573        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18574        return baseState;
18575    }
18576
18577    /**
18578     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18579     * on all Drawable objects associated with this view.
18580     * <p>
18581     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18582     * attached to this view.
18583     */
18584    @CallSuper
18585    public void jumpDrawablesToCurrentState() {
18586        if (mBackground != null) {
18587            mBackground.jumpToCurrentState();
18588        }
18589        if (mStateListAnimator != null) {
18590            mStateListAnimator.jumpToCurrentState();
18591        }
18592        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18593            mForegroundInfo.mDrawable.jumpToCurrentState();
18594        }
18595    }
18596
18597    /**
18598     * Sets the background color for this view.
18599     * @param color the color of the background
18600     */
18601    @RemotableViewMethod
18602    public void setBackgroundColor(@ColorInt int color) {
18603        if (mBackground instanceof ColorDrawable) {
18604            ((ColorDrawable) mBackground.mutate()).setColor(color);
18605            computeOpaqueFlags();
18606            mBackgroundResource = 0;
18607        } else {
18608            setBackground(new ColorDrawable(color));
18609        }
18610    }
18611
18612    /**
18613     * Set the background to a given resource. The resource should refer to
18614     * a Drawable object or 0 to remove the background.
18615     * @param resid The identifier of the resource.
18616     *
18617     * @attr ref android.R.styleable#View_background
18618     */
18619    @RemotableViewMethod
18620    public void setBackgroundResource(@DrawableRes int resid) {
18621        if (resid != 0 && resid == mBackgroundResource) {
18622            return;
18623        }
18624
18625        Drawable d = null;
18626        if (resid != 0) {
18627            d = mContext.getDrawable(resid);
18628        }
18629        setBackground(d);
18630
18631        mBackgroundResource = resid;
18632    }
18633
18634    /**
18635     * Set the background to a given Drawable, or remove the background. If the
18636     * background has padding, this View's padding is set to the background's
18637     * padding. However, when a background is removed, this View's padding isn't
18638     * touched. If setting the padding is desired, please use
18639     * {@link #setPadding(int, int, int, int)}.
18640     *
18641     * @param background The Drawable to use as the background, or null to remove the
18642     *        background
18643     */
18644    public void setBackground(Drawable background) {
18645        //noinspection deprecation
18646        setBackgroundDrawable(background);
18647    }
18648
18649    /**
18650     * @deprecated use {@link #setBackground(Drawable)} instead
18651     */
18652    @Deprecated
18653    public void setBackgroundDrawable(Drawable background) {
18654        computeOpaqueFlags();
18655
18656        if (background == mBackground) {
18657            return;
18658        }
18659
18660        boolean requestLayout = false;
18661
18662        mBackgroundResource = 0;
18663
18664        /*
18665         * Regardless of whether we're setting a new background or not, we want
18666         * to clear the previous drawable. setVisible first while we still have the callback set.
18667         */
18668        if (mBackground != null) {
18669            if (isAttachedToWindow()) {
18670                mBackground.setVisible(false, false);
18671            }
18672            mBackground.setCallback(null);
18673            unscheduleDrawable(mBackground);
18674        }
18675
18676        if (background != null) {
18677            Rect padding = sThreadLocal.get();
18678            if (padding == null) {
18679                padding = new Rect();
18680                sThreadLocal.set(padding);
18681            }
18682            resetResolvedDrawablesInternal();
18683            background.setLayoutDirection(getLayoutDirection());
18684            if (background.getPadding(padding)) {
18685                resetResolvedPaddingInternal();
18686                switch (background.getLayoutDirection()) {
18687                    case LAYOUT_DIRECTION_RTL:
18688                        mUserPaddingLeftInitial = padding.right;
18689                        mUserPaddingRightInitial = padding.left;
18690                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18691                        break;
18692                    case LAYOUT_DIRECTION_LTR:
18693                    default:
18694                        mUserPaddingLeftInitial = padding.left;
18695                        mUserPaddingRightInitial = padding.right;
18696                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18697                }
18698                mLeftPaddingDefined = false;
18699                mRightPaddingDefined = false;
18700            }
18701
18702            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18703            // if it has a different minimum size, we should layout again
18704            if (mBackground == null
18705                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18706                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18707                requestLayout = true;
18708            }
18709
18710            // Set mBackground before we set this as the callback and start making other
18711            // background drawable state change calls. In particular, the setVisible call below
18712            // can result in drawables attempting to start animations or otherwise invalidate,
18713            // which requires the view set as the callback (us) to recognize the drawable as
18714            // belonging to it as per verifyDrawable.
18715            mBackground = background;
18716            if (background.isStateful()) {
18717                background.setState(getDrawableState());
18718            }
18719            if (isAttachedToWindow()) {
18720                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18721            }
18722
18723            applyBackgroundTint();
18724
18725            // Set callback last, since the view may still be initializing.
18726            background.setCallback(this);
18727
18728            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18729                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18730                requestLayout = true;
18731            }
18732        } else {
18733            /* Remove the background */
18734            mBackground = null;
18735            if ((mViewFlags & WILL_NOT_DRAW) != 0
18736                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18737                mPrivateFlags |= PFLAG_SKIP_DRAW;
18738            }
18739
18740            /*
18741             * When the background is set, we try to apply its padding to this
18742             * View. When the background is removed, we don't touch this View's
18743             * padding. This is noted in the Javadocs. Hence, we don't need to
18744             * requestLayout(), the invalidate() below is sufficient.
18745             */
18746
18747            // The old background's minimum size could have affected this
18748            // View's layout, so let's requestLayout
18749            requestLayout = true;
18750        }
18751
18752        computeOpaqueFlags();
18753
18754        if (requestLayout) {
18755            requestLayout();
18756        }
18757
18758        mBackgroundSizeChanged = true;
18759        invalidate(true);
18760        invalidateOutline();
18761    }
18762
18763    /**
18764     * Gets the background drawable
18765     *
18766     * @return The drawable used as the background for this view, if any.
18767     *
18768     * @see #setBackground(Drawable)
18769     *
18770     * @attr ref android.R.styleable#View_background
18771     */
18772    public Drawable getBackground() {
18773        return mBackground;
18774    }
18775
18776    /**
18777     * Applies a tint to the background drawable. Does not modify the current tint
18778     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18779     * <p>
18780     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18781     * mutate the drawable and apply the specified tint and tint mode using
18782     * {@link Drawable#setTintList(ColorStateList)}.
18783     *
18784     * @param tint the tint to apply, may be {@code null} to clear tint
18785     *
18786     * @attr ref android.R.styleable#View_backgroundTint
18787     * @see #getBackgroundTintList()
18788     * @see Drawable#setTintList(ColorStateList)
18789     */
18790    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18791        if (mBackgroundTint == null) {
18792            mBackgroundTint = new TintInfo();
18793        }
18794        mBackgroundTint.mTintList = tint;
18795        mBackgroundTint.mHasTintList = true;
18796
18797        applyBackgroundTint();
18798    }
18799
18800    /**
18801     * Return the tint applied to the background drawable, if specified.
18802     *
18803     * @return the tint applied to the background drawable
18804     * @attr ref android.R.styleable#View_backgroundTint
18805     * @see #setBackgroundTintList(ColorStateList)
18806     */
18807    @Nullable
18808    public ColorStateList getBackgroundTintList() {
18809        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18810    }
18811
18812    /**
18813     * Specifies the blending mode used to apply the tint specified by
18814     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18815     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18816     *
18817     * @param tintMode the blending mode used to apply the tint, may be
18818     *                 {@code null} to clear tint
18819     * @attr ref android.R.styleable#View_backgroundTintMode
18820     * @see #getBackgroundTintMode()
18821     * @see Drawable#setTintMode(PorterDuff.Mode)
18822     */
18823    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18824        if (mBackgroundTint == null) {
18825            mBackgroundTint = new TintInfo();
18826        }
18827        mBackgroundTint.mTintMode = tintMode;
18828        mBackgroundTint.mHasTintMode = true;
18829
18830        applyBackgroundTint();
18831    }
18832
18833    /**
18834     * Return the blending mode used to apply the tint to the background
18835     * drawable, if specified.
18836     *
18837     * @return the blending mode used to apply the tint to the background
18838     *         drawable
18839     * @attr ref android.R.styleable#View_backgroundTintMode
18840     * @see #setBackgroundTintMode(PorterDuff.Mode)
18841     */
18842    @Nullable
18843    public PorterDuff.Mode getBackgroundTintMode() {
18844        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18845    }
18846
18847    private void applyBackgroundTint() {
18848        if (mBackground != null && mBackgroundTint != null) {
18849            final TintInfo tintInfo = mBackgroundTint;
18850            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18851                mBackground = mBackground.mutate();
18852
18853                if (tintInfo.mHasTintList) {
18854                    mBackground.setTintList(tintInfo.mTintList);
18855                }
18856
18857                if (tintInfo.mHasTintMode) {
18858                    mBackground.setTintMode(tintInfo.mTintMode);
18859                }
18860
18861                // The drawable (or one of its children) may not have been
18862                // stateful before applying the tint, so let's try again.
18863                if (mBackground.isStateful()) {
18864                    mBackground.setState(getDrawableState());
18865                }
18866            }
18867        }
18868    }
18869
18870    /**
18871     * Returns the drawable used as the foreground of this View. The
18872     * foreground drawable, if non-null, is always drawn on top of the view's content.
18873     *
18874     * @return a Drawable or null if no foreground was set
18875     *
18876     * @see #onDrawForeground(Canvas)
18877     */
18878    public Drawable getForeground() {
18879        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18880    }
18881
18882    /**
18883     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18884     *
18885     * @param foreground the Drawable to be drawn on top of the children
18886     *
18887     * @attr ref android.R.styleable#View_foreground
18888     */
18889    public void setForeground(Drawable foreground) {
18890        if (mForegroundInfo == null) {
18891            if (foreground == null) {
18892                // Nothing to do.
18893                return;
18894            }
18895            mForegroundInfo = new ForegroundInfo();
18896        }
18897
18898        if (foreground == mForegroundInfo.mDrawable) {
18899            // Nothing to do
18900            return;
18901        }
18902
18903        if (mForegroundInfo.mDrawable != null) {
18904            if (isAttachedToWindow()) {
18905                mForegroundInfo.mDrawable.setVisible(false, false);
18906            }
18907            mForegroundInfo.mDrawable.setCallback(null);
18908            unscheduleDrawable(mForegroundInfo.mDrawable);
18909        }
18910
18911        mForegroundInfo.mDrawable = foreground;
18912        mForegroundInfo.mBoundsChanged = true;
18913        if (foreground != null) {
18914            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18915                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18916            }
18917            foreground.setLayoutDirection(getLayoutDirection());
18918            if (foreground.isStateful()) {
18919                foreground.setState(getDrawableState());
18920            }
18921            applyForegroundTint();
18922            if (isAttachedToWindow()) {
18923                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18924            }
18925            // Set callback last, since the view may still be initializing.
18926            foreground.setCallback(this);
18927        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18928            mPrivateFlags |= PFLAG_SKIP_DRAW;
18929        }
18930        requestLayout();
18931        invalidate();
18932    }
18933
18934    /**
18935     * Magic bit used to support features of framework-internal window decor implementation details.
18936     * This used to live exclusively in FrameLayout.
18937     *
18938     * @return true if the foreground should draw inside the padding region or false
18939     *         if it should draw inset by the view's padding
18940     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18941     */
18942    public boolean isForegroundInsidePadding() {
18943        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18944    }
18945
18946    /**
18947     * Describes how the foreground is positioned.
18948     *
18949     * @return foreground gravity.
18950     *
18951     * @see #setForegroundGravity(int)
18952     *
18953     * @attr ref android.R.styleable#View_foregroundGravity
18954     */
18955    public int getForegroundGravity() {
18956        return mForegroundInfo != null ? mForegroundInfo.mGravity
18957                : Gravity.START | Gravity.TOP;
18958    }
18959
18960    /**
18961     * Describes how the foreground is positioned. Defaults to START and TOP.
18962     *
18963     * @param gravity see {@link android.view.Gravity}
18964     *
18965     * @see #getForegroundGravity()
18966     *
18967     * @attr ref android.R.styleable#View_foregroundGravity
18968     */
18969    public void setForegroundGravity(int gravity) {
18970        if (mForegroundInfo == null) {
18971            mForegroundInfo = new ForegroundInfo();
18972        }
18973
18974        if (mForegroundInfo.mGravity != gravity) {
18975            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18976                gravity |= Gravity.START;
18977            }
18978
18979            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18980                gravity |= Gravity.TOP;
18981            }
18982
18983            mForegroundInfo.mGravity = gravity;
18984            requestLayout();
18985        }
18986    }
18987
18988    /**
18989     * Applies a tint to the foreground drawable. Does not modify the current tint
18990     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18991     * <p>
18992     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18993     * mutate the drawable and apply the specified tint and tint mode using
18994     * {@link Drawable#setTintList(ColorStateList)}.
18995     *
18996     * @param tint the tint to apply, may be {@code null} to clear tint
18997     *
18998     * @attr ref android.R.styleable#View_foregroundTint
18999     * @see #getForegroundTintList()
19000     * @see Drawable#setTintList(ColorStateList)
19001     */
19002    public void setForegroundTintList(@Nullable ColorStateList tint) {
19003        if (mForegroundInfo == null) {
19004            mForegroundInfo = new ForegroundInfo();
19005        }
19006        if (mForegroundInfo.mTintInfo == null) {
19007            mForegroundInfo.mTintInfo = new TintInfo();
19008        }
19009        mForegroundInfo.mTintInfo.mTintList = tint;
19010        mForegroundInfo.mTintInfo.mHasTintList = true;
19011
19012        applyForegroundTint();
19013    }
19014
19015    /**
19016     * Return the tint applied to the foreground drawable, if specified.
19017     *
19018     * @return the tint applied to the foreground drawable
19019     * @attr ref android.R.styleable#View_foregroundTint
19020     * @see #setForegroundTintList(ColorStateList)
19021     */
19022    @Nullable
19023    public ColorStateList getForegroundTintList() {
19024        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19025                ? mForegroundInfo.mTintInfo.mTintList : null;
19026    }
19027
19028    /**
19029     * Specifies the blending mode used to apply the tint specified by
19030     * {@link #setForegroundTintList(ColorStateList)}} to the background
19031     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19032     *
19033     * @param tintMode the blending mode used to apply the tint, may be
19034     *                 {@code null} to clear tint
19035     * @attr ref android.R.styleable#View_foregroundTintMode
19036     * @see #getForegroundTintMode()
19037     * @see Drawable#setTintMode(PorterDuff.Mode)
19038     */
19039    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19040        if (mForegroundInfo == null) {
19041            mForegroundInfo = new ForegroundInfo();
19042        }
19043        if (mForegroundInfo.mTintInfo == null) {
19044            mForegroundInfo.mTintInfo = new TintInfo();
19045        }
19046        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19047        mForegroundInfo.mTintInfo.mHasTintMode = true;
19048
19049        applyForegroundTint();
19050    }
19051
19052    /**
19053     * Return the blending mode used to apply the tint to the foreground
19054     * drawable, if specified.
19055     *
19056     * @return the blending mode used to apply the tint to the foreground
19057     *         drawable
19058     * @attr ref android.R.styleable#View_foregroundTintMode
19059     * @see #setForegroundTintMode(PorterDuff.Mode)
19060     */
19061    @Nullable
19062    public PorterDuff.Mode getForegroundTintMode() {
19063        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19064                ? mForegroundInfo.mTintInfo.mTintMode : null;
19065    }
19066
19067    private void applyForegroundTint() {
19068        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19069                && mForegroundInfo.mTintInfo != null) {
19070            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19071            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19072                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19073
19074                if (tintInfo.mHasTintList) {
19075                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19076                }
19077
19078                if (tintInfo.mHasTintMode) {
19079                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19080                }
19081
19082                // The drawable (or one of its children) may not have been
19083                // stateful before applying the tint, so let's try again.
19084                if (mForegroundInfo.mDrawable.isStateful()) {
19085                    mForegroundInfo.mDrawable.setState(getDrawableState());
19086                }
19087            }
19088        }
19089    }
19090
19091    /**
19092     * Draw any foreground content for this view.
19093     *
19094     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19095     * drawable or other view-specific decorations. The foreground is drawn on top of the
19096     * primary view content.</p>
19097     *
19098     * @param canvas canvas to draw into
19099     */
19100    public void onDrawForeground(Canvas canvas) {
19101        onDrawScrollIndicators(canvas);
19102        onDrawScrollBars(canvas);
19103
19104        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19105        if (foreground != null) {
19106            if (mForegroundInfo.mBoundsChanged) {
19107                mForegroundInfo.mBoundsChanged = false;
19108                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19109                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19110
19111                if (mForegroundInfo.mInsidePadding) {
19112                    selfBounds.set(0, 0, getWidth(), getHeight());
19113                } else {
19114                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19115                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19116                }
19117
19118                final int ld = getLayoutDirection();
19119                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19120                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19121                foreground.setBounds(overlayBounds);
19122            }
19123
19124            foreground.draw(canvas);
19125        }
19126    }
19127
19128    /**
19129     * Sets the padding. The view may add on the space required to display
19130     * the scrollbars, depending on the style and visibility of the scrollbars.
19131     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19132     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19133     * from the values set in this call.
19134     *
19135     * @attr ref android.R.styleable#View_padding
19136     * @attr ref android.R.styleable#View_paddingBottom
19137     * @attr ref android.R.styleable#View_paddingLeft
19138     * @attr ref android.R.styleable#View_paddingRight
19139     * @attr ref android.R.styleable#View_paddingTop
19140     * @param left the left padding in pixels
19141     * @param top the top padding in pixels
19142     * @param right the right padding in pixels
19143     * @param bottom the bottom padding in pixels
19144     */
19145    public void setPadding(int left, int top, int right, int bottom) {
19146        resetResolvedPaddingInternal();
19147
19148        mUserPaddingStart = UNDEFINED_PADDING;
19149        mUserPaddingEnd = UNDEFINED_PADDING;
19150
19151        mUserPaddingLeftInitial = left;
19152        mUserPaddingRightInitial = right;
19153
19154        mLeftPaddingDefined = true;
19155        mRightPaddingDefined = true;
19156
19157        internalSetPadding(left, top, right, bottom);
19158    }
19159
19160    /**
19161     * @hide
19162     */
19163    protected void internalSetPadding(int left, int top, int right, int bottom) {
19164        mUserPaddingLeft = left;
19165        mUserPaddingRight = right;
19166        mUserPaddingBottom = bottom;
19167
19168        final int viewFlags = mViewFlags;
19169        boolean changed = false;
19170
19171        // Common case is there are no scroll bars.
19172        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19173            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19174                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19175                        ? 0 : getVerticalScrollbarWidth();
19176                switch (mVerticalScrollbarPosition) {
19177                    case SCROLLBAR_POSITION_DEFAULT:
19178                        if (isLayoutRtl()) {
19179                            left += offset;
19180                        } else {
19181                            right += offset;
19182                        }
19183                        break;
19184                    case SCROLLBAR_POSITION_RIGHT:
19185                        right += offset;
19186                        break;
19187                    case SCROLLBAR_POSITION_LEFT:
19188                        left += offset;
19189                        break;
19190                }
19191            }
19192            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19193                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19194                        ? 0 : getHorizontalScrollbarHeight();
19195            }
19196        }
19197
19198        if (mPaddingLeft != left) {
19199            changed = true;
19200            mPaddingLeft = left;
19201        }
19202        if (mPaddingTop != top) {
19203            changed = true;
19204            mPaddingTop = top;
19205        }
19206        if (mPaddingRight != right) {
19207            changed = true;
19208            mPaddingRight = right;
19209        }
19210        if (mPaddingBottom != bottom) {
19211            changed = true;
19212            mPaddingBottom = bottom;
19213        }
19214
19215        if (changed) {
19216            requestLayout();
19217            invalidateOutline();
19218        }
19219    }
19220
19221    /**
19222     * Sets the relative padding. The view may add on the space required to display
19223     * the scrollbars, depending on the style and visibility of the scrollbars.
19224     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19225     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19226     * from the values set in this call.
19227     *
19228     * @attr ref android.R.styleable#View_padding
19229     * @attr ref android.R.styleable#View_paddingBottom
19230     * @attr ref android.R.styleable#View_paddingStart
19231     * @attr ref android.R.styleable#View_paddingEnd
19232     * @attr ref android.R.styleable#View_paddingTop
19233     * @param start the start padding in pixels
19234     * @param top the top padding in pixels
19235     * @param end the end padding in pixels
19236     * @param bottom the bottom padding in pixels
19237     */
19238    public void setPaddingRelative(int start, int top, int end, int bottom) {
19239        resetResolvedPaddingInternal();
19240
19241        mUserPaddingStart = start;
19242        mUserPaddingEnd = end;
19243        mLeftPaddingDefined = true;
19244        mRightPaddingDefined = true;
19245
19246        switch(getLayoutDirection()) {
19247            case LAYOUT_DIRECTION_RTL:
19248                mUserPaddingLeftInitial = end;
19249                mUserPaddingRightInitial = start;
19250                internalSetPadding(end, top, start, bottom);
19251                break;
19252            case LAYOUT_DIRECTION_LTR:
19253            default:
19254                mUserPaddingLeftInitial = start;
19255                mUserPaddingRightInitial = end;
19256                internalSetPadding(start, top, end, bottom);
19257        }
19258    }
19259
19260    /**
19261     * Returns the top padding of this view.
19262     *
19263     * @return the top padding in pixels
19264     */
19265    public int getPaddingTop() {
19266        return mPaddingTop;
19267    }
19268
19269    /**
19270     * Returns the bottom padding of this view. If there are inset and enabled
19271     * scrollbars, this value may include the space required to display the
19272     * scrollbars as well.
19273     *
19274     * @return the bottom padding in pixels
19275     */
19276    public int getPaddingBottom() {
19277        return mPaddingBottom;
19278    }
19279
19280    /**
19281     * Returns the left padding of this view. If there are inset and enabled
19282     * scrollbars, this value may include the space required to display the
19283     * scrollbars as well.
19284     *
19285     * @return the left padding in pixels
19286     */
19287    public int getPaddingLeft() {
19288        if (!isPaddingResolved()) {
19289            resolvePadding();
19290        }
19291        return mPaddingLeft;
19292    }
19293
19294    /**
19295     * Returns the start padding of this view depending on its resolved layout direction.
19296     * If there are inset and enabled scrollbars, this value may include the space
19297     * required to display the scrollbars as well.
19298     *
19299     * @return the start padding in pixels
19300     */
19301    public int getPaddingStart() {
19302        if (!isPaddingResolved()) {
19303            resolvePadding();
19304        }
19305        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19306                mPaddingRight : mPaddingLeft;
19307    }
19308
19309    /**
19310     * Returns the right padding of this view. If there are inset and enabled
19311     * scrollbars, this value may include the space required to display the
19312     * scrollbars as well.
19313     *
19314     * @return the right padding in pixels
19315     */
19316    public int getPaddingRight() {
19317        if (!isPaddingResolved()) {
19318            resolvePadding();
19319        }
19320        return mPaddingRight;
19321    }
19322
19323    /**
19324     * Returns the end padding of this view depending on its resolved layout direction.
19325     * If there are inset and enabled scrollbars, this value may include the space
19326     * required to display the scrollbars as well.
19327     *
19328     * @return the end padding in pixels
19329     */
19330    public int getPaddingEnd() {
19331        if (!isPaddingResolved()) {
19332            resolvePadding();
19333        }
19334        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19335                mPaddingLeft : mPaddingRight;
19336    }
19337
19338    /**
19339     * Return if the padding has been set through relative values
19340     * {@link #setPaddingRelative(int, int, int, int)} or through
19341     * @attr ref android.R.styleable#View_paddingStart or
19342     * @attr ref android.R.styleable#View_paddingEnd
19343     *
19344     * @return true if the padding is relative or false if it is not.
19345     */
19346    public boolean isPaddingRelative() {
19347        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19348    }
19349
19350    Insets computeOpticalInsets() {
19351        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19352    }
19353
19354    /**
19355     * @hide
19356     */
19357    public void resetPaddingToInitialValues() {
19358        if (isRtlCompatibilityMode()) {
19359            mPaddingLeft = mUserPaddingLeftInitial;
19360            mPaddingRight = mUserPaddingRightInitial;
19361            return;
19362        }
19363        if (isLayoutRtl()) {
19364            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19365            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19366        } else {
19367            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19368            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19369        }
19370    }
19371
19372    /**
19373     * @hide
19374     */
19375    public Insets getOpticalInsets() {
19376        if (mLayoutInsets == null) {
19377            mLayoutInsets = computeOpticalInsets();
19378        }
19379        return mLayoutInsets;
19380    }
19381
19382    /**
19383     * Set this view's optical insets.
19384     *
19385     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19386     * property. Views that compute their own optical insets should call it as part of measurement.
19387     * This method does not request layout. If you are setting optical insets outside of
19388     * measure/layout itself you will want to call requestLayout() yourself.
19389     * </p>
19390     * @hide
19391     */
19392    public void setOpticalInsets(Insets insets) {
19393        mLayoutInsets = insets;
19394    }
19395
19396    /**
19397     * Changes the selection state of this view. A view can be selected or not.
19398     * Note that selection is not the same as focus. Views are typically
19399     * selected in the context of an AdapterView like ListView or GridView;
19400     * the selected view is the view that is highlighted.
19401     *
19402     * @param selected true if the view must be selected, false otherwise
19403     */
19404    public void setSelected(boolean selected) {
19405        //noinspection DoubleNegation
19406        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19407            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19408            if (!selected) resetPressedState();
19409            invalidate(true);
19410            refreshDrawableState();
19411            dispatchSetSelected(selected);
19412            if (selected) {
19413                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19414            } else {
19415                notifyViewAccessibilityStateChangedIfNeeded(
19416                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19417            }
19418        }
19419    }
19420
19421    /**
19422     * Dispatch setSelected to all of this View's children.
19423     *
19424     * @see #setSelected(boolean)
19425     *
19426     * @param selected The new selected state
19427     */
19428    protected void dispatchSetSelected(boolean selected) {
19429    }
19430
19431    /**
19432     * Indicates the selection state of this view.
19433     *
19434     * @return true if the view is selected, false otherwise
19435     */
19436    @ViewDebug.ExportedProperty
19437    public boolean isSelected() {
19438        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19439    }
19440
19441    /**
19442     * Changes the activated state of this view. A view can be activated or not.
19443     * Note that activation is not the same as selection.  Selection is
19444     * a transient property, representing the view (hierarchy) the user is
19445     * currently interacting with.  Activation is a longer-term state that the
19446     * user can move views in and out of.  For example, in a list view with
19447     * single or multiple selection enabled, the views in the current selection
19448     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19449     * here.)  The activated state is propagated down to children of the view it
19450     * is set on.
19451     *
19452     * @param activated true if the view must be activated, false otherwise
19453     */
19454    public void setActivated(boolean activated) {
19455        //noinspection DoubleNegation
19456        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19457            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19458            invalidate(true);
19459            refreshDrawableState();
19460            dispatchSetActivated(activated);
19461        }
19462    }
19463
19464    /**
19465     * Dispatch setActivated to all of this View's children.
19466     *
19467     * @see #setActivated(boolean)
19468     *
19469     * @param activated The new activated state
19470     */
19471    protected void dispatchSetActivated(boolean activated) {
19472    }
19473
19474    /**
19475     * Indicates the activation state of this view.
19476     *
19477     * @return true if the view is activated, false otherwise
19478     */
19479    @ViewDebug.ExportedProperty
19480    public boolean isActivated() {
19481        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19482    }
19483
19484    /**
19485     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19486     * observer can be used to get notifications when global events, like
19487     * layout, happen.
19488     *
19489     * The returned ViewTreeObserver observer is not guaranteed to remain
19490     * valid for the lifetime of this View. If the caller of this method keeps
19491     * a long-lived reference to ViewTreeObserver, it should always check for
19492     * the return value of {@link ViewTreeObserver#isAlive()}.
19493     *
19494     * @return The ViewTreeObserver for this view's hierarchy.
19495     */
19496    public ViewTreeObserver getViewTreeObserver() {
19497        if (mAttachInfo != null) {
19498            return mAttachInfo.mTreeObserver;
19499        }
19500        if (mFloatingTreeObserver == null) {
19501            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19502        }
19503        return mFloatingTreeObserver;
19504    }
19505
19506    /**
19507     * <p>Finds the topmost view in the current view hierarchy.</p>
19508     *
19509     * @return the topmost view containing this view
19510     */
19511    public View getRootView() {
19512        if (mAttachInfo != null) {
19513            final View v = mAttachInfo.mRootView;
19514            if (v != null) {
19515                return v;
19516            }
19517        }
19518
19519        View parent = this;
19520
19521        while (parent.mParent != null && parent.mParent instanceof View) {
19522            parent = (View) parent.mParent;
19523        }
19524
19525        return parent;
19526    }
19527
19528    /**
19529     * Transforms a motion event from view-local coordinates to on-screen
19530     * coordinates.
19531     *
19532     * @param ev the view-local motion event
19533     * @return false if the transformation could not be applied
19534     * @hide
19535     */
19536    public boolean toGlobalMotionEvent(MotionEvent ev) {
19537        final AttachInfo info = mAttachInfo;
19538        if (info == null) {
19539            return false;
19540        }
19541
19542        final Matrix m = info.mTmpMatrix;
19543        m.set(Matrix.IDENTITY_MATRIX);
19544        transformMatrixToGlobal(m);
19545        ev.transform(m);
19546        return true;
19547    }
19548
19549    /**
19550     * Transforms a motion event from on-screen coordinates to view-local
19551     * coordinates.
19552     *
19553     * @param ev the on-screen motion event
19554     * @return false if the transformation could not be applied
19555     * @hide
19556     */
19557    public boolean toLocalMotionEvent(MotionEvent ev) {
19558        final AttachInfo info = mAttachInfo;
19559        if (info == null) {
19560            return false;
19561        }
19562
19563        final Matrix m = info.mTmpMatrix;
19564        m.set(Matrix.IDENTITY_MATRIX);
19565        transformMatrixToLocal(m);
19566        ev.transform(m);
19567        return true;
19568    }
19569
19570    /**
19571     * Modifies the input matrix such that it maps view-local coordinates to
19572     * on-screen coordinates.
19573     *
19574     * @param m input matrix to modify
19575     * @hide
19576     */
19577    public void transformMatrixToGlobal(Matrix m) {
19578        final ViewParent parent = mParent;
19579        if (parent instanceof View) {
19580            final View vp = (View) parent;
19581            vp.transformMatrixToGlobal(m);
19582            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19583        } else if (parent instanceof ViewRootImpl) {
19584            final ViewRootImpl vr = (ViewRootImpl) parent;
19585            vr.transformMatrixToGlobal(m);
19586            m.preTranslate(0, -vr.mCurScrollY);
19587        }
19588
19589        m.preTranslate(mLeft, mTop);
19590
19591        if (!hasIdentityMatrix()) {
19592            m.preConcat(getMatrix());
19593        }
19594    }
19595
19596    /**
19597     * Modifies the input matrix such that it maps on-screen coordinates to
19598     * view-local coordinates.
19599     *
19600     * @param m input matrix to modify
19601     * @hide
19602     */
19603    public void transformMatrixToLocal(Matrix m) {
19604        final ViewParent parent = mParent;
19605        if (parent instanceof View) {
19606            final View vp = (View) parent;
19607            vp.transformMatrixToLocal(m);
19608            m.postTranslate(vp.mScrollX, vp.mScrollY);
19609        } else if (parent instanceof ViewRootImpl) {
19610            final ViewRootImpl vr = (ViewRootImpl) parent;
19611            vr.transformMatrixToLocal(m);
19612            m.postTranslate(0, vr.mCurScrollY);
19613        }
19614
19615        m.postTranslate(-mLeft, -mTop);
19616
19617        if (!hasIdentityMatrix()) {
19618            m.postConcat(getInverseMatrix());
19619        }
19620    }
19621
19622    /**
19623     * @hide
19624     */
19625    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19626            @ViewDebug.IntToString(from = 0, to = "x"),
19627            @ViewDebug.IntToString(from = 1, to = "y")
19628    })
19629    public int[] getLocationOnScreen() {
19630        int[] location = new int[2];
19631        getLocationOnScreen(location);
19632        return location;
19633    }
19634
19635    /**
19636     * <p>Computes the coordinates of this view on the screen. The argument
19637     * must be an array of two integers. After the method returns, the array
19638     * contains the x and y location in that order.</p>
19639     *
19640     * @param outLocation an array of two integers in which to hold the coordinates
19641     */
19642    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19643        getLocationInWindow(outLocation);
19644
19645        final AttachInfo info = mAttachInfo;
19646        if (info != null) {
19647            outLocation[0] += info.mWindowLeft;
19648            outLocation[1] += info.mWindowTop;
19649        }
19650    }
19651
19652    /**
19653     * <p>Computes the coordinates of this view in its window. The argument
19654     * must be an array of two integers. After the method returns, the array
19655     * contains the x and y location in that order.</p>
19656     *
19657     * @param outLocation an array of two integers in which to hold the coordinates
19658     */
19659    public void getLocationInWindow(@Size(2) int[] outLocation) {
19660        if (outLocation == null || outLocation.length < 2) {
19661            throw new IllegalArgumentException("outLocation must be an array of two integers");
19662        }
19663
19664        outLocation[0] = 0;
19665        outLocation[1] = 0;
19666
19667        transformFromViewToWindowSpace(outLocation);
19668    }
19669
19670    /** @hide */
19671    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19672        if (inOutLocation == null || inOutLocation.length < 2) {
19673            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19674        }
19675
19676        if (mAttachInfo == null) {
19677            // When the view is not attached to a window, this method does not make sense
19678            inOutLocation[0] = inOutLocation[1] = 0;
19679            return;
19680        }
19681
19682        float position[] = mAttachInfo.mTmpTransformLocation;
19683        position[0] = inOutLocation[0];
19684        position[1] = inOutLocation[1];
19685
19686        if (!hasIdentityMatrix()) {
19687            getMatrix().mapPoints(position);
19688        }
19689
19690        position[0] += mLeft;
19691        position[1] += mTop;
19692
19693        ViewParent viewParent = mParent;
19694        while (viewParent instanceof View) {
19695            final View view = (View) viewParent;
19696
19697            position[0] -= view.mScrollX;
19698            position[1] -= view.mScrollY;
19699
19700            if (!view.hasIdentityMatrix()) {
19701                view.getMatrix().mapPoints(position);
19702            }
19703
19704            position[0] += view.mLeft;
19705            position[1] += view.mTop;
19706
19707            viewParent = view.mParent;
19708         }
19709
19710        if (viewParent instanceof ViewRootImpl) {
19711            // *cough*
19712            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19713            position[1] -= vr.mCurScrollY;
19714        }
19715
19716        inOutLocation[0] = Math.round(position[0]);
19717        inOutLocation[1] = Math.round(position[1]);
19718    }
19719
19720    /**
19721     * {@hide}
19722     * @param id the id of the view to be found
19723     * @return the view of the specified id, null if cannot be found
19724     */
19725    protected View findViewTraversal(@IdRes int id) {
19726        if (id == mID) {
19727            return this;
19728        }
19729        return null;
19730    }
19731
19732    /**
19733     * {@hide}
19734     * @param tag the tag of the view to be found
19735     * @return the view of specified tag, null if cannot be found
19736     */
19737    protected View findViewWithTagTraversal(Object tag) {
19738        if (tag != null && tag.equals(mTag)) {
19739            return this;
19740        }
19741        return null;
19742    }
19743
19744    /**
19745     * {@hide}
19746     * @param predicate The predicate to evaluate.
19747     * @param childToSkip If not null, ignores this child during the recursive traversal.
19748     * @return The first view that matches the predicate or null.
19749     */
19750    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19751        if (predicate.apply(this)) {
19752            return this;
19753        }
19754        return null;
19755    }
19756
19757    /**
19758     * Look for a child view with the given id.  If this view has the given
19759     * id, return this view.
19760     *
19761     * @param id The id to search for.
19762     * @return The view that has the given id in the hierarchy or null
19763     */
19764    @Nullable
19765    public final View findViewById(@IdRes int id) {
19766        if (id < 0) {
19767            return null;
19768        }
19769        return findViewTraversal(id);
19770    }
19771
19772    /**
19773     * Finds a view by its unuque and stable accessibility id.
19774     *
19775     * @param accessibilityId The searched accessibility id.
19776     * @return The found view.
19777     */
19778    final View findViewByAccessibilityId(int accessibilityId) {
19779        if (accessibilityId < 0) {
19780            return null;
19781        }
19782        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19783        if (view != null) {
19784            return view.includeForAccessibility() ? view : null;
19785        }
19786        return null;
19787    }
19788
19789    /**
19790     * Performs the traversal to find a view by its unuque and stable accessibility id.
19791     *
19792     * <strong>Note:</strong>This method does not stop at the root namespace
19793     * boundary since the user can touch the screen at an arbitrary location
19794     * potentially crossing the root namespace bounday which will send an
19795     * accessibility event to accessibility services and they should be able
19796     * to obtain the event source. Also accessibility ids are guaranteed to be
19797     * unique in the window.
19798     *
19799     * @param accessibilityId The accessibility id.
19800     * @return The found view.
19801     *
19802     * @hide
19803     */
19804    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19805        if (getAccessibilityViewId() == accessibilityId) {
19806            return this;
19807        }
19808        return null;
19809    }
19810
19811    /**
19812     * Look for a child view with the given tag.  If this view has the given
19813     * tag, return this view.
19814     *
19815     * @param tag The tag to search for, using "tag.equals(getTag())".
19816     * @return The View that has the given tag in the hierarchy or null
19817     */
19818    public final View findViewWithTag(Object tag) {
19819        if (tag == null) {
19820            return null;
19821        }
19822        return findViewWithTagTraversal(tag);
19823    }
19824
19825    /**
19826     * {@hide}
19827     * Look for a child view that matches the specified predicate.
19828     * If this view matches the predicate, return this view.
19829     *
19830     * @param predicate The predicate to evaluate.
19831     * @return The first view that matches the predicate or null.
19832     */
19833    public final View findViewByPredicate(Predicate<View> predicate) {
19834        return findViewByPredicateTraversal(predicate, null);
19835    }
19836
19837    /**
19838     * {@hide}
19839     * Look for a child view that matches the specified predicate,
19840     * starting with the specified view and its descendents and then
19841     * recusively searching the ancestors and siblings of that view
19842     * until this view is reached.
19843     *
19844     * This method is useful in cases where the predicate does not match
19845     * a single unique view (perhaps multiple views use the same id)
19846     * and we are trying to find the view that is "closest" in scope to the
19847     * starting view.
19848     *
19849     * @param start The view to start from.
19850     * @param predicate The predicate to evaluate.
19851     * @return The first view that matches the predicate or null.
19852     */
19853    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19854        View childToSkip = null;
19855        for (;;) {
19856            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19857            if (view != null || start == this) {
19858                return view;
19859            }
19860
19861            ViewParent parent = start.getParent();
19862            if (parent == null || !(parent instanceof View)) {
19863                return null;
19864            }
19865
19866            childToSkip = start;
19867            start = (View) parent;
19868        }
19869    }
19870
19871    /**
19872     * Sets the identifier for this view. The identifier does not have to be
19873     * unique in this view's hierarchy. The identifier should be a positive
19874     * number.
19875     *
19876     * @see #NO_ID
19877     * @see #getId()
19878     * @see #findViewById(int)
19879     *
19880     * @param id a number used to identify the view
19881     *
19882     * @attr ref android.R.styleable#View_id
19883     */
19884    public void setId(@IdRes int id) {
19885        mID = id;
19886        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19887            mID = generateViewId();
19888        }
19889    }
19890
19891    /**
19892     * {@hide}
19893     *
19894     * @param isRoot true if the view belongs to the root namespace, false
19895     *        otherwise
19896     */
19897    public void setIsRootNamespace(boolean isRoot) {
19898        if (isRoot) {
19899            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19900        } else {
19901            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19902        }
19903    }
19904
19905    /**
19906     * {@hide}
19907     *
19908     * @return true if the view belongs to the root namespace, false otherwise
19909     */
19910    public boolean isRootNamespace() {
19911        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19912    }
19913
19914    /**
19915     * Returns this view's identifier.
19916     *
19917     * @return a positive integer used to identify the view or {@link #NO_ID}
19918     *         if the view has no ID
19919     *
19920     * @see #setId(int)
19921     * @see #findViewById(int)
19922     * @attr ref android.R.styleable#View_id
19923     */
19924    @IdRes
19925    @ViewDebug.CapturedViewProperty
19926    public int getId() {
19927        return mID;
19928    }
19929
19930    /**
19931     * Returns this view's tag.
19932     *
19933     * @return the Object stored in this view as a tag, or {@code null} if not
19934     *         set
19935     *
19936     * @see #setTag(Object)
19937     * @see #getTag(int)
19938     */
19939    @ViewDebug.ExportedProperty
19940    public Object getTag() {
19941        return mTag;
19942    }
19943
19944    /**
19945     * Sets the tag associated with this view. A tag can be used to mark
19946     * a view in its hierarchy and does not have to be unique within the
19947     * hierarchy. Tags can also be used to store data within a view without
19948     * resorting to another data structure.
19949     *
19950     * @param tag an Object to tag the view with
19951     *
19952     * @see #getTag()
19953     * @see #setTag(int, Object)
19954     */
19955    public void setTag(final Object tag) {
19956        mTag = tag;
19957    }
19958
19959    /**
19960     * Returns the tag associated with this view and the specified key.
19961     *
19962     * @param key The key identifying the tag
19963     *
19964     * @return the Object stored in this view as a tag, or {@code null} if not
19965     *         set
19966     *
19967     * @see #setTag(int, Object)
19968     * @see #getTag()
19969     */
19970    public Object getTag(int key) {
19971        if (mKeyedTags != null) return mKeyedTags.get(key);
19972        return null;
19973    }
19974
19975    /**
19976     * Sets a tag associated with this view and a key. A tag can be used
19977     * to mark a view in its hierarchy and does not have to be unique within
19978     * the hierarchy. Tags can also be used to store data within a view
19979     * without resorting to another data structure.
19980     *
19981     * The specified key should be an id declared in the resources of the
19982     * application to ensure it is unique (see the <a
19983     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19984     * Keys identified as belonging to
19985     * the Android framework or not associated with any package will cause
19986     * an {@link IllegalArgumentException} to be thrown.
19987     *
19988     * @param key The key identifying the tag
19989     * @param tag An Object to tag the view with
19990     *
19991     * @throws IllegalArgumentException If they specified key is not valid
19992     *
19993     * @see #setTag(Object)
19994     * @see #getTag(int)
19995     */
19996    public void setTag(int key, final Object tag) {
19997        // If the package id is 0x00 or 0x01, it's either an undefined package
19998        // or a framework id
19999        if ((key >>> 24) < 2) {
20000            throw new IllegalArgumentException("The key must be an application-specific "
20001                    + "resource id.");
20002        }
20003
20004        setKeyedTag(key, tag);
20005    }
20006
20007    /**
20008     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20009     * framework id.
20010     *
20011     * @hide
20012     */
20013    public void setTagInternal(int key, Object tag) {
20014        if ((key >>> 24) != 0x1) {
20015            throw new IllegalArgumentException("The key must be a framework-specific "
20016                    + "resource id.");
20017        }
20018
20019        setKeyedTag(key, tag);
20020    }
20021
20022    private void setKeyedTag(int key, Object tag) {
20023        if (mKeyedTags == null) {
20024            mKeyedTags = new SparseArray<Object>(2);
20025        }
20026
20027        mKeyedTags.put(key, tag);
20028    }
20029
20030    /**
20031     * Prints information about this view in the log output, with the tag
20032     * {@link #VIEW_LOG_TAG}.
20033     *
20034     * @hide
20035     */
20036    public void debug() {
20037        debug(0);
20038    }
20039
20040    /**
20041     * Prints information about this view in the log output, with the tag
20042     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20043     * indentation defined by the <code>depth</code>.
20044     *
20045     * @param depth the indentation level
20046     *
20047     * @hide
20048     */
20049    protected void debug(int depth) {
20050        String output = debugIndent(depth - 1);
20051
20052        output += "+ " + this;
20053        int id = getId();
20054        if (id != -1) {
20055            output += " (id=" + id + ")";
20056        }
20057        Object tag = getTag();
20058        if (tag != null) {
20059            output += " (tag=" + tag + ")";
20060        }
20061        Log.d(VIEW_LOG_TAG, output);
20062
20063        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20064            output = debugIndent(depth) + " FOCUSED";
20065            Log.d(VIEW_LOG_TAG, output);
20066        }
20067
20068        output = debugIndent(depth);
20069        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20070                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20071                + "} ";
20072        Log.d(VIEW_LOG_TAG, output);
20073
20074        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20075                || mPaddingBottom != 0) {
20076            output = debugIndent(depth);
20077            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20078                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20079            Log.d(VIEW_LOG_TAG, output);
20080        }
20081
20082        output = debugIndent(depth);
20083        output += "mMeasureWidth=" + mMeasuredWidth +
20084                " mMeasureHeight=" + mMeasuredHeight;
20085        Log.d(VIEW_LOG_TAG, output);
20086
20087        output = debugIndent(depth);
20088        if (mLayoutParams == null) {
20089            output += "BAD! no layout params";
20090        } else {
20091            output = mLayoutParams.debug(output);
20092        }
20093        Log.d(VIEW_LOG_TAG, output);
20094
20095        output = debugIndent(depth);
20096        output += "flags={";
20097        output += View.printFlags(mViewFlags);
20098        output += "}";
20099        Log.d(VIEW_LOG_TAG, output);
20100
20101        output = debugIndent(depth);
20102        output += "privateFlags={";
20103        output += View.printPrivateFlags(mPrivateFlags);
20104        output += "}";
20105        Log.d(VIEW_LOG_TAG, output);
20106    }
20107
20108    /**
20109     * Creates a string of whitespaces used for indentation.
20110     *
20111     * @param depth the indentation level
20112     * @return a String containing (depth * 2 + 3) * 2 white spaces
20113     *
20114     * @hide
20115     */
20116    protected static String debugIndent(int depth) {
20117        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20118        for (int i = 0; i < (depth * 2) + 3; i++) {
20119            spaces.append(' ').append(' ');
20120        }
20121        return spaces.toString();
20122    }
20123
20124    /**
20125     * <p>Return the offset of the widget's text baseline from the widget's top
20126     * boundary. If this widget does not support baseline alignment, this
20127     * method returns -1. </p>
20128     *
20129     * @return the offset of the baseline within the widget's bounds or -1
20130     *         if baseline alignment is not supported
20131     */
20132    @ViewDebug.ExportedProperty(category = "layout")
20133    public int getBaseline() {
20134        return -1;
20135    }
20136
20137    /**
20138     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20139     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20140     * a layout pass.
20141     *
20142     * @return whether the view hierarchy is currently undergoing a layout pass
20143     */
20144    public boolean isInLayout() {
20145        ViewRootImpl viewRoot = getViewRootImpl();
20146        return (viewRoot != null && viewRoot.isInLayout());
20147    }
20148
20149    /**
20150     * Call this when something has changed which has invalidated the
20151     * layout of this view. This will schedule a layout pass of the view
20152     * tree. This should not be called while the view hierarchy is currently in a layout
20153     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20154     * end of the current layout pass (and then layout will run again) or after the current
20155     * frame is drawn and the next layout occurs.
20156     *
20157     * <p>Subclasses which override this method should call the superclass method to
20158     * handle possible request-during-layout errors correctly.</p>
20159     */
20160    @CallSuper
20161    public void requestLayout() {
20162        if (mMeasureCache != null) mMeasureCache.clear();
20163
20164        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20165            // Only trigger request-during-layout logic if this is the view requesting it,
20166            // not the views in its parent hierarchy
20167            ViewRootImpl viewRoot = getViewRootImpl();
20168            if (viewRoot != null && viewRoot.isInLayout()) {
20169                if (!viewRoot.requestLayoutDuringLayout(this)) {
20170                    return;
20171                }
20172            }
20173            mAttachInfo.mViewRequestingLayout = this;
20174        }
20175
20176        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20177        mPrivateFlags |= PFLAG_INVALIDATED;
20178
20179        if (mParent != null && !mParent.isLayoutRequested()) {
20180            mParent.requestLayout();
20181        }
20182        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20183            mAttachInfo.mViewRequestingLayout = null;
20184        }
20185    }
20186
20187    /**
20188     * Forces this view to be laid out during the next layout pass.
20189     * This method does not call requestLayout() or forceLayout()
20190     * on the parent.
20191     */
20192    public void forceLayout() {
20193        if (mMeasureCache != null) mMeasureCache.clear();
20194
20195        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20196        mPrivateFlags |= PFLAG_INVALIDATED;
20197    }
20198
20199    /**
20200     * <p>
20201     * This is called to find out how big a view should be. The parent
20202     * supplies constraint information in the width and height parameters.
20203     * </p>
20204     *
20205     * <p>
20206     * The actual measurement work of a view is performed in
20207     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20208     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20209     * </p>
20210     *
20211     *
20212     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20213     *        parent
20214     * @param heightMeasureSpec Vertical space requirements as imposed by the
20215     *        parent
20216     *
20217     * @see #onMeasure(int, int)
20218     */
20219    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20220        boolean optical = isLayoutModeOptical(this);
20221        if (optical != isLayoutModeOptical(mParent)) {
20222            Insets insets = getOpticalInsets();
20223            int oWidth  = insets.left + insets.right;
20224            int oHeight = insets.top  + insets.bottom;
20225            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20226            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20227        }
20228
20229        // Suppress sign extension for the low bytes
20230        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20231        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20232
20233        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20234
20235        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20236        // already measured as the correct size. In API 23 and below, this
20237        // extra pass is required to make LinearLayout re-distribute weight.
20238        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20239                || heightMeasureSpec != mOldHeightMeasureSpec;
20240        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20241                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20242        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20243                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20244        final boolean needsLayout = specChanged
20245                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20246
20247        if (forceLayout || needsLayout) {
20248            // first clears the measured dimension flag
20249            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20250
20251            resolveRtlPropertiesIfNeeded();
20252
20253            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20254            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20255                // measure ourselves, this should set the measured dimension flag back
20256                onMeasure(widthMeasureSpec, heightMeasureSpec);
20257                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20258            } else {
20259                long value = mMeasureCache.valueAt(cacheIndex);
20260                // Casting a long to int drops the high 32 bits, no mask needed
20261                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20262                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20263            }
20264
20265            // flag not set, setMeasuredDimension() was not invoked, we raise
20266            // an exception to warn the developer
20267            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20268                throw new IllegalStateException("View with id " + getId() + ": "
20269                        + getClass().getName() + "#onMeasure() did not set the"
20270                        + " measured dimension by calling"
20271                        + " setMeasuredDimension()");
20272            }
20273
20274            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20275        }
20276
20277        mOldWidthMeasureSpec = widthMeasureSpec;
20278        mOldHeightMeasureSpec = heightMeasureSpec;
20279
20280        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20281                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20282    }
20283
20284    /**
20285     * <p>
20286     * Measure the view and its content to determine the measured width and the
20287     * measured height. This method is invoked by {@link #measure(int, int)} and
20288     * should be overridden by subclasses to provide accurate and efficient
20289     * measurement of their contents.
20290     * </p>
20291     *
20292     * <p>
20293     * <strong>CONTRACT:</strong> When overriding this method, you
20294     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20295     * measured width and height of this view. Failure to do so will trigger an
20296     * <code>IllegalStateException</code>, thrown by
20297     * {@link #measure(int, int)}. Calling the superclass'
20298     * {@link #onMeasure(int, int)} is a valid use.
20299     * </p>
20300     *
20301     * <p>
20302     * The base class implementation of measure defaults to the background size,
20303     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20304     * override {@link #onMeasure(int, int)} to provide better measurements of
20305     * their content.
20306     * </p>
20307     *
20308     * <p>
20309     * If this method is overridden, it is the subclass's responsibility to make
20310     * sure the measured height and width are at least the view's minimum height
20311     * and width ({@link #getSuggestedMinimumHeight()} and
20312     * {@link #getSuggestedMinimumWidth()}).
20313     * </p>
20314     *
20315     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20316     *                         The requirements are encoded with
20317     *                         {@link android.view.View.MeasureSpec}.
20318     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20319     *                         The requirements are encoded with
20320     *                         {@link android.view.View.MeasureSpec}.
20321     *
20322     * @see #getMeasuredWidth()
20323     * @see #getMeasuredHeight()
20324     * @see #setMeasuredDimension(int, int)
20325     * @see #getSuggestedMinimumHeight()
20326     * @see #getSuggestedMinimumWidth()
20327     * @see android.view.View.MeasureSpec#getMode(int)
20328     * @see android.view.View.MeasureSpec#getSize(int)
20329     */
20330    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20331        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20332                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20333    }
20334
20335    /**
20336     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20337     * measured width and measured height. Failing to do so will trigger an
20338     * exception at measurement time.</p>
20339     *
20340     * @param measuredWidth The measured width of this view.  May be a complex
20341     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20342     * {@link #MEASURED_STATE_TOO_SMALL}.
20343     * @param measuredHeight The measured height of this view.  May be a complex
20344     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20345     * {@link #MEASURED_STATE_TOO_SMALL}.
20346     */
20347    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20348        boolean optical = isLayoutModeOptical(this);
20349        if (optical != isLayoutModeOptical(mParent)) {
20350            Insets insets = getOpticalInsets();
20351            int opticalWidth  = insets.left + insets.right;
20352            int opticalHeight = insets.top  + insets.bottom;
20353
20354            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20355            measuredHeight += optical ? opticalHeight : -opticalHeight;
20356        }
20357        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20358    }
20359
20360    /**
20361     * Sets the measured dimension without extra processing for things like optical bounds.
20362     * Useful for reapplying consistent values that have already been cooked with adjustments
20363     * for optical bounds, etc. such as those from the measurement cache.
20364     *
20365     * @param measuredWidth The measured width of this view.  May be a complex
20366     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20367     * {@link #MEASURED_STATE_TOO_SMALL}.
20368     * @param measuredHeight The measured height of this view.  May be a complex
20369     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20370     * {@link #MEASURED_STATE_TOO_SMALL}.
20371     */
20372    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20373        mMeasuredWidth = measuredWidth;
20374        mMeasuredHeight = measuredHeight;
20375
20376        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20377    }
20378
20379    /**
20380     * Merge two states as returned by {@link #getMeasuredState()}.
20381     * @param curState The current state as returned from a view or the result
20382     * of combining multiple views.
20383     * @param newState The new view state to combine.
20384     * @return Returns a new integer reflecting the combination of the two
20385     * states.
20386     */
20387    public static int combineMeasuredStates(int curState, int newState) {
20388        return curState | newState;
20389    }
20390
20391    /**
20392     * Version of {@link #resolveSizeAndState(int, int, int)}
20393     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20394     */
20395    public static int resolveSize(int size, int measureSpec) {
20396        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20397    }
20398
20399    /**
20400     * Utility to reconcile a desired size and state, with constraints imposed
20401     * by a MeasureSpec. Will take the desired size, unless a different size
20402     * is imposed by the constraints. The returned value is a compound integer,
20403     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20404     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20405     * resulting size is smaller than the size the view wants to be.
20406     *
20407     * @param size How big the view wants to be.
20408     * @param measureSpec Constraints imposed by the parent.
20409     * @param childMeasuredState Size information bit mask for the view's
20410     *                           children.
20411     * @return Size information bit mask as defined by
20412     *         {@link #MEASURED_SIZE_MASK} and
20413     *         {@link #MEASURED_STATE_TOO_SMALL}.
20414     */
20415    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20416        final int specMode = MeasureSpec.getMode(measureSpec);
20417        final int specSize = MeasureSpec.getSize(measureSpec);
20418        final int result;
20419        switch (specMode) {
20420            case MeasureSpec.AT_MOST:
20421                if (specSize < size) {
20422                    result = specSize | MEASURED_STATE_TOO_SMALL;
20423                } else {
20424                    result = size;
20425                }
20426                break;
20427            case MeasureSpec.EXACTLY:
20428                result = specSize;
20429                break;
20430            case MeasureSpec.UNSPECIFIED:
20431            default:
20432                result = size;
20433        }
20434        return result | (childMeasuredState & MEASURED_STATE_MASK);
20435    }
20436
20437    /**
20438     * Utility to return a default size. Uses the supplied size if the
20439     * MeasureSpec imposed no constraints. Will get larger if allowed
20440     * by the MeasureSpec.
20441     *
20442     * @param size Default size for this view
20443     * @param measureSpec Constraints imposed by the parent
20444     * @return The size this view should be.
20445     */
20446    public static int getDefaultSize(int size, int measureSpec) {
20447        int result = size;
20448        int specMode = MeasureSpec.getMode(measureSpec);
20449        int specSize = MeasureSpec.getSize(measureSpec);
20450
20451        switch (specMode) {
20452        case MeasureSpec.UNSPECIFIED:
20453            result = size;
20454            break;
20455        case MeasureSpec.AT_MOST:
20456        case MeasureSpec.EXACTLY:
20457            result = specSize;
20458            break;
20459        }
20460        return result;
20461    }
20462
20463    /**
20464     * Returns the suggested minimum height that the view should use. This
20465     * returns the maximum of the view's minimum height
20466     * and the background's minimum height
20467     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20468     * <p>
20469     * When being used in {@link #onMeasure(int, int)}, the caller should still
20470     * ensure the returned height is within the requirements of the parent.
20471     *
20472     * @return The suggested minimum height of the view.
20473     */
20474    protected int getSuggestedMinimumHeight() {
20475        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20476
20477    }
20478
20479    /**
20480     * Returns the suggested minimum width that the view should use. This
20481     * returns the maximum of the view's minimum width
20482     * and the background's minimum width
20483     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20484     * <p>
20485     * When being used in {@link #onMeasure(int, int)}, the caller should still
20486     * ensure the returned width is within the requirements of the parent.
20487     *
20488     * @return The suggested minimum width of the view.
20489     */
20490    protected int getSuggestedMinimumWidth() {
20491        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20492    }
20493
20494    /**
20495     * Returns the minimum height of the view.
20496     *
20497     * @return the minimum height the view will try to be, in pixels
20498     *
20499     * @see #setMinimumHeight(int)
20500     *
20501     * @attr ref android.R.styleable#View_minHeight
20502     */
20503    public int getMinimumHeight() {
20504        return mMinHeight;
20505    }
20506
20507    /**
20508     * Sets the minimum height of the view. It is not guaranteed the view will
20509     * be able to achieve this minimum height (for example, if its parent layout
20510     * constrains it with less available height).
20511     *
20512     * @param minHeight The minimum height the view will try to be, in pixels
20513     *
20514     * @see #getMinimumHeight()
20515     *
20516     * @attr ref android.R.styleable#View_minHeight
20517     */
20518    @RemotableViewMethod
20519    public void setMinimumHeight(int minHeight) {
20520        mMinHeight = minHeight;
20521        requestLayout();
20522    }
20523
20524    /**
20525     * Returns the minimum width of the view.
20526     *
20527     * @return the minimum width the view will try to be, in pixels
20528     *
20529     * @see #setMinimumWidth(int)
20530     *
20531     * @attr ref android.R.styleable#View_minWidth
20532     */
20533    public int getMinimumWidth() {
20534        return mMinWidth;
20535    }
20536
20537    /**
20538     * Sets the minimum width of the view. It is not guaranteed the view will
20539     * be able to achieve this minimum width (for example, if its parent layout
20540     * constrains it with less available width).
20541     *
20542     * @param minWidth The minimum width the view will try to be, in pixels
20543     *
20544     * @see #getMinimumWidth()
20545     *
20546     * @attr ref android.R.styleable#View_minWidth
20547     */
20548    public void setMinimumWidth(int minWidth) {
20549        mMinWidth = minWidth;
20550        requestLayout();
20551
20552    }
20553
20554    /**
20555     * Get the animation currently associated with this view.
20556     *
20557     * @return The animation that is currently playing or
20558     *         scheduled to play for this view.
20559     */
20560    public Animation getAnimation() {
20561        return mCurrentAnimation;
20562    }
20563
20564    /**
20565     * Start the specified animation now.
20566     *
20567     * @param animation the animation to start now
20568     */
20569    public void startAnimation(Animation animation) {
20570        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20571        setAnimation(animation);
20572        invalidateParentCaches();
20573        invalidate(true);
20574    }
20575
20576    /**
20577     * Cancels any animations for this view.
20578     */
20579    public void clearAnimation() {
20580        if (mCurrentAnimation != null) {
20581            mCurrentAnimation.detach();
20582        }
20583        mCurrentAnimation = null;
20584        invalidateParentIfNeeded();
20585    }
20586
20587    /**
20588     * Sets the next animation to play for this view.
20589     * If you want the animation to play immediately, use
20590     * {@link #startAnimation(android.view.animation.Animation)} instead.
20591     * This method provides allows fine-grained
20592     * control over the start time and invalidation, but you
20593     * must make sure that 1) the animation has a start time set, and
20594     * 2) the view's parent (which controls animations on its children)
20595     * will be invalidated when the animation is supposed to
20596     * start.
20597     *
20598     * @param animation The next animation, or null.
20599     */
20600    public void setAnimation(Animation animation) {
20601        mCurrentAnimation = animation;
20602
20603        if (animation != null) {
20604            // If the screen is off assume the animation start time is now instead of
20605            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20606            // would cause the animation to start when the screen turns back on
20607            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20608                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20609                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20610            }
20611            animation.reset();
20612        }
20613    }
20614
20615    /**
20616     * Invoked by a parent ViewGroup to notify the start of the animation
20617     * currently associated with this view. If you override this method,
20618     * always call super.onAnimationStart();
20619     *
20620     * @see #setAnimation(android.view.animation.Animation)
20621     * @see #getAnimation()
20622     */
20623    @CallSuper
20624    protected void onAnimationStart() {
20625        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20626    }
20627
20628    /**
20629     * Invoked by a parent ViewGroup to notify the end of the animation
20630     * currently associated with this view. If you override this method,
20631     * always call super.onAnimationEnd();
20632     *
20633     * @see #setAnimation(android.view.animation.Animation)
20634     * @see #getAnimation()
20635     */
20636    @CallSuper
20637    protected void onAnimationEnd() {
20638        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20639    }
20640
20641    /**
20642     * Invoked if there is a Transform that involves alpha. Subclass that can
20643     * draw themselves with the specified alpha should return true, and then
20644     * respect that alpha when their onDraw() is called. If this returns false
20645     * then the view may be redirected to draw into an offscreen buffer to
20646     * fulfill the request, which will look fine, but may be slower than if the
20647     * subclass handles it internally. The default implementation returns false.
20648     *
20649     * @param alpha The alpha (0..255) to apply to the view's drawing
20650     * @return true if the view can draw with the specified alpha.
20651     */
20652    protected boolean onSetAlpha(int alpha) {
20653        return false;
20654    }
20655
20656    /**
20657     * This is used by the RootView to perform an optimization when
20658     * the view hierarchy contains one or several SurfaceView.
20659     * SurfaceView is always considered transparent, but its children are not,
20660     * therefore all View objects remove themselves from the global transparent
20661     * region (passed as a parameter to this function).
20662     *
20663     * @param region The transparent region for this ViewAncestor (window).
20664     *
20665     * @return Returns true if the effective visibility of the view at this
20666     * point is opaque, regardless of the transparent region; returns false
20667     * if it is possible for underlying windows to be seen behind the view.
20668     *
20669     * {@hide}
20670     */
20671    public boolean gatherTransparentRegion(Region region) {
20672        final AttachInfo attachInfo = mAttachInfo;
20673        if (region != null && attachInfo != null) {
20674            final int pflags = mPrivateFlags;
20675            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20676                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20677                // remove it from the transparent region.
20678                final int[] location = attachInfo.mTransparentLocation;
20679                getLocationInWindow(location);
20680                // When a view has Z value, then it will be better to leave some area below the view
20681                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20682                // the bottom part needs more offset than the left, top and right parts due to the
20683                // spot light effects.
20684                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20685                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20686                        location[0] + mRight - mLeft + shadowOffset,
20687                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20688            } else {
20689                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20690                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20691                    // the background drawable's non-transparent parts from this transparent region.
20692                    applyDrawableToTransparentRegion(mBackground, region);
20693                }
20694                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20695                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20696                    // Similarly, we remove the foreground drawable's non-transparent parts.
20697                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20698                }
20699            }
20700        }
20701        return true;
20702    }
20703
20704    /**
20705     * Play a sound effect for this view.
20706     *
20707     * <p>The framework will play sound effects for some built in actions, such as
20708     * clicking, but you may wish to play these effects in your widget,
20709     * for instance, for internal navigation.
20710     *
20711     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20712     * {@link #isSoundEffectsEnabled()} is true.
20713     *
20714     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20715     */
20716    public void playSoundEffect(int soundConstant) {
20717        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20718            return;
20719        }
20720        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20721    }
20722
20723    /**
20724     * BZZZTT!!1!
20725     *
20726     * <p>Provide haptic feedback to the user for this view.
20727     *
20728     * <p>The framework will provide haptic feedback for some built in actions,
20729     * such as long presses, but you may wish to provide feedback for your
20730     * own widget.
20731     *
20732     * <p>The feedback will only be performed if
20733     * {@link #isHapticFeedbackEnabled()} is true.
20734     *
20735     * @param feedbackConstant One of the constants defined in
20736     * {@link HapticFeedbackConstants}
20737     */
20738    public boolean performHapticFeedback(int feedbackConstant) {
20739        return performHapticFeedback(feedbackConstant, 0);
20740    }
20741
20742    /**
20743     * BZZZTT!!1!
20744     *
20745     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20746     *
20747     * @param feedbackConstant One of the constants defined in
20748     * {@link HapticFeedbackConstants}
20749     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20750     */
20751    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20752        if (mAttachInfo == null) {
20753            return false;
20754        }
20755        //noinspection SimplifiableIfStatement
20756        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20757                && !isHapticFeedbackEnabled()) {
20758            return false;
20759        }
20760        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20761                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20762    }
20763
20764    /**
20765     * Request that the visibility of the status bar or other screen/window
20766     * decorations be changed.
20767     *
20768     * <p>This method is used to put the over device UI into temporary modes
20769     * where the user's attention is focused more on the application content,
20770     * by dimming or hiding surrounding system affordances.  This is typically
20771     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20772     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20773     * to be placed behind the action bar (and with these flags other system
20774     * affordances) so that smooth transitions between hiding and showing them
20775     * can be done.
20776     *
20777     * <p>Two representative examples of the use of system UI visibility is
20778     * implementing a content browsing application (like a magazine reader)
20779     * and a video playing application.
20780     *
20781     * <p>The first code shows a typical implementation of a View in a content
20782     * browsing application.  In this implementation, the application goes
20783     * into a content-oriented mode by hiding the status bar and action bar,
20784     * and putting the navigation elements into lights out mode.  The user can
20785     * then interact with content while in this mode.  Such an application should
20786     * provide an easy way for the user to toggle out of the mode (such as to
20787     * check information in the status bar or access notifications).  In the
20788     * implementation here, this is done simply by tapping on the content.
20789     *
20790     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20791     *      content}
20792     *
20793     * <p>This second code sample shows a typical implementation of a View
20794     * in a video playing application.  In this situation, while the video is
20795     * playing the application would like to go into a complete full-screen mode,
20796     * to use as much of the display as possible for the video.  When in this state
20797     * the user can not interact with the application; the system intercepts
20798     * touching on the screen to pop the UI out of full screen mode.  See
20799     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20800     *
20801     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20802     *      content}
20803     *
20804     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20805     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20806     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20807     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20808     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20809     */
20810    public void setSystemUiVisibility(int visibility) {
20811        if (visibility != mSystemUiVisibility) {
20812            mSystemUiVisibility = visibility;
20813            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20814                mParent.recomputeViewAttributes(this);
20815            }
20816        }
20817    }
20818
20819    /**
20820     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20821     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20822     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20823     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20824     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20825     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20826     */
20827    public int getSystemUiVisibility() {
20828        return mSystemUiVisibility;
20829    }
20830
20831    /**
20832     * Returns the current system UI visibility that is currently set for
20833     * the entire window.  This is the combination of the
20834     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20835     * views in the window.
20836     */
20837    public int getWindowSystemUiVisibility() {
20838        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20839    }
20840
20841    /**
20842     * Override to find out when the window's requested system UI visibility
20843     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20844     * This is different from the callbacks received through
20845     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20846     * in that this is only telling you about the local request of the window,
20847     * not the actual values applied by the system.
20848     */
20849    public void onWindowSystemUiVisibilityChanged(int visible) {
20850    }
20851
20852    /**
20853     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20854     * the view hierarchy.
20855     */
20856    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20857        onWindowSystemUiVisibilityChanged(visible);
20858    }
20859
20860    /**
20861     * Set a listener to receive callbacks when the visibility of the system bar changes.
20862     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20863     */
20864    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20865        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20866        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20867            mParent.recomputeViewAttributes(this);
20868        }
20869    }
20870
20871    /**
20872     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20873     * the view hierarchy.
20874     */
20875    public void dispatchSystemUiVisibilityChanged(int visibility) {
20876        ListenerInfo li = mListenerInfo;
20877        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20878            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20879                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20880        }
20881    }
20882
20883    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20884        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20885        if (val != mSystemUiVisibility) {
20886            setSystemUiVisibility(val);
20887            return true;
20888        }
20889        return false;
20890    }
20891
20892    /** @hide */
20893    public void setDisabledSystemUiVisibility(int flags) {
20894        if (mAttachInfo != null) {
20895            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20896                mAttachInfo.mDisabledSystemUiVisibility = flags;
20897                if (mParent != null) {
20898                    mParent.recomputeViewAttributes(this);
20899                }
20900            }
20901        }
20902    }
20903
20904    /**
20905     * Creates an image that the system displays during the drag and drop
20906     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20907     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20908     * appearance as the given View. The default also positions the center of the drag shadow
20909     * directly under the touch point. If no View is provided (the constructor with no parameters
20910     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20911     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20912     * default is an invisible drag shadow.
20913     * <p>
20914     * You are not required to use the View you provide to the constructor as the basis of the
20915     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20916     * anything you want as the drag shadow.
20917     * </p>
20918     * <p>
20919     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20920     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20921     *  size and position of the drag shadow. It uses this data to construct a
20922     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20923     *  so that your application can draw the shadow image in the Canvas.
20924     * </p>
20925     *
20926     * <div class="special reference">
20927     * <h3>Developer Guides</h3>
20928     * <p>For a guide to implementing drag and drop features, read the
20929     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20930     * </div>
20931     */
20932    public static class DragShadowBuilder {
20933        private final WeakReference<View> mView;
20934
20935        /**
20936         * Constructs a shadow image builder based on a View. By default, the resulting drag
20937         * shadow will have the same appearance and dimensions as the View, with the touch point
20938         * over the center of the View.
20939         * @param view A View. Any View in scope can be used.
20940         */
20941        public DragShadowBuilder(View view) {
20942            mView = new WeakReference<View>(view);
20943        }
20944
20945        /**
20946         * Construct a shadow builder object with no associated View.  This
20947         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20948         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20949         * to supply the drag shadow's dimensions and appearance without
20950         * reference to any View object. If they are not overridden, then the result is an
20951         * invisible drag shadow.
20952         */
20953        public DragShadowBuilder() {
20954            mView = new WeakReference<View>(null);
20955        }
20956
20957        /**
20958         * Returns the View object that had been passed to the
20959         * {@link #View.DragShadowBuilder(View)}
20960         * constructor.  If that View parameter was {@code null} or if the
20961         * {@link #View.DragShadowBuilder()}
20962         * constructor was used to instantiate the builder object, this method will return
20963         * null.
20964         *
20965         * @return The View object associate with this builder object.
20966         */
20967        @SuppressWarnings({"JavadocReference"})
20968        final public View getView() {
20969            return mView.get();
20970        }
20971
20972        /**
20973         * Provides the metrics for the shadow image. These include the dimensions of
20974         * the shadow image, and the point within that shadow that should
20975         * be centered under the touch location while dragging.
20976         * <p>
20977         * The default implementation sets the dimensions of the shadow to be the
20978         * same as the dimensions of the View itself and centers the shadow under
20979         * the touch point.
20980         * </p>
20981         *
20982         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20983         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20984         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20985         * image.
20986         *
20987         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20988         * shadow image that should be underneath the touch point during the drag and drop
20989         * operation. Your application must set {@link android.graphics.Point#x} to the
20990         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20991         */
20992        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20993            final View view = mView.get();
20994            if (view != null) {
20995                outShadowSize.set(view.getWidth(), view.getHeight());
20996                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20997            } else {
20998                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20999            }
21000        }
21001
21002        /**
21003         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21004         * based on the dimensions it received from the
21005         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21006         *
21007         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21008         */
21009        public void onDrawShadow(Canvas canvas) {
21010            final View view = mView.get();
21011            if (view != null) {
21012                view.draw(canvas);
21013            } else {
21014                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21015            }
21016        }
21017    }
21018
21019    /**
21020     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21021     * startDragAndDrop()} for newer platform versions.
21022     */
21023    @Deprecated
21024    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21025                                   Object myLocalState, int flags) {
21026        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21027    }
21028
21029    /**
21030     * Starts a drag and drop operation. When your application calls this method, it passes a
21031     * {@link android.view.View.DragShadowBuilder} object to the system. The
21032     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21033     * to get metrics for the drag shadow, and then calls the object's
21034     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21035     * <p>
21036     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21037     *  drag events to all the View objects in your application that are currently visible. It does
21038     *  this either by calling the View object's drag listener (an implementation of
21039     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21040     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21041     *  Both are passed a {@link android.view.DragEvent} object that has a
21042     *  {@link android.view.DragEvent#getAction()} value of
21043     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21044     * </p>
21045     * <p>
21046     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21047     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21048     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21049     * to the View the user selected for dragging.
21050     * </p>
21051     * @param data A {@link android.content.ClipData} object pointing to the data to be
21052     * transferred by the drag and drop operation.
21053     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21054     * drag shadow.
21055     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21056     * drop operation. When dispatching drag events to views in the same activity this object
21057     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21058     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21059     * will return null).
21060     * <p>
21061     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21062     * to the target Views. For example, it can contain flags that differentiate between a
21063     * a copy operation and a move operation.
21064     * </p>
21065     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21066     * flags, or any combination of the following:
21067     *     <ul>
21068     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21069     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21070     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21071     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21072     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21073     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21074     *     </ul>
21075     * @return {@code true} if the method completes successfully, or
21076     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21077     * do a drag, and so no drag operation is in progress.
21078     */
21079    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21080            Object myLocalState, int flags) {
21081        if (ViewDebug.DEBUG_DRAG) {
21082            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21083        }
21084        if (mAttachInfo == null) {
21085            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21086            return false;
21087        }
21088
21089        if (data != null) {
21090            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21091        }
21092
21093        boolean okay = false;
21094
21095        Point shadowSize = new Point();
21096        Point shadowTouchPoint = new Point();
21097        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21098
21099        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21100                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21101            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21102        }
21103
21104        if (ViewDebug.DEBUG_DRAG) {
21105            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21106                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21107        }
21108        if (mAttachInfo.mDragSurface != null) {
21109            mAttachInfo.mDragSurface.release();
21110        }
21111        mAttachInfo.mDragSurface = new Surface();
21112        try {
21113            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21114                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21115            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21116                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21117            if (mAttachInfo.mDragToken != null) {
21118                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21119                try {
21120                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21121                    shadowBuilder.onDrawShadow(canvas);
21122                } finally {
21123                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21124                }
21125
21126                final ViewRootImpl root = getViewRootImpl();
21127
21128                // Cache the local state object for delivery with DragEvents
21129                root.setLocalDragState(myLocalState);
21130
21131                // repurpose 'shadowSize' for the last touch point
21132                root.getLastTouchPoint(shadowSize);
21133
21134                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21135                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21136                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21137                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21138            }
21139        } catch (Exception e) {
21140            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21141            mAttachInfo.mDragSurface.destroy();
21142            mAttachInfo.mDragSurface = null;
21143        }
21144
21145        return okay;
21146    }
21147
21148    /**
21149     * Cancels an ongoing drag and drop operation.
21150     * <p>
21151     * A {@link android.view.DragEvent} object with
21152     * {@link android.view.DragEvent#getAction()} value of
21153     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21154     * {@link android.view.DragEvent#getResult()} value of {@code false}
21155     * will be sent to every
21156     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21157     * even if they are not currently visible.
21158     * </p>
21159     * <p>
21160     * This method can be called on any View in the same window as the View on which
21161     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21162     * was called.
21163     * </p>
21164     */
21165    public final void cancelDragAndDrop() {
21166        if (ViewDebug.DEBUG_DRAG) {
21167            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21168        }
21169        if (mAttachInfo == null) {
21170            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21171            return;
21172        }
21173        if (mAttachInfo.mDragToken != null) {
21174            try {
21175                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21176            } catch (Exception e) {
21177                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21178            }
21179            mAttachInfo.mDragToken = null;
21180        } else {
21181            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21182        }
21183    }
21184
21185    /**
21186     * Updates the drag shadow for the ongoing drag and drop operation.
21187     *
21188     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21189     * new drag shadow.
21190     */
21191    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21192        if (ViewDebug.DEBUG_DRAG) {
21193            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21194        }
21195        if (mAttachInfo == null) {
21196            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21197            return;
21198        }
21199        if (mAttachInfo.mDragToken != null) {
21200            try {
21201                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21202                try {
21203                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21204                    shadowBuilder.onDrawShadow(canvas);
21205                } finally {
21206                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21207                }
21208            } catch (Exception e) {
21209                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21210            }
21211        } else {
21212            Log.e(VIEW_LOG_TAG, "No active drag");
21213        }
21214    }
21215
21216    /**
21217     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21218     * between {startX, startY} and the new cursor positon.
21219     * @param startX horizontal coordinate where the move started.
21220     * @param startY vertical coordinate where the move started.
21221     * @return whether moving was started successfully.
21222     * @hide
21223     */
21224    public final boolean startMovingTask(float startX, float startY) {
21225        if (ViewDebug.DEBUG_POSITIONING) {
21226            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21227        }
21228        try {
21229            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21230        } catch (RemoteException e) {
21231            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21232        }
21233        return false;
21234    }
21235
21236    /**
21237     * Handles drag events sent by the system following a call to
21238     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21239     * startDragAndDrop()}.
21240     *<p>
21241     * When the system calls this method, it passes a
21242     * {@link android.view.DragEvent} object. A call to
21243     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21244     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21245     * operation.
21246     * @param event The {@link android.view.DragEvent} sent by the system.
21247     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21248     * in DragEvent, indicating the type of drag event represented by this object.
21249     * @return {@code true} if the method was successful, otherwise {@code false}.
21250     * <p>
21251     *  The method should return {@code true} in response to an action type of
21252     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21253     *  operation.
21254     * </p>
21255     * <p>
21256     *  The method should also return {@code true} in response to an action type of
21257     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21258     *  {@code false} if it didn't.
21259     * </p>
21260     * <p>
21261     *  For all other events, the return value is ignored.
21262     * </p>
21263     */
21264    public boolean onDragEvent(DragEvent event) {
21265        return false;
21266    }
21267
21268    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21269    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21270        return callDragEventHandler(event);
21271    }
21272
21273    /**
21274     * Detects if this View is enabled and has a drag event listener.
21275     * If both are true, then it calls the drag event listener with the
21276     * {@link android.view.DragEvent} it received. If the drag event listener returns
21277     * {@code true}, then dispatchDragEvent() returns {@code true}.
21278     * <p>
21279     * For all other cases, the method calls the
21280     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21281     * method and returns its result.
21282     * </p>
21283     * <p>
21284     * This ensures that a drag event is always consumed, even if the View does not have a drag
21285     * event listener. However, if the View has a listener and the listener returns true, then
21286     * onDragEvent() is not called.
21287     * </p>
21288     */
21289    public boolean dispatchDragEvent(DragEvent event) {
21290        event.mEventHandlerWasCalled = true;
21291        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21292            event.mAction == DragEvent.ACTION_DROP) {
21293            // About to deliver an event with coordinates to this view. Notify that now this view
21294            // has drag focus. This will send exit/enter events as needed.
21295            getViewRootImpl().setDragFocus(this, event);
21296        }
21297        return callDragEventHandler(event);
21298    }
21299
21300    final boolean callDragEventHandler(DragEvent event) {
21301        final boolean result;
21302
21303        ListenerInfo li = mListenerInfo;
21304        //noinspection SimplifiableIfStatement
21305        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21306                && li.mOnDragListener.onDrag(this, event)) {
21307            result = true;
21308        } else {
21309            result = onDragEvent(event);
21310        }
21311
21312        switch (event.mAction) {
21313            case DragEvent.ACTION_DRAG_ENTERED: {
21314                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21315                refreshDrawableState();
21316            } break;
21317            case DragEvent.ACTION_DRAG_EXITED: {
21318                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21319                refreshDrawableState();
21320            } break;
21321            case DragEvent.ACTION_DRAG_ENDED: {
21322                mPrivateFlags2 &= ~View.DRAG_MASK;
21323                refreshDrawableState();
21324            } break;
21325        }
21326
21327        return result;
21328    }
21329
21330    boolean canAcceptDrag() {
21331        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21332    }
21333
21334    /**
21335     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21336     * it is ever exposed at all.
21337     * @hide
21338     */
21339    public void onCloseSystemDialogs(String reason) {
21340    }
21341
21342    /**
21343     * Given a Drawable whose bounds have been set to draw into this view,
21344     * update a Region being computed for
21345     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21346     * that any non-transparent parts of the Drawable are removed from the
21347     * given transparent region.
21348     *
21349     * @param dr The Drawable whose transparency is to be applied to the region.
21350     * @param region A Region holding the current transparency information,
21351     * where any parts of the region that are set are considered to be
21352     * transparent.  On return, this region will be modified to have the
21353     * transparency information reduced by the corresponding parts of the
21354     * Drawable that are not transparent.
21355     * {@hide}
21356     */
21357    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21358        if (DBG) {
21359            Log.i("View", "Getting transparent region for: " + this);
21360        }
21361        final Region r = dr.getTransparentRegion();
21362        final Rect db = dr.getBounds();
21363        final AttachInfo attachInfo = mAttachInfo;
21364        if (r != null && attachInfo != null) {
21365            final int w = getRight()-getLeft();
21366            final int h = getBottom()-getTop();
21367            if (db.left > 0) {
21368                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21369                r.op(0, 0, db.left, h, Region.Op.UNION);
21370            }
21371            if (db.right < w) {
21372                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21373                r.op(db.right, 0, w, h, Region.Op.UNION);
21374            }
21375            if (db.top > 0) {
21376                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21377                r.op(0, 0, w, db.top, Region.Op.UNION);
21378            }
21379            if (db.bottom < h) {
21380                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21381                r.op(0, db.bottom, w, h, Region.Op.UNION);
21382            }
21383            final int[] location = attachInfo.mTransparentLocation;
21384            getLocationInWindow(location);
21385            r.translate(location[0], location[1]);
21386            region.op(r, Region.Op.INTERSECT);
21387        } else {
21388            region.op(db, Region.Op.DIFFERENCE);
21389        }
21390    }
21391
21392    private void checkForLongClick(int delayOffset, float x, float y) {
21393        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21394            mHasPerformedLongPress = false;
21395
21396            if (mPendingCheckForLongPress == null) {
21397                mPendingCheckForLongPress = new CheckForLongPress();
21398            }
21399            mPendingCheckForLongPress.setAnchor(x, y);
21400            mPendingCheckForLongPress.rememberWindowAttachCount();
21401            mPendingCheckForLongPress.rememberPressedState();
21402            postDelayed(mPendingCheckForLongPress,
21403                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21404        }
21405    }
21406
21407    /**
21408     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21409     * LayoutInflater} class, which provides a full range of options for view inflation.
21410     *
21411     * @param context The Context object for your activity or application.
21412     * @param resource The resource ID to inflate
21413     * @param root A view group that will be the parent.  Used to properly inflate the
21414     * layout_* parameters.
21415     * @see LayoutInflater
21416     */
21417    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21418        LayoutInflater factory = LayoutInflater.from(context);
21419        return factory.inflate(resource, root);
21420    }
21421
21422    /**
21423     * Scroll the view with standard behavior for scrolling beyond the normal
21424     * content boundaries. Views that call this method should override
21425     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21426     * results of an over-scroll operation.
21427     *
21428     * Views can use this method to handle any touch or fling-based scrolling.
21429     *
21430     * @param deltaX Change in X in pixels
21431     * @param deltaY Change in Y in pixels
21432     * @param scrollX Current X scroll value in pixels before applying deltaX
21433     * @param scrollY Current Y scroll value in pixels before applying deltaY
21434     * @param scrollRangeX Maximum content scroll range along the X axis
21435     * @param scrollRangeY Maximum content scroll range along the Y axis
21436     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21437     *          along the X axis.
21438     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21439     *          along the Y axis.
21440     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21441     * @return true if scrolling was clamped to an over-scroll boundary along either
21442     *          axis, false otherwise.
21443     */
21444    @SuppressWarnings({"UnusedParameters"})
21445    protected boolean overScrollBy(int deltaX, int deltaY,
21446            int scrollX, int scrollY,
21447            int scrollRangeX, int scrollRangeY,
21448            int maxOverScrollX, int maxOverScrollY,
21449            boolean isTouchEvent) {
21450        final int overScrollMode = mOverScrollMode;
21451        final boolean canScrollHorizontal =
21452                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21453        final boolean canScrollVertical =
21454                computeVerticalScrollRange() > computeVerticalScrollExtent();
21455        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21456                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21457        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21458                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21459
21460        int newScrollX = scrollX + deltaX;
21461        if (!overScrollHorizontal) {
21462            maxOverScrollX = 0;
21463        }
21464
21465        int newScrollY = scrollY + deltaY;
21466        if (!overScrollVertical) {
21467            maxOverScrollY = 0;
21468        }
21469
21470        // Clamp values if at the limits and record
21471        final int left = -maxOverScrollX;
21472        final int right = maxOverScrollX + scrollRangeX;
21473        final int top = -maxOverScrollY;
21474        final int bottom = maxOverScrollY + scrollRangeY;
21475
21476        boolean clampedX = false;
21477        if (newScrollX > right) {
21478            newScrollX = right;
21479            clampedX = true;
21480        } else if (newScrollX < left) {
21481            newScrollX = left;
21482            clampedX = true;
21483        }
21484
21485        boolean clampedY = false;
21486        if (newScrollY > bottom) {
21487            newScrollY = bottom;
21488            clampedY = true;
21489        } else if (newScrollY < top) {
21490            newScrollY = top;
21491            clampedY = true;
21492        }
21493
21494        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21495
21496        return clampedX || clampedY;
21497    }
21498
21499    /**
21500     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21501     * respond to the results of an over-scroll operation.
21502     *
21503     * @param scrollX New X scroll value in pixels
21504     * @param scrollY New Y scroll value in pixels
21505     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21506     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21507     */
21508    protected void onOverScrolled(int scrollX, int scrollY,
21509            boolean clampedX, boolean clampedY) {
21510        // Intentionally empty.
21511    }
21512
21513    /**
21514     * Returns the over-scroll mode for this view. The result will be
21515     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21516     * (allow over-scrolling only if the view content is larger than the container),
21517     * or {@link #OVER_SCROLL_NEVER}.
21518     *
21519     * @return This view's over-scroll mode.
21520     */
21521    public int getOverScrollMode() {
21522        return mOverScrollMode;
21523    }
21524
21525    /**
21526     * Set the over-scroll mode for this view. Valid over-scroll modes are
21527     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21528     * (allow over-scrolling only if the view content is larger than the container),
21529     * or {@link #OVER_SCROLL_NEVER}.
21530     *
21531     * Setting the over-scroll mode of a view will have an effect only if the
21532     * view is capable of scrolling.
21533     *
21534     * @param overScrollMode The new over-scroll mode for this view.
21535     */
21536    public void setOverScrollMode(int overScrollMode) {
21537        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21538                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21539                overScrollMode != OVER_SCROLL_NEVER) {
21540            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21541        }
21542        mOverScrollMode = overScrollMode;
21543    }
21544
21545    /**
21546     * Enable or disable nested scrolling for this view.
21547     *
21548     * <p>If this property is set to true the view will be permitted to initiate nested
21549     * scrolling operations with a compatible parent view in the current hierarchy. If this
21550     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21551     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21552     * the nested scroll.</p>
21553     *
21554     * @param enabled true to enable nested scrolling, false to disable
21555     *
21556     * @see #isNestedScrollingEnabled()
21557     */
21558    public void setNestedScrollingEnabled(boolean enabled) {
21559        if (enabled) {
21560            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21561        } else {
21562            stopNestedScroll();
21563            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21564        }
21565    }
21566
21567    /**
21568     * Returns true if nested scrolling is enabled for this view.
21569     *
21570     * <p>If nested scrolling is enabled and this View class implementation supports it,
21571     * this view will act as a nested scrolling child view when applicable, forwarding data
21572     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21573     * parent.</p>
21574     *
21575     * @return true if nested scrolling is enabled
21576     *
21577     * @see #setNestedScrollingEnabled(boolean)
21578     */
21579    public boolean isNestedScrollingEnabled() {
21580        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21581                PFLAG3_NESTED_SCROLLING_ENABLED;
21582    }
21583
21584    /**
21585     * Begin a nestable scroll operation along the given axes.
21586     *
21587     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21588     *
21589     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21590     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21591     * In the case of touch scrolling the nested scroll will be terminated automatically in
21592     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21593     * In the event of programmatic scrolling the caller must explicitly call
21594     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21595     *
21596     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21597     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21598     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21599     *
21600     * <p>At each incremental step of the scroll the caller should invoke
21601     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21602     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21603     * parent at least partially consumed the scroll and the caller should adjust the amount it
21604     * scrolls by.</p>
21605     *
21606     * <p>After applying the remainder of the scroll delta the caller should invoke
21607     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21608     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21609     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21610     * </p>
21611     *
21612     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21613     *             {@link #SCROLL_AXIS_VERTICAL}.
21614     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21615     *         the current gesture.
21616     *
21617     * @see #stopNestedScroll()
21618     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21619     * @see #dispatchNestedScroll(int, int, int, int, int[])
21620     */
21621    public boolean startNestedScroll(int axes) {
21622        if (hasNestedScrollingParent()) {
21623            // Already in progress
21624            return true;
21625        }
21626        if (isNestedScrollingEnabled()) {
21627            ViewParent p = getParent();
21628            View child = this;
21629            while (p != null) {
21630                try {
21631                    if (p.onStartNestedScroll(child, this, axes)) {
21632                        mNestedScrollingParent = p;
21633                        p.onNestedScrollAccepted(child, this, axes);
21634                        return true;
21635                    }
21636                } catch (AbstractMethodError e) {
21637                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21638                            "method onStartNestedScroll", e);
21639                    // Allow the search upward to continue
21640                }
21641                if (p instanceof View) {
21642                    child = (View) p;
21643                }
21644                p = p.getParent();
21645            }
21646        }
21647        return false;
21648    }
21649
21650    /**
21651     * Stop a nested scroll in progress.
21652     *
21653     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21654     *
21655     * @see #startNestedScroll(int)
21656     */
21657    public void stopNestedScroll() {
21658        if (mNestedScrollingParent != null) {
21659            mNestedScrollingParent.onStopNestedScroll(this);
21660            mNestedScrollingParent = null;
21661        }
21662    }
21663
21664    /**
21665     * Returns true if this view has a nested scrolling parent.
21666     *
21667     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21668     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21669     *
21670     * @return whether this view has a nested scrolling parent
21671     */
21672    public boolean hasNestedScrollingParent() {
21673        return mNestedScrollingParent != null;
21674    }
21675
21676    /**
21677     * Dispatch one step of a nested scroll in progress.
21678     *
21679     * <p>Implementations of views that support nested scrolling should call this to report
21680     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21681     * is not currently in progress or nested scrolling is not
21682     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21683     *
21684     * <p>Compatible View implementations should also call
21685     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21686     * consuming a component of the scroll event themselves.</p>
21687     *
21688     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21689     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21690     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21691     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21692     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21693     *                       in local view coordinates of this view from before this operation
21694     *                       to after it completes. View implementations may use this to adjust
21695     *                       expected input coordinate tracking.
21696     * @return true if the event was dispatched, false if it could not be dispatched.
21697     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21698     */
21699    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21700            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21701        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21702            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21703                int startX = 0;
21704                int startY = 0;
21705                if (offsetInWindow != null) {
21706                    getLocationInWindow(offsetInWindow);
21707                    startX = offsetInWindow[0];
21708                    startY = offsetInWindow[1];
21709                }
21710
21711                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21712                        dxUnconsumed, dyUnconsumed);
21713
21714                if (offsetInWindow != null) {
21715                    getLocationInWindow(offsetInWindow);
21716                    offsetInWindow[0] -= startX;
21717                    offsetInWindow[1] -= startY;
21718                }
21719                return true;
21720            } else if (offsetInWindow != null) {
21721                // No motion, no dispatch. Keep offsetInWindow up to date.
21722                offsetInWindow[0] = 0;
21723                offsetInWindow[1] = 0;
21724            }
21725        }
21726        return false;
21727    }
21728
21729    /**
21730     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21731     *
21732     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21733     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21734     * scrolling operation to consume some or all of the scroll operation before the child view
21735     * consumes it.</p>
21736     *
21737     * @param dx Horizontal scroll distance in pixels
21738     * @param dy Vertical scroll distance in pixels
21739     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21740     *                 and consumed[1] the consumed dy.
21741     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21742     *                       in local view coordinates of this view from before this operation
21743     *                       to after it completes. View implementations may use this to adjust
21744     *                       expected input coordinate tracking.
21745     * @return true if the parent consumed some or all of the scroll delta
21746     * @see #dispatchNestedScroll(int, int, int, int, int[])
21747     */
21748    public boolean dispatchNestedPreScroll(int dx, int dy,
21749            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21750        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21751            if (dx != 0 || dy != 0) {
21752                int startX = 0;
21753                int startY = 0;
21754                if (offsetInWindow != null) {
21755                    getLocationInWindow(offsetInWindow);
21756                    startX = offsetInWindow[0];
21757                    startY = offsetInWindow[1];
21758                }
21759
21760                if (consumed == null) {
21761                    if (mTempNestedScrollConsumed == null) {
21762                        mTempNestedScrollConsumed = new int[2];
21763                    }
21764                    consumed = mTempNestedScrollConsumed;
21765                }
21766                consumed[0] = 0;
21767                consumed[1] = 0;
21768                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21769
21770                if (offsetInWindow != null) {
21771                    getLocationInWindow(offsetInWindow);
21772                    offsetInWindow[0] -= startX;
21773                    offsetInWindow[1] -= startY;
21774                }
21775                return consumed[0] != 0 || consumed[1] != 0;
21776            } else if (offsetInWindow != null) {
21777                offsetInWindow[0] = 0;
21778                offsetInWindow[1] = 0;
21779            }
21780        }
21781        return false;
21782    }
21783
21784    /**
21785     * Dispatch a fling to a nested scrolling parent.
21786     *
21787     * <p>This method should be used to indicate that a nested scrolling child has detected
21788     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21789     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21790     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21791     * along a scrollable axis.</p>
21792     *
21793     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21794     * its own content, it can use this method to delegate the fling to its nested scrolling
21795     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21796     *
21797     * @param velocityX Horizontal fling velocity in pixels per second
21798     * @param velocityY Vertical fling velocity in pixels per second
21799     * @param consumed true if the child consumed the fling, false otherwise
21800     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21801     */
21802    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21803        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21804            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21805        }
21806        return false;
21807    }
21808
21809    /**
21810     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21811     *
21812     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21813     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21814     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21815     * before the child view consumes it. If this method returns <code>true</code>, a nested
21816     * parent view consumed the fling and this view should not scroll as a result.</p>
21817     *
21818     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21819     * the fling at a time. If a parent view consumed the fling this method will return false.
21820     * Custom view implementations should account for this in two ways:</p>
21821     *
21822     * <ul>
21823     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21824     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21825     *     position regardless.</li>
21826     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21827     *     even to settle back to a valid idle position.</li>
21828     * </ul>
21829     *
21830     * <p>Views should also not offer fling velocities to nested parent views along an axis
21831     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21832     * should not offer a horizontal fling velocity to its parents since scrolling along that
21833     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21834     *
21835     * @param velocityX Horizontal fling velocity in pixels per second
21836     * @param velocityY Vertical fling velocity in pixels per second
21837     * @return true if a nested scrolling parent consumed the fling
21838     */
21839    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21840        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21841            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21842        }
21843        return false;
21844    }
21845
21846    /**
21847     * Gets a scale factor that determines the distance the view should scroll
21848     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21849     * @return The vertical scroll scale factor.
21850     * @hide
21851     */
21852    protected float getVerticalScrollFactor() {
21853        if (mVerticalScrollFactor == 0) {
21854            TypedValue outValue = new TypedValue();
21855            if (!mContext.getTheme().resolveAttribute(
21856                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21857                throw new IllegalStateException(
21858                        "Expected theme to define listPreferredItemHeight.");
21859            }
21860            mVerticalScrollFactor = outValue.getDimension(
21861                    mContext.getResources().getDisplayMetrics());
21862        }
21863        return mVerticalScrollFactor;
21864    }
21865
21866    /**
21867     * Gets a scale factor that determines the distance the view should scroll
21868     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21869     * @return The horizontal scroll scale factor.
21870     * @hide
21871     */
21872    protected float getHorizontalScrollFactor() {
21873        // TODO: Should use something else.
21874        return getVerticalScrollFactor();
21875    }
21876
21877    /**
21878     * Return the value specifying the text direction or policy that was set with
21879     * {@link #setTextDirection(int)}.
21880     *
21881     * @return the defined text direction. It can be one of:
21882     *
21883     * {@link #TEXT_DIRECTION_INHERIT},
21884     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21885     * {@link #TEXT_DIRECTION_ANY_RTL},
21886     * {@link #TEXT_DIRECTION_LTR},
21887     * {@link #TEXT_DIRECTION_RTL},
21888     * {@link #TEXT_DIRECTION_LOCALE},
21889     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21890     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21891     *
21892     * @attr ref android.R.styleable#View_textDirection
21893     *
21894     * @hide
21895     */
21896    @ViewDebug.ExportedProperty(category = "text", mapping = {
21897            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21898            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21899            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21900            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21901            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21902            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21903            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21904            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21905    })
21906    public int getRawTextDirection() {
21907        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21908    }
21909
21910    /**
21911     * Set the text direction.
21912     *
21913     * @param textDirection the direction to set. Should be one of:
21914     *
21915     * {@link #TEXT_DIRECTION_INHERIT},
21916     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21917     * {@link #TEXT_DIRECTION_ANY_RTL},
21918     * {@link #TEXT_DIRECTION_LTR},
21919     * {@link #TEXT_DIRECTION_RTL},
21920     * {@link #TEXT_DIRECTION_LOCALE}
21921     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21922     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21923     *
21924     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21925     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21926     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21927     *
21928     * @attr ref android.R.styleable#View_textDirection
21929     */
21930    public void setTextDirection(int textDirection) {
21931        if (getRawTextDirection() != textDirection) {
21932            // Reset the current text direction and the resolved one
21933            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21934            resetResolvedTextDirection();
21935            // Set the new text direction
21936            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21937            // Do resolution
21938            resolveTextDirection();
21939            // Notify change
21940            onRtlPropertiesChanged(getLayoutDirection());
21941            // Refresh
21942            requestLayout();
21943            invalidate(true);
21944        }
21945    }
21946
21947    /**
21948     * Return the resolved text direction.
21949     *
21950     * @return the resolved text direction. Returns one of:
21951     *
21952     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21953     * {@link #TEXT_DIRECTION_ANY_RTL},
21954     * {@link #TEXT_DIRECTION_LTR},
21955     * {@link #TEXT_DIRECTION_RTL},
21956     * {@link #TEXT_DIRECTION_LOCALE},
21957     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21958     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21959     *
21960     * @attr ref android.R.styleable#View_textDirection
21961     */
21962    @ViewDebug.ExportedProperty(category = "text", mapping = {
21963            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21964            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21965            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21966            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21967            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21968            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21969            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21970            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21971    })
21972    public int getTextDirection() {
21973        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21974    }
21975
21976    /**
21977     * Resolve the text direction.
21978     *
21979     * @return true if resolution has been done, false otherwise.
21980     *
21981     * @hide
21982     */
21983    public boolean resolveTextDirection() {
21984        // Reset any previous text direction resolution
21985        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21986
21987        if (hasRtlSupport()) {
21988            // Set resolved text direction flag depending on text direction flag
21989            final int textDirection = getRawTextDirection();
21990            switch(textDirection) {
21991                case TEXT_DIRECTION_INHERIT:
21992                    if (!canResolveTextDirection()) {
21993                        // We cannot do the resolution if there is no parent, so use the default one
21994                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21995                        // Resolution will need to happen again later
21996                        return false;
21997                    }
21998
21999                    // Parent has not yet resolved, so we still return the default
22000                    try {
22001                        if (!mParent.isTextDirectionResolved()) {
22002                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22003                            // Resolution will need to happen again later
22004                            return false;
22005                        }
22006                    } catch (AbstractMethodError e) {
22007                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22008                                " does not fully implement ViewParent", e);
22009                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22010                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22011                        return true;
22012                    }
22013
22014                    // Set current resolved direction to the same value as the parent's one
22015                    int parentResolvedDirection;
22016                    try {
22017                        parentResolvedDirection = mParent.getTextDirection();
22018                    } catch (AbstractMethodError e) {
22019                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22020                                " does not fully implement ViewParent", e);
22021                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22022                    }
22023                    switch (parentResolvedDirection) {
22024                        case TEXT_DIRECTION_FIRST_STRONG:
22025                        case TEXT_DIRECTION_ANY_RTL:
22026                        case TEXT_DIRECTION_LTR:
22027                        case TEXT_DIRECTION_RTL:
22028                        case TEXT_DIRECTION_LOCALE:
22029                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22030                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22031                            mPrivateFlags2 |=
22032                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22033                            break;
22034                        default:
22035                            // Default resolved direction is "first strong" heuristic
22036                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22037                    }
22038                    break;
22039                case TEXT_DIRECTION_FIRST_STRONG:
22040                case TEXT_DIRECTION_ANY_RTL:
22041                case TEXT_DIRECTION_LTR:
22042                case TEXT_DIRECTION_RTL:
22043                case TEXT_DIRECTION_LOCALE:
22044                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22045                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22046                    // Resolved direction is the same as text direction
22047                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22048                    break;
22049                default:
22050                    // Default resolved direction is "first strong" heuristic
22051                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22052            }
22053        } else {
22054            // Default resolved direction is "first strong" heuristic
22055            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22056        }
22057
22058        // Set to resolved
22059        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22060        return true;
22061    }
22062
22063    /**
22064     * Check if text direction resolution can be done.
22065     *
22066     * @return true if text direction resolution can be done otherwise return false.
22067     */
22068    public boolean canResolveTextDirection() {
22069        switch (getRawTextDirection()) {
22070            case TEXT_DIRECTION_INHERIT:
22071                if (mParent != null) {
22072                    try {
22073                        return mParent.canResolveTextDirection();
22074                    } catch (AbstractMethodError e) {
22075                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22076                                " does not fully implement ViewParent", e);
22077                    }
22078                }
22079                return false;
22080
22081            default:
22082                return true;
22083        }
22084    }
22085
22086    /**
22087     * Reset resolved text direction. Text direction will be resolved during a call to
22088     * {@link #onMeasure(int, int)}.
22089     *
22090     * @hide
22091     */
22092    public void resetResolvedTextDirection() {
22093        // Reset any previous text direction resolution
22094        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22095        // Set to default value
22096        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22097    }
22098
22099    /**
22100     * @return true if text direction is inherited.
22101     *
22102     * @hide
22103     */
22104    public boolean isTextDirectionInherited() {
22105        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22106    }
22107
22108    /**
22109     * @return true if text direction is resolved.
22110     */
22111    public boolean isTextDirectionResolved() {
22112        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22113    }
22114
22115    /**
22116     * Return the value specifying the text alignment or policy that was set with
22117     * {@link #setTextAlignment(int)}.
22118     *
22119     * @return the defined text alignment. It can be one of:
22120     *
22121     * {@link #TEXT_ALIGNMENT_INHERIT},
22122     * {@link #TEXT_ALIGNMENT_GRAVITY},
22123     * {@link #TEXT_ALIGNMENT_CENTER},
22124     * {@link #TEXT_ALIGNMENT_TEXT_START},
22125     * {@link #TEXT_ALIGNMENT_TEXT_END},
22126     * {@link #TEXT_ALIGNMENT_VIEW_START},
22127     * {@link #TEXT_ALIGNMENT_VIEW_END}
22128     *
22129     * @attr ref android.R.styleable#View_textAlignment
22130     *
22131     * @hide
22132     */
22133    @ViewDebug.ExportedProperty(category = "text", mapping = {
22134            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22135            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22136            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22137            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22138            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22139            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22140            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22141    })
22142    @TextAlignment
22143    public int getRawTextAlignment() {
22144        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22145    }
22146
22147    /**
22148     * Set the text alignment.
22149     *
22150     * @param textAlignment The text alignment to set. Should be one of
22151     *
22152     * {@link #TEXT_ALIGNMENT_INHERIT},
22153     * {@link #TEXT_ALIGNMENT_GRAVITY},
22154     * {@link #TEXT_ALIGNMENT_CENTER},
22155     * {@link #TEXT_ALIGNMENT_TEXT_START},
22156     * {@link #TEXT_ALIGNMENT_TEXT_END},
22157     * {@link #TEXT_ALIGNMENT_VIEW_START},
22158     * {@link #TEXT_ALIGNMENT_VIEW_END}
22159     *
22160     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22161     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22162     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22163     *
22164     * @attr ref android.R.styleable#View_textAlignment
22165     */
22166    public void setTextAlignment(@TextAlignment int textAlignment) {
22167        if (textAlignment != getRawTextAlignment()) {
22168            // Reset the current and resolved text alignment
22169            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22170            resetResolvedTextAlignment();
22171            // Set the new text alignment
22172            mPrivateFlags2 |=
22173                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22174            // Do resolution
22175            resolveTextAlignment();
22176            // Notify change
22177            onRtlPropertiesChanged(getLayoutDirection());
22178            // Refresh
22179            requestLayout();
22180            invalidate(true);
22181        }
22182    }
22183
22184    /**
22185     * Return the resolved text alignment.
22186     *
22187     * @return the resolved text alignment. Returns one of:
22188     *
22189     * {@link #TEXT_ALIGNMENT_GRAVITY},
22190     * {@link #TEXT_ALIGNMENT_CENTER},
22191     * {@link #TEXT_ALIGNMENT_TEXT_START},
22192     * {@link #TEXT_ALIGNMENT_TEXT_END},
22193     * {@link #TEXT_ALIGNMENT_VIEW_START},
22194     * {@link #TEXT_ALIGNMENT_VIEW_END}
22195     *
22196     * @attr ref android.R.styleable#View_textAlignment
22197     */
22198    @ViewDebug.ExportedProperty(category = "text", mapping = {
22199            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22200            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22201            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22202            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22203            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22204            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22205            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22206    })
22207    @TextAlignment
22208    public int getTextAlignment() {
22209        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22210                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22211    }
22212
22213    /**
22214     * Resolve the text alignment.
22215     *
22216     * @return true if resolution has been done, false otherwise.
22217     *
22218     * @hide
22219     */
22220    public boolean resolveTextAlignment() {
22221        // Reset any previous text alignment resolution
22222        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22223
22224        if (hasRtlSupport()) {
22225            // Set resolved text alignment flag depending on text alignment flag
22226            final int textAlignment = getRawTextAlignment();
22227            switch (textAlignment) {
22228                case TEXT_ALIGNMENT_INHERIT:
22229                    // Check if we can resolve the text alignment
22230                    if (!canResolveTextAlignment()) {
22231                        // We cannot do the resolution if there is no parent so use the default
22232                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22233                        // Resolution will need to happen again later
22234                        return false;
22235                    }
22236
22237                    // Parent has not yet resolved, so we still return the default
22238                    try {
22239                        if (!mParent.isTextAlignmentResolved()) {
22240                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22241                            // Resolution will need to happen again later
22242                            return false;
22243                        }
22244                    } catch (AbstractMethodError e) {
22245                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22246                                " does not fully implement ViewParent", e);
22247                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22248                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22249                        return true;
22250                    }
22251
22252                    int parentResolvedTextAlignment;
22253                    try {
22254                        parentResolvedTextAlignment = mParent.getTextAlignment();
22255                    } catch (AbstractMethodError e) {
22256                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22257                                " does not fully implement ViewParent", e);
22258                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22259                    }
22260                    switch (parentResolvedTextAlignment) {
22261                        case TEXT_ALIGNMENT_GRAVITY:
22262                        case TEXT_ALIGNMENT_TEXT_START:
22263                        case TEXT_ALIGNMENT_TEXT_END:
22264                        case TEXT_ALIGNMENT_CENTER:
22265                        case TEXT_ALIGNMENT_VIEW_START:
22266                        case TEXT_ALIGNMENT_VIEW_END:
22267                            // Resolved text alignment is the same as the parent resolved
22268                            // text alignment
22269                            mPrivateFlags2 |=
22270                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22271                            break;
22272                        default:
22273                            // Use default resolved text alignment
22274                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22275                    }
22276                    break;
22277                case TEXT_ALIGNMENT_GRAVITY:
22278                case TEXT_ALIGNMENT_TEXT_START:
22279                case TEXT_ALIGNMENT_TEXT_END:
22280                case TEXT_ALIGNMENT_CENTER:
22281                case TEXT_ALIGNMENT_VIEW_START:
22282                case TEXT_ALIGNMENT_VIEW_END:
22283                    // Resolved text alignment is the same as text alignment
22284                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22285                    break;
22286                default:
22287                    // Use default resolved text alignment
22288                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22289            }
22290        } else {
22291            // Use default resolved text alignment
22292            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22293        }
22294
22295        // Set the resolved
22296        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22297        return true;
22298    }
22299
22300    /**
22301     * Check if text alignment resolution can be done.
22302     *
22303     * @return true if text alignment resolution can be done otherwise return false.
22304     */
22305    public boolean canResolveTextAlignment() {
22306        switch (getRawTextAlignment()) {
22307            case TEXT_DIRECTION_INHERIT:
22308                if (mParent != null) {
22309                    try {
22310                        return mParent.canResolveTextAlignment();
22311                    } catch (AbstractMethodError e) {
22312                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22313                                " does not fully implement ViewParent", e);
22314                    }
22315                }
22316                return false;
22317
22318            default:
22319                return true;
22320        }
22321    }
22322
22323    /**
22324     * Reset resolved text alignment. Text alignment will be resolved during a call to
22325     * {@link #onMeasure(int, int)}.
22326     *
22327     * @hide
22328     */
22329    public void resetResolvedTextAlignment() {
22330        // Reset any previous text alignment resolution
22331        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22332        // Set to default
22333        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22334    }
22335
22336    /**
22337     * @return true if text alignment is inherited.
22338     *
22339     * @hide
22340     */
22341    public boolean isTextAlignmentInherited() {
22342        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22343    }
22344
22345    /**
22346     * @return true if text alignment is resolved.
22347     */
22348    public boolean isTextAlignmentResolved() {
22349        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22350    }
22351
22352    /**
22353     * Generate a value suitable for use in {@link #setId(int)}.
22354     * This value will not collide with ID values generated at build time by aapt for R.id.
22355     *
22356     * @return a generated ID value
22357     */
22358    public static int generateViewId() {
22359        for (;;) {
22360            final int result = sNextGeneratedId.get();
22361            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22362            int newValue = result + 1;
22363            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22364            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22365                return result;
22366            }
22367        }
22368    }
22369
22370    /**
22371     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22372     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22373     *                           a normal View or a ViewGroup with
22374     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22375     * @hide
22376     */
22377    public void captureTransitioningViews(List<View> transitioningViews) {
22378        if (getVisibility() == View.VISIBLE) {
22379            transitioningViews.add(this);
22380        }
22381    }
22382
22383    /**
22384     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22385     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22386     * @hide
22387     */
22388    public void findNamedViews(Map<String, View> namedElements) {
22389        if (getVisibility() == VISIBLE || mGhostView != null) {
22390            String transitionName = getTransitionName();
22391            if (transitionName != null) {
22392                namedElements.put(transitionName, this);
22393            }
22394        }
22395    }
22396
22397    /**
22398     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22399     * The default implementation does not care the location or event types, but some subclasses
22400     * may use it (such as WebViews).
22401     * @param event The MotionEvent from a mouse
22402     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22403     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22404     * @see PointerIcon
22405     */
22406    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22407        final float x = event.getX(pointerIndex);
22408        final float y = event.getY(pointerIndex);
22409        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22410            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22411        }
22412        return mPointerIcon;
22413    }
22414
22415    /**
22416     * Set the pointer icon for the current view.
22417     * Passing {@code null} will restore the pointer icon to its default value.
22418     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22419     */
22420    public void setPointerIcon(PointerIcon pointerIcon) {
22421        mPointerIcon = pointerIcon;
22422        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22423            return;
22424        }
22425        try {
22426            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22427        } catch (RemoteException e) {
22428        }
22429    }
22430
22431    /**
22432     * Gets the pointer icon for the current view.
22433     */
22434    public PointerIcon getPointerIcon() {
22435        return mPointerIcon;
22436    }
22437
22438    //
22439    // Properties
22440    //
22441    /**
22442     * A Property wrapper around the <code>alpha</code> functionality handled by the
22443     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22444     */
22445    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22446        @Override
22447        public void setValue(View object, float value) {
22448            object.setAlpha(value);
22449        }
22450
22451        @Override
22452        public Float get(View object) {
22453            return object.getAlpha();
22454        }
22455    };
22456
22457    /**
22458     * A Property wrapper around the <code>translationX</code> functionality handled by the
22459     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22460     */
22461    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22462        @Override
22463        public void setValue(View object, float value) {
22464            object.setTranslationX(value);
22465        }
22466
22467                @Override
22468        public Float get(View object) {
22469            return object.getTranslationX();
22470        }
22471    };
22472
22473    /**
22474     * A Property wrapper around the <code>translationY</code> functionality handled by the
22475     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22476     */
22477    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22478        @Override
22479        public void setValue(View object, float value) {
22480            object.setTranslationY(value);
22481        }
22482
22483        @Override
22484        public Float get(View object) {
22485            return object.getTranslationY();
22486        }
22487    };
22488
22489    /**
22490     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22491     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22492     */
22493    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22494        @Override
22495        public void setValue(View object, float value) {
22496            object.setTranslationZ(value);
22497        }
22498
22499        @Override
22500        public Float get(View object) {
22501            return object.getTranslationZ();
22502        }
22503    };
22504
22505    /**
22506     * A Property wrapper around the <code>x</code> functionality handled by the
22507     * {@link View#setX(float)} and {@link View#getX()} methods.
22508     */
22509    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22510        @Override
22511        public void setValue(View object, float value) {
22512            object.setX(value);
22513        }
22514
22515        @Override
22516        public Float get(View object) {
22517            return object.getX();
22518        }
22519    };
22520
22521    /**
22522     * A Property wrapper around the <code>y</code> functionality handled by the
22523     * {@link View#setY(float)} and {@link View#getY()} methods.
22524     */
22525    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22526        @Override
22527        public void setValue(View object, float value) {
22528            object.setY(value);
22529        }
22530
22531        @Override
22532        public Float get(View object) {
22533            return object.getY();
22534        }
22535    };
22536
22537    /**
22538     * A Property wrapper around the <code>z</code> functionality handled by the
22539     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22540     */
22541    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22542        @Override
22543        public void setValue(View object, float value) {
22544            object.setZ(value);
22545        }
22546
22547        @Override
22548        public Float get(View object) {
22549            return object.getZ();
22550        }
22551    };
22552
22553    /**
22554     * A Property wrapper around the <code>rotation</code> functionality handled by the
22555     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22556     */
22557    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22558        @Override
22559        public void setValue(View object, float value) {
22560            object.setRotation(value);
22561        }
22562
22563        @Override
22564        public Float get(View object) {
22565            return object.getRotation();
22566        }
22567    };
22568
22569    /**
22570     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22571     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22572     */
22573    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22574        @Override
22575        public void setValue(View object, float value) {
22576            object.setRotationX(value);
22577        }
22578
22579        @Override
22580        public Float get(View object) {
22581            return object.getRotationX();
22582        }
22583    };
22584
22585    /**
22586     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22587     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22588     */
22589    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22590        @Override
22591        public void setValue(View object, float value) {
22592            object.setRotationY(value);
22593        }
22594
22595        @Override
22596        public Float get(View object) {
22597            return object.getRotationY();
22598        }
22599    };
22600
22601    /**
22602     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22603     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22604     */
22605    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22606        @Override
22607        public void setValue(View object, float value) {
22608            object.setScaleX(value);
22609        }
22610
22611        @Override
22612        public Float get(View object) {
22613            return object.getScaleX();
22614        }
22615    };
22616
22617    /**
22618     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22619     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22620     */
22621    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22622        @Override
22623        public void setValue(View object, float value) {
22624            object.setScaleY(value);
22625        }
22626
22627        @Override
22628        public Float get(View object) {
22629            return object.getScaleY();
22630        }
22631    };
22632
22633    /**
22634     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22635     * Each MeasureSpec represents a requirement for either the width or the height.
22636     * A MeasureSpec is comprised of a size and a mode. There are three possible
22637     * modes:
22638     * <dl>
22639     * <dt>UNSPECIFIED</dt>
22640     * <dd>
22641     * The parent has not imposed any constraint on the child. It can be whatever size
22642     * it wants.
22643     * </dd>
22644     *
22645     * <dt>EXACTLY</dt>
22646     * <dd>
22647     * The parent has determined an exact size for the child. The child is going to be
22648     * given those bounds regardless of how big it wants to be.
22649     * </dd>
22650     *
22651     * <dt>AT_MOST</dt>
22652     * <dd>
22653     * The child can be as large as it wants up to the specified size.
22654     * </dd>
22655     * </dl>
22656     *
22657     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22658     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22659     */
22660    public static class MeasureSpec {
22661        private static final int MODE_SHIFT = 30;
22662        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22663
22664        /** @hide */
22665        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22666        @Retention(RetentionPolicy.SOURCE)
22667        public @interface MeasureSpecMode {}
22668
22669        /**
22670         * Measure specification mode: The parent has not imposed any constraint
22671         * on the child. It can be whatever size it wants.
22672         */
22673        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22674
22675        /**
22676         * Measure specification mode: The parent has determined an exact size
22677         * for the child. The child is going to be given those bounds regardless
22678         * of how big it wants to be.
22679         */
22680        public static final int EXACTLY     = 1 << MODE_SHIFT;
22681
22682        /**
22683         * Measure specification mode: The child can be as large as it wants up
22684         * to the specified size.
22685         */
22686        public static final int AT_MOST     = 2 << MODE_SHIFT;
22687
22688        /**
22689         * Creates a measure specification based on the supplied size and mode.
22690         *
22691         * The mode must always be one of the following:
22692         * <ul>
22693         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22694         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22695         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22696         * </ul>
22697         *
22698         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22699         * implementation was such that the order of arguments did not matter
22700         * and overflow in either value could impact the resulting MeasureSpec.
22701         * {@link android.widget.RelativeLayout} was affected by this bug.
22702         * Apps targeting API levels greater than 17 will get the fixed, more strict
22703         * behavior.</p>
22704         *
22705         * @param size the size of the measure specification
22706         * @param mode the mode of the measure specification
22707         * @return the measure specification based on size and mode
22708         */
22709        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22710                                          @MeasureSpecMode int mode) {
22711            if (sUseBrokenMakeMeasureSpec) {
22712                return size + mode;
22713            } else {
22714                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22715            }
22716        }
22717
22718        /**
22719         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22720         * will automatically get a size of 0. Older apps expect this.
22721         *
22722         * @hide internal use only for compatibility with system widgets and older apps
22723         */
22724        public static int makeSafeMeasureSpec(int size, int mode) {
22725            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22726                return 0;
22727            }
22728            return makeMeasureSpec(size, mode);
22729        }
22730
22731        /**
22732         * Extracts the mode from the supplied measure specification.
22733         *
22734         * @param measureSpec the measure specification to extract the mode from
22735         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22736         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22737         *         {@link android.view.View.MeasureSpec#EXACTLY}
22738         */
22739        @MeasureSpecMode
22740        public static int getMode(int measureSpec) {
22741            //noinspection ResourceType
22742            return (measureSpec & MODE_MASK);
22743        }
22744
22745        /**
22746         * Extracts the size from the supplied measure specification.
22747         *
22748         * @param measureSpec the measure specification to extract the size from
22749         * @return the size in pixels defined in the supplied measure specification
22750         */
22751        public static int getSize(int measureSpec) {
22752            return (measureSpec & ~MODE_MASK);
22753        }
22754
22755        static int adjust(int measureSpec, int delta) {
22756            final int mode = getMode(measureSpec);
22757            int size = getSize(measureSpec);
22758            if (mode == UNSPECIFIED) {
22759                // No need to adjust size for UNSPECIFIED mode.
22760                return makeMeasureSpec(size, UNSPECIFIED);
22761            }
22762            size += delta;
22763            if (size < 0) {
22764                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22765                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22766                size = 0;
22767            }
22768            return makeMeasureSpec(size, mode);
22769        }
22770
22771        /**
22772         * Returns a String representation of the specified measure
22773         * specification.
22774         *
22775         * @param measureSpec the measure specification to convert to a String
22776         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22777         */
22778        public static String toString(int measureSpec) {
22779            int mode = getMode(measureSpec);
22780            int size = getSize(measureSpec);
22781
22782            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22783
22784            if (mode == UNSPECIFIED)
22785                sb.append("UNSPECIFIED ");
22786            else if (mode == EXACTLY)
22787                sb.append("EXACTLY ");
22788            else if (mode == AT_MOST)
22789                sb.append("AT_MOST ");
22790            else
22791                sb.append(mode).append(" ");
22792
22793            sb.append(size);
22794            return sb.toString();
22795        }
22796    }
22797
22798    private final class CheckForLongPress implements Runnable {
22799        private int mOriginalWindowAttachCount;
22800        private float mX;
22801        private float mY;
22802        private boolean mOriginalPressedState;
22803
22804        @Override
22805        public void run() {
22806            if ((mOriginalPressedState == isPressed()) && (mParent != null)
22807                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22808                if (performLongClick(mX, mY)) {
22809                    mHasPerformedLongPress = true;
22810                }
22811            }
22812        }
22813
22814        public void setAnchor(float x, float y) {
22815            mX = x;
22816            mY = y;
22817        }
22818
22819        public void rememberWindowAttachCount() {
22820            mOriginalWindowAttachCount = mWindowAttachCount;
22821        }
22822
22823        public void rememberPressedState() {
22824            mOriginalPressedState = isPressed();
22825        }
22826    }
22827
22828    private final class CheckForTap implements Runnable {
22829        public float x;
22830        public float y;
22831
22832        @Override
22833        public void run() {
22834            mPrivateFlags &= ~PFLAG_PREPRESSED;
22835            setPressed(true, x, y);
22836            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22837        }
22838    }
22839
22840    private final class PerformClick implements Runnable {
22841        @Override
22842        public void run() {
22843            performClick();
22844        }
22845    }
22846
22847    /**
22848     * This method returns a ViewPropertyAnimator object, which can be used to animate
22849     * specific properties on this View.
22850     *
22851     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22852     */
22853    public ViewPropertyAnimator animate() {
22854        if (mAnimator == null) {
22855            mAnimator = new ViewPropertyAnimator(this);
22856        }
22857        return mAnimator;
22858    }
22859
22860    /**
22861     * Sets the name of the View to be used to identify Views in Transitions.
22862     * Names should be unique in the View hierarchy.
22863     *
22864     * @param transitionName The name of the View to uniquely identify it for Transitions.
22865     */
22866    public final void setTransitionName(String transitionName) {
22867        mTransitionName = transitionName;
22868    }
22869
22870    /**
22871     * Returns the name of the View to be used to identify Views in Transitions.
22872     * Names should be unique in the View hierarchy.
22873     *
22874     * <p>This returns null if the View has not been given a name.</p>
22875     *
22876     * @return The name used of the View to be used to identify Views in Transitions or null
22877     * if no name has been given.
22878     */
22879    @ViewDebug.ExportedProperty
22880    public String getTransitionName() {
22881        return mTransitionName;
22882    }
22883
22884    /**
22885     * @hide
22886     */
22887    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22888        // Do nothing.
22889    }
22890
22891    /**
22892     * Interface definition for a callback to be invoked when a hardware key event is
22893     * dispatched to this view. The callback will be invoked before the key event is
22894     * given to the view. This is only useful for hardware keyboards; a software input
22895     * method has no obligation to trigger this listener.
22896     */
22897    public interface OnKeyListener {
22898        /**
22899         * Called when a hardware key is dispatched to a view. This allows listeners to
22900         * get a chance to respond before the target view.
22901         * <p>Key presses in software keyboards will generally NOT trigger this method,
22902         * although some may elect to do so in some situations. Do not assume a
22903         * software input method has to be key-based; even if it is, it may use key presses
22904         * in a different way than you expect, so there is no way to reliably catch soft
22905         * input key presses.
22906         *
22907         * @param v The view the key has been dispatched to.
22908         * @param keyCode The code for the physical key that was pressed
22909         * @param event The KeyEvent object containing full information about
22910         *        the event.
22911         * @return True if the listener has consumed the event, false otherwise.
22912         */
22913        boolean onKey(View v, int keyCode, KeyEvent event);
22914    }
22915
22916    /**
22917     * Interface definition for a callback to be invoked when a touch event is
22918     * dispatched to this view. The callback will be invoked before the touch
22919     * event is given to the view.
22920     */
22921    public interface OnTouchListener {
22922        /**
22923         * Called when a touch event is dispatched to a view. This allows listeners to
22924         * get a chance to respond before the target view.
22925         *
22926         * @param v The view the touch event has been dispatched to.
22927         * @param event The MotionEvent object containing full information about
22928         *        the event.
22929         * @return True if the listener has consumed the event, false otherwise.
22930         */
22931        boolean onTouch(View v, MotionEvent event);
22932    }
22933
22934    /**
22935     * Interface definition for a callback to be invoked when a hover event is
22936     * dispatched to this view. The callback will be invoked before the hover
22937     * event is given to the view.
22938     */
22939    public interface OnHoverListener {
22940        /**
22941         * Called when a hover event is dispatched to a view. This allows listeners to
22942         * get a chance to respond before the target view.
22943         *
22944         * @param v The view the hover event has been dispatched to.
22945         * @param event The MotionEvent object containing full information about
22946         *        the event.
22947         * @return True if the listener has consumed the event, false otherwise.
22948         */
22949        boolean onHover(View v, MotionEvent event);
22950    }
22951
22952    /**
22953     * Interface definition for a callback to be invoked when a generic motion event is
22954     * dispatched to this view. The callback will be invoked before the generic motion
22955     * event is given to the view.
22956     */
22957    public interface OnGenericMotionListener {
22958        /**
22959         * Called when a generic motion event is dispatched to a view. This allows listeners to
22960         * get a chance to respond before the target view.
22961         *
22962         * @param v The view the generic motion event has been dispatched to.
22963         * @param event The MotionEvent object containing full information about
22964         *        the event.
22965         * @return True if the listener has consumed the event, false otherwise.
22966         */
22967        boolean onGenericMotion(View v, MotionEvent event);
22968    }
22969
22970    /**
22971     * Interface definition for a callback to be invoked when a view has been clicked and held.
22972     */
22973    public interface OnLongClickListener {
22974        /**
22975         * Called when a view has been clicked and held.
22976         *
22977         * @param v The view that was clicked and held.
22978         *
22979         * @return true if the callback consumed the long click, false otherwise.
22980         */
22981        boolean onLongClick(View v);
22982    }
22983
22984    /**
22985     * Interface definition for a callback to be invoked when a drag is being dispatched
22986     * to this view.  The callback will be invoked before the hosting view's own
22987     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22988     * onDrag(event) behavior, it should return 'false' from this callback.
22989     *
22990     * <div class="special reference">
22991     * <h3>Developer Guides</h3>
22992     * <p>For a guide to implementing drag and drop features, read the
22993     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22994     * </div>
22995     */
22996    public interface OnDragListener {
22997        /**
22998         * Called when a drag event is dispatched to a view. This allows listeners
22999         * to get a chance to override base View behavior.
23000         *
23001         * @param v The View that received the drag event.
23002         * @param event The {@link android.view.DragEvent} object for the drag event.
23003         * @return {@code true} if the drag event was handled successfully, or {@code false}
23004         * if the drag event was not handled. Note that {@code false} will trigger the View
23005         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23006         */
23007        boolean onDrag(View v, DragEvent event);
23008    }
23009
23010    /**
23011     * Interface definition for a callback to be invoked when the focus state of
23012     * a view changed.
23013     */
23014    public interface OnFocusChangeListener {
23015        /**
23016         * Called when the focus state of a view has changed.
23017         *
23018         * @param v The view whose state has changed.
23019         * @param hasFocus The new focus state of v.
23020         */
23021        void onFocusChange(View v, boolean hasFocus);
23022    }
23023
23024    /**
23025     * Interface definition for a callback to be invoked when a view is clicked.
23026     */
23027    public interface OnClickListener {
23028        /**
23029         * Called when a view has been clicked.
23030         *
23031         * @param v The view that was clicked.
23032         */
23033        void onClick(View v);
23034    }
23035
23036    /**
23037     * Interface definition for a callback to be invoked when a view is context clicked.
23038     */
23039    public interface OnContextClickListener {
23040        /**
23041         * Called when a view is context clicked.
23042         *
23043         * @param v The view that has been context clicked.
23044         * @return true if the callback consumed the context click, false otherwise.
23045         */
23046        boolean onContextClick(View v);
23047    }
23048
23049    /**
23050     * Interface definition for a callback to be invoked when the context menu
23051     * for this view is being built.
23052     */
23053    public interface OnCreateContextMenuListener {
23054        /**
23055         * Called when the context menu for this view is being built. It is not
23056         * safe to hold onto the menu after this method returns.
23057         *
23058         * @param menu The context menu that is being built
23059         * @param v The view for which the context menu is being built
23060         * @param menuInfo Extra information about the item for which the
23061         *            context menu should be shown. This information will vary
23062         *            depending on the class of v.
23063         */
23064        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23065    }
23066
23067    /**
23068     * Interface definition for a callback to be invoked when the status bar changes
23069     * visibility.  This reports <strong>global</strong> changes to the system UI
23070     * state, not what the application is requesting.
23071     *
23072     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23073     */
23074    public interface OnSystemUiVisibilityChangeListener {
23075        /**
23076         * Called when the status bar changes visibility because of a call to
23077         * {@link View#setSystemUiVisibility(int)}.
23078         *
23079         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23080         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23081         * This tells you the <strong>global</strong> state of these UI visibility
23082         * flags, not what your app is currently applying.
23083         */
23084        public void onSystemUiVisibilityChange(int visibility);
23085    }
23086
23087    /**
23088     * Interface definition for a callback to be invoked when this view is attached
23089     * or detached from its window.
23090     */
23091    public interface OnAttachStateChangeListener {
23092        /**
23093         * Called when the view is attached to a window.
23094         * @param v The view that was attached
23095         */
23096        public void onViewAttachedToWindow(View v);
23097        /**
23098         * Called when the view is detached from a window.
23099         * @param v The view that was detached
23100         */
23101        public void onViewDetachedFromWindow(View v);
23102    }
23103
23104    /**
23105     * Listener for applying window insets on a view in a custom way.
23106     *
23107     * <p>Apps may choose to implement this interface if they want to apply custom policy
23108     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23109     * is set, its
23110     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23111     * method will be called instead of the View's own
23112     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23113     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23114     * the View's normal behavior as part of its own.</p>
23115     */
23116    public interface OnApplyWindowInsetsListener {
23117        /**
23118         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23119         * on a View, this listener method will be called instead of the view's own
23120         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23121         *
23122         * @param v The view applying window insets
23123         * @param insets The insets to apply
23124         * @return The insets supplied, minus any insets that were consumed
23125         */
23126        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23127    }
23128
23129    private final class UnsetPressedState implements Runnable {
23130        @Override
23131        public void run() {
23132            setPressed(false);
23133        }
23134    }
23135
23136    /**
23137     * Base class for derived classes that want to save and restore their own
23138     * state in {@link android.view.View#onSaveInstanceState()}.
23139     */
23140    public static class BaseSavedState extends AbsSavedState {
23141        String mStartActivityRequestWhoSaved;
23142
23143        /**
23144         * Constructor used when reading from a parcel. Reads the state of the superclass.
23145         *
23146         * @param source parcel to read from
23147         */
23148        public BaseSavedState(Parcel source) {
23149            this(source, null);
23150        }
23151
23152        /**
23153         * Constructor used when reading from a parcel using a given class loader.
23154         * Reads the state of the superclass.
23155         *
23156         * @param source parcel to read from
23157         * @param loader ClassLoader to use for reading
23158         */
23159        public BaseSavedState(Parcel source, ClassLoader loader) {
23160            super(source, loader);
23161            mStartActivityRequestWhoSaved = source.readString();
23162        }
23163
23164        /**
23165         * Constructor called by derived classes when creating their SavedState objects
23166         *
23167         * @param superState The state of the superclass of this view
23168         */
23169        public BaseSavedState(Parcelable superState) {
23170            super(superState);
23171        }
23172
23173        @Override
23174        public void writeToParcel(Parcel out, int flags) {
23175            super.writeToParcel(out, flags);
23176            out.writeString(mStartActivityRequestWhoSaved);
23177        }
23178
23179        public static final Parcelable.Creator<BaseSavedState> CREATOR
23180                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23181            @Override
23182            public BaseSavedState createFromParcel(Parcel in) {
23183                return new BaseSavedState(in);
23184            }
23185
23186            @Override
23187            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23188                return new BaseSavedState(in, loader);
23189            }
23190
23191            @Override
23192            public BaseSavedState[] newArray(int size) {
23193                return new BaseSavedState[size];
23194            }
23195        };
23196    }
23197
23198    /**
23199     * A set of information given to a view when it is attached to its parent
23200     * window.
23201     */
23202    final static class AttachInfo {
23203        interface Callbacks {
23204            void playSoundEffect(int effectId);
23205            boolean performHapticFeedback(int effectId, boolean always);
23206        }
23207
23208        /**
23209         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23210         * to a Handler. This class contains the target (View) to invalidate and
23211         * the coordinates of the dirty rectangle.
23212         *
23213         * For performance purposes, this class also implements a pool of up to
23214         * POOL_LIMIT objects that get reused. This reduces memory allocations
23215         * whenever possible.
23216         */
23217        static class InvalidateInfo {
23218            private static final int POOL_LIMIT = 10;
23219
23220            private static final SynchronizedPool<InvalidateInfo> sPool =
23221                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23222
23223            View target;
23224
23225            int left;
23226            int top;
23227            int right;
23228            int bottom;
23229
23230            public static InvalidateInfo obtain() {
23231                InvalidateInfo instance = sPool.acquire();
23232                return (instance != null) ? instance : new InvalidateInfo();
23233            }
23234
23235            public void recycle() {
23236                target = null;
23237                sPool.release(this);
23238            }
23239        }
23240
23241        final IWindowSession mSession;
23242
23243        final IWindow mWindow;
23244
23245        final IBinder mWindowToken;
23246
23247        final Display mDisplay;
23248
23249        final Callbacks mRootCallbacks;
23250
23251        IWindowId mIWindowId;
23252        WindowId mWindowId;
23253
23254        /**
23255         * The top view of the hierarchy.
23256         */
23257        View mRootView;
23258
23259        IBinder mPanelParentWindowToken;
23260
23261        boolean mHardwareAccelerated;
23262        boolean mHardwareAccelerationRequested;
23263        ThreadedRenderer mThreadedRenderer;
23264        List<RenderNode> mPendingAnimatingRenderNodes;
23265
23266        /**
23267         * The state of the display to which the window is attached, as reported
23268         * by {@link Display#getState()}.  Note that the display state constants
23269         * declared by {@link Display} do not exactly line up with the screen state
23270         * constants declared by {@link View} (there are more display states than
23271         * screen states).
23272         */
23273        int mDisplayState = Display.STATE_UNKNOWN;
23274
23275        /**
23276         * Scale factor used by the compatibility mode
23277         */
23278        float mApplicationScale;
23279
23280        /**
23281         * Indicates whether the application is in compatibility mode
23282         */
23283        boolean mScalingRequired;
23284
23285        /**
23286         * Left position of this view's window
23287         */
23288        int mWindowLeft;
23289
23290        /**
23291         * Top position of this view's window
23292         */
23293        int mWindowTop;
23294
23295        /**
23296         * Indicates whether views need to use 32-bit drawing caches
23297         */
23298        boolean mUse32BitDrawingCache;
23299
23300        /**
23301         * For windows that are full-screen but using insets to layout inside
23302         * of the screen areas, these are the current insets to appear inside
23303         * the overscan area of the display.
23304         */
23305        final Rect mOverscanInsets = new Rect();
23306
23307        /**
23308         * For windows that are full-screen but using insets to layout inside
23309         * of the screen decorations, these are the current insets for the
23310         * content of the window.
23311         */
23312        final Rect mContentInsets = new Rect();
23313
23314        /**
23315         * For windows that are full-screen but using insets to layout inside
23316         * of the screen decorations, these are the current insets for the
23317         * actual visible parts of the window.
23318         */
23319        final Rect mVisibleInsets = new Rect();
23320
23321        /**
23322         * For windows that are full-screen but using insets to layout inside
23323         * of the screen decorations, these are the current insets for the
23324         * stable system windows.
23325         */
23326        final Rect mStableInsets = new Rect();
23327
23328        /**
23329         * For windows that include areas that are not covered by real surface these are the outsets
23330         * for real surface.
23331         */
23332        final Rect mOutsets = new Rect();
23333
23334        /**
23335         * In multi-window we force show the navigation bar. Because we don't want that the surface
23336         * size changes in this mode, we instead have a flag whether the navigation bar size should
23337         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23338         */
23339        boolean mAlwaysConsumeNavBar;
23340
23341        /**
23342         * The internal insets given by this window.  This value is
23343         * supplied by the client (through
23344         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23345         * be given to the window manager when changed to be used in laying
23346         * out windows behind it.
23347         */
23348        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23349                = new ViewTreeObserver.InternalInsetsInfo();
23350
23351        /**
23352         * Set to true when mGivenInternalInsets is non-empty.
23353         */
23354        boolean mHasNonEmptyGivenInternalInsets;
23355
23356        /**
23357         * All views in the window's hierarchy that serve as scroll containers,
23358         * used to determine if the window can be resized or must be panned
23359         * to adjust for a soft input area.
23360         */
23361        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23362
23363        final KeyEvent.DispatcherState mKeyDispatchState
23364                = new KeyEvent.DispatcherState();
23365
23366        /**
23367         * Indicates whether the view's window currently has the focus.
23368         */
23369        boolean mHasWindowFocus;
23370
23371        /**
23372         * The current visibility of the window.
23373         */
23374        int mWindowVisibility;
23375
23376        /**
23377         * Indicates the time at which drawing started to occur.
23378         */
23379        long mDrawingTime;
23380
23381        /**
23382         * Indicates whether or not ignoring the DIRTY_MASK flags.
23383         */
23384        boolean mIgnoreDirtyState;
23385
23386        /**
23387         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23388         * to avoid clearing that flag prematurely.
23389         */
23390        boolean mSetIgnoreDirtyState = false;
23391
23392        /**
23393         * Indicates whether the view's window is currently in touch mode.
23394         */
23395        boolean mInTouchMode;
23396
23397        /**
23398         * Indicates whether the view has requested unbuffered input dispatching for the current
23399         * event stream.
23400         */
23401        boolean mUnbufferedDispatchRequested;
23402
23403        /**
23404         * Indicates that ViewAncestor should trigger a global layout change
23405         * the next time it performs a traversal
23406         */
23407        boolean mRecomputeGlobalAttributes;
23408
23409        /**
23410         * Always report new attributes at next traversal.
23411         */
23412        boolean mForceReportNewAttributes;
23413
23414        /**
23415         * Set during a traveral if any views want to keep the screen on.
23416         */
23417        boolean mKeepScreenOn;
23418
23419        /**
23420         * Set during a traveral if the light center needs to be updated.
23421         */
23422        boolean mNeedsUpdateLightCenter;
23423
23424        /**
23425         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23426         */
23427        int mSystemUiVisibility;
23428
23429        /**
23430         * Hack to force certain system UI visibility flags to be cleared.
23431         */
23432        int mDisabledSystemUiVisibility;
23433
23434        /**
23435         * Last global system UI visibility reported by the window manager.
23436         */
23437        int mGlobalSystemUiVisibility = -1;
23438
23439        /**
23440         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23441         * attached.
23442         */
23443        boolean mHasSystemUiListeners;
23444
23445        /**
23446         * Set if the window has requested to extend into the overscan region
23447         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23448         */
23449        boolean mOverscanRequested;
23450
23451        /**
23452         * Set if the visibility of any views has changed.
23453         */
23454        boolean mViewVisibilityChanged;
23455
23456        /**
23457         * Set to true if a view has been scrolled.
23458         */
23459        boolean mViewScrollChanged;
23460
23461        /**
23462         * Set to true if high contrast mode enabled
23463         */
23464        boolean mHighContrastText;
23465
23466        /**
23467         * Set to true if a pointer event is currently being handled.
23468         */
23469        boolean mHandlingPointerEvent;
23470
23471        /**
23472         * Global to the view hierarchy used as a temporary for dealing with
23473         * x/y points in the transparent region computations.
23474         */
23475        final int[] mTransparentLocation = new int[2];
23476
23477        /**
23478         * Global to the view hierarchy used as a temporary for dealing with
23479         * x/y points in the ViewGroup.invalidateChild implementation.
23480         */
23481        final int[] mInvalidateChildLocation = new int[2];
23482
23483        /**
23484         * Global to the view hierarchy used as a temporary for dealing with
23485         * computing absolute on-screen location.
23486         */
23487        final int[] mTmpLocation = new int[2];
23488
23489        /**
23490         * Global to the view hierarchy used as a temporary for dealing with
23491         * x/y location when view is transformed.
23492         */
23493        final float[] mTmpTransformLocation = new float[2];
23494
23495        /**
23496         * The view tree observer used to dispatch global events like
23497         * layout, pre-draw, touch mode change, etc.
23498         */
23499        final ViewTreeObserver mTreeObserver;
23500
23501        /**
23502         * A Canvas used by the view hierarchy to perform bitmap caching.
23503         */
23504        Canvas mCanvas;
23505
23506        /**
23507         * The view root impl.
23508         */
23509        final ViewRootImpl mViewRootImpl;
23510
23511        /**
23512         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23513         * handler can be used to pump events in the UI events queue.
23514         */
23515        final Handler mHandler;
23516
23517        /**
23518         * Temporary for use in computing invalidate rectangles while
23519         * calling up the hierarchy.
23520         */
23521        final Rect mTmpInvalRect = new Rect();
23522
23523        /**
23524         * Temporary for use in computing hit areas with transformed views
23525         */
23526        final RectF mTmpTransformRect = new RectF();
23527
23528        /**
23529         * Temporary for use in computing hit areas with transformed views
23530         */
23531        final RectF mTmpTransformRect1 = new RectF();
23532
23533        /**
23534         * Temporary list of rectanges.
23535         */
23536        final List<RectF> mTmpRectList = new ArrayList<>();
23537
23538        /**
23539         * Temporary for use in transforming invalidation rect
23540         */
23541        final Matrix mTmpMatrix = new Matrix();
23542
23543        /**
23544         * Temporary for use in transforming invalidation rect
23545         */
23546        final Transformation mTmpTransformation = new Transformation();
23547
23548        /**
23549         * Temporary for use in querying outlines from OutlineProviders
23550         */
23551        final Outline mTmpOutline = new Outline();
23552
23553        /**
23554         * Temporary list for use in collecting focusable descendents of a view.
23555         */
23556        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23557
23558        /**
23559         * The id of the window for accessibility purposes.
23560         */
23561        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23562
23563        /**
23564         * Flags related to accessibility processing.
23565         *
23566         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23567         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23568         */
23569        int mAccessibilityFetchFlags;
23570
23571        /**
23572         * The drawable for highlighting accessibility focus.
23573         */
23574        Drawable mAccessibilityFocusDrawable;
23575
23576        /**
23577         * Show where the margins, bounds and layout bounds are for each view.
23578         */
23579        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23580
23581        /**
23582         * Point used to compute visible regions.
23583         */
23584        final Point mPoint = new Point();
23585
23586        /**
23587         * Used to track which View originated a requestLayout() call, used when
23588         * requestLayout() is called during layout.
23589         */
23590        View mViewRequestingLayout;
23591
23592        /**
23593         * Used to track views that need (at least) a partial relayout at their current size
23594         * during the next traversal.
23595         */
23596        List<View> mPartialLayoutViews = new ArrayList<>();
23597
23598        /**
23599         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23600         * modification. Lazily assigned during ViewRootImpl layout.
23601         */
23602        List<View> mEmptyPartialLayoutViews;
23603
23604        /**
23605         * Used to track the identity of the current drag operation.
23606         */
23607        IBinder mDragToken;
23608
23609        /**
23610         * The drag shadow surface for the current drag operation.
23611         */
23612        public Surface mDragSurface;
23613
23614
23615        /**
23616         * The view that currently has a tooltip displayed.
23617         */
23618        View mTooltipHost;
23619
23620        /**
23621         * Creates a new set of attachment information with the specified
23622         * events handler and thread.
23623         *
23624         * @param handler the events handler the view must use
23625         */
23626        AttachInfo(IWindowSession session, IWindow window, Display display,
23627                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
23628                Context context) {
23629            mSession = session;
23630            mWindow = window;
23631            mWindowToken = window.asBinder();
23632            mDisplay = display;
23633            mViewRootImpl = viewRootImpl;
23634            mHandler = handler;
23635            mRootCallbacks = effectPlayer;
23636            mTreeObserver = new ViewTreeObserver(context);
23637        }
23638    }
23639
23640    /**
23641     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23642     * is supported. This avoids keeping too many unused fields in most
23643     * instances of View.</p>
23644     */
23645    private static class ScrollabilityCache implements Runnable {
23646
23647        /**
23648         * Scrollbars are not visible
23649         */
23650        public static final int OFF = 0;
23651
23652        /**
23653         * Scrollbars are visible
23654         */
23655        public static final int ON = 1;
23656
23657        /**
23658         * Scrollbars are fading away
23659         */
23660        public static final int FADING = 2;
23661
23662        public boolean fadeScrollBars;
23663
23664        public int fadingEdgeLength;
23665        public int scrollBarDefaultDelayBeforeFade;
23666        public int scrollBarFadeDuration;
23667
23668        public int scrollBarSize;
23669        public ScrollBarDrawable scrollBar;
23670        public float[] interpolatorValues;
23671        public View host;
23672
23673        public final Paint paint;
23674        public final Matrix matrix;
23675        public Shader shader;
23676
23677        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23678
23679        private static final float[] OPAQUE = { 255 };
23680        private static final float[] TRANSPARENT = { 0.0f };
23681
23682        /**
23683         * When fading should start. This time moves into the future every time
23684         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23685         */
23686        public long fadeStartTime;
23687
23688
23689        /**
23690         * The current state of the scrollbars: ON, OFF, or FADING
23691         */
23692        public int state = OFF;
23693
23694        private int mLastColor;
23695
23696        public final Rect mScrollBarBounds = new Rect();
23697
23698        public static final int NOT_DRAGGING = 0;
23699        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23700        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23701        public int mScrollBarDraggingState = NOT_DRAGGING;
23702
23703        public float mScrollBarDraggingPos = 0;
23704
23705        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23706            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23707            scrollBarSize = configuration.getScaledScrollBarSize();
23708            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23709            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23710
23711            paint = new Paint();
23712            matrix = new Matrix();
23713            // use use a height of 1, and then wack the matrix each time we
23714            // actually use it.
23715            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23716            paint.setShader(shader);
23717            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23718
23719            this.host = host;
23720        }
23721
23722        public void setFadeColor(int color) {
23723            if (color != mLastColor) {
23724                mLastColor = color;
23725
23726                if (color != 0) {
23727                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23728                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23729                    paint.setShader(shader);
23730                    // Restore the default transfer mode (src_over)
23731                    paint.setXfermode(null);
23732                } else {
23733                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23734                    paint.setShader(shader);
23735                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23736                }
23737            }
23738        }
23739
23740        public void run() {
23741            long now = AnimationUtils.currentAnimationTimeMillis();
23742            if (now >= fadeStartTime) {
23743
23744                // the animation fades the scrollbars out by changing
23745                // the opacity (alpha) from fully opaque to fully
23746                // transparent
23747                int nextFrame = (int) now;
23748                int framesCount = 0;
23749
23750                Interpolator interpolator = scrollBarInterpolator;
23751
23752                // Start opaque
23753                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23754
23755                // End transparent
23756                nextFrame += scrollBarFadeDuration;
23757                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23758
23759                state = FADING;
23760
23761                // Kick off the fade animation
23762                host.invalidate(true);
23763            }
23764        }
23765    }
23766
23767    /**
23768     * Resuable callback for sending
23769     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23770     */
23771    private class SendViewScrolledAccessibilityEvent implements Runnable {
23772        public volatile boolean mIsPending;
23773
23774        public void run() {
23775            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23776            mIsPending = false;
23777        }
23778    }
23779
23780    /**
23781     * <p>
23782     * This class represents a delegate that can be registered in a {@link View}
23783     * to enhance accessibility support via composition rather via inheritance.
23784     * It is specifically targeted to widget developers that extend basic View
23785     * classes i.e. classes in package android.view, that would like their
23786     * applications to be backwards compatible.
23787     * </p>
23788     * <div class="special reference">
23789     * <h3>Developer Guides</h3>
23790     * <p>For more information about making applications accessible, read the
23791     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23792     * developer guide.</p>
23793     * </div>
23794     * <p>
23795     * A scenario in which a developer would like to use an accessibility delegate
23796     * is overriding a method introduced in a later API version than the minimal API
23797     * version supported by the application. For example, the method
23798     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23799     * in API version 4 when the accessibility APIs were first introduced. If a
23800     * developer would like his application to run on API version 4 devices (assuming
23801     * all other APIs used by the application are version 4 or lower) and take advantage
23802     * of this method, instead of overriding the method which would break the application's
23803     * backwards compatibility, he can override the corresponding method in this
23804     * delegate and register the delegate in the target View if the API version of
23805     * the system is high enough, i.e. the API version is the same as or higher than the API
23806     * version that introduced
23807     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23808     * </p>
23809     * <p>
23810     * Here is an example implementation:
23811     * </p>
23812     * <code><pre><p>
23813     * if (Build.VERSION.SDK_INT >= 14) {
23814     *     // If the API version is equal of higher than the version in
23815     *     // which onInitializeAccessibilityNodeInfo was introduced we
23816     *     // register a delegate with a customized implementation.
23817     *     View view = findViewById(R.id.view_id);
23818     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23819     *         public void onInitializeAccessibilityNodeInfo(View host,
23820     *                 AccessibilityNodeInfo info) {
23821     *             // Let the default implementation populate the info.
23822     *             super.onInitializeAccessibilityNodeInfo(host, info);
23823     *             // Set some other information.
23824     *             info.setEnabled(host.isEnabled());
23825     *         }
23826     *     });
23827     * }
23828     * </code></pre></p>
23829     * <p>
23830     * This delegate contains methods that correspond to the accessibility methods
23831     * in View. If a delegate has been specified the implementation in View hands
23832     * off handling to the corresponding method in this delegate. The default
23833     * implementation the delegate methods behaves exactly as the corresponding
23834     * method in View for the case of no accessibility delegate been set. Hence,
23835     * to customize the behavior of a View method, clients can override only the
23836     * corresponding delegate method without altering the behavior of the rest
23837     * accessibility related methods of the host view.
23838     * </p>
23839     * <p>
23840     * <strong>Note:</strong> On platform versions prior to
23841     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23842     * views in the {@code android.widget.*} package are called <i>before</i>
23843     * host methods. This prevents certain properties such as class name from
23844     * being modified by overriding
23845     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23846     * as any changes will be overwritten by the host class.
23847     * <p>
23848     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23849     * methods are called <i>after</i> host methods, which all properties to be
23850     * modified without being overwritten by the host class.
23851     */
23852    public static class AccessibilityDelegate {
23853
23854        /**
23855         * Sends an accessibility event of the given type. If accessibility is not
23856         * enabled this method has no effect.
23857         * <p>
23858         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23859         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23860         * been set.
23861         * </p>
23862         *
23863         * @param host The View hosting the delegate.
23864         * @param eventType The type of the event to send.
23865         *
23866         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23867         */
23868        public void sendAccessibilityEvent(View host, int eventType) {
23869            host.sendAccessibilityEventInternal(eventType);
23870        }
23871
23872        /**
23873         * Performs the specified accessibility action on the view. For
23874         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23875         * <p>
23876         * The default implementation behaves as
23877         * {@link View#performAccessibilityAction(int, Bundle)
23878         *  View#performAccessibilityAction(int, Bundle)} for the case of
23879         *  no accessibility delegate been set.
23880         * </p>
23881         *
23882         * @param action The action to perform.
23883         * @return Whether the action was performed.
23884         *
23885         * @see View#performAccessibilityAction(int, Bundle)
23886         *      View#performAccessibilityAction(int, Bundle)
23887         */
23888        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23889            return host.performAccessibilityActionInternal(action, args);
23890        }
23891
23892        /**
23893         * Sends an accessibility event. This method behaves exactly as
23894         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23895         * empty {@link AccessibilityEvent} and does not perform a check whether
23896         * accessibility is enabled.
23897         * <p>
23898         * The default implementation behaves as
23899         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23900         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23901         * the case of no accessibility delegate been set.
23902         * </p>
23903         *
23904         * @param host The View hosting the delegate.
23905         * @param event The event to send.
23906         *
23907         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23908         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23909         */
23910        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23911            host.sendAccessibilityEventUncheckedInternal(event);
23912        }
23913
23914        /**
23915         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23916         * to its children for adding their text content to the event.
23917         * <p>
23918         * The default implementation behaves as
23919         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23920         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23921         * the case of no accessibility delegate been set.
23922         * </p>
23923         *
23924         * @param host The View hosting the delegate.
23925         * @param event The event.
23926         * @return True if the event population was completed.
23927         *
23928         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23929         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23930         */
23931        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23932            return host.dispatchPopulateAccessibilityEventInternal(event);
23933        }
23934
23935        /**
23936         * Gives a chance to the host View to populate the accessibility event with its
23937         * text content.
23938         * <p>
23939         * The default implementation behaves as
23940         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23941         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23942         * the case of no accessibility delegate been set.
23943         * </p>
23944         *
23945         * @param host The View hosting the delegate.
23946         * @param event The accessibility event which to populate.
23947         *
23948         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23949         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23950         */
23951        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23952            host.onPopulateAccessibilityEventInternal(event);
23953        }
23954
23955        /**
23956         * Initializes an {@link AccessibilityEvent} with information about the
23957         * the host View which is the event source.
23958         * <p>
23959         * The default implementation behaves as
23960         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23961         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23962         * the case of no accessibility delegate been set.
23963         * </p>
23964         *
23965         * @param host The View hosting the delegate.
23966         * @param event The event to initialize.
23967         *
23968         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23969         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23970         */
23971        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23972            host.onInitializeAccessibilityEventInternal(event);
23973        }
23974
23975        /**
23976         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23977         * <p>
23978         * The default implementation behaves as
23979         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23980         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23981         * the case of no accessibility delegate been set.
23982         * </p>
23983         *
23984         * @param host The View hosting the delegate.
23985         * @param info The instance to initialize.
23986         *
23987         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23988         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23989         */
23990        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23991            host.onInitializeAccessibilityNodeInfoInternal(info);
23992        }
23993
23994        /**
23995         * Called when a child of the host View has requested sending an
23996         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23997         * to augment the event.
23998         * <p>
23999         * The default implementation behaves as
24000         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24001         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24002         * the case of no accessibility delegate been set.
24003         * </p>
24004         *
24005         * @param host The View hosting the delegate.
24006         * @param child The child which requests sending the event.
24007         * @param event The event to be sent.
24008         * @return True if the event should be sent
24009         *
24010         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24011         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24012         */
24013        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24014                AccessibilityEvent event) {
24015            return host.onRequestSendAccessibilityEventInternal(child, event);
24016        }
24017
24018        /**
24019         * Gets the provider for managing a virtual view hierarchy rooted at this View
24020         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24021         * that explore the window content.
24022         * <p>
24023         * The default implementation behaves as
24024         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24025         * the case of no accessibility delegate been set.
24026         * </p>
24027         *
24028         * @return The provider.
24029         *
24030         * @see AccessibilityNodeProvider
24031         */
24032        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24033            return null;
24034        }
24035
24036        /**
24037         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24038         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24039         * This method is responsible for obtaining an accessibility node info from a
24040         * pool of reusable instances and calling
24041         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24042         * view to initialize the former.
24043         * <p>
24044         * <strong>Note:</strong> The client is responsible for recycling the obtained
24045         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24046         * creation.
24047         * </p>
24048         * <p>
24049         * The default implementation behaves as
24050         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24051         * the case of no accessibility delegate been set.
24052         * </p>
24053         * @return A populated {@link AccessibilityNodeInfo}.
24054         *
24055         * @see AccessibilityNodeInfo
24056         *
24057         * @hide
24058         */
24059        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24060            return host.createAccessibilityNodeInfoInternal();
24061        }
24062    }
24063
24064    private class MatchIdPredicate implements Predicate<View> {
24065        public int mId;
24066
24067        @Override
24068        public boolean apply(View view) {
24069            return (view.mID == mId);
24070        }
24071    }
24072
24073    private class MatchLabelForPredicate implements Predicate<View> {
24074        private int mLabeledId;
24075
24076        @Override
24077        public boolean apply(View view) {
24078            return (view.mLabelForId == mLabeledId);
24079        }
24080    }
24081
24082    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24083        private int mChangeTypes = 0;
24084        private boolean mPosted;
24085        private boolean mPostedWithDelay;
24086        private long mLastEventTimeMillis;
24087
24088        @Override
24089        public void run() {
24090            mPosted = false;
24091            mPostedWithDelay = false;
24092            mLastEventTimeMillis = SystemClock.uptimeMillis();
24093            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24094                final AccessibilityEvent event = AccessibilityEvent.obtain();
24095                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24096                event.setContentChangeTypes(mChangeTypes);
24097                sendAccessibilityEventUnchecked(event);
24098            }
24099            mChangeTypes = 0;
24100        }
24101
24102        public void runOrPost(int changeType) {
24103            mChangeTypes |= changeType;
24104
24105            // If this is a live region or the child of a live region, collect
24106            // all events from this frame and send them on the next frame.
24107            if (inLiveRegion()) {
24108                // If we're already posted with a delay, remove that.
24109                if (mPostedWithDelay) {
24110                    removeCallbacks(this);
24111                    mPostedWithDelay = false;
24112                }
24113                // Only post if we're not already posted.
24114                if (!mPosted) {
24115                    post(this);
24116                    mPosted = true;
24117                }
24118                return;
24119            }
24120
24121            if (mPosted) {
24122                return;
24123            }
24124
24125            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24126            final long minEventIntevalMillis =
24127                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24128            if (timeSinceLastMillis >= minEventIntevalMillis) {
24129                removeCallbacks(this);
24130                run();
24131            } else {
24132                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24133                mPostedWithDelay = true;
24134            }
24135        }
24136    }
24137
24138    private boolean inLiveRegion() {
24139        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24140            return true;
24141        }
24142
24143        ViewParent parent = getParent();
24144        while (parent instanceof View) {
24145            if (((View) parent).getAccessibilityLiveRegion()
24146                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24147                return true;
24148            }
24149            parent = parent.getParent();
24150        }
24151
24152        return false;
24153    }
24154
24155    /**
24156     * Dump all private flags in readable format, useful for documentation and
24157     * sanity checking.
24158     */
24159    private static void dumpFlags() {
24160        final HashMap<String, String> found = Maps.newHashMap();
24161        try {
24162            for (Field field : View.class.getDeclaredFields()) {
24163                final int modifiers = field.getModifiers();
24164                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24165                    if (field.getType().equals(int.class)) {
24166                        final int value = field.getInt(null);
24167                        dumpFlag(found, field.getName(), value);
24168                    } else if (field.getType().equals(int[].class)) {
24169                        final int[] values = (int[]) field.get(null);
24170                        for (int i = 0; i < values.length; i++) {
24171                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24172                        }
24173                    }
24174                }
24175            }
24176        } catch (IllegalAccessException e) {
24177            throw new RuntimeException(e);
24178        }
24179
24180        final ArrayList<String> keys = Lists.newArrayList();
24181        keys.addAll(found.keySet());
24182        Collections.sort(keys);
24183        for (String key : keys) {
24184            Log.d(VIEW_LOG_TAG, found.get(key));
24185        }
24186    }
24187
24188    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24189        // Sort flags by prefix, then by bits, always keeping unique keys
24190        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24191        final int prefix = name.indexOf('_');
24192        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24193        final String output = bits + " " + name;
24194        found.put(key, output);
24195    }
24196
24197    /** {@hide} */
24198    public void encode(@NonNull ViewHierarchyEncoder stream) {
24199        stream.beginObject(this);
24200        encodeProperties(stream);
24201        stream.endObject();
24202    }
24203
24204    /** {@hide} */
24205    @CallSuper
24206    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24207        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24208        if (resolveId instanceof String) {
24209            stream.addProperty("id", (String) resolveId);
24210        } else {
24211            stream.addProperty("id", mID);
24212        }
24213
24214        stream.addProperty("misc:transformation.alpha",
24215                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24216        stream.addProperty("misc:transitionName", getTransitionName());
24217
24218        // layout
24219        stream.addProperty("layout:left", mLeft);
24220        stream.addProperty("layout:right", mRight);
24221        stream.addProperty("layout:top", mTop);
24222        stream.addProperty("layout:bottom", mBottom);
24223        stream.addProperty("layout:width", getWidth());
24224        stream.addProperty("layout:height", getHeight());
24225        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24226        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24227        stream.addProperty("layout:hasTransientState", hasTransientState());
24228        stream.addProperty("layout:baseline", getBaseline());
24229
24230        // layout params
24231        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24232        if (layoutParams != null) {
24233            stream.addPropertyKey("layoutParams");
24234            layoutParams.encode(stream);
24235        }
24236
24237        // scrolling
24238        stream.addProperty("scrolling:scrollX", mScrollX);
24239        stream.addProperty("scrolling:scrollY", mScrollY);
24240
24241        // padding
24242        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24243        stream.addProperty("padding:paddingRight", mPaddingRight);
24244        stream.addProperty("padding:paddingTop", mPaddingTop);
24245        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24246        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24247        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24248        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24249        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24250        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24251
24252        // measurement
24253        stream.addProperty("measurement:minHeight", mMinHeight);
24254        stream.addProperty("measurement:minWidth", mMinWidth);
24255        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24256        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24257
24258        // drawing
24259        stream.addProperty("drawing:elevation", getElevation());
24260        stream.addProperty("drawing:translationX", getTranslationX());
24261        stream.addProperty("drawing:translationY", getTranslationY());
24262        stream.addProperty("drawing:translationZ", getTranslationZ());
24263        stream.addProperty("drawing:rotation", getRotation());
24264        stream.addProperty("drawing:rotationX", getRotationX());
24265        stream.addProperty("drawing:rotationY", getRotationY());
24266        stream.addProperty("drawing:scaleX", getScaleX());
24267        stream.addProperty("drawing:scaleY", getScaleY());
24268        stream.addProperty("drawing:pivotX", getPivotX());
24269        stream.addProperty("drawing:pivotY", getPivotY());
24270        stream.addProperty("drawing:opaque", isOpaque());
24271        stream.addProperty("drawing:alpha", getAlpha());
24272        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24273        stream.addProperty("drawing:shadow", hasShadow());
24274        stream.addProperty("drawing:solidColor", getSolidColor());
24275        stream.addProperty("drawing:layerType", mLayerType);
24276        stream.addProperty("drawing:willNotDraw", willNotDraw());
24277        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24278        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24279        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24280        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24281
24282        // focus
24283        stream.addProperty("focus:hasFocus", hasFocus());
24284        stream.addProperty("focus:isFocused", isFocused());
24285        stream.addProperty("focus:isFocusable", isFocusable());
24286        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24287
24288        stream.addProperty("misc:clickable", isClickable());
24289        stream.addProperty("misc:pressed", isPressed());
24290        stream.addProperty("misc:selected", isSelected());
24291        stream.addProperty("misc:touchMode", isInTouchMode());
24292        stream.addProperty("misc:hovered", isHovered());
24293        stream.addProperty("misc:activated", isActivated());
24294
24295        stream.addProperty("misc:visibility", getVisibility());
24296        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24297        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24298
24299        stream.addProperty("misc:enabled", isEnabled());
24300        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24301        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24302
24303        // theme attributes
24304        Resources.Theme theme = getContext().getTheme();
24305        if (theme != null) {
24306            stream.addPropertyKey("theme");
24307            theme.encode(stream);
24308        }
24309
24310        // view attribute information
24311        int n = mAttributes != null ? mAttributes.length : 0;
24312        stream.addProperty("meta:__attrCount__", n/2);
24313        for (int i = 0; i < n; i += 2) {
24314            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24315        }
24316
24317        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24318
24319        // text
24320        stream.addProperty("text:textDirection", getTextDirection());
24321        stream.addProperty("text:textAlignment", getTextAlignment());
24322
24323        // accessibility
24324        CharSequence contentDescription = getContentDescription();
24325        stream.addProperty("accessibility:contentDescription",
24326                contentDescription == null ? "" : contentDescription.toString());
24327        stream.addProperty("accessibility:labelFor", getLabelFor());
24328        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24329    }
24330
24331    /**
24332     * Determine if this view is rendered on a round wearable device and is the main view
24333     * on the screen.
24334     */
24335    private boolean shouldDrawRoundScrollbar() {
24336        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24337            return false;
24338        }
24339
24340        final View rootView = getRootView();
24341        final WindowInsets insets = getRootWindowInsets();
24342
24343        int height = getHeight();
24344        int width = getWidth();
24345        int displayHeight = rootView.getHeight();
24346        int displayWidth = rootView.getWidth();
24347
24348        if (height != displayHeight || width != displayWidth) {
24349            return false;
24350        }
24351
24352        getLocationOnScreen(mAttachInfo.mTmpLocation);
24353        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24354                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24355    }
24356
24357    /**
24358     * Sets the tooltip text which will be displayed in a small popup next to the view.
24359     * <p>
24360     * The tooltip will be displayed:
24361     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24362     * menu). </li>
24363     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24364     *
24365     * @param tooltip the tooltip text, or null if no tooltip is required
24366     */
24367    public final void setTooltip(@Nullable CharSequence tooltip) {
24368        if (TextUtils.isEmpty(tooltip)) {
24369            setFlags(0, TOOLTIP);
24370            hideTooltip();
24371            mTooltipInfo = null;
24372        } else {
24373            setFlags(TOOLTIP, TOOLTIP);
24374            if (mTooltipInfo == null) {
24375                mTooltipInfo = new TooltipInfo();
24376                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24377                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24378            }
24379            mTooltipInfo.mTooltip = tooltip;
24380            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24381                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltip);
24382            }
24383        }
24384    }
24385
24386    /**
24387     * Returns the view's tooltip text.
24388     *
24389     * @return the tooltip text
24390     */
24391    @Nullable
24392    public final CharSequence getTooltip() {
24393        return mTooltipInfo != null ? mTooltipInfo.mTooltip : null;
24394    }
24395
24396    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24397        if (mAttachInfo == null) {
24398            return false;
24399        }
24400        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24401            return false;
24402        }
24403        final CharSequence tooltipText = getTooltip();
24404        if (TextUtils.isEmpty(tooltipText)) {
24405            return false;
24406        }
24407        hideTooltip();
24408        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24409        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24410        mTooltipInfo.mTooltipPopup.show(this, x, y, tooltipText);
24411        mAttachInfo.mTooltipHost = this;
24412        return true;
24413    }
24414
24415    void hideTooltip() {
24416        if (mTooltipInfo == null) {
24417            return;
24418        }
24419        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24420        if (mTooltipInfo.mTooltipPopup == null) {
24421            return;
24422        }
24423        mTooltipInfo.mTooltipPopup.hide();
24424        mTooltipInfo.mTooltipPopup = null;
24425        mTooltipInfo.mTooltipFromLongClick = false;
24426        if (mAttachInfo != null) {
24427            mAttachInfo.mTooltipHost = null;
24428        }
24429    }
24430
24431    private boolean showLongClickTooltip(int x, int y) {
24432        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24433        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24434        return showTooltip(x, y, true);
24435    }
24436
24437    private void showHoverTooltip() {
24438        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24439    }
24440
24441    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24442        if (mTooltipInfo == null) {
24443            return false;
24444        }
24445        switch(event.getAction()) {
24446            case MotionEvent.ACTION_HOVER_MOVE:
24447                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24448                    break;
24449                }
24450                if (!mTooltipInfo.mTooltipFromLongClick) {
24451                    if (mTooltipInfo.mTooltipPopup == null) {
24452                        // Schedule showing the tooltip after a timeout.
24453                        mTooltipInfo.mAnchorX = (int) event.getX();
24454                        mTooltipInfo.mAnchorY = (int) event.getY();
24455                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24456                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24457                                ViewConfiguration.getHoverTooltipShowTimeout());
24458                    }
24459
24460                    // Hide hover-triggered tooltip after a period of inactivity.
24461                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24462                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24463                    final int timeout;
24464                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24465                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24466                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24467                    } else {
24468                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24469                    }
24470                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24471                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24472                }
24473                return true;
24474
24475            case MotionEvent.ACTION_HOVER_EXIT:
24476                if (!mTooltipInfo.mTooltipFromLongClick) {
24477                    hideTooltip();
24478                }
24479                break;
24480        }
24481        return false;
24482    }
24483
24484    void handleTooltipKey(KeyEvent event) {
24485        switch (event.getAction()) {
24486            case KeyEvent.ACTION_DOWN:
24487                if (event.getRepeatCount() == 0) {
24488                    hideTooltip();
24489                }
24490                break;
24491
24492            case KeyEvent.ACTION_UP:
24493                handleTooltipUp();
24494                break;
24495        }
24496    }
24497
24498    private void handleTooltipUp() {
24499        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24500            return;
24501        }
24502        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24503        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24504                ViewConfiguration.getLongPressTooltipHideTimeout());
24505    }
24506
24507    /**
24508     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24509     * is not showing.
24510     * @hide
24511     */
24512    @TestApi
24513    public View getTooltipView() {
24514        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24515            return null;
24516        }
24517        return mTooltipInfo.mTooltipPopup.getContentView();
24518    }
24519}
24520