View.java revision ce3264dac7818d1e97149953705c6a123e74cd3e
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            // Damage the entire IsolatedZVolume receiving this view's shadow.
14046            if (isHardwareAccelerated() && getZ() != 0) {
14047                damageShadowReceiver();
14048            }
14049        }
14050    }
14051
14052    /**
14053     * @return this view's projection receiver, or {@code null} if none exists
14054     */
14055    private View getProjectionReceiver() {
14056        ViewParent p = getParent();
14057        while (p != null && p instanceof View) {
14058            final View v = (View) p;
14059            if (v.isProjectionReceiver()) {
14060                return v;
14061            }
14062            p = p.getParent();
14063        }
14064
14065        return null;
14066    }
14067
14068    /**
14069     * @return whether the view is a projection receiver
14070     */
14071    private boolean isProjectionReceiver() {
14072        return mBackground != null;
14073    }
14074
14075    /**
14076     * Damage area of the screen that can be covered by this View's shadow.
14077     *
14078     * This method will guarantee that any changes to shadows cast by a View
14079     * are damaged on the screen for future redraw.
14080     */
14081    private void damageShadowReceiver() {
14082        final AttachInfo ai = mAttachInfo;
14083        if (ai != null) {
14084            ViewParent p = getParent();
14085            if (p != null && p instanceof ViewGroup) {
14086                final ViewGroup vg = (ViewGroup) p;
14087                vg.damageInParent();
14088            }
14089        }
14090    }
14091
14092    /**
14093     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14094     * set any flags or handle all of the cases handled by the default invalidation methods.
14095     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14096     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14097     * walk up the hierarchy, transforming the dirty rect as necessary.
14098     *
14099     * The method also handles normal invalidation logic if display list properties are not
14100     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14101     * backup approach, to handle these cases used in the various property-setting methods.
14102     *
14103     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14104     * are not being used in this view
14105     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14106     * list properties are not being used in this view
14107     */
14108    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14109        if (!isHardwareAccelerated()
14110                || !mRenderNode.isValid()
14111                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14112            if (invalidateParent) {
14113                invalidateParentCaches();
14114            }
14115            if (forceRedraw) {
14116                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14117            }
14118            invalidate(false);
14119        } else {
14120            damageInParent();
14121        }
14122        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
14123            damageShadowReceiver();
14124        }
14125    }
14126
14127    /**
14128     * Tells the parent view to damage this view's bounds.
14129     *
14130     * @hide
14131     */
14132    protected void damageInParent() {
14133        final AttachInfo ai = mAttachInfo;
14134        final ViewParent p = mParent;
14135        if (p != null && ai != null) {
14136            final Rect r = ai.mTmpInvalRect;
14137            r.set(0, 0, mRight - mLeft, mBottom - mTop);
14138            if (mParent instanceof ViewGroup) {
14139                ((ViewGroup) mParent).damageChild(this, r);
14140            } else {
14141                mParent.invalidateChild(this, r);
14142            }
14143        }
14144    }
14145
14146    /**
14147     * Utility method to transform a given Rect by the current matrix of this view.
14148     */
14149    void transformRect(final Rect rect) {
14150        if (!getMatrix().isIdentity()) {
14151            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14152            boundingRect.set(rect);
14153            getMatrix().mapRect(boundingRect);
14154            rect.set((int) Math.floor(boundingRect.left),
14155                    (int) Math.floor(boundingRect.top),
14156                    (int) Math.ceil(boundingRect.right),
14157                    (int) Math.ceil(boundingRect.bottom));
14158        }
14159    }
14160
14161    /**
14162     * Used to indicate that the parent of this view should clear its caches. This functionality
14163     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14164     * which is necessary when various parent-managed properties of the view change, such as
14165     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14166     * clears the parent caches and does not causes an invalidate event.
14167     *
14168     * @hide
14169     */
14170    protected void invalidateParentCaches() {
14171        if (mParent instanceof View) {
14172            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14173        }
14174    }
14175
14176    /**
14177     * Used to indicate that the parent of this view should be invalidated. This functionality
14178     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14179     * which is necessary when various parent-managed properties of the view change, such as
14180     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14181     * an invalidation event to the parent.
14182     *
14183     * @hide
14184     */
14185    protected void invalidateParentIfNeeded() {
14186        if (isHardwareAccelerated() && mParent instanceof View) {
14187            ((View) mParent).invalidate(true);
14188        }
14189    }
14190
14191    /**
14192     * @hide
14193     */
14194    protected void invalidateParentIfNeededAndWasQuickRejected() {
14195        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14196            // View was rejected last time it was drawn by its parent; this may have changed
14197            invalidateParentIfNeeded();
14198        }
14199    }
14200
14201    /**
14202     * Indicates whether this View is opaque. An opaque View guarantees that it will
14203     * draw all the pixels overlapping its bounds using a fully opaque color.
14204     *
14205     * Subclasses of View should override this method whenever possible to indicate
14206     * whether an instance is opaque. Opaque Views are treated in a special way by
14207     * the View hierarchy, possibly allowing it to perform optimizations during
14208     * invalidate/draw passes.
14209     *
14210     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14211     */
14212    @ViewDebug.ExportedProperty(category = "drawing")
14213    public boolean isOpaque() {
14214        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14215                getFinalAlpha() >= 1.0f;
14216    }
14217
14218    /**
14219     * @hide
14220     */
14221    protected void computeOpaqueFlags() {
14222        // Opaque if:
14223        //   - Has a background
14224        //   - Background is opaque
14225        //   - Doesn't have scrollbars or scrollbars overlay
14226
14227        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14228            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14229        } else {
14230            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14231        }
14232
14233        final int flags = mViewFlags;
14234        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14235                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14236                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14237            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14238        } else {
14239            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14240        }
14241    }
14242
14243    /**
14244     * @hide
14245     */
14246    protected boolean hasOpaqueScrollbars() {
14247        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14248    }
14249
14250    /**
14251     * @return A handler associated with the thread running the View. This
14252     * handler can be used to pump events in the UI events queue.
14253     */
14254    public Handler getHandler() {
14255        final AttachInfo attachInfo = mAttachInfo;
14256        if (attachInfo != null) {
14257            return attachInfo.mHandler;
14258        }
14259        return null;
14260    }
14261
14262    /**
14263     * Returns the queue of runnable for this view.
14264     *
14265     * @return the queue of runnables for this view
14266     */
14267    private HandlerActionQueue getRunQueue() {
14268        if (mRunQueue == null) {
14269            mRunQueue = new HandlerActionQueue();
14270        }
14271        return mRunQueue;
14272    }
14273
14274    /**
14275     * Gets the view root associated with the View.
14276     * @return The view root, or null if none.
14277     * @hide
14278     */
14279    public ViewRootImpl getViewRootImpl() {
14280        if (mAttachInfo != null) {
14281            return mAttachInfo.mViewRootImpl;
14282        }
14283        return null;
14284    }
14285
14286    /**
14287     * @hide
14288     */
14289    public ThreadedRenderer getThreadedRenderer() {
14290        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14291    }
14292
14293    /**
14294     * <p>Causes the Runnable to be added to the message queue.
14295     * The runnable will be run on the user interface thread.</p>
14296     *
14297     * @param action The Runnable that will be executed.
14298     *
14299     * @return Returns true if the Runnable was successfully placed in to the
14300     *         message queue.  Returns false on failure, usually because the
14301     *         looper processing the message queue is exiting.
14302     *
14303     * @see #postDelayed
14304     * @see #removeCallbacks
14305     */
14306    public boolean post(Runnable action) {
14307        final AttachInfo attachInfo = mAttachInfo;
14308        if (attachInfo != null) {
14309            return attachInfo.mHandler.post(action);
14310        }
14311
14312        // Postpone the runnable until we know on which thread it needs to run.
14313        // Assume that the runnable will be successfully placed after attach.
14314        getRunQueue().post(action);
14315        return true;
14316    }
14317
14318    /**
14319     * <p>Causes the Runnable to be added to the message queue, to be run
14320     * after the specified amount of time elapses.
14321     * The runnable will be run on the user interface thread.</p>
14322     *
14323     * @param action The Runnable that will be executed.
14324     * @param delayMillis The delay (in milliseconds) until the Runnable
14325     *        will be executed.
14326     *
14327     * @return true if the Runnable was successfully placed in to the
14328     *         message queue.  Returns false on failure, usually because the
14329     *         looper processing the message queue is exiting.  Note that a
14330     *         result of true does not mean the Runnable will be processed --
14331     *         if the looper is quit before the delivery time of the message
14332     *         occurs then the message will be dropped.
14333     *
14334     * @see #post
14335     * @see #removeCallbacks
14336     */
14337    public boolean postDelayed(Runnable action, long delayMillis) {
14338        final AttachInfo attachInfo = mAttachInfo;
14339        if (attachInfo != null) {
14340            return attachInfo.mHandler.postDelayed(action, delayMillis);
14341        }
14342
14343        // Postpone the runnable until we know on which thread it needs to run.
14344        // Assume that the runnable will be successfully placed after attach.
14345        getRunQueue().postDelayed(action, delayMillis);
14346        return true;
14347    }
14348
14349    /**
14350     * <p>Causes the Runnable to execute on the next animation time step.
14351     * The runnable will be run on the user interface thread.</p>
14352     *
14353     * @param action The Runnable that will be executed.
14354     *
14355     * @see #postOnAnimationDelayed
14356     * @see #removeCallbacks
14357     */
14358    public void postOnAnimation(Runnable action) {
14359        final AttachInfo attachInfo = mAttachInfo;
14360        if (attachInfo != null) {
14361            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14362                    Choreographer.CALLBACK_ANIMATION, action, null);
14363        } else {
14364            // Postpone the runnable until we know
14365            // on which thread it needs to run.
14366            getRunQueue().post(action);
14367        }
14368    }
14369
14370    /**
14371     * <p>Causes the Runnable to execute on the next animation time step,
14372     * after the specified amount of time elapses.
14373     * The runnable will be run on the user interface thread.</p>
14374     *
14375     * @param action The Runnable that will be executed.
14376     * @param delayMillis The delay (in milliseconds) until the Runnable
14377     *        will be executed.
14378     *
14379     * @see #postOnAnimation
14380     * @see #removeCallbacks
14381     */
14382    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14383        final AttachInfo attachInfo = mAttachInfo;
14384        if (attachInfo != null) {
14385            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14386                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14387        } else {
14388            // Postpone the runnable until we know
14389            // on which thread it needs to run.
14390            getRunQueue().postDelayed(action, delayMillis);
14391        }
14392    }
14393
14394    /**
14395     * <p>Removes the specified Runnable from the message queue.</p>
14396     *
14397     * @param action The Runnable to remove from the message handling queue
14398     *
14399     * @return true if this view could ask the Handler to remove the Runnable,
14400     *         false otherwise. When the returned value is true, the Runnable
14401     *         may or may not have been actually removed from the message queue
14402     *         (for instance, if the Runnable was not in the queue already.)
14403     *
14404     * @see #post
14405     * @see #postDelayed
14406     * @see #postOnAnimation
14407     * @see #postOnAnimationDelayed
14408     */
14409    public boolean removeCallbacks(Runnable action) {
14410        if (action != null) {
14411            final AttachInfo attachInfo = mAttachInfo;
14412            if (attachInfo != null) {
14413                attachInfo.mHandler.removeCallbacks(action);
14414                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14415                        Choreographer.CALLBACK_ANIMATION, action, null);
14416            }
14417            getRunQueue().removeCallbacks(action);
14418        }
14419        return true;
14420    }
14421
14422    /**
14423     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14424     * Use this to invalidate the View from a non-UI thread.</p>
14425     *
14426     * <p>This method can be invoked from outside of the UI thread
14427     * only when this View is attached to a window.</p>
14428     *
14429     * @see #invalidate()
14430     * @see #postInvalidateDelayed(long)
14431     */
14432    public void postInvalidate() {
14433        postInvalidateDelayed(0);
14434    }
14435
14436    /**
14437     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14438     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14439     *
14440     * <p>This method can be invoked from outside of the UI thread
14441     * only when this View is attached to a window.</p>
14442     *
14443     * @param left The left coordinate of the rectangle to invalidate.
14444     * @param top The top coordinate of the rectangle to invalidate.
14445     * @param right The right coordinate of the rectangle to invalidate.
14446     * @param bottom The bottom coordinate of the rectangle to invalidate.
14447     *
14448     * @see #invalidate(int, int, int, int)
14449     * @see #invalidate(Rect)
14450     * @see #postInvalidateDelayed(long, int, int, int, int)
14451     */
14452    public void postInvalidate(int left, int top, int right, int bottom) {
14453        postInvalidateDelayed(0, left, top, right, bottom);
14454    }
14455
14456    /**
14457     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14458     * loop. Waits for the specified amount of time.</p>
14459     *
14460     * <p>This method can be invoked from outside of the UI thread
14461     * only when this View is attached to a window.</p>
14462     *
14463     * @param delayMilliseconds the duration in milliseconds to delay the
14464     *         invalidation by
14465     *
14466     * @see #invalidate()
14467     * @see #postInvalidate()
14468     */
14469    public void postInvalidateDelayed(long delayMilliseconds) {
14470        // We try only with the AttachInfo because there's no point in invalidating
14471        // if we are not attached to our window
14472        final AttachInfo attachInfo = mAttachInfo;
14473        if (attachInfo != null) {
14474            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14475        }
14476    }
14477
14478    /**
14479     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14480     * through the event loop. Waits for the specified amount of time.</p>
14481     *
14482     * <p>This method can be invoked from outside of the UI thread
14483     * only when this View is attached to a window.</p>
14484     *
14485     * @param delayMilliseconds the duration in milliseconds to delay the
14486     *         invalidation by
14487     * @param left The left coordinate of the rectangle to invalidate.
14488     * @param top The top coordinate of the rectangle to invalidate.
14489     * @param right The right coordinate of the rectangle to invalidate.
14490     * @param bottom The bottom coordinate of the rectangle to invalidate.
14491     *
14492     * @see #invalidate(int, int, int, int)
14493     * @see #invalidate(Rect)
14494     * @see #postInvalidate(int, int, int, int)
14495     */
14496    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14497            int right, int bottom) {
14498
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            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14504            info.target = this;
14505            info.left = left;
14506            info.top = top;
14507            info.right = right;
14508            info.bottom = bottom;
14509
14510            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14511        }
14512    }
14513
14514    /**
14515     * <p>Cause an invalidate to happen on the next animation time step, typically the
14516     * next display frame.</p>
14517     *
14518     * <p>This method can be invoked from outside of the UI thread
14519     * only when this View is attached to a window.</p>
14520     *
14521     * @see #invalidate()
14522     */
14523    public void postInvalidateOnAnimation() {
14524        // We try only with the AttachInfo because there's no point in invalidating
14525        // if we are not attached to our window
14526        final AttachInfo attachInfo = mAttachInfo;
14527        if (attachInfo != null) {
14528            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14529        }
14530    }
14531
14532    /**
14533     * <p>Cause an invalidate of the specified area to happen on the next animation
14534     * time step, typically the next display frame.</p>
14535     *
14536     * <p>This method can be invoked from outside of the UI thread
14537     * only when this View is attached to a window.</p>
14538     *
14539     * @param left The left coordinate of the rectangle to invalidate.
14540     * @param top The top coordinate of the rectangle to invalidate.
14541     * @param right The right coordinate of the rectangle to invalidate.
14542     * @param bottom The bottom coordinate of the rectangle to invalidate.
14543     *
14544     * @see #invalidate(int, int, int, int)
14545     * @see #invalidate(Rect)
14546     */
14547    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14548        // We try only with the AttachInfo because there's no point in invalidating
14549        // if we are not attached to our window
14550        final AttachInfo attachInfo = mAttachInfo;
14551        if (attachInfo != null) {
14552            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14553            info.target = this;
14554            info.left = left;
14555            info.top = top;
14556            info.right = right;
14557            info.bottom = bottom;
14558
14559            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14560        }
14561    }
14562
14563    /**
14564     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14565     * This event is sent at most once every
14566     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14567     */
14568    private void postSendViewScrolledAccessibilityEventCallback() {
14569        if (mSendViewScrolledAccessibilityEvent == null) {
14570            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14571        }
14572        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14573            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14574            postDelayed(mSendViewScrolledAccessibilityEvent,
14575                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14576        }
14577    }
14578
14579    /**
14580     * Called by a parent to request that a child update its values for mScrollX
14581     * and mScrollY if necessary. This will typically be done if the child is
14582     * animating a scroll using a {@link android.widget.Scroller Scroller}
14583     * object.
14584     */
14585    public void computeScroll() {
14586    }
14587
14588    /**
14589     * <p>Indicate whether the horizontal edges are faded when the view is
14590     * scrolled horizontally.</p>
14591     *
14592     * @return true if the horizontal edges should are faded on scroll, false
14593     *         otherwise
14594     *
14595     * @see #setHorizontalFadingEdgeEnabled(boolean)
14596     *
14597     * @attr ref android.R.styleable#View_requiresFadingEdge
14598     */
14599    public boolean isHorizontalFadingEdgeEnabled() {
14600        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14601    }
14602
14603    /**
14604     * <p>Define whether the horizontal edges should be faded when this view
14605     * is scrolled horizontally.</p>
14606     *
14607     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14608     *                                    be faded when the view is scrolled
14609     *                                    horizontally
14610     *
14611     * @see #isHorizontalFadingEdgeEnabled()
14612     *
14613     * @attr ref android.R.styleable#View_requiresFadingEdge
14614     */
14615    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14616        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14617            if (horizontalFadingEdgeEnabled) {
14618                initScrollCache();
14619            }
14620
14621            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14622        }
14623    }
14624
14625    /**
14626     * <p>Indicate whether the vertical edges are faded when the view is
14627     * scrolled horizontally.</p>
14628     *
14629     * @return true if the vertical edges should are faded on scroll, false
14630     *         otherwise
14631     *
14632     * @see #setVerticalFadingEdgeEnabled(boolean)
14633     *
14634     * @attr ref android.R.styleable#View_requiresFadingEdge
14635     */
14636    public boolean isVerticalFadingEdgeEnabled() {
14637        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14638    }
14639
14640    /**
14641     * <p>Define whether the vertical edges should be faded when this view
14642     * is scrolled vertically.</p>
14643     *
14644     * @param verticalFadingEdgeEnabled true if the vertical edges should
14645     *                                  be faded when the view is scrolled
14646     *                                  vertically
14647     *
14648     * @see #isVerticalFadingEdgeEnabled()
14649     *
14650     * @attr ref android.R.styleable#View_requiresFadingEdge
14651     */
14652    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14653        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14654            if (verticalFadingEdgeEnabled) {
14655                initScrollCache();
14656            }
14657
14658            mViewFlags ^= FADING_EDGE_VERTICAL;
14659        }
14660    }
14661
14662    /**
14663     * Returns the strength, or intensity, of the top faded edge. The strength is
14664     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14665     * returns 0.0 or 1.0 but no value in between.
14666     *
14667     * Subclasses should override this method to provide a smoother fade transition
14668     * when scrolling occurs.
14669     *
14670     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14671     */
14672    protected float getTopFadingEdgeStrength() {
14673        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14674    }
14675
14676    /**
14677     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14678     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14679     * returns 0.0 or 1.0 but no value in between.
14680     *
14681     * Subclasses should override this method to provide a smoother fade transition
14682     * when scrolling occurs.
14683     *
14684     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14685     */
14686    protected float getBottomFadingEdgeStrength() {
14687        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14688                computeVerticalScrollRange() ? 1.0f : 0.0f;
14689    }
14690
14691    /**
14692     * Returns the strength, or intensity, of the left faded edge. The strength is
14693     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14694     * returns 0.0 or 1.0 but no value in between.
14695     *
14696     * Subclasses should override this method to provide a smoother fade transition
14697     * when scrolling occurs.
14698     *
14699     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14700     */
14701    protected float getLeftFadingEdgeStrength() {
14702        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14703    }
14704
14705    /**
14706     * Returns the strength, or intensity, of the right faded edge. The strength is
14707     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14708     * returns 0.0 or 1.0 but no value in between.
14709     *
14710     * Subclasses should override this method to provide a smoother fade transition
14711     * when scrolling occurs.
14712     *
14713     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14714     */
14715    protected float getRightFadingEdgeStrength() {
14716        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14717                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14718    }
14719
14720    /**
14721     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14722     * scrollbar is not drawn by default.</p>
14723     *
14724     * @return true if the horizontal scrollbar should be painted, false
14725     *         otherwise
14726     *
14727     * @see #setHorizontalScrollBarEnabled(boolean)
14728     */
14729    public boolean isHorizontalScrollBarEnabled() {
14730        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14731    }
14732
14733    /**
14734     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14735     * scrollbar is not drawn by default.</p>
14736     *
14737     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14738     *                                   be painted
14739     *
14740     * @see #isHorizontalScrollBarEnabled()
14741     */
14742    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14743        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14744            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14745            computeOpaqueFlags();
14746            resolvePadding();
14747        }
14748    }
14749
14750    /**
14751     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14752     * scrollbar is not drawn by default.</p>
14753     *
14754     * @return true if the vertical scrollbar should be painted, false
14755     *         otherwise
14756     *
14757     * @see #setVerticalScrollBarEnabled(boolean)
14758     */
14759    public boolean isVerticalScrollBarEnabled() {
14760        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14761    }
14762
14763    /**
14764     * <p>Define whether the vertical scrollbar should be drawn or not. The
14765     * scrollbar is not drawn by default.</p>
14766     *
14767     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14768     *                                 be painted
14769     *
14770     * @see #isVerticalScrollBarEnabled()
14771     */
14772    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14773        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14774            mViewFlags ^= SCROLLBARS_VERTICAL;
14775            computeOpaqueFlags();
14776            resolvePadding();
14777        }
14778    }
14779
14780    /**
14781     * @hide
14782     */
14783    protected void recomputePadding() {
14784        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14785    }
14786
14787    /**
14788     * Define whether scrollbars will fade when the view is not scrolling.
14789     *
14790     * @param fadeScrollbars whether to enable fading
14791     *
14792     * @attr ref android.R.styleable#View_fadeScrollbars
14793     */
14794    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14795        initScrollCache();
14796        final ScrollabilityCache scrollabilityCache = mScrollCache;
14797        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14798        if (fadeScrollbars) {
14799            scrollabilityCache.state = ScrollabilityCache.OFF;
14800        } else {
14801            scrollabilityCache.state = ScrollabilityCache.ON;
14802        }
14803    }
14804
14805    /**
14806     *
14807     * Returns true if scrollbars will fade when this view is not scrolling
14808     *
14809     * @return true if scrollbar fading is enabled
14810     *
14811     * @attr ref android.R.styleable#View_fadeScrollbars
14812     */
14813    public boolean isScrollbarFadingEnabled() {
14814        return mScrollCache != null && mScrollCache.fadeScrollBars;
14815    }
14816
14817    /**
14818     *
14819     * Returns the delay before scrollbars fade.
14820     *
14821     * @return the delay before scrollbars fade
14822     *
14823     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14824     */
14825    public int getScrollBarDefaultDelayBeforeFade() {
14826        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14827                mScrollCache.scrollBarDefaultDelayBeforeFade;
14828    }
14829
14830    /**
14831     * Define the delay before scrollbars fade.
14832     *
14833     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14834     *
14835     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14836     */
14837    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14838        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14839    }
14840
14841    /**
14842     *
14843     * Returns the scrollbar fade duration.
14844     *
14845     * @return the scrollbar fade duration, in milliseconds
14846     *
14847     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14848     */
14849    public int getScrollBarFadeDuration() {
14850        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14851                mScrollCache.scrollBarFadeDuration;
14852    }
14853
14854    /**
14855     * Define the scrollbar fade duration.
14856     *
14857     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
14858     *
14859     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14860     */
14861    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14862        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14863    }
14864
14865    /**
14866     *
14867     * Returns the scrollbar size.
14868     *
14869     * @return the scrollbar size
14870     *
14871     * @attr ref android.R.styleable#View_scrollbarSize
14872     */
14873    public int getScrollBarSize() {
14874        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14875                mScrollCache.scrollBarSize;
14876    }
14877
14878    /**
14879     * Define the scrollbar size.
14880     *
14881     * @param scrollBarSize - the scrollbar size
14882     *
14883     * @attr ref android.R.styleable#View_scrollbarSize
14884     */
14885    public void setScrollBarSize(int scrollBarSize) {
14886        getScrollCache().scrollBarSize = scrollBarSize;
14887    }
14888
14889    /**
14890     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14891     * inset. When inset, they add to the padding of the view. And the scrollbars
14892     * can be drawn inside the padding area or on the edge of the view. For example,
14893     * if a view has a background drawable and you want to draw the scrollbars
14894     * inside the padding specified by the drawable, you can use
14895     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14896     * appear at the edge of the view, ignoring the padding, then you can use
14897     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14898     * @param style the style of the scrollbars. Should be one of
14899     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14900     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14901     * @see #SCROLLBARS_INSIDE_OVERLAY
14902     * @see #SCROLLBARS_INSIDE_INSET
14903     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14904     * @see #SCROLLBARS_OUTSIDE_INSET
14905     *
14906     * @attr ref android.R.styleable#View_scrollbarStyle
14907     */
14908    public void setScrollBarStyle(@ScrollBarStyle int style) {
14909        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14910            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14911            computeOpaqueFlags();
14912            resolvePadding();
14913        }
14914    }
14915
14916    /**
14917     * <p>Returns the current scrollbar style.</p>
14918     * @return the current scrollbar style
14919     * @see #SCROLLBARS_INSIDE_OVERLAY
14920     * @see #SCROLLBARS_INSIDE_INSET
14921     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14922     * @see #SCROLLBARS_OUTSIDE_INSET
14923     *
14924     * @attr ref android.R.styleable#View_scrollbarStyle
14925     */
14926    @ViewDebug.ExportedProperty(mapping = {
14927            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14928            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14929            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14930            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14931    })
14932    @ScrollBarStyle
14933    public int getScrollBarStyle() {
14934        return mViewFlags & SCROLLBARS_STYLE_MASK;
14935    }
14936
14937    /**
14938     * <p>Compute the horizontal range that the horizontal scrollbar
14939     * represents.</p>
14940     *
14941     * <p>The range is expressed in arbitrary units that must be the same as the
14942     * units used by {@link #computeHorizontalScrollExtent()} and
14943     * {@link #computeHorizontalScrollOffset()}.</p>
14944     *
14945     * <p>The default range is the drawing width of this view.</p>
14946     *
14947     * @return the total horizontal range represented by the horizontal
14948     *         scrollbar
14949     *
14950     * @see #computeHorizontalScrollExtent()
14951     * @see #computeHorizontalScrollOffset()
14952     * @see android.widget.ScrollBarDrawable
14953     */
14954    protected int computeHorizontalScrollRange() {
14955        return getWidth();
14956    }
14957
14958    /**
14959     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14960     * within the horizontal range. This value is used to compute the position
14961     * of the thumb within the scrollbar's track.</p>
14962     *
14963     * <p>The range is expressed in arbitrary units that must be the same as the
14964     * units used by {@link #computeHorizontalScrollRange()} and
14965     * {@link #computeHorizontalScrollExtent()}.</p>
14966     *
14967     * <p>The default offset is the scroll offset of this view.</p>
14968     *
14969     * @return the horizontal offset of the scrollbar's thumb
14970     *
14971     * @see #computeHorizontalScrollRange()
14972     * @see #computeHorizontalScrollExtent()
14973     * @see android.widget.ScrollBarDrawable
14974     */
14975    protected int computeHorizontalScrollOffset() {
14976        return mScrollX;
14977    }
14978
14979    /**
14980     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14981     * within the horizontal range. This value is used to compute the length
14982     * of the thumb within the scrollbar's track.</p>
14983     *
14984     * <p>The range is expressed in arbitrary units that must be the same as the
14985     * units used by {@link #computeHorizontalScrollRange()} and
14986     * {@link #computeHorizontalScrollOffset()}.</p>
14987     *
14988     * <p>The default extent is the drawing width of this view.</p>
14989     *
14990     * @return the horizontal extent of the scrollbar's thumb
14991     *
14992     * @see #computeHorizontalScrollRange()
14993     * @see #computeHorizontalScrollOffset()
14994     * @see android.widget.ScrollBarDrawable
14995     */
14996    protected int computeHorizontalScrollExtent() {
14997        return getWidth();
14998    }
14999
15000    /**
15001     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15002     *
15003     * <p>The range is expressed in arbitrary units that must be the same as the
15004     * units used by {@link #computeVerticalScrollExtent()} and
15005     * {@link #computeVerticalScrollOffset()}.</p>
15006     *
15007     * @return the total vertical range represented by the vertical scrollbar
15008     *
15009     * <p>The default range is the drawing height of this view.</p>
15010     *
15011     * @see #computeVerticalScrollExtent()
15012     * @see #computeVerticalScrollOffset()
15013     * @see android.widget.ScrollBarDrawable
15014     */
15015    protected int computeVerticalScrollRange() {
15016        return getHeight();
15017    }
15018
15019    /**
15020     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15021     * within the horizontal range. This value is used to compute the position
15022     * of the thumb within the scrollbar's track.</p>
15023     *
15024     * <p>The range is expressed in arbitrary units that must be the same as the
15025     * units used by {@link #computeVerticalScrollRange()} and
15026     * {@link #computeVerticalScrollExtent()}.</p>
15027     *
15028     * <p>The default offset is the scroll offset of this view.</p>
15029     *
15030     * @return the vertical offset of the scrollbar's thumb
15031     *
15032     * @see #computeVerticalScrollRange()
15033     * @see #computeVerticalScrollExtent()
15034     * @see android.widget.ScrollBarDrawable
15035     */
15036    protected int computeVerticalScrollOffset() {
15037        return mScrollY;
15038    }
15039
15040    /**
15041     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15042     * within the vertical range. This value is used to compute the length
15043     * of the thumb within the scrollbar's track.</p>
15044     *
15045     * <p>The range is expressed in arbitrary units that must be the same as the
15046     * units used by {@link #computeVerticalScrollRange()} and
15047     * {@link #computeVerticalScrollOffset()}.</p>
15048     *
15049     * <p>The default extent is the drawing height of this view.</p>
15050     *
15051     * @return the vertical extent of the scrollbar's thumb
15052     *
15053     * @see #computeVerticalScrollRange()
15054     * @see #computeVerticalScrollOffset()
15055     * @see android.widget.ScrollBarDrawable
15056     */
15057    protected int computeVerticalScrollExtent() {
15058        return getHeight();
15059    }
15060
15061    /**
15062     * Check if this view can be scrolled horizontally in a certain direction.
15063     *
15064     * @param direction Negative to check scrolling left, positive to check scrolling right.
15065     * @return true if this view can be scrolled in the specified direction, false otherwise.
15066     */
15067    public boolean canScrollHorizontally(int direction) {
15068        final int offset = computeHorizontalScrollOffset();
15069        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15070        if (range == 0) return false;
15071        if (direction < 0) {
15072            return offset > 0;
15073        } else {
15074            return offset < range - 1;
15075        }
15076    }
15077
15078    /**
15079     * Check if this view can be scrolled vertically in a certain direction.
15080     *
15081     * @param direction Negative to check scrolling up, positive to check scrolling down.
15082     * @return true if this view can be scrolled in the specified direction, false otherwise.
15083     */
15084    public boolean canScrollVertically(int direction) {
15085        final int offset = computeVerticalScrollOffset();
15086        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15087        if (range == 0) return false;
15088        if (direction < 0) {
15089            return offset > 0;
15090        } else {
15091            return offset < range - 1;
15092        }
15093    }
15094
15095    void getScrollIndicatorBounds(@NonNull Rect out) {
15096        out.left = mScrollX;
15097        out.right = mScrollX + mRight - mLeft;
15098        out.top = mScrollY;
15099        out.bottom = mScrollY + mBottom - mTop;
15100    }
15101
15102    private void onDrawScrollIndicators(Canvas c) {
15103        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15104            // No scroll indicators enabled.
15105            return;
15106        }
15107
15108        final Drawable dr = mScrollIndicatorDrawable;
15109        if (dr == null) {
15110            // Scroll indicators aren't supported here.
15111            return;
15112        }
15113
15114        final int h = dr.getIntrinsicHeight();
15115        final int w = dr.getIntrinsicWidth();
15116        final Rect rect = mAttachInfo.mTmpInvalRect;
15117        getScrollIndicatorBounds(rect);
15118
15119        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15120            final boolean canScrollUp = canScrollVertically(-1);
15121            if (canScrollUp) {
15122                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15123                dr.draw(c);
15124            }
15125        }
15126
15127        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15128            final boolean canScrollDown = canScrollVertically(1);
15129            if (canScrollDown) {
15130                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15131                dr.draw(c);
15132            }
15133        }
15134
15135        final int leftRtl;
15136        final int rightRtl;
15137        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15138            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15139            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15140        } else {
15141            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15142            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15143        }
15144
15145        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15146        if ((mPrivateFlags3 & leftMask) != 0) {
15147            final boolean canScrollLeft = canScrollHorizontally(-1);
15148            if (canScrollLeft) {
15149                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15150                dr.draw(c);
15151            }
15152        }
15153
15154        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15155        if ((mPrivateFlags3 & rightMask) != 0) {
15156            final boolean canScrollRight = canScrollHorizontally(1);
15157            if (canScrollRight) {
15158                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15159                dr.draw(c);
15160            }
15161        }
15162    }
15163
15164    private void getHorizontalScrollBarBounds(Rect bounds) {
15165        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15166        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15167                && !isVerticalScrollBarHidden();
15168        final int size = getHorizontalScrollbarHeight();
15169        final int verticalScrollBarGap = drawVerticalScrollBar ?
15170                getVerticalScrollbarWidth() : 0;
15171        final int width = mRight - mLeft;
15172        final int height = mBottom - mTop;
15173        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15174        bounds.left = mScrollX + (mPaddingLeft & inside);
15175        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15176        bounds.bottom = bounds.top + size;
15177    }
15178
15179    private void getVerticalScrollBarBounds(Rect bounds) {
15180        if (mRoundScrollbarRenderer == null) {
15181            getStraightVerticalScrollBarBounds(bounds);
15182        } else {
15183            getRoundVerticalScrollBarBounds(bounds);
15184        }
15185    }
15186
15187    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15188        final int width = mRight - mLeft;
15189        final int height = mBottom - mTop;
15190        // Do not take padding into account as we always want the scrollbars
15191        // to hug the screen for round wearable devices.
15192        bounds.left = mScrollX;
15193        bounds.top = mScrollY;
15194        bounds.right = bounds.left + width;
15195        bounds.bottom = mScrollY + height;
15196    }
15197
15198    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15199        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15200        final int size = getVerticalScrollbarWidth();
15201        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15202        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15203            verticalScrollbarPosition = isLayoutRtl() ?
15204                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15205        }
15206        final int width = mRight - mLeft;
15207        final int height = mBottom - mTop;
15208        switch (verticalScrollbarPosition) {
15209            default:
15210            case SCROLLBAR_POSITION_RIGHT:
15211                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15212                break;
15213            case SCROLLBAR_POSITION_LEFT:
15214                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15215                break;
15216        }
15217        bounds.top = mScrollY + (mPaddingTop & inside);
15218        bounds.right = bounds.left + size;
15219        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15220    }
15221
15222    /**
15223     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15224     * scrollbars are painted only if they have been awakened first.</p>
15225     *
15226     * @param canvas the canvas on which to draw the scrollbars
15227     *
15228     * @see #awakenScrollBars(int)
15229     */
15230    protected final void onDrawScrollBars(Canvas canvas) {
15231        // scrollbars are drawn only when the animation is running
15232        final ScrollabilityCache cache = mScrollCache;
15233
15234        if (cache != null) {
15235
15236            int state = cache.state;
15237
15238            if (state == ScrollabilityCache.OFF) {
15239                return;
15240            }
15241
15242            boolean invalidate = false;
15243
15244            if (state == ScrollabilityCache.FADING) {
15245                // We're fading -- get our fade interpolation
15246                if (cache.interpolatorValues == null) {
15247                    cache.interpolatorValues = new float[1];
15248                }
15249
15250                float[] values = cache.interpolatorValues;
15251
15252                // Stops the animation if we're done
15253                if (cache.scrollBarInterpolator.timeToValues(values) ==
15254                        Interpolator.Result.FREEZE_END) {
15255                    cache.state = ScrollabilityCache.OFF;
15256                } else {
15257                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15258                }
15259
15260                // This will make the scroll bars inval themselves after
15261                // drawing. We only want this when we're fading so that
15262                // we prevent excessive redraws
15263                invalidate = true;
15264            } else {
15265                // We're just on -- but we may have been fading before so
15266                // reset alpha
15267                cache.scrollBar.mutate().setAlpha(255);
15268            }
15269
15270            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15271            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15272                    && !isVerticalScrollBarHidden();
15273
15274            // Fork out the scroll bar drawing for round wearable devices.
15275            if (mRoundScrollbarRenderer != null) {
15276                if (drawVerticalScrollBar) {
15277                    final Rect bounds = cache.mScrollBarBounds;
15278                    getVerticalScrollBarBounds(bounds);
15279                    mRoundScrollbarRenderer.drawRoundScrollbars(
15280                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15281                    if (invalidate) {
15282                        invalidate();
15283                    }
15284                }
15285                // Do not draw horizontal scroll bars for round wearable devices.
15286            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15287                final ScrollBarDrawable scrollBar = cache.scrollBar;
15288
15289                if (drawHorizontalScrollBar) {
15290                    scrollBar.setParameters(computeHorizontalScrollRange(),
15291                            computeHorizontalScrollOffset(),
15292                            computeHorizontalScrollExtent(), false);
15293                    final Rect bounds = cache.mScrollBarBounds;
15294                    getHorizontalScrollBarBounds(bounds);
15295                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15296                            bounds.right, bounds.bottom);
15297                    if (invalidate) {
15298                        invalidate(bounds);
15299                    }
15300                }
15301
15302                if (drawVerticalScrollBar) {
15303                    scrollBar.setParameters(computeVerticalScrollRange(),
15304                            computeVerticalScrollOffset(),
15305                            computeVerticalScrollExtent(), true);
15306                    final Rect bounds = cache.mScrollBarBounds;
15307                    getVerticalScrollBarBounds(bounds);
15308                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15309                            bounds.right, bounds.bottom);
15310                    if (invalidate) {
15311                        invalidate(bounds);
15312                    }
15313                }
15314            }
15315        }
15316    }
15317
15318    /**
15319     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15320     * FastScroller is visible.
15321     * @return whether to temporarily hide the vertical scrollbar
15322     * @hide
15323     */
15324    protected boolean isVerticalScrollBarHidden() {
15325        return false;
15326    }
15327
15328    /**
15329     * <p>Draw the horizontal scrollbar if
15330     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15331     *
15332     * @param canvas the canvas on which to draw the scrollbar
15333     * @param scrollBar the scrollbar's drawable
15334     *
15335     * @see #isHorizontalScrollBarEnabled()
15336     * @see #computeHorizontalScrollRange()
15337     * @see #computeHorizontalScrollExtent()
15338     * @see #computeHorizontalScrollOffset()
15339     * @see android.widget.ScrollBarDrawable
15340     * @hide
15341     */
15342    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15343            int l, int t, int r, int b) {
15344        scrollBar.setBounds(l, t, r, b);
15345        scrollBar.draw(canvas);
15346    }
15347
15348    /**
15349     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15350     * returns true.</p>
15351     *
15352     * @param canvas the canvas on which to draw the scrollbar
15353     * @param scrollBar the scrollbar's drawable
15354     *
15355     * @see #isVerticalScrollBarEnabled()
15356     * @see #computeVerticalScrollRange()
15357     * @see #computeVerticalScrollExtent()
15358     * @see #computeVerticalScrollOffset()
15359     * @see android.widget.ScrollBarDrawable
15360     * @hide
15361     */
15362    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15363            int l, int t, int r, int b) {
15364        scrollBar.setBounds(l, t, r, b);
15365        scrollBar.draw(canvas);
15366    }
15367
15368    /**
15369     * Implement this to do your drawing.
15370     *
15371     * @param canvas the canvas on which the background will be drawn
15372     */
15373    protected void onDraw(Canvas canvas) {
15374    }
15375
15376    /*
15377     * Caller is responsible for calling requestLayout if necessary.
15378     * (This allows addViewInLayout to not request a new layout.)
15379     */
15380    void assignParent(ViewParent parent) {
15381        if (mParent == null) {
15382            mParent = parent;
15383        } else if (parent == null) {
15384            mParent = null;
15385        } else {
15386            throw new RuntimeException("view " + this + " being added, but"
15387                    + " it already has a parent");
15388        }
15389    }
15390
15391    /**
15392     * This is called when the view is attached to a window.  At this point it
15393     * has a Surface and will start drawing.  Note that this function is
15394     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15395     * however it may be called any time before the first onDraw -- including
15396     * before or after {@link #onMeasure(int, int)}.
15397     *
15398     * @see #onDetachedFromWindow()
15399     */
15400    @CallSuper
15401    protected void onAttachedToWindow() {
15402        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15403            mParent.requestTransparentRegion(this);
15404        }
15405
15406        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15407
15408        jumpDrawablesToCurrentState();
15409
15410        resetSubtreeAccessibilityStateChanged();
15411
15412        // rebuild, since Outline not maintained while View is detached
15413        rebuildOutline();
15414
15415        if (isFocused()) {
15416            InputMethodManager imm = InputMethodManager.peekInstance();
15417            if (imm != null) {
15418                imm.focusIn(this);
15419            }
15420        }
15421    }
15422
15423    /**
15424     * Resolve all RTL related properties.
15425     *
15426     * @return true if resolution of RTL properties has been done
15427     *
15428     * @hide
15429     */
15430    public boolean resolveRtlPropertiesIfNeeded() {
15431        if (!needRtlPropertiesResolution()) return false;
15432
15433        // Order is important here: LayoutDirection MUST be resolved first
15434        if (!isLayoutDirectionResolved()) {
15435            resolveLayoutDirection();
15436            resolveLayoutParams();
15437        }
15438        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15439        if (!isTextDirectionResolved()) {
15440            resolveTextDirection();
15441        }
15442        if (!isTextAlignmentResolved()) {
15443            resolveTextAlignment();
15444        }
15445        // Should resolve Drawables before Padding because we need the layout direction of the
15446        // Drawable to correctly resolve Padding.
15447        if (!areDrawablesResolved()) {
15448            resolveDrawables();
15449        }
15450        if (!isPaddingResolved()) {
15451            resolvePadding();
15452        }
15453        onRtlPropertiesChanged(getLayoutDirection());
15454        return true;
15455    }
15456
15457    /**
15458     * Reset resolution of all RTL related properties.
15459     *
15460     * @hide
15461     */
15462    public void resetRtlProperties() {
15463        resetResolvedLayoutDirection();
15464        resetResolvedTextDirection();
15465        resetResolvedTextAlignment();
15466        resetResolvedPadding();
15467        resetResolvedDrawables();
15468    }
15469
15470    /**
15471     * @see #onScreenStateChanged(int)
15472     */
15473    void dispatchScreenStateChanged(int screenState) {
15474        onScreenStateChanged(screenState);
15475    }
15476
15477    /**
15478     * This method is called whenever the state of the screen this view is
15479     * attached to changes. A state change will usually occurs when the screen
15480     * turns on or off (whether it happens automatically or the user does it
15481     * manually.)
15482     *
15483     * @param screenState The new state of the screen. Can be either
15484     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15485     */
15486    public void onScreenStateChanged(int screenState) {
15487    }
15488
15489    /**
15490     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15491     */
15492    private boolean hasRtlSupport() {
15493        return mContext.getApplicationInfo().hasRtlSupport();
15494    }
15495
15496    /**
15497     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15498     * RTL not supported)
15499     */
15500    private boolean isRtlCompatibilityMode() {
15501        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15502        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15503    }
15504
15505    /**
15506     * @return true if RTL properties need resolution.
15507     *
15508     */
15509    private boolean needRtlPropertiesResolution() {
15510        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15511    }
15512
15513    /**
15514     * Called when any RTL property (layout direction or text direction or text alignment) has
15515     * been changed.
15516     *
15517     * Subclasses need to override this method to take care of cached information that depends on the
15518     * resolved layout direction, or to inform child views that inherit their layout direction.
15519     *
15520     * The default implementation does nothing.
15521     *
15522     * @param layoutDirection the direction of the layout
15523     *
15524     * @see #LAYOUT_DIRECTION_LTR
15525     * @see #LAYOUT_DIRECTION_RTL
15526     */
15527    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15528    }
15529
15530    /**
15531     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15532     * that the parent directionality can and will be resolved before its children.
15533     *
15534     * @return true if resolution has been done, false otherwise.
15535     *
15536     * @hide
15537     */
15538    public boolean resolveLayoutDirection() {
15539        // Clear any previous layout direction resolution
15540        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15541
15542        if (hasRtlSupport()) {
15543            // Set resolved depending on layout direction
15544            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15545                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15546                case LAYOUT_DIRECTION_INHERIT:
15547                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15548                    // later to get the correct resolved value
15549                    if (!canResolveLayoutDirection()) return false;
15550
15551                    // Parent has not yet resolved, LTR is still the default
15552                    try {
15553                        if (!mParent.isLayoutDirectionResolved()) return false;
15554
15555                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15556                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15557                        }
15558                    } catch (AbstractMethodError e) {
15559                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15560                                " does not fully implement ViewParent", e);
15561                    }
15562                    break;
15563                case LAYOUT_DIRECTION_RTL:
15564                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15565                    break;
15566                case LAYOUT_DIRECTION_LOCALE:
15567                    if((LAYOUT_DIRECTION_RTL ==
15568                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15569                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15570                    }
15571                    break;
15572                default:
15573                    // Nothing to do, LTR by default
15574            }
15575        }
15576
15577        // Set to resolved
15578        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15579        return true;
15580    }
15581
15582    /**
15583     * Check if layout direction resolution can be done.
15584     *
15585     * @return true if layout direction resolution can be done otherwise return false.
15586     */
15587    public boolean canResolveLayoutDirection() {
15588        switch (getRawLayoutDirection()) {
15589            case LAYOUT_DIRECTION_INHERIT:
15590                if (mParent != null) {
15591                    try {
15592                        return mParent.canResolveLayoutDirection();
15593                    } catch (AbstractMethodError e) {
15594                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15595                                " does not fully implement ViewParent", e);
15596                    }
15597                }
15598                return false;
15599
15600            default:
15601                return true;
15602        }
15603    }
15604
15605    /**
15606     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15607     * {@link #onMeasure(int, int)}.
15608     *
15609     * @hide
15610     */
15611    public void resetResolvedLayoutDirection() {
15612        // Reset the current resolved bits
15613        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15614    }
15615
15616    /**
15617     * @return true if the layout direction is inherited.
15618     *
15619     * @hide
15620     */
15621    public boolean isLayoutDirectionInherited() {
15622        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15623    }
15624
15625    /**
15626     * @return true if layout direction has been resolved.
15627     */
15628    public boolean isLayoutDirectionResolved() {
15629        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15630    }
15631
15632    /**
15633     * Return if padding has been resolved
15634     *
15635     * @hide
15636     */
15637    boolean isPaddingResolved() {
15638        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15639    }
15640
15641    /**
15642     * Resolves padding depending on layout direction, if applicable, and
15643     * recomputes internal padding values to adjust for scroll bars.
15644     *
15645     * @hide
15646     */
15647    public void resolvePadding() {
15648        final int resolvedLayoutDirection = getLayoutDirection();
15649
15650        if (!isRtlCompatibilityMode()) {
15651            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15652            // If start / end padding are defined, they will be resolved (hence overriding) to
15653            // left / right or right / left depending on the resolved layout direction.
15654            // If start / end padding are not defined, use the left / right ones.
15655            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15656                Rect padding = sThreadLocal.get();
15657                if (padding == null) {
15658                    padding = new Rect();
15659                    sThreadLocal.set(padding);
15660                }
15661                mBackground.getPadding(padding);
15662                if (!mLeftPaddingDefined) {
15663                    mUserPaddingLeftInitial = padding.left;
15664                }
15665                if (!mRightPaddingDefined) {
15666                    mUserPaddingRightInitial = padding.right;
15667                }
15668            }
15669            switch (resolvedLayoutDirection) {
15670                case LAYOUT_DIRECTION_RTL:
15671                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15672                        mUserPaddingRight = mUserPaddingStart;
15673                    } else {
15674                        mUserPaddingRight = mUserPaddingRightInitial;
15675                    }
15676                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15677                        mUserPaddingLeft = mUserPaddingEnd;
15678                    } else {
15679                        mUserPaddingLeft = mUserPaddingLeftInitial;
15680                    }
15681                    break;
15682                case LAYOUT_DIRECTION_LTR:
15683                default:
15684                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15685                        mUserPaddingLeft = mUserPaddingStart;
15686                    } else {
15687                        mUserPaddingLeft = mUserPaddingLeftInitial;
15688                    }
15689                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15690                        mUserPaddingRight = mUserPaddingEnd;
15691                    } else {
15692                        mUserPaddingRight = mUserPaddingRightInitial;
15693                    }
15694            }
15695
15696            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15697        }
15698
15699        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15700        onRtlPropertiesChanged(resolvedLayoutDirection);
15701
15702        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15703    }
15704
15705    /**
15706     * Reset the resolved layout direction.
15707     *
15708     * @hide
15709     */
15710    public void resetResolvedPadding() {
15711        resetResolvedPaddingInternal();
15712    }
15713
15714    /**
15715     * Used when we only want to reset *this* view's padding and not trigger overrides
15716     * in ViewGroup that reset children too.
15717     */
15718    void resetResolvedPaddingInternal() {
15719        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15720    }
15721
15722    /**
15723     * This is called when the view is detached from a window.  At this point it
15724     * no longer has a surface for drawing.
15725     *
15726     * @see #onAttachedToWindow()
15727     */
15728    @CallSuper
15729    protected void onDetachedFromWindow() {
15730    }
15731
15732    /**
15733     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15734     * after onDetachedFromWindow().
15735     *
15736     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15737     * The super method should be called at the end of the overridden method to ensure
15738     * subclasses are destroyed first
15739     *
15740     * @hide
15741     */
15742    @CallSuper
15743    protected void onDetachedFromWindowInternal() {
15744        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15745        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15746        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15747
15748        removeUnsetPressCallback();
15749        removeLongPressCallback();
15750        removePerformClickCallback();
15751        removeSendViewScrolledAccessibilityEventCallback();
15752        stopNestedScroll();
15753
15754        // Anything that started animating right before detach should already
15755        // be in its final state when re-attached.
15756        jumpDrawablesToCurrentState();
15757
15758        destroyDrawingCache();
15759
15760        cleanupDraw();
15761        mCurrentAnimation = null;
15762
15763        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
15764            hideTooltip();
15765        }
15766    }
15767
15768    private void cleanupDraw() {
15769        resetDisplayList();
15770        if (mAttachInfo != null) {
15771            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15772        }
15773    }
15774
15775    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15776    }
15777
15778    /**
15779     * @return The number of times this view has been attached to a window
15780     */
15781    protected int getWindowAttachCount() {
15782        return mWindowAttachCount;
15783    }
15784
15785    /**
15786     * Retrieve a unique token identifying the window this view is attached to.
15787     * @return Return the window's token for use in
15788     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15789     */
15790    public IBinder getWindowToken() {
15791        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15792    }
15793
15794    /**
15795     * Retrieve the {@link WindowId} for the window this view is
15796     * currently attached to.
15797     */
15798    public WindowId getWindowId() {
15799        if (mAttachInfo == null) {
15800            return null;
15801        }
15802        if (mAttachInfo.mWindowId == null) {
15803            try {
15804                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15805                        mAttachInfo.mWindowToken);
15806                mAttachInfo.mWindowId = new WindowId(
15807                        mAttachInfo.mIWindowId);
15808            } catch (RemoteException e) {
15809            }
15810        }
15811        return mAttachInfo.mWindowId;
15812    }
15813
15814    /**
15815     * Retrieve a unique token identifying the top-level "real" window of
15816     * the window that this view is attached to.  That is, this is like
15817     * {@link #getWindowToken}, except if the window this view in is a panel
15818     * window (attached to another containing window), then the token of
15819     * the containing window is returned instead.
15820     *
15821     * @return Returns the associated window token, either
15822     * {@link #getWindowToken()} or the containing window's token.
15823     */
15824    public IBinder getApplicationWindowToken() {
15825        AttachInfo ai = mAttachInfo;
15826        if (ai != null) {
15827            IBinder appWindowToken = ai.mPanelParentWindowToken;
15828            if (appWindowToken == null) {
15829                appWindowToken = ai.mWindowToken;
15830            }
15831            return appWindowToken;
15832        }
15833        return null;
15834    }
15835
15836    /**
15837     * Gets the logical display to which the view's window has been attached.
15838     *
15839     * @return The logical display, or null if the view is not currently attached to a window.
15840     */
15841    public Display getDisplay() {
15842        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15843    }
15844
15845    /**
15846     * Retrieve private session object this view hierarchy is using to
15847     * communicate with the window manager.
15848     * @return the session object to communicate with the window manager
15849     */
15850    /*package*/ IWindowSession getWindowSession() {
15851        return mAttachInfo != null ? mAttachInfo.mSession : null;
15852    }
15853
15854    /**
15855     * Return the visibility value of the least visible component passed.
15856     */
15857    int combineVisibility(int vis1, int vis2) {
15858        // This works because VISIBLE < INVISIBLE < GONE.
15859        return Math.max(vis1, vis2);
15860    }
15861
15862    /**
15863     * @param info the {@link android.view.View.AttachInfo} to associated with
15864     *        this view
15865     */
15866    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15867        mAttachInfo = info;
15868        if (mOverlay != null) {
15869            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15870        }
15871        mWindowAttachCount++;
15872        // We will need to evaluate the drawable state at least once.
15873        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15874        if (mFloatingTreeObserver != null) {
15875            info.mTreeObserver.merge(mFloatingTreeObserver);
15876            mFloatingTreeObserver = null;
15877        }
15878
15879        registerPendingFrameMetricsObservers();
15880
15881        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15882            mAttachInfo.mScrollContainers.add(this);
15883            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15884        }
15885        // Transfer all pending runnables.
15886        if (mRunQueue != null) {
15887            mRunQueue.executeActions(info.mHandler);
15888            mRunQueue = null;
15889        }
15890        performCollectViewAttributes(mAttachInfo, visibility);
15891        onAttachedToWindow();
15892
15893        ListenerInfo li = mListenerInfo;
15894        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15895                li != null ? li.mOnAttachStateChangeListeners : null;
15896        if (listeners != null && listeners.size() > 0) {
15897            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15898            // perform the dispatching. The iterator is a safe guard against listeners that
15899            // could mutate the list by calling the various add/remove methods. This prevents
15900            // the array from being modified while we iterate it.
15901            for (OnAttachStateChangeListener listener : listeners) {
15902                listener.onViewAttachedToWindow(this);
15903            }
15904        }
15905
15906        int vis = info.mWindowVisibility;
15907        if (vis != GONE) {
15908            onWindowVisibilityChanged(vis);
15909            if (isShown()) {
15910                // Calling onVisibilityAggregated directly here since the subtree will also
15911                // receive dispatchAttachedToWindow and this same call
15912                onVisibilityAggregated(vis == VISIBLE);
15913            }
15914        }
15915
15916        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15917        // As all views in the subtree will already receive dispatchAttachedToWindow
15918        // traversing the subtree again here is not desired.
15919        onVisibilityChanged(this, visibility);
15920
15921        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15922            // If nobody has evaluated the drawable state yet, then do it now.
15923            refreshDrawableState();
15924        }
15925        needGlobalAttributesUpdate(false);
15926    }
15927
15928    void dispatchDetachedFromWindow() {
15929        AttachInfo info = mAttachInfo;
15930        if (info != null) {
15931            int vis = info.mWindowVisibility;
15932            if (vis != GONE) {
15933                onWindowVisibilityChanged(GONE);
15934                if (isShown()) {
15935                    // Invoking onVisibilityAggregated directly here since the subtree
15936                    // will also receive detached from window
15937                    onVisibilityAggregated(false);
15938                }
15939            }
15940        }
15941
15942        onDetachedFromWindow();
15943        onDetachedFromWindowInternal();
15944
15945        InputMethodManager imm = InputMethodManager.peekInstance();
15946        if (imm != null) {
15947            imm.onViewDetachedFromWindow(this);
15948        }
15949
15950        ListenerInfo li = mListenerInfo;
15951        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15952                li != null ? li.mOnAttachStateChangeListeners : null;
15953        if (listeners != null && listeners.size() > 0) {
15954            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15955            // perform the dispatching. The iterator is a safe guard against listeners that
15956            // could mutate the list by calling the various add/remove methods. This prevents
15957            // the array from being modified while we iterate it.
15958            for (OnAttachStateChangeListener listener : listeners) {
15959                listener.onViewDetachedFromWindow(this);
15960            }
15961        }
15962
15963        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15964            mAttachInfo.mScrollContainers.remove(this);
15965            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15966        }
15967
15968        mAttachInfo = null;
15969        if (mOverlay != null) {
15970            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15971        }
15972    }
15973
15974    /**
15975     * Cancel any deferred high-level input events that were previously posted to the event queue.
15976     *
15977     * <p>Many views post high-level events such as click handlers to the event queue
15978     * to run deferred in order to preserve a desired user experience - clearing visible
15979     * pressed states before executing, etc. This method will abort any events of this nature
15980     * that are currently in flight.</p>
15981     *
15982     * <p>Custom views that generate their own high-level deferred input events should override
15983     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15984     *
15985     * <p>This will also cancel pending input events for any child views.</p>
15986     *
15987     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15988     * This will not impact newer events posted after this call that may occur as a result of
15989     * lower-level input events still waiting in the queue. If you are trying to prevent
15990     * double-submitted  events for the duration of some sort of asynchronous transaction
15991     * you should also take other steps to protect against unexpected double inputs e.g. calling
15992     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15993     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15994     */
15995    public final void cancelPendingInputEvents() {
15996        dispatchCancelPendingInputEvents();
15997    }
15998
15999    /**
16000     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16001     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16002     */
16003    void dispatchCancelPendingInputEvents() {
16004        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16005        onCancelPendingInputEvents();
16006        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16007            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16008                    " did not call through to super.onCancelPendingInputEvents()");
16009        }
16010    }
16011
16012    /**
16013     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16014     * a parent view.
16015     *
16016     * <p>This method is responsible for removing any pending high-level input events that were
16017     * posted to the event queue to run later. Custom view classes that post their own deferred
16018     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16019     * {@link android.os.Handler} should override this method, call
16020     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16021     * </p>
16022     */
16023    public void onCancelPendingInputEvents() {
16024        removePerformClickCallback();
16025        cancelLongPress();
16026        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16027    }
16028
16029    /**
16030     * Store this view hierarchy's frozen state into the given container.
16031     *
16032     * @param container The SparseArray in which to save the view's state.
16033     *
16034     * @see #restoreHierarchyState(android.util.SparseArray)
16035     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16036     * @see #onSaveInstanceState()
16037     */
16038    public void saveHierarchyState(SparseArray<Parcelable> container) {
16039        dispatchSaveInstanceState(container);
16040    }
16041
16042    /**
16043     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16044     * this view and its children. May be overridden to modify how freezing happens to a
16045     * view's children; for example, some views may want to not store state for their children.
16046     *
16047     * @param container The SparseArray in which to save the view's state.
16048     *
16049     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16050     * @see #saveHierarchyState(android.util.SparseArray)
16051     * @see #onSaveInstanceState()
16052     */
16053    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16054        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16055            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16056            Parcelable state = onSaveInstanceState();
16057            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16058                throw new IllegalStateException(
16059                        "Derived class did not call super.onSaveInstanceState()");
16060            }
16061            if (state != null) {
16062                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16063                // + ": " + state);
16064                container.put(mID, state);
16065            }
16066        }
16067    }
16068
16069    /**
16070     * Hook allowing a view to generate a representation of its internal state
16071     * that can later be used to create a new instance with that same state.
16072     * This state should only contain information that is not persistent or can
16073     * not be reconstructed later. For example, you will never store your
16074     * current position on screen because that will be computed again when a
16075     * new instance of the view is placed in its view hierarchy.
16076     * <p>
16077     * Some examples of things you may store here: the current cursor position
16078     * in a text view (but usually not the text itself since that is stored in a
16079     * content provider or other persistent storage), the currently selected
16080     * item in a list view.
16081     *
16082     * @return Returns a Parcelable object containing the view's current dynamic
16083     *         state, or null if there is nothing interesting to save. The
16084     *         default implementation returns null.
16085     * @see #onRestoreInstanceState(android.os.Parcelable)
16086     * @see #saveHierarchyState(android.util.SparseArray)
16087     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16088     * @see #setSaveEnabled(boolean)
16089     */
16090    @CallSuper
16091    protected Parcelable onSaveInstanceState() {
16092        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16093        if (mStartActivityRequestWho != null) {
16094            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16095            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16096            return state;
16097        }
16098        return BaseSavedState.EMPTY_STATE;
16099    }
16100
16101    /**
16102     * Restore this view hierarchy's frozen state from the given container.
16103     *
16104     * @param container The SparseArray which holds previously frozen states.
16105     *
16106     * @see #saveHierarchyState(android.util.SparseArray)
16107     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16108     * @see #onRestoreInstanceState(android.os.Parcelable)
16109     */
16110    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16111        dispatchRestoreInstanceState(container);
16112    }
16113
16114    /**
16115     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16116     * state for this view and its children. May be overridden to modify how restoring
16117     * happens to a view's children; for example, some views may want to not store state
16118     * for their children.
16119     *
16120     * @param container The SparseArray which holds previously saved state.
16121     *
16122     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16123     * @see #restoreHierarchyState(android.util.SparseArray)
16124     * @see #onRestoreInstanceState(android.os.Parcelable)
16125     */
16126    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16127        if (mID != NO_ID) {
16128            Parcelable state = container.get(mID);
16129            if (state != null) {
16130                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16131                // + ": " + state);
16132                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16133                onRestoreInstanceState(state);
16134                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16135                    throw new IllegalStateException(
16136                            "Derived class did not call super.onRestoreInstanceState()");
16137                }
16138            }
16139        }
16140    }
16141
16142    /**
16143     * Hook allowing a view to re-apply a representation of its internal state that had previously
16144     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16145     * null state.
16146     *
16147     * @param state The frozen state that had previously been returned by
16148     *        {@link #onSaveInstanceState}.
16149     *
16150     * @see #onSaveInstanceState()
16151     * @see #restoreHierarchyState(android.util.SparseArray)
16152     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16153     */
16154    @CallSuper
16155    protected void onRestoreInstanceState(Parcelable state) {
16156        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16157        if (state != null && !(state instanceof AbsSavedState)) {
16158            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16159                    + "received " + state.getClass().toString() + " instead. This usually happens "
16160                    + "when two views of different type have the same id in the same hierarchy. "
16161                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16162                    + "other views do not use the same id.");
16163        }
16164        if (state != null && state instanceof BaseSavedState) {
16165            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16166        }
16167    }
16168
16169    /**
16170     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16171     *
16172     * @return the drawing start time in milliseconds
16173     */
16174    public long getDrawingTime() {
16175        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16176    }
16177
16178    /**
16179     * <p>Enables or disables the duplication of the parent's state into this view. When
16180     * duplication is enabled, this view gets its drawable state from its parent rather
16181     * than from its own internal properties.</p>
16182     *
16183     * <p>Note: in the current implementation, setting this property to true after the
16184     * view was added to a ViewGroup might have no effect at all. This property should
16185     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16186     *
16187     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16188     * property is enabled, an exception will be thrown.</p>
16189     *
16190     * <p>Note: if the child view uses and updates additional states which are unknown to the
16191     * parent, these states should not be affected by this method.</p>
16192     *
16193     * @param enabled True to enable duplication of the parent's drawable state, false
16194     *                to disable it.
16195     *
16196     * @see #getDrawableState()
16197     * @see #isDuplicateParentStateEnabled()
16198     */
16199    public void setDuplicateParentStateEnabled(boolean enabled) {
16200        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16201    }
16202
16203    /**
16204     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16205     *
16206     * @return True if this view's drawable state is duplicated from the parent,
16207     *         false otherwise
16208     *
16209     * @see #getDrawableState()
16210     * @see #setDuplicateParentStateEnabled(boolean)
16211     */
16212    public boolean isDuplicateParentStateEnabled() {
16213        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16214    }
16215
16216    /**
16217     * <p>Specifies the type of layer backing this view. The layer can be
16218     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16219     * {@link #LAYER_TYPE_HARDWARE}.</p>
16220     *
16221     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16222     * instance that controls how the layer is composed on screen. The following
16223     * properties of the paint are taken into account when composing the layer:</p>
16224     * <ul>
16225     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16226     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16227     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16228     * </ul>
16229     *
16230     * <p>If this view has an alpha value set to < 1.0 by calling
16231     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16232     * by this view's alpha value.</p>
16233     *
16234     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16235     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16236     * for more information on when and how to use layers.</p>
16237     *
16238     * @param layerType The type of layer to use with this view, must be one of
16239     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16240     *        {@link #LAYER_TYPE_HARDWARE}
16241     * @param paint The paint used to compose the layer. This argument is optional
16242     *        and can be null. It is ignored when the layer type is
16243     *        {@link #LAYER_TYPE_NONE}
16244     *
16245     * @see #getLayerType()
16246     * @see #LAYER_TYPE_NONE
16247     * @see #LAYER_TYPE_SOFTWARE
16248     * @see #LAYER_TYPE_HARDWARE
16249     * @see #setAlpha(float)
16250     *
16251     * @attr ref android.R.styleable#View_layerType
16252     */
16253    public void setLayerType(int layerType, @Nullable Paint paint) {
16254        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16255            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16256                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16257        }
16258
16259        boolean typeChanged = mRenderNode.setLayerType(layerType);
16260
16261        if (!typeChanged) {
16262            setLayerPaint(paint);
16263            return;
16264        }
16265
16266        if (layerType != LAYER_TYPE_SOFTWARE) {
16267            // Destroy any previous software drawing cache if present
16268            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16269            // drawing cache created in View#draw when drawing to a SW canvas.
16270            destroyDrawingCache();
16271        }
16272
16273        mLayerType = layerType;
16274        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16275        mRenderNode.setLayerPaint(mLayerPaint);
16276
16277        // draw() behaves differently if we are on a layer, so we need to
16278        // invalidate() here
16279        invalidateParentCaches();
16280        invalidate(true);
16281    }
16282
16283    /**
16284     * Updates the {@link Paint} object used with the current layer (used only if the current
16285     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16286     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16287     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16288     * ensure that the view gets redrawn immediately.
16289     *
16290     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16291     * instance that controls how the layer is composed on screen. The following
16292     * properties of the paint are taken into account when composing the layer:</p>
16293     * <ul>
16294     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16295     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16296     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16297     * </ul>
16298     *
16299     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16300     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16301     *
16302     * @param paint The paint used to compose the layer. This argument is optional
16303     *        and can be null. It is ignored when the layer type is
16304     *        {@link #LAYER_TYPE_NONE}
16305     *
16306     * @see #setLayerType(int, android.graphics.Paint)
16307     */
16308    public void setLayerPaint(@Nullable Paint paint) {
16309        int layerType = getLayerType();
16310        if (layerType != LAYER_TYPE_NONE) {
16311            mLayerPaint = paint;
16312            if (layerType == LAYER_TYPE_HARDWARE) {
16313                if (mRenderNode.setLayerPaint(paint)) {
16314                    invalidateViewProperty(false, false);
16315                }
16316            } else {
16317                invalidate();
16318            }
16319        }
16320    }
16321
16322    /**
16323     * Indicates what type of layer is currently associated with this view. By default
16324     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16325     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16326     * for more information on the different types of layers.
16327     *
16328     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16329     *         {@link #LAYER_TYPE_HARDWARE}
16330     *
16331     * @see #setLayerType(int, android.graphics.Paint)
16332     * @see #buildLayer()
16333     * @see #LAYER_TYPE_NONE
16334     * @see #LAYER_TYPE_SOFTWARE
16335     * @see #LAYER_TYPE_HARDWARE
16336     */
16337    public int getLayerType() {
16338        return mLayerType;
16339    }
16340
16341    /**
16342     * Forces this view's layer to be created and this view to be rendered
16343     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16344     * invoking this method will have no effect.
16345     *
16346     * This method can for instance be used to render a view into its layer before
16347     * starting an animation. If this view is complex, rendering into the layer
16348     * before starting the animation will avoid skipping frames.
16349     *
16350     * @throws IllegalStateException If this view is not attached to a window
16351     *
16352     * @see #setLayerType(int, android.graphics.Paint)
16353     */
16354    public void buildLayer() {
16355        if (mLayerType == LAYER_TYPE_NONE) return;
16356
16357        final AttachInfo attachInfo = mAttachInfo;
16358        if (attachInfo == null) {
16359            throw new IllegalStateException("This view must be attached to a window first");
16360        }
16361
16362        if (getWidth() == 0 || getHeight() == 0) {
16363            return;
16364        }
16365
16366        switch (mLayerType) {
16367            case LAYER_TYPE_HARDWARE:
16368                updateDisplayListIfDirty();
16369                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16370                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16371                }
16372                break;
16373            case LAYER_TYPE_SOFTWARE:
16374                buildDrawingCache(true);
16375                break;
16376        }
16377    }
16378
16379    /**
16380     * Destroys all hardware rendering resources. This method is invoked
16381     * when the system needs to reclaim resources. Upon execution of this
16382     * method, you should free any OpenGL resources created by the view.
16383     *
16384     * Note: you <strong>must</strong> call
16385     * <code>super.destroyHardwareResources()</code> when overriding
16386     * this method.
16387     *
16388     * @hide
16389     */
16390    @CallSuper
16391    protected void destroyHardwareResources() {
16392        // Although the Layer will be destroyed by RenderNode, we want to release
16393        // the staging display list, which is also a signal to RenderNode that it's
16394        // safe to free its copy of the display list as it knows that we will
16395        // push an updated DisplayList if we try to draw again
16396        resetDisplayList();
16397    }
16398
16399    /**
16400     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16401     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16402     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16403     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16404     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16405     * null.</p>
16406     *
16407     * <p>Enabling the drawing cache is similar to
16408     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16409     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16410     * drawing cache has no effect on rendering because the system uses a different mechanism
16411     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16412     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16413     * for information on how to enable software and hardware layers.</p>
16414     *
16415     * <p>This API can be used to manually generate
16416     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16417     * {@link #getDrawingCache()}.</p>
16418     *
16419     * @param enabled true to enable the drawing cache, false otherwise
16420     *
16421     * @see #isDrawingCacheEnabled()
16422     * @see #getDrawingCache()
16423     * @see #buildDrawingCache()
16424     * @see #setLayerType(int, android.graphics.Paint)
16425     */
16426    public void setDrawingCacheEnabled(boolean enabled) {
16427        mCachingFailed = false;
16428        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16429    }
16430
16431    /**
16432     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16433     *
16434     * @return true if the drawing cache is enabled
16435     *
16436     * @see #setDrawingCacheEnabled(boolean)
16437     * @see #getDrawingCache()
16438     */
16439    @ViewDebug.ExportedProperty(category = "drawing")
16440    public boolean isDrawingCacheEnabled() {
16441        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16442    }
16443
16444    /**
16445     * Debugging utility which recursively outputs the dirty state of a view and its
16446     * descendants.
16447     *
16448     * @hide
16449     */
16450    @SuppressWarnings({"UnusedDeclaration"})
16451    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16452        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16453                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16454                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16455                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16456        if (clear) {
16457            mPrivateFlags &= clearMask;
16458        }
16459        if (this instanceof ViewGroup) {
16460            ViewGroup parent = (ViewGroup) this;
16461            final int count = parent.getChildCount();
16462            for (int i = 0; i < count; i++) {
16463                final View child = parent.getChildAt(i);
16464                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16465            }
16466        }
16467    }
16468
16469    /**
16470     * This method is used by ViewGroup to cause its children to restore or recreate their
16471     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16472     * to recreate its own display list, which would happen if it went through the normal
16473     * draw/dispatchDraw mechanisms.
16474     *
16475     * @hide
16476     */
16477    protected void dispatchGetDisplayList() {}
16478
16479    /**
16480     * A view that is not attached or hardware accelerated cannot create a display list.
16481     * This method checks these conditions and returns the appropriate result.
16482     *
16483     * @return true if view has the ability to create a display list, false otherwise.
16484     *
16485     * @hide
16486     */
16487    public boolean canHaveDisplayList() {
16488        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16489    }
16490
16491    /**
16492     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16493     * @hide
16494     */
16495    @NonNull
16496    public RenderNode updateDisplayListIfDirty() {
16497        final RenderNode renderNode = mRenderNode;
16498        if (!canHaveDisplayList()) {
16499            // can't populate RenderNode, don't try
16500            return renderNode;
16501        }
16502
16503        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16504                || !renderNode.isValid()
16505                || (mRecreateDisplayList)) {
16506            // Don't need to recreate the display list, just need to tell our
16507            // children to restore/recreate theirs
16508            if (renderNode.isValid()
16509                    && !mRecreateDisplayList) {
16510                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16511                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16512                dispatchGetDisplayList();
16513
16514                return renderNode; // no work needed
16515            }
16516
16517            // If we got here, we're recreating it. Mark it as such to ensure that
16518            // we copy in child display lists into ours in drawChild()
16519            mRecreateDisplayList = true;
16520
16521            int width = mRight - mLeft;
16522            int height = mBottom - mTop;
16523            int layerType = getLayerType();
16524
16525            final DisplayListCanvas canvas = renderNode.start(width, height);
16526            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16527
16528            try {
16529                if (layerType == LAYER_TYPE_SOFTWARE) {
16530                    buildDrawingCache(true);
16531                    Bitmap cache = getDrawingCache(true);
16532                    if (cache != null) {
16533                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16534                    }
16535                } else {
16536                    computeScroll();
16537
16538                    canvas.translate(-mScrollX, -mScrollY);
16539                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16540                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16541
16542                    // Fast path for layouts with no backgrounds
16543                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16544                        dispatchDraw(canvas);
16545                        if (mOverlay != null && !mOverlay.isEmpty()) {
16546                            mOverlay.getOverlayView().draw(canvas);
16547                        }
16548                        if (debugDraw()) {
16549                            debugDrawFocus(canvas);
16550                        }
16551                    } else {
16552                        draw(canvas);
16553                    }
16554                }
16555            } finally {
16556                renderNode.end(canvas);
16557                setDisplayListProperties(renderNode);
16558            }
16559        } else {
16560            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16561            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16562        }
16563        return renderNode;
16564    }
16565
16566    private void resetDisplayList() {
16567        if (mRenderNode.isValid()) {
16568            mRenderNode.discardDisplayList();
16569        }
16570
16571        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16572            mBackgroundRenderNode.discardDisplayList();
16573        }
16574    }
16575
16576    /**
16577     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16578     *
16579     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16580     *
16581     * @see #getDrawingCache(boolean)
16582     */
16583    public Bitmap getDrawingCache() {
16584        return getDrawingCache(false);
16585    }
16586
16587    /**
16588     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16589     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16590     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16591     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16592     * request the drawing cache by calling this method and draw it on screen if the
16593     * returned bitmap is not null.</p>
16594     *
16595     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16596     * this method will create a bitmap of the same size as this view. Because this bitmap
16597     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16598     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16599     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16600     * size than the view. This implies that your application must be able to handle this
16601     * size.</p>
16602     *
16603     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16604     *        the current density of the screen when the application is in compatibility
16605     *        mode.
16606     *
16607     * @return A bitmap representing this view or null if cache is disabled.
16608     *
16609     * @see #setDrawingCacheEnabled(boolean)
16610     * @see #isDrawingCacheEnabled()
16611     * @see #buildDrawingCache(boolean)
16612     * @see #destroyDrawingCache()
16613     */
16614    public Bitmap getDrawingCache(boolean autoScale) {
16615        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16616            return null;
16617        }
16618        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16619            buildDrawingCache(autoScale);
16620        }
16621        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16622    }
16623
16624    /**
16625     * <p>Frees the resources used by the drawing cache. If you call
16626     * {@link #buildDrawingCache()} manually without calling
16627     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16628     * should cleanup the cache with this method afterwards.</p>
16629     *
16630     * @see #setDrawingCacheEnabled(boolean)
16631     * @see #buildDrawingCache()
16632     * @see #getDrawingCache()
16633     */
16634    public void destroyDrawingCache() {
16635        if (mDrawingCache != null) {
16636            mDrawingCache.recycle();
16637            mDrawingCache = null;
16638        }
16639        if (mUnscaledDrawingCache != null) {
16640            mUnscaledDrawingCache.recycle();
16641            mUnscaledDrawingCache = null;
16642        }
16643    }
16644
16645    /**
16646     * Setting a solid background color for the drawing cache's bitmaps will improve
16647     * performance and memory usage. Note, though that this should only be used if this
16648     * view will always be drawn on top of a solid color.
16649     *
16650     * @param color The background color to use for the drawing cache's bitmap
16651     *
16652     * @see #setDrawingCacheEnabled(boolean)
16653     * @see #buildDrawingCache()
16654     * @see #getDrawingCache()
16655     */
16656    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16657        if (color != mDrawingCacheBackgroundColor) {
16658            mDrawingCacheBackgroundColor = color;
16659            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16660        }
16661    }
16662
16663    /**
16664     * @see #setDrawingCacheBackgroundColor(int)
16665     *
16666     * @return The background color to used for the drawing cache's bitmap
16667     */
16668    @ColorInt
16669    public int getDrawingCacheBackgroundColor() {
16670        return mDrawingCacheBackgroundColor;
16671    }
16672
16673    /**
16674     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16675     *
16676     * @see #buildDrawingCache(boolean)
16677     */
16678    public void buildDrawingCache() {
16679        buildDrawingCache(false);
16680    }
16681
16682    /**
16683     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16684     *
16685     * <p>If you call {@link #buildDrawingCache()} manually without calling
16686     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16687     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16688     *
16689     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16690     * this method will create a bitmap of the same size as this view. Because this bitmap
16691     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16692     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16693     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16694     * size than the view. This implies that your application must be able to handle this
16695     * size.</p>
16696     *
16697     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16698     * you do not need the drawing cache bitmap, calling this method will increase memory
16699     * usage and cause the view to be rendered in software once, thus negatively impacting
16700     * performance.</p>
16701     *
16702     * @see #getDrawingCache()
16703     * @see #destroyDrawingCache()
16704     */
16705    public void buildDrawingCache(boolean autoScale) {
16706        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16707                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16708            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16709                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16710                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16711            }
16712            try {
16713                buildDrawingCacheImpl(autoScale);
16714            } finally {
16715                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16716            }
16717        }
16718    }
16719
16720    /**
16721     * private, internal implementation of buildDrawingCache, used to enable tracing
16722     */
16723    private void buildDrawingCacheImpl(boolean autoScale) {
16724        mCachingFailed = false;
16725
16726        int width = mRight - mLeft;
16727        int height = mBottom - mTop;
16728
16729        final AttachInfo attachInfo = mAttachInfo;
16730        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16731
16732        if (autoScale && scalingRequired) {
16733            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16734            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16735        }
16736
16737        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16738        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16739        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16740
16741        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16742        final long drawingCacheSize =
16743                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16744        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16745            if (width > 0 && height > 0) {
16746                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16747                        + " too large to fit into a software layer (or drawing cache), needs "
16748                        + projectedBitmapSize + " bytes, only "
16749                        + drawingCacheSize + " available");
16750            }
16751            destroyDrawingCache();
16752            mCachingFailed = true;
16753            return;
16754        }
16755
16756        boolean clear = true;
16757        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16758
16759        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16760            Bitmap.Config quality;
16761            if (!opaque) {
16762                // Never pick ARGB_4444 because it looks awful
16763                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16764                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16765                    case DRAWING_CACHE_QUALITY_AUTO:
16766                    case DRAWING_CACHE_QUALITY_LOW:
16767                    case DRAWING_CACHE_QUALITY_HIGH:
16768                    default:
16769                        quality = Bitmap.Config.ARGB_8888;
16770                        break;
16771                }
16772            } else {
16773                // Optimization for translucent windows
16774                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16775                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16776            }
16777
16778            // Try to cleanup memory
16779            if (bitmap != null) bitmap.recycle();
16780
16781            try {
16782                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16783                        width, height, quality);
16784                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16785                if (autoScale) {
16786                    mDrawingCache = bitmap;
16787                } else {
16788                    mUnscaledDrawingCache = bitmap;
16789                }
16790                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16791            } catch (OutOfMemoryError e) {
16792                // If there is not enough memory to create the bitmap cache, just
16793                // ignore the issue as bitmap caches are not required to draw the
16794                // view hierarchy
16795                if (autoScale) {
16796                    mDrawingCache = null;
16797                } else {
16798                    mUnscaledDrawingCache = null;
16799                }
16800                mCachingFailed = true;
16801                return;
16802            }
16803
16804            clear = drawingCacheBackgroundColor != 0;
16805        }
16806
16807        Canvas canvas;
16808        if (attachInfo != null) {
16809            canvas = attachInfo.mCanvas;
16810            if (canvas == null) {
16811                canvas = new Canvas();
16812            }
16813            canvas.setBitmap(bitmap);
16814            // Temporarily clobber the cached Canvas in case one of our children
16815            // is also using a drawing cache. Without this, the children would
16816            // steal the canvas by attaching their own bitmap to it and bad, bad
16817            // thing would happen (invisible views, corrupted drawings, etc.)
16818            attachInfo.mCanvas = null;
16819        } else {
16820            // This case should hopefully never or seldom happen
16821            canvas = new Canvas(bitmap);
16822        }
16823
16824        if (clear) {
16825            bitmap.eraseColor(drawingCacheBackgroundColor);
16826        }
16827
16828        computeScroll();
16829        final int restoreCount = canvas.save();
16830
16831        if (autoScale && scalingRequired) {
16832            final float scale = attachInfo.mApplicationScale;
16833            canvas.scale(scale, scale);
16834        }
16835
16836        canvas.translate(-mScrollX, -mScrollY);
16837
16838        mPrivateFlags |= PFLAG_DRAWN;
16839        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16840                mLayerType != LAYER_TYPE_NONE) {
16841            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16842        }
16843
16844        // Fast path for layouts with no backgrounds
16845        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16846            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16847            dispatchDraw(canvas);
16848            if (mOverlay != null && !mOverlay.isEmpty()) {
16849                mOverlay.getOverlayView().draw(canvas);
16850            }
16851        } else {
16852            draw(canvas);
16853        }
16854
16855        canvas.restoreToCount(restoreCount);
16856        canvas.setBitmap(null);
16857
16858        if (attachInfo != null) {
16859            // Restore the cached Canvas for our siblings
16860            attachInfo.mCanvas = canvas;
16861        }
16862    }
16863
16864    /**
16865     * Create a snapshot of the view into a bitmap.  We should probably make
16866     * some form of this public, but should think about the API.
16867     *
16868     * @hide
16869     */
16870    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16871        int width = mRight - mLeft;
16872        int height = mBottom - mTop;
16873
16874        final AttachInfo attachInfo = mAttachInfo;
16875        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16876        width = (int) ((width * scale) + 0.5f);
16877        height = (int) ((height * scale) + 0.5f);
16878
16879        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16880                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16881        if (bitmap == null) {
16882            throw new OutOfMemoryError();
16883        }
16884
16885        Resources resources = getResources();
16886        if (resources != null) {
16887            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16888        }
16889
16890        Canvas canvas;
16891        if (attachInfo != null) {
16892            canvas = attachInfo.mCanvas;
16893            if (canvas == null) {
16894                canvas = new Canvas();
16895            }
16896            canvas.setBitmap(bitmap);
16897            // Temporarily clobber the cached Canvas in case one of our children
16898            // is also using a drawing cache. Without this, the children would
16899            // steal the canvas by attaching their own bitmap to it and bad, bad
16900            // things would happen (invisible views, corrupted drawings, etc.)
16901            attachInfo.mCanvas = null;
16902        } else {
16903            // This case should hopefully never or seldom happen
16904            canvas = new Canvas(bitmap);
16905        }
16906
16907        if ((backgroundColor & 0xff000000) != 0) {
16908            bitmap.eraseColor(backgroundColor);
16909        }
16910
16911        computeScroll();
16912        final int restoreCount = canvas.save();
16913        canvas.scale(scale, scale);
16914        canvas.translate(-mScrollX, -mScrollY);
16915
16916        // Temporarily remove the dirty mask
16917        int flags = mPrivateFlags;
16918        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16919
16920        // Fast path for layouts with no backgrounds
16921        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16922            dispatchDraw(canvas);
16923            if (mOverlay != null && !mOverlay.isEmpty()) {
16924                mOverlay.getOverlayView().draw(canvas);
16925            }
16926        } else {
16927            draw(canvas);
16928        }
16929
16930        mPrivateFlags = flags;
16931
16932        canvas.restoreToCount(restoreCount);
16933        canvas.setBitmap(null);
16934
16935        if (attachInfo != null) {
16936            // Restore the cached Canvas for our siblings
16937            attachInfo.mCanvas = canvas;
16938        }
16939
16940        return bitmap;
16941    }
16942
16943    /**
16944     * Indicates whether this View is currently in edit mode. A View is usually
16945     * in edit mode when displayed within a developer tool. For instance, if
16946     * this View is being drawn by a visual user interface builder, this method
16947     * should return true.
16948     *
16949     * Subclasses should check the return value of this method to provide
16950     * different behaviors if their normal behavior might interfere with the
16951     * host environment. For instance: the class spawns a thread in its
16952     * constructor, the drawing code relies on device-specific features, etc.
16953     *
16954     * This method is usually checked in the drawing code of custom widgets.
16955     *
16956     * @return True if this View is in edit mode, false otherwise.
16957     */
16958    public boolean isInEditMode() {
16959        return false;
16960    }
16961
16962    /**
16963     * If the View draws content inside its padding and enables fading edges,
16964     * it needs to support padding offsets. Padding offsets are added to the
16965     * fading edges to extend the length of the fade so that it covers pixels
16966     * drawn inside the padding.
16967     *
16968     * Subclasses of this class should override this method if they need
16969     * to draw content inside the padding.
16970     *
16971     * @return True if padding offset must be applied, false otherwise.
16972     *
16973     * @see #getLeftPaddingOffset()
16974     * @see #getRightPaddingOffset()
16975     * @see #getTopPaddingOffset()
16976     * @see #getBottomPaddingOffset()
16977     *
16978     * @since CURRENT
16979     */
16980    protected boolean isPaddingOffsetRequired() {
16981        return false;
16982    }
16983
16984    /**
16985     * Amount by which to extend the left fading region. Called only when
16986     * {@link #isPaddingOffsetRequired()} returns true.
16987     *
16988     * @return The left padding offset in pixels.
16989     *
16990     * @see #isPaddingOffsetRequired()
16991     *
16992     * @since CURRENT
16993     */
16994    protected int getLeftPaddingOffset() {
16995        return 0;
16996    }
16997
16998    /**
16999     * Amount by which to extend the right fading region. Called only when
17000     * {@link #isPaddingOffsetRequired()} returns true.
17001     *
17002     * @return The right padding offset in pixels.
17003     *
17004     * @see #isPaddingOffsetRequired()
17005     *
17006     * @since CURRENT
17007     */
17008    protected int getRightPaddingOffset() {
17009        return 0;
17010    }
17011
17012    /**
17013     * Amount by which to extend the top fading region. Called only when
17014     * {@link #isPaddingOffsetRequired()} returns true.
17015     *
17016     * @return The top padding offset in pixels.
17017     *
17018     * @see #isPaddingOffsetRequired()
17019     *
17020     * @since CURRENT
17021     */
17022    protected int getTopPaddingOffset() {
17023        return 0;
17024    }
17025
17026    /**
17027     * Amount by which to extend the bottom fading region. Called only when
17028     * {@link #isPaddingOffsetRequired()} returns true.
17029     *
17030     * @return The bottom padding offset in pixels.
17031     *
17032     * @see #isPaddingOffsetRequired()
17033     *
17034     * @since CURRENT
17035     */
17036    protected int getBottomPaddingOffset() {
17037        return 0;
17038    }
17039
17040    /**
17041     * @hide
17042     * @param offsetRequired
17043     */
17044    protected int getFadeTop(boolean offsetRequired) {
17045        int top = mPaddingTop;
17046        if (offsetRequired) top += getTopPaddingOffset();
17047        return top;
17048    }
17049
17050    /**
17051     * @hide
17052     * @param offsetRequired
17053     */
17054    protected int getFadeHeight(boolean offsetRequired) {
17055        int padding = mPaddingTop;
17056        if (offsetRequired) padding += getTopPaddingOffset();
17057        return mBottom - mTop - mPaddingBottom - padding;
17058    }
17059
17060    /**
17061     * <p>Indicates whether this view is attached to a hardware accelerated
17062     * window or not.</p>
17063     *
17064     * <p>Even if this method returns true, it does not mean that every call
17065     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17066     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17067     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17068     * window is hardware accelerated,
17069     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17070     * return false, and this method will return true.</p>
17071     *
17072     * @return True if the view is attached to a window and the window is
17073     *         hardware accelerated; false in any other case.
17074     */
17075    @ViewDebug.ExportedProperty(category = "drawing")
17076    public boolean isHardwareAccelerated() {
17077        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17078    }
17079
17080    /**
17081     * Sets a rectangular area on this view to which the view will be clipped
17082     * when it is drawn. Setting the value to null will remove the clip bounds
17083     * and the view will draw normally, using its full bounds.
17084     *
17085     * @param clipBounds The rectangular area, in the local coordinates of
17086     * this view, to which future drawing operations will be clipped.
17087     */
17088    public void setClipBounds(Rect clipBounds) {
17089        if (clipBounds == mClipBounds
17090                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17091            return;
17092        }
17093        if (clipBounds != null) {
17094            if (mClipBounds == null) {
17095                mClipBounds = new Rect(clipBounds);
17096            } else {
17097                mClipBounds.set(clipBounds);
17098            }
17099        } else {
17100            mClipBounds = null;
17101        }
17102        mRenderNode.setClipBounds(mClipBounds);
17103        invalidateViewProperty(false, false);
17104    }
17105
17106    /**
17107     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17108     *
17109     * @return A copy of the current clip bounds if clip bounds are set,
17110     * otherwise null.
17111     */
17112    public Rect getClipBounds() {
17113        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17114    }
17115
17116
17117    /**
17118     * Populates an output rectangle with the clip bounds of the view,
17119     * returning {@code true} if successful or {@code false} if the view's
17120     * clip bounds are {@code null}.
17121     *
17122     * @param outRect rectangle in which to place the clip bounds of the view
17123     * @return {@code true} if successful or {@code false} if the view's
17124     *         clip bounds are {@code null}
17125     */
17126    public boolean getClipBounds(Rect outRect) {
17127        if (mClipBounds != null) {
17128            outRect.set(mClipBounds);
17129            return true;
17130        }
17131        return false;
17132    }
17133
17134    /**
17135     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17136     * case of an active Animation being run on the view.
17137     */
17138    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17139            Animation a, boolean scalingRequired) {
17140        Transformation invalidationTransform;
17141        final int flags = parent.mGroupFlags;
17142        final boolean initialized = a.isInitialized();
17143        if (!initialized) {
17144            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17145            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17146            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17147            onAnimationStart();
17148        }
17149
17150        final Transformation t = parent.getChildTransformation();
17151        boolean more = a.getTransformation(drawingTime, t, 1f);
17152        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17153            if (parent.mInvalidationTransformation == null) {
17154                parent.mInvalidationTransformation = new Transformation();
17155            }
17156            invalidationTransform = parent.mInvalidationTransformation;
17157            a.getTransformation(drawingTime, invalidationTransform, 1f);
17158        } else {
17159            invalidationTransform = t;
17160        }
17161
17162        if (more) {
17163            if (!a.willChangeBounds()) {
17164                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17165                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17166                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17167                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17168                    // The child need to draw an animation, potentially offscreen, so
17169                    // make sure we do not cancel invalidate requests
17170                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17171                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17172                }
17173            } else {
17174                if (parent.mInvalidateRegion == null) {
17175                    parent.mInvalidateRegion = new RectF();
17176                }
17177                final RectF region = parent.mInvalidateRegion;
17178                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17179                        invalidationTransform);
17180
17181                // The child need to draw an animation, potentially offscreen, so
17182                // make sure we do not cancel invalidate requests
17183                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17184
17185                final int left = mLeft + (int) region.left;
17186                final int top = mTop + (int) region.top;
17187                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17188                        top + (int) (region.height() + .5f));
17189            }
17190        }
17191        return more;
17192    }
17193
17194    /**
17195     * This method is called by getDisplayList() when a display list is recorded for a View.
17196     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17197     */
17198    void setDisplayListProperties(RenderNode renderNode) {
17199        if (renderNode != null) {
17200            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17201            renderNode.setClipToBounds(mParent instanceof ViewGroup
17202                    && ((ViewGroup) mParent).getClipChildren());
17203
17204            float alpha = 1;
17205            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17206                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17207                ViewGroup parentVG = (ViewGroup) mParent;
17208                final Transformation t = parentVG.getChildTransformation();
17209                if (parentVG.getChildStaticTransformation(this, t)) {
17210                    final int transformType = t.getTransformationType();
17211                    if (transformType != Transformation.TYPE_IDENTITY) {
17212                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17213                            alpha = t.getAlpha();
17214                        }
17215                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17216                            renderNode.setStaticMatrix(t.getMatrix());
17217                        }
17218                    }
17219                }
17220            }
17221            if (mTransformationInfo != null) {
17222                alpha *= getFinalAlpha();
17223                if (alpha < 1) {
17224                    final int multipliedAlpha = (int) (255 * alpha);
17225                    if (onSetAlpha(multipliedAlpha)) {
17226                        alpha = 1;
17227                    }
17228                }
17229                renderNode.setAlpha(alpha);
17230            } else if (alpha < 1) {
17231                renderNode.setAlpha(alpha);
17232            }
17233        }
17234    }
17235
17236    /**
17237     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17238     *
17239     * This is where the View specializes rendering behavior based on layer type,
17240     * and hardware acceleration.
17241     */
17242    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17243        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17244        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17245         *
17246         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17247         * HW accelerated, it can't handle drawing RenderNodes.
17248         */
17249        boolean drawingWithRenderNode = mAttachInfo != null
17250                && mAttachInfo.mHardwareAccelerated
17251                && hardwareAcceleratedCanvas;
17252
17253        boolean more = false;
17254        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17255        final int parentFlags = parent.mGroupFlags;
17256
17257        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17258            parent.getChildTransformation().clear();
17259            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17260        }
17261
17262        Transformation transformToApply = null;
17263        boolean concatMatrix = false;
17264        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17265        final Animation a = getAnimation();
17266        if (a != null) {
17267            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17268            concatMatrix = a.willChangeTransformationMatrix();
17269            if (concatMatrix) {
17270                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17271            }
17272            transformToApply = parent.getChildTransformation();
17273        } else {
17274            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17275                // No longer animating: clear out old animation matrix
17276                mRenderNode.setAnimationMatrix(null);
17277                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17278            }
17279            if (!drawingWithRenderNode
17280                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17281                final Transformation t = parent.getChildTransformation();
17282                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17283                if (hasTransform) {
17284                    final int transformType = t.getTransformationType();
17285                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17286                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17287                }
17288            }
17289        }
17290
17291        concatMatrix |= !childHasIdentityMatrix;
17292
17293        // Sets the flag as early as possible to allow draw() implementations
17294        // to call invalidate() successfully when doing animations
17295        mPrivateFlags |= PFLAG_DRAWN;
17296
17297        if (!concatMatrix &&
17298                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17299                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17300                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17301                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17302            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17303            return more;
17304        }
17305        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17306
17307        if (hardwareAcceleratedCanvas) {
17308            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17309            // retain the flag's value temporarily in the mRecreateDisplayList flag
17310            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17311            mPrivateFlags &= ~PFLAG_INVALIDATED;
17312        }
17313
17314        RenderNode renderNode = null;
17315        Bitmap cache = null;
17316        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17317        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17318             if (layerType != LAYER_TYPE_NONE) {
17319                 // If not drawing with RenderNode, treat HW layers as SW
17320                 layerType = LAYER_TYPE_SOFTWARE;
17321                 buildDrawingCache(true);
17322            }
17323            cache = getDrawingCache(true);
17324        }
17325
17326        if (drawingWithRenderNode) {
17327            // Delay getting the display list until animation-driven alpha values are
17328            // set up and possibly passed on to the view
17329            renderNode = updateDisplayListIfDirty();
17330            if (!renderNode.isValid()) {
17331                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17332                // to getDisplayList(), the display list will be marked invalid and we should not
17333                // try to use it again.
17334                renderNode = null;
17335                drawingWithRenderNode = false;
17336            }
17337        }
17338
17339        int sx = 0;
17340        int sy = 0;
17341        if (!drawingWithRenderNode) {
17342            computeScroll();
17343            sx = mScrollX;
17344            sy = mScrollY;
17345        }
17346
17347        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17348        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17349
17350        int restoreTo = -1;
17351        if (!drawingWithRenderNode || transformToApply != null) {
17352            restoreTo = canvas.save();
17353        }
17354        if (offsetForScroll) {
17355            canvas.translate(mLeft - sx, mTop - sy);
17356        } else {
17357            if (!drawingWithRenderNode) {
17358                canvas.translate(mLeft, mTop);
17359            }
17360            if (scalingRequired) {
17361                if (drawingWithRenderNode) {
17362                    // TODO: Might not need this if we put everything inside the DL
17363                    restoreTo = canvas.save();
17364                }
17365                // mAttachInfo cannot be null, otherwise scalingRequired == false
17366                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17367                canvas.scale(scale, scale);
17368            }
17369        }
17370
17371        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17372        if (transformToApply != null
17373                || alpha < 1
17374                || !hasIdentityMatrix()
17375                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17376            if (transformToApply != null || !childHasIdentityMatrix) {
17377                int transX = 0;
17378                int transY = 0;
17379
17380                if (offsetForScroll) {
17381                    transX = -sx;
17382                    transY = -sy;
17383                }
17384
17385                if (transformToApply != null) {
17386                    if (concatMatrix) {
17387                        if (drawingWithRenderNode) {
17388                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17389                        } else {
17390                            // Undo the scroll translation, apply the transformation matrix,
17391                            // then redo the scroll translate to get the correct result.
17392                            canvas.translate(-transX, -transY);
17393                            canvas.concat(transformToApply.getMatrix());
17394                            canvas.translate(transX, transY);
17395                        }
17396                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17397                    }
17398
17399                    float transformAlpha = transformToApply.getAlpha();
17400                    if (transformAlpha < 1) {
17401                        alpha *= transformAlpha;
17402                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17403                    }
17404                }
17405
17406                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17407                    canvas.translate(-transX, -transY);
17408                    canvas.concat(getMatrix());
17409                    canvas.translate(transX, transY);
17410                }
17411            }
17412
17413            // Deal with alpha if it is or used to be <1
17414            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17415                if (alpha < 1) {
17416                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17417                } else {
17418                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17419                }
17420                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17421                if (!drawingWithDrawingCache) {
17422                    final int multipliedAlpha = (int) (255 * alpha);
17423                    if (!onSetAlpha(multipliedAlpha)) {
17424                        if (drawingWithRenderNode) {
17425                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17426                        } else if (layerType == LAYER_TYPE_NONE) {
17427                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17428                                    multipliedAlpha);
17429                        }
17430                    } else {
17431                        // Alpha is handled by the child directly, clobber the layer's alpha
17432                        mPrivateFlags |= PFLAG_ALPHA_SET;
17433                    }
17434                }
17435            }
17436        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17437            onSetAlpha(255);
17438            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17439        }
17440
17441        if (!drawingWithRenderNode) {
17442            // apply clips directly, since RenderNode won't do it for this draw
17443            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17444                if (offsetForScroll) {
17445                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17446                } else {
17447                    if (!scalingRequired || cache == null) {
17448                        canvas.clipRect(0, 0, getWidth(), getHeight());
17449                    } else {
17450                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17451                    }
17452                }
17453            }
17454
17455            if (mClipBounds != null) {
17456                // clip bounds ignore scroll
17457                canvas.clipRect(mClipBounds);
17458            }
17459        }
17460
17461        if (!drawingWithDrawingCache) {
17462            if (drawingWithRenderNode) {
17463                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17464                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17465            } else {
17466                // Fast path for layouts with no backgrounds
17467                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17468                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17469                    dispatchDraw(canvas);
17470                } else {
17471                    draw(canvas);
17472                }
17473            }
17474        } else if (cache != null) {
17475            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17476            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17477                // no layer paint, use temporary paint to draw bitmap
17478                Paint cachePaint = parent.mCachePaint;
17479                if (cachePaint == null) {
17480                    cachePaint = new Paint();
17481                    cachePaint.setDither(false);
17482                    parent.mCachePaint = cachePaint;
17483                }
17484                cachePaint.setAlpha((int) (alpha * 255));
17485                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17486            } else {
17487                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17488                int layerPaintAlpha = mLayerPaint.getAlpha();
17489                if (alpha < 1) {
17490                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17491                }
17492                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17493                if (alpha < 1) {
17494                    mLayerPaint.setAlpha(layerPaintAlpha);
17495                }
17496            }
17497        }
17498
17499        if (restoreTo >= 0) {
17500            canvas.restoreToCount(restoreTo);
17501        }
17502
17503        if (a != null && !more) {
17504            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17505                onSetAlpha(255);
17506            }
17507            parent.finishAnimatingView(this, a);
17508        }
17509
17510        if (more && hardwareAcceleratedCanvas) {
17511            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17512                // alpha animations should cause the child to recreate its display list
17513                invalidate(true);
17514            }
17515        }
17516
17517        mRecreateDisplayList = false;
17518
17519        return more;
17520    }
17521
17522    static Paint getDebugPaint() {
17523        if (sDebugPaint == null) {
17524            sDebugPaint = new Paint();
17525            sDebugPaint.setAntiAlias(false);
17526        }
17527        return sDebugPaint;
17528    }
17529
17530    final int dipsToPixels(int dips) {
17531        float scale = getContext().getResources().getDisplayMetrics().density;
17532        return (int) (dips * scale + 0.5f);
17533    }
17534
17535    final private void debugDrawFocus(Canvas canvas) {
17536        if (isFocused()) {
17537            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17538            final int l = mScrollX;
17539            final int r = l + mRight - mLeft;
17540            final int t = mScrollY;
17541            final int b = t + mBottom - mTop;
17542
17543            final Paint paint = getDebugPaint();
17544            paint.setColor(DEBUG_CORNERS_COLOR);
17545
17546            // Draw squares in corners.
17547            paint.setStyle(Paint.Style.FILL);
17548            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17549            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17550            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17551            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17552
17553            // Draw big X across the view.
17554            paint.setStyle(Paint.Style.STROKE);
17555            canvas.drawLine(l, t, r, b, paint);
17556            canvas.drawLine(l, b, r, t, paint);
17557        }
17558    }
17559
17560    /**
17561     * Manually render this view (and all of its children) to the given Canvas.
17562     * The view must have already done a full layout before this function is
17563     * called.  When implementing a view, implement
17564     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17565     * If you do need to override this method, call the superclass version.
17566     *
17567     * @param canvas The Canvas to which the View is rendered.
17568     */
17569    @CallSuper
17570    public void draw(Canvas canvas) {
17571        final int privateFlags = mPrivateFlags;
17572        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17573                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17574        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17575
17576        /*
17577         * Draw traversal performs several drawing steps which must be executed
17578         * in the appropriate order:
17579         *
17580         *      1. Draw the background
17581         *      2. If necessary, save the canvas' layers to prepare for fading
17582         *      3. Draw view's content
17583         *      4. Draw children
17584         *      5. If necessary, draw the fading edges and restore layers
17585         *      6. Draw decorations (scrollbars for instance)
17586         */
17587
17588        // Step 1, draw the background, if needed
17589        int saveCount;
17590
17591        if (!dirtyOpaque) {
17592            drawBackground(canvas);
17593        }
17594
17595        // skip step 2 & 5 if possible (common case)
17596        final int viewFlags = mViewFlags;
17597        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17598        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17599        if (!verticalEdges && !horizontalEdges) {
17600            // Step 3, draw the content
17601            if (!dirtyOpaque) onDraw(canvas);
17602
17603            // Step 4, draw the children
17604            dispatchDraw(canvas);
17605
17606            // Overlay is part of the content and draws beneath Foreground
17607            if (mOverlay != null && !mOverlay.isEmpty()) {
17608                mOverlay.getOverlayView().dispatchDraw(canvas);
17609            }
17610
17611            // Step 6, draw decorations (foreground, scrollbars)
17612            onDrawForeground(canvas);
17613
17614            if (debugDraw()) {
17615                debugDrawFocus(canvas);
17616            }
17617
17618            // we're done...
17619            return;
17620        }
17621
17622        /*
17623         * Here we do the full fledged routine...
17624         * (this is an uncommon case where speed matters less,
17625         * this is why we repeat some of the tests that have been
17626         * done above)
17627         */
17628
17629        boolean drawTop = false;
17630        boolean drawBottom = false;
17631        boolean drawLeft = false;
17632        boolean drawRight = false;
17633
17634        float topFadeStrength = 0.0f;
17635        float bottomFadeStrength = 0.0f;
17636        float leftFadeStrength = 0.0f;
17637        float rightFadeStrength = 0.0f;
17638
17639        // Step 2, save the canvas' layers
17640        int paddingLeft = mPaddingLeft;
17641
17642        final boolean offsetRequired = isPaddingOffsetRequired();
17643        if (offsetRequired) {
17644            paddingLeft += getLeftPaddingOffset();
17645        }
17646
17647        int left = mScrollX + paddingLeft;
17648        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17649        int top = mScrollY + getFadeTop(offsetRequired);
17650        int bottom = top + getFadeHeight(offsetRequired);
17651
17652        if (offsetRequired) {
17653            right += getRightPaddingOffset();
17654            bottom += getBottomPaddingOffset();
17655        }
17656
17657        final ScrollabilityCache scrollabilityCache = mScrollCache;
17658        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17659        int length = (int) fadeHeight;
17660
17661        // clip the fade length if top and bottom fades overlap
17662        // overlapping fades produce odd-looking artifacts
17663        if (verticalEdges && (top + length > bottom - length)) {
17664            length = (bottom - top) / 2;
17665        }
17666
17667        // also clip horizontal fades if necessary
17668        if (horizontalEdges && (left + length > right - length)) {
17669            length = (right - left) / 2;
17670        }
17671
17672        if (verticalEdges) {
17673            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17674            drawTop = topFadeStrength * fadeHeight > 1.0f;
17675            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17676            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17677        }
17678
17679        if (horizontalEdges) {
17680            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17681            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17682            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17683            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17684        }
17685
17686        saveCount = canvas.getSaveCount();
17687
17688        int solidColor = getSolidColor();
17689        if (solidColor == 0) {
17690            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17691
17692            if (drawTop) {
17693                canvas.saveLayer(left, top, right, top + length, null, flags);
17694            }
17695
17696            if (drawBottom) {
17697                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17698            }
17699
17700            if (drawLeft) {
17701                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17702            }
17703
17704            if (drawRight) {
17705                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17706            }
17707        } else {
17708            scrollabilityCache.setFadeColor(solidColor);
17709        }
17710
17711        // Step 3, draw the content
17712        if (!dirtyOpaque) onDraw(canvas);
17713
17714        // Step 4, draw the children
17715        dispatchDraw(canvas);
17716
17717        // Step 5, draw the fade effect and restore layers
17718        final Paint p = scrollabilityCache.paint;
17719        final Matrix matrix = scrollabilityCache.matrix;
17720        final Shader fade = scrollabilityCache.shader;
17721
17722        if (drawTop) {
17723            matrix.setScale(1, fadeHeight * topFadeStrength);
17724            matrix.postTranslate(left, top);
17725            fade.setLocalMatrix(matrix);
17726            p.setShader(fade);
17727            canvas.drawRect(left, top, right, top + length, p);
17728        }
17729
17730        if (drawBottom) {
17731            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17732            matrix.postRotate(180);
17733            matrix.postTranslate(left, bottom);
17734            fade.setLocalMatrix(matrix);
17735            p.setShader(fade);
17736            canvas.drawRect(left, bottom - length, right, bottom, p);
17737        }
17738
17739        if (drawLeft) {
17740            matrix.setScale(1, fadeHeight * leftFadeStrength);
17741            matrix.postRotate(-90);
17742            matrix.postTranslate(left, top);
17743            fade.setLocalMatrix(matrix);
17744            p.setShader(fade);
17745            canvas.drawRect(left, top, left + length, bottom, p);
17746        }
17747
17748        if (drawRight) {
17749            matrix.setScale(1, fadeHeight * rightFadeStrength);
17750            matrix.postRotate(90);
17751            matrix.postTranslate(right, top);
17752            fade.setLocalMatrix(matrix);
17753            p.setShader(fade);
17754            canvas.drawRect(right - length, top, right, bottom, p);
17755        }
17756
17757        canvas.restoreToCount(saveCount);
17758
17759        // Overlay is part of the content and draws beneath Foreground
17760        if (mOverlay != null && !mOverlay.isEmpty()) {
17761            mOverlay.getOverlayView().dispatchDraw(canvas);
17762        }
17763
17764        // Step 6, draw decorations (foreground, scrollbars)
17765        onDrawForeground(canvas);
17766
17767        if (debugDraw()) {
17768            debugDrawFocus(canvas);
17769        }
17770    }
17771
17772    /**
17773     * Draws the background onto the specified canvas.
17774     *
17775     * @param canvas Canvas on which to draw the background
17776     */
17777    private void drawBackground(Canvas canvas) {
17778        final Drawable background = mBackground;
17779        if (background == null) {
17780            return;
17781        }
17782
17783        setBackgroundBounds();
17784
17785        // Attempt to use a display list if requested.
17786        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17787                && mAttachInfo.mThreadedRenderer != null) {
17788            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17789
17790            final RenderNode renderNode = mBackgroundRenderNode;
17791            if (renderNode != null && renderNode.isValid()) {
17792                setBackgroundRenderNodeProperties(renderNode);
17793                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17794                return;
17795            }
17796        }
17797
17798        final int scrollX = mScrollX;
17799        final int scrollY = mScrollY;
17800        if ((scrollX | scrollY) == 0) {
17801            background.draw(canvas);
17802        } else {
17803            canvas.translate(scrollX, scrollY);
17804            background.draw(canvas);
17805            canvas.translate(-scrollX, -scrollY);
17806        }
17807    }
17808
17809    /**
17810     * Sets the correct background bounds and rebuilds the outline, if needed.
17811     * <p/>
17812     * This is called by LayoutLib.
17813     */
17814    void setBackgroundBounds() {
17815        if (mBackgroundSizeChanged && mBackground != null) {
17816            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17817            mBackgroundSizeChanged = false;
17818            rebuildOutline();
17819        }
17820    }
17821
17822    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17823        renderNode.setTranslationX(mScrollX);
17824        renderNode.setTranslationY(mScrollY);
17825    }
17826
17827    /**
17828     * Creates a new display list or updates the existing display list for the
17829     * specified Drawable.
17830     *
17831     * @param drawable Drawable for which to create a display list
17832     * @param renderNode Existing RenderNode, or {@code null}
17833     * @return A valid display list for the specified drawable
17834     */
17835    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17836        if (renderNode == null) {
17837            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17838        }
17839
17840        final Rect bounds = drawable.getBounds();
17841        final int width = bounds.width();
17842        final int height = bounds.height();
17843        final DisplayListCanvas canvas = renderNode.start(width, height);
17844
17845        // Reverse left/top translation done by drawable canvas, which will
17846        // instead be applied by rendernode's LTRB bounds below. This way, the
17847        // drawable's bounds match with its rendernode bounds and its content
17848        // will lie within those bounds in the rendernode tree.
17849        canvas.translate(-bounds.left, -bounds.top);
17850
17851        try {
17852            drawable.draw(canvas);
17853        } finally {
17854            renderNode.end(canvas);
17855        }
17856
17857        // Set up drawable properties that are view-independent.
17858        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17859        renderNode.setProjectBackwards(drawable.isProjected());
17860        renderNode.setProjectionReceiver(true);
17861        renderNode.setClipToBounds(false);
17862        return renderNode;
17863    }
17864
17865    /**
17866     * Returns the overlay for this view, creating it if it does not yet exist.
17867     * Adding drawables to the overlay will cause them to be displayed whenever
17868     * the view itself is redrawn. Objects in the overlay should be actively
17869     * managed: remove them when they should not be displayed anymore. The
17870     * overlay will always have the same size as its host view.
17871     *
17872     * <p>Note: Overlays do not currently work correctly with {@link
17873     * SurfaceView} or {@link TextureView}; contents in overlays for these
17874     * types of views may not display correctly.</p>
17875     *
17876     * @return The ViewOverlay object for this view.
17877     * @see ViewOverlay
17878     */
17879    public ViewOverlay getOverlay() {
17880        if (mOverlay == null) {
17881            mOverlay = new ViewOverlay(mContext, this);
17882        }
17883        return mOverlay;
17884    }
17885
17886    /**
17887     * Override this if your view is known to always be drawn on top of a solid color background,
17888     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17889     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17890     * should be set to 0xFF.
17891     *
17892     * @see #setVerticalFadingEdgeEnabled(boolean)
17893     * @see #setHorizontalFadingEdgeEnabled(boolean)
17894     *
17895     * @return The known solid color background for this view, or 0 if the color may vary
17896     */
17897    @ViewDebug.ExportedProperty(category = "drawing")
17898    @ColorInt
17899    public int getSolidColor() {
17900        return 0;
17901    }
17902
17903    /**
17904     * Build a human readable string representation of the specified view flags.
17905     *
17906     * @param flags the view flags to convert to a string
17907     * @return a String representing the supplied flags
17908     */
17909    private static String printFlags(int flags) {
17910        String output = "";
17911        int numFlags = 0;
17912        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17913            output += "TAKES_FOCUS";
17914            numFlags++;
17915        }
17916
17917        switch (flags & VISIBILITY_MASK) {
17918        case INVISIBLE:
17919            if (numFlags > 0) {
17920                output += " ";
17921            }
17922            output += "INVISIBLE";
17923            // USELESS HERE numFlags++;
17924            break;
17925        case GONE:
17926            if (numFlags > 0) {
17927                output += " ";
17928            }
17929            output += "GONE";
17930            // USELESS HERE numFlags++;
17931            break;
17932        default:
17933            break;
17934        }
17935        return output;
17936    }
17937
17938    /**
17939     * Build a human readable string representation of the specified private
17940     * view flags.
17941     *
17942     * @param privateFlags the private view flags to convert to a string
17943     * @return a String representing the supplied flags
17944     */
17945    private static String printPrivateFlags(int privateFlags) {
17946        String output = "";
17947        int numFlags = 0;
17948
17949        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17950            output += "WANTS_FOCUS";
17951            numFlags++;
17952        }
17953
17954        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17955            if (numFlags > 0) {
17956                output += " ";
17957            }
17958            output += "FOCUSED";
17959            numFlags++;
17960        }
17961
17962        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17963            if (numFlags > 0) {
17964                output += " ";
17965            }
17966            output += "SELECTED";
17967            numFlags++;
17968        }
17969
17970        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17971            if (numFlags > 0) {
17972                output += " ";
17973            }
17974            output += "IS_ROOT_NAMESPACE";
17975            numFlags++;
17976        }
17977
17978        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17979            if (numFlags > 0) {
17980                output += " ";
17981            }
17982            output += "HAS_BOUNDS";
17983            numFlags++;
17984        }
17985
17986        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17987            if (numFlags > 0) {
17988                output += " ";
17989            }
17990            output += "DRAWN";
17991            // USELESS HERE numFlags++;
17992        }
17993        return output;
17994    }
17995
17996    /**
17997     * <p>Indicates whether or not this view's layout will be requested during
17998     * the next hierarchy layout pass.</p>
17999     *
18000     * @return true if the layout will be forced during next layout pass
18001     */
18002    public boolean isLayoutRequested() {
18003        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18004    }
18005
18006    /**
18007     * Return true if o is a ViewGroup that is laying out using optical bounds.
18008     * @hide
18009     */
18010    public static boolean isLayoutModeOptical(Object o) {
18011        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18012    }
18013
18014    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18015        Insets parentInsets = mParent instanceof View ?
18016                ((View) mParent).getOpticalInsets() : Insets.NONE;
18017        Insets childInsets = getOpticalInsets();
18018        return setFrame(
18019                left   + parentInsets.left - childInsets.left,
18020                top    + parentInsets.top  - childInsets.top,
18021                right  + parentInsets.left + childInsets.right,
18022                bottom + parentInsets.top  + childInsets.bottom);
18023    }
18024
18025    /**
18026     * Assign a size and position to a view and all of its
18027     * descendants
18028     *
18029     * <p>This is the second phase of the layout mechanism.
18030     * (The first is measuring). In this phase, each parent calls
18031     * layout on all of its children to position them.
18032     * This is typically done using the child measurements
18033     * that were stored in the measure pass().</p>
18034     *
18035     * <p>Derived classes should not override this method.
18036     * Derived classes with children should override
18037     * onLayout. In that method, they should
18038     * call layout on each of their children.</p>
18039     *
18040     * @param l Left position, relative to parent
18041     * @param t Top position, relative to parent
18042     * @param r Right position, relative to parent
18043     * @param b Bottom position, relative to parent
18044     */
18045    @SuppressWarnings({"unchecked"})
18046    public void layout(int l, int t, int r, int b) {
18047        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18048            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18049            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18050        }
18051
18052        int oldL = mLeft;
18053        int oldT = mTop;
18054        int oldB = mBottom;
18055        int oldR = mRight;
18056
18057        boolean changed = isLayoutModeOptical(mParent) ?
18058                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18059
18060        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18061            onLayout(changed, l, t, r, b);
18062
18063            if (shouldDrawRoundScrollbar()) {
18064                if(mRoundScrollbarRenderer == null) {
18065                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18066                }
18067            } else {
18068                mRoundScrollbarRenderer = null;
18069            }
18070
18071            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18072
18073            ListenerInfo li = mListenerInfo;
18074            if (li != null && li.mOnLayoutChangeListeners != null) {
18075                ArrayList<OnLayoutChangeListener> listenersCopy =
18076                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18077                int numListeners = listenersCopy.size();
18078                for (int i = 0; i < numListeners; ++i) {
18079                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18080                }
18081            }
18082        }
18083
18084        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18085        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18086    }
18087
18088    /**
18089     * Called from layout when this view should
18090     * assign a size and position to each of its children.
18091     *
18092     * Derived classes with children should override
18093     * this method and call layout on each of
18094     * their children.
18095     * @param changed This is a new size or position for this view
18096     * @param left Left position, relative to parent
18097     * @param top Top position, relative to parent
18098     * @param right Right position, relative to parent
18099     * @param bottom Bottom position, relative to parent
18100     */
18101    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18102    }
18103
18104    /**
18105     * Assign a size and position to this view.
18106     *
18107     * This is called from layout.
18108     *
18109     * @param left Left position, relative to parent
18110     * @param top Top position, relative to parent
18111     * @param right Right position, relative to parent
18112     * @param bottom Bottom position, relative to parent
18113     * @return true if the new size and position are different than the
18114     *         previous ones
18115     * {@hide}
18116     */
18117    protected boolean setFrame(int left, int top, int right, int bottom) {
18118        boolean changed = false;
18119
18120        if (DBG) {
18121            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18122                    + right + "," + bottom + ")");
18123        }
18124
18125        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18126            changed = true;
18127
18128            // Remember our drawn bit
18129            int drawn = mPrivateFlags & PFLAG_DRAWN;
18130
18131            int oldWidth = mRight - mLeft;
18132            int oldHeight = mBottom - mTop;
18133            int newWidth = right - left;
18134            int newHeight = bottom - top;
18135            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18136
18137            // Invalidate our old position
18138            invalidate(sizeChanged);
18139
18140            mLeft = left;
18141            mTop = top;
18142            mRight = right;
18143            mBottom = bottom;
18144            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18145
18146            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18147
18148
18149            if (sizeChanged) {
18150                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18151            }
18152
18153            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18154                // If we are visible, force the DRAWN bit to on so that
18155                // this invalidate will go through (at least to our parent).
18156                // This is because someone may have invalidated this view
18157                // before this call to setFrame came in, thereby clearing
18158                // the DRAWN bit.
18159                mPrivateFlags |= PFLAG_DRAWN;
18160                invalidate(sizeChanged);
18161                // parent display list may need to be recreated based on a change in the bounds
18162                // of any child
18163                invalidateParentCaches();
18164            }
18165
18166            // Reset drawn bit to original value (invalidate turns it off)
18167            mPrivateFlags |= drawn;
18168
18169            mBackgroundSizeChanged = true;
18170            if (mForegroundInfo != null) {
18171                mForegroundInfo.mBoundsChanged = true;
18172            }
18173
18174            notifySubtreeAccessibilityStateChangedIfNeeded();
18175        }
18176        return changed;
18177    }
18178
18179    /**
18180     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18181     * @hide
18182     */
18183    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18184        setFrame(left, top, right, bottom);
18185    }
18186
18187    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18188        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18189        if (mOverlay != null) {
18190            mOverlay.getOverlayView().setRight(newWidth);
18191            mOverlay.getOverlayView().setBottom(newHeight);
18192        }
18193        rebuildOutline();
18194    }
18195
18196    /**
18197     * Finalize inflating a view from XML.  This is called as the last phase
18198     * of inflation, after all child views have been added.
18199     *
18200     * <p>Even if the subclass overrides onFinishInflate, they should always be
18201     * sure to call the super method, so that we get called.
18202     */
18203    @CallSuper
18204    protected void onFinishInflate() {
18205    }
18206
18207    /**
18208     * Returns the resources associated with this view.
18209     *
18210     * @return Resources object.
18211     */
18212    public Resources getResources() {
18213        return mResources;
18214    }
18215
18216    /**
18217     * Invalidates the specified Drawable.
18218     *
18219     * @param drawable the drawable to invalidate
18220     */
18221    @Override
18222    public void invalidateDrawable(@NonNull Drawable drawable) {
18223        if (verifyDrawable(drawable)) {
18224            final Rect dirty = drawable.getDirtyBounds();
18225            final int scrollX = mScrollX;
18226            final int scrollY = mScrollY;
18227
18228            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18229                    dirty.right + scrollX, dirty.bottom + scrollY);
18230            rebuildOutline();
18231        }
18232    }
18233
18234    /**
18235     * Schedules an action on a drawable to occur at a specified time.
18236     *
18237     * @param who the recipient of the action
18238     * @param what the action to run on the drawable
18239     * @param when the time at which the action must occur. Uses the
18240     *        {@link SystemClock#uptimeMillis} timebase.
18241     */
18242    @Override
18243    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18244        if (verifyDrawable(who) && what != null) {
18245            final long delay = when - SystemClock.uptimeMillis();
18246            if (mAttachInfo != null) {
18247                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18248                        Choreographer.CALLBACK_ANIMATION, what, who,
18249                        Choreographer.subtractFrameDelay(delay));
18250            } else {
18251                // Postpone the runnable until we know
18252                // on which thread it needs to run.
18253                getRunQueue().postDelayed(what, delay);
18254            }
18255        }
18256    }
18257
18258    /**
18259     * Cancels a scheduled action on a drawable.
18260     *
18261     * @param who the recipient of the action
18262     * @param what the action to cancel
18263     */
18264    @Override
18265    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18266        if (verifyDrawable(who) && what != null) {
18267            if (mAttachInfo != null) {
18268                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18269                        Choreographer.CALLBACK_ANIMATION, what, who);
18270            }
18271            getRunQueue().removeCallbacks(what);
18272        }
18273    }
18274
18275    /**
18276     * Unschedule any events associated with the given Drawable.  This can be
18277     * used when selecting a new Drawable into a view, so that the previous
18278     * one is completely unscheduled.
18279     *
18280     * @param who The Drawable to unschedule.
18281     *
18282     * @see #drawableStateChanged
18283     */
18284    public void unscheduleDrawable(Drawable who) {
18285        if (mAttachInfo != null && who != null) {
18286            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18287                    Choreographer.CALLBACK_ANIMATION, null, who);
18288        }
18289    }
18290
18291    /**
18292     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18293     * that the View directionality can and will be resolved before its Drawables.
18294     *
18295     * Will call {@link View#onResolveDrawables} when resolution is done.
18296     *
18297     * @hide
18298     */
18299    protected void resolveDrawables() {
18300        // Drawables resolution may need to happen before resolving the layout direction (which is
18301        // done only during the measure() call).
18302        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18303        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18304        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18305        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18306        // direction to be resolved as its resolved value will be the same as its raw value.
18307        if (!isLayoutDirectionResolved() &&
18308                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18309            return;
18310        }
18311
18312        final int layoutDirection = isLayoutDirectionResolved() ?
18313                getLayoutDirection() : getRawLayoutDirection();
18314
18315        if (mBackground != null) {
18316            mBackground.setLayoutDirection(layoutDirection);
18317        }
18318        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18319            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18320        }
18321        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18322        onResolveDrawables(layoutDirection);
18323    }
18324
18325    boolean areDrawablesResolved() {
18326        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18327    }
18328
18329    /**
18330     * Called when layout direction has been resolved.
18331     *
18332     * The default implementation does nothing.
18333     *
18334     * @param layoutDirection The resolved layout direction.
18335     *
18336     * @see #LAYOUT_DIRECTION_LTR
18337     * @see #LAYOUT_DIRECTION_RTL
18338     *
18339     * @hide
18340     */
18341    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18342    }
18343
18344    /**
18345     * @hide
18346     */
18347    protected void resetResolvedDrawables() {
18348        resetResolvedDrawablesInternal();
18349    }
18350
18351    void resetResolvedDrawablesInternal() {
18352        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18353    }
18354
18355    /**
18356     * If your view subclass is displaying its own Drawable objects, it should
18357     * override this function and return true for any Drawable it is
18358     * displaying.  This allows animations for those drawables to be
18359     * scheduled.
18360     *
18361     * <p>Be sure to call through to the super class when overriding this
18362     * function.
18363     *
18364     * @param who The Drawable to verify.  Return true if it is one you are
18365     *            displaying, else return the result of calling through to the
18366     *            super class.
18367     *
18368     * @return boolean If true than the Drawable is being displayed in the
18369     *         view; else false and it is not allowed to animate.
18370     *
18371     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18372     * @see #drawableStateChanged()
18373     */
18374    @CallSuper
18375    protected boolean verifyDrawable(@NonNull Drawable who) {
18376        // Avoid verifying the scroll bar drawable so that we don't end up in
18377        // an invalidation loop. This effectively prevents the scroll bar
18378        // drawable from triggering invalidations and scheduling runnables.
18379        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18380    }
18381
18382    /**
18383     * This function is called whenever the state of the view changes in such
18384     * a way that it impacts the state of drawables being shown.
18385     * <p>
18386     * If the View has a StateListAnimator, it will also be called to run necessary state
18387     * change animations.
18388     * <p>
18389     * Be sure to call through to the superclass when overriding this function.
18390     *
18391     * @see Drawable#setState(int[])
18392     */
18393    @CallSuper
18394    protected void drawableStateChanged() {
18395        final int[] state = getDrawableState();
18396        boolean changed = false;
18397
18398        final Drawable bg = mBackground;
18399        if (bg != null && bg.isStateful()) {
18400            changed |= bg.setState(state);
18401        }
18402
18403        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18404        if (fg != null && fg.isStateful()) {
18405            changed |= fg.setState(state);
18406        }
18407
18408        if (mScrollCache != null) {
18409            final Drawable scrollBar = mScrollCache.scrollBar;
18410            if (scrollBar != null && scrollBar.isStateful()) {
18411                changed |= scrollBar.setState(state)
18412                        && mScrollCache.state != ScrollabilityCache.OFF;
18413            }
18414        }
18415
18416        if (mStateListAnimator != null) {
18417            mStateListAnimator.setState(state);
18418        }
18419
18420        if (changed) {
18421            invalidate();
18422        }
18423    }
18424
18425    /**
18426     * This function is called whenever the view hotspot changes and needs to
18427     * be propagated to drawables or child views managed by the view.
18428     * <p>
18429     * Dispatching to child views is handled by
18430     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18431     * <p>
18432     * Be sure to call through to the superclass when overriding this function.
18433     *
18434     * @param x hotspot x coordinate
18435     * @param y hotspot y coordinate
18436     */
18437    @CallSuper
18438    public void drawableHotspotChanged(float x, float y) {
18439        if (mBackground != null) {
18440            mBackground.setHotspot(x, y);
18441        }
18442        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18443            mForegroundInfo.mDrawable.setHotspot(x, y);
18444        }
18445
18446        dispatchDrawableHotspotChanged(x, y);
18447    }
18448
18449    /**
18450     * Dispatches drawableHotspotChanged to all of this View's children.
18451     *
18452     * @param x hotspot x coordinate
18453     * @param y hotspot y coordinate
18454     * @see #drawableHotspotChanged(float, float)
18455     */
18456    public void dispatchDrawableHotspotChanged(float x, float y) {
18457    }
18458
18459    /**
18460     * Call this to force a view to update its drawable state. This will cause
18461     * drawableStateChanged to be called on this view. Views that are interested
18462     * in the new state should call getDrawableState.
18463     *
18464     * @see #drawableStateChanged
18465     * @see #getDrawableState
18466     */
18467    public void refreshDrawableState() {
18468        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18469        drawableStateChanged();
18470
18471        ViewParent parent = mParent;
18472        if (parent != null) {
18473            parent.childDrawableStateChanged(this);
18474        }
18475    }
18476
18477    /**
18478     * Return an array of resource IDs of the drawable states representing the
18479     * current state of the view.
18480     *
18481     * @return The current drawable state
18482     *
18483     * @see Drawable#setState(int[])
18484     * @see #drawableStateChanged()
18485     * @see #onCreateDrawableState(int)
18486     */
18487    public final int[] getDrawableState() {
18488        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18489            return mDrawableState;
18490        } else {
18491            mDrawableState = onCreateDrawableState(0);
18492            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18493            return mDrawableState;
18494        }
18495    }
18496
18497    /**
18498     * Generate the new {@link android.graphics.drawable.Drawable} state for
18499     * this view. This is called by the view
18500     * system when the cached Drawable state is determined to be invalid.  To
18501     * retrieve the current state, you should use {@link #getDrawableState}.
18502     *
18503     * @param extraSpace if non-zero, this is the number of extra entries you
18504     * would like in the returned array in which you can place your own
18505     * states.
18506     *
18507     * @return Returns an array holding the current {@link Drawable} state of
18508     * the view.
18509     *
18510     * @see #mergeDrawableStates(int[], int[])
18511     */
18512    protected int[] onCreateDrawableState(int extraSpace) {
18513        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18514                mParent instanceof View) {
18515            return ((View) mParent).onCreateDrawableState(extraSpace);
18516        }
18517
18518        int[] drawableState;
18519
18520        int privateFlags = mPrivateFlags;
18521
18522        int viewStateIndex = 0;
18523        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18524        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18525        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18526        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18527        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18528        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18529        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18530                ThreadedRenderer.isAvailable()) {
18531            // This is set if HW acceleration is requested, even if the current
18532            // process doesn't allow it.  This is just to allow app preview
18533            // windows to better match their app.
18534            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18535        }
18536        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18537
18538        final int privateFlags2 = mPrivateFlags2;
18539        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18540            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18541        }
18542        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18543            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18544        }
18545
18546        drawableState = StateSet.get(viewStateIndex);
18547
18548        //noinspection ConstantIfStatement
18549        if (false) {
18550            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18551            Log.i("View", toString()
18552                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18553                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18554                    + " fo=" + hasFocus()
18555                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18556                    + " wf=" + hasWindowFocus()
18557                    + ": " + Arrays.toString(drawableState));
18558        }
18559
18560        if (extraSpace == 0) {
18561            return drawableState;
18562        }
18563
18564        final int[] fullState;
18565        if (drawableState != null) {
18566            fullState = new int[drawableState.length + extraSpace];
18567            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18568        } else {
18569            fullState = new int[extraSpace];
18570        }
18571
18572        return fullState;
18573    }
18574
18575    /**
18576     * Merge your own state values in <var>additionalState</var> into the base
18577     * state values <var>baseState</var> that were returned by
18578     * {@link #onCreateDrawableState(int)}.
18579     *
18580     * @param baseState The base state values returned by
18581     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18582     * own additional state values.
18583     *
18584     * @param additionalState The additional state values you would like
18585     * added to <var>baseState</var>; this array is not modified.
18586     *
18587     * @return As a convenience, the <var>baseState</var> array you originally
18588     * passed into the function is returned.
18589     *
18590     * @see #onCreateDrawableState(int)
18591     */
18592    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18593        final int N = baseState.length;
18594        int i = N - 1;
18595        while (i >= 0 && baseState[i] == 0) {
18596            i--;
18597        }
18598        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18599        return baseState;
18600    }
18601
18602    /**
18603     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18604     * on all Drawable objects associated with this view.
18605     * <p>
18606     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18607     * attached to this view.
18608     */
18609    @CallSuper
18610    public void jumpDrawablesToCurrentState() {
18611        if (mBackground != null) {
18612            mBackground.jumpToCurrentState();
18613        }
18614        if (mStateListAnimator != null) {
18615            mStateListAnimator.jumpToCurrentState();
18616        }
18617        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18618            mForegroundInfo.mDrawable.jumpToCurrentState();
18619        }
18620    }
18621
18622    /**
18623     * Sets the background color for this view.
18624     * @param color the color of the background
18625     */
18626    @RemotableViewMethod
18627    public void setBackgroundColor(@ColorInt int color) {
18628        if (mBackground instanceof ColorDrawable) {
18629            ((ColorDrawable) mBackground.mutate()).setColor(color);
18630            computeOpaqueFlags();
18631            mBackgroundResource = 0;
18632        } else {
18633            setBackground(new ColorDrawable(color));
18634        }
18635    }
18636
18637    /**
18638     * Set the background to a given resource. The resource should refer to
18639     * a Drawable object or 0 to remove the background.
18640     * @param resid The identifier of the resource.
18641     *
18642     * @attr ref android.R.styleable#View_background
18643     */
18644    @RemotableViewMethod
18645    public void setBackgroundResource(@DrawableRes int resid) {
18646        if (resid != 0 && resid == mBackgroundResource) {
18647            return;
18648        }
18649
18650        Drawable d = null;
18651        if (resid != 0) {
18652            d = mContext.getDrawable(resid);
18653        }
18654        setBackground(d);
18655
18656        mBackgroundResource = resid;
18657    }
18658
18659    /**
18660     * Set the background to a given Drawable, or remove the background. If the
18661     * background has padding, this View's padding is set to the background's
18662     * padding. However, when a background is removed, this View's padding isn't
18663     * touched. If setting the padding is desired, please use
18664     * {@link #setPadding(int, int, int, int)}.
18665     *
18666     * @param background The Drawable to use as the background, or null to remove the
18667     *        background
18668     */
18669    public void setBackground(Drawable background) {
18670        //noinspection deprecation
18671        setBackgroundDrawable(background);
18672    }
18673
18674    /**
18675     * @deprecated use {@link #setBackground(Drawable)} instead
18676     */
18677    @Deprecated
18678    public void setBackgroundDrawable(Drawable background) {
18679        computeOpaqueFlags();
18680
18681        if (background == mBackground) {
18682            return;
18683        }
18684
18685        boolean requestLayout = false;
18686
18687        mBackgroundResource = 0;
18688
18689        /*
18690         * Regardless of whether we're setting a new background or not, we want
18691         * to clear the previous drawable. setVisible first while we still have the callback set.
18692         */
18693        if (mBackground != null) {
18694            if (isAttachedToWindow()) {
18695                mBackground.setVisible(false, false);
18696            }
18697            mBackground.setCallback(null);
18698            unscheduleDrawable(mBackground);
18699        }
18700
18701        if (background != null) {
18702            Rect padding = sThreadLocal.get();
18703            if (padding == null) {
18704                padding = new Rect();
18705                sThreadLocal.set(padding);
18706            }
18707            resetResolvedDrawablesInternal();
18708            background.setLayoutDirection(getLayoutDirection());
18709            if (background.getPadding(padding)) {
18710                resetResolvedPaddingInternal();
18711                switch (background.getLayoutDirection()) {
18712                    case LAYOUT_DIRECTION_RTL:
18713                        mUserPaddingLeftInitial = padding.right;
18714                        mUserPaddingRightInitial = padding.left;
18715                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18716                        break;
18717                    case LAYOUT_DIRECTION_LTR:
18718                    default:
18719                        mUserPaddingLeftInitial = padding.left;
18720                        mUserPaddingRightInitial = padding.right;
18721                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18722                }
18723                mLeftPaddingDefined = false;
18724                mRightPaddingDefined = false;
18725            }
18726
18727            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18728            // if it has a different minimum size, we should layout again
18729            if (mBackground == null
18730                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18731                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18732                requestLayout = true;
18733            }
18734
18735            // Set mBackground before we set this as the callback and start making other
18736            // background drawable state change calls. In particular, the setVisible call below
18737            // can result in drawables attempting to start animations or otherwise invalidate,
18738            // which requires the view set as the callback (us) to recognize the drawable as
18739            // belonging to it as per verifyDrawable.
18740            mBackground = background;
18741            if (background.isStateful()) {
18742                background.setState(getDrawableState());
18743            }
18744            if (isAttachedToWindow()) {
18745                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18746            }
18747
18748            applyBackgroundTint();
18749
18750            // Set callback last, since the view may still be initializing.
18751            background.setCallback(this);
18752
18753            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18754                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18755                requestLayout = true;
18756            }
18757        } else {
18758            /* Remove the background */
18759            mBackground = null;
18760            if ((mViewFlags & WILL_NOT_DRAW) != 0
18761                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18762                mPrivateFlags |= PFLAG_SKIP_DRAW;
18763            }
18764
18765            /*
18766             * When the background is set, we try to apply its padding to this
18767             * View. When the background is removed, we don't touch this View's
18768             * padding. This is noted in the Javadocs. Hence, we don't need to
18769             * requestLayout(), the invalidate() below is sufficient.
18770             */
18771
18772            // The old background's minimum size could have affected this
18773            // View's layout, so let's requestLayout
18774            requestLayout = true;
18775        }
18776
18777        computeOpaqueFlags();
18778
18779        if (requestLayout) {
18780            requestLayout();
18781        }
18782
18783        mBackgroundSizeChanged = true;
18784        invalidate(true);
18785        invalidateOutline();
18786    }
18787
18788    /**
18789     * Gets the background drawable
18790     *
18791     * @return The drawable used as the background for this view, if any.
18792     *
18793     * @see #setBackground(Drawable)
18794     *
18795     * @attr ref android.R.styleable#View_background
18796     */
18797    public Drawable getBackground() {
18798        return mBackground;
18799    }
18800
18801    /**
18802     * Applies a tint to the background drawable. Does not modify the current tint
18803     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18804     * <p>
18805     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18806     * mutate the drawable and apply the specified tint and tint mode using
18807     * {@link Drawable#setTintList(ColorStateList)}.
18808     *
18809     * @param tint the tint to apply, may be {@code null} to clear tint
18810     *
18811     * @attr ref android.R.styleable#View_backgroundTint
18812     * @see #getBackgroundTintList()
18813     * @see Drawable#setTintList(ColorStateList)
18814     */
18815    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18816        if (mBackgroundTint == null) {
18817            mBackgroundTint = new TintInfo();
18818        }
18819        mBackgroundTint.mTintList = tint;
18820        mBackgroundTint.mHasTintList = true;
18821
18822        applyBackgroundTint();
18823    }
18824
18825    /**
18826     * Return the tint applied to the background drawable, if specified.
18827     *
18828     * @return the tint applied to the background drawable
18829     * @attr ref android.R.styleable#View_backgroundTint
18830     * @see #setBackgroundTintList(ColorStateList)
18831     */
18832    @Nullable
18833    public ColorStateList getBackgroundTintList() {
18834        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18835    }
18836
18837    /**
18838     * Specifies the blending mode used to apply the tint specified by
18839     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18840     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18841     *
18842     * @param tintMode the blending mode used to apply the tint, may be
18843     *                 {@code null} to clear tint
18844     * @attr ref android.R.styleable#View_backgroundTintMode
18845     * @see #getBackgroundTintMode()
18846     * @see Drawable#setTintMode(PorterDuff.Mode)
18847     */
18848    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18849        if (mBackgroundTint == null) {
18850            mBackgroundTint = new TintInfo();
18851        }
18852        mBackgroundTint.mTintMode = tintMode;
18853        mBackgroundTint.mHasTintMode = true;
18854
18855        applyBackgroundTint();
18856    }
18857
18858    /**
18859     * Return the blending mode used to apply the tint to the background
18860     * drawable, if specified.
18861     *
18862     * @return the blending mode used to apply the tint to the background
18863     *         drawable
18864     * @attr ref android.R.styleable#View_backgroundTintMode
18865     * @see #setBackgroundTintMode(PorterDuff.Mode)
18866     */
18867    @Nullable
18868    public PorterDuff.Mode getBackgroundTintMode() {
18869        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18870    }
18871
18872    private void applyBackgroundTint() {
18873        if (mBackground != null && mBackgroundTint != null) {
18874            final TintInfo tintInfo = mBackgroundTint;
18875            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18876                mBackground = mBackground.mutate();
18877
18878                if (tintInfo.mHasTintList) {
18879                    mBackground.setTintList(tintInfo.mTintList);
18880                }
18881
18882                if (tintInfo.mHasTintMode) {
18883                    mBackground.setTintMode(tintInfo.mTintMode);
18884                }
18885
18886                // The drawable (or one of its children) may not have been
18887                // stateful before applying the tint, so let's try again.
18888                if (mBackground.isStateful()) {
18889                    mBackground.setState(getDrawableState());
18890                }
18891            }
18892        }
18893    }
18894
18895    /**
18896     * Returns the drawable used as the foreground of this View. The
18897     * foreground drawable, if non-null, is always drawn on top of the view's content.
18898     *
18899     * @return a Drawable or null if no foreground was set
18900     *
18901     * @see #onDrawForeground(Canvas)
18902     */
18903    public Drawable getForeground() {
18904        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18905    }
18906
18907    /**
18908     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18909     *
18910     * @param foreground the Drawable to be drawn on top of the children
18911     *
18912     * @attr ref android.R.styleable#View_foreground
18913     */
18914    public void setForeground(Drawable foreground) {
18915        if (mForegroundInfo == null) {
18916            if (foreground == null) {
18917                // Nothing to do.
18918                return;
18919            }
18920            mForegroundInfo = new ForegroundInfo();
18921        }
18922
18923        if (foreground == mForegroundInfo.mDrawable) {
18924            // Nothing to do
18925            return;
18926        }
18927
18928        if (mForegroundInfo.mDrawable != null) {
18929            if (isAttachedToWindow()) {
18930                mForegroundInfo.mDrawable.setVisible(false, false);
18931            }
18932            mForegroundInfo.mDrawable.setCallback(null);
18933            unscheduleDrawable(mForegroundInfo.mDrawable);
18934        }
18935
18936        mForegroundInfo.mDrawable = foreground;
18937        mForegroundInfo.mBoundsChanged = true;
18938        if (foreground != null) {
18939            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18940                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18941            }
18942            foreground.setLayoutDirection(getLayoutDirection());
18943            if (foreground.isStateful()) {
18944                foreground.setState(getDrawableState());
18945            }
18946            applyForegroundTint();
18947            if (isAttachedToWindow()) {
18948                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18949            }
18950            // Set callback last, since the view may still be initializing.
18951            foreground.setCallback(this);
18952        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18953            mPrivateFlags |= PFLAG_SKIP_DRAW;
18954        }
18955        requestLayout();
18956        invalidate();
18957    }
18958
18959    /**
18960     * Magic bit used to support features of framework-internal window decor implementation details.
18961     * This used to live exclusively in FrameLayout.
18962     *
18963     * @return true if the foreground should draw inside the padding region or false
18964     *         if it should draw inset by the view's padding
18965     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18966     */
18967    public boolean isForegroundInsidePadding() {
18968        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18969    }
18970
18971    /**
18972     * Describes how the foreground is positioned.
18973     *
18974     * @return foreground gravity.
18975     *
18976     * @see #setForegroundGravity(int)
18977     *
18978     * @attr ref android.R.styleable#View_foregroundGravity
18979     */
18980    public int getForegroundGravity() {
18981        return mForegroundInfo != null ? mForegroundInfo.mGravity
18982                : Gravity.START | Gravity.TOP;
18983    }
18984
18985    /**
18986     * Describes how the foreground is positioned. Defaults to START and TOP.
18987     *
18988     * @param gravity see {@link android.view.Gravity}
18989     *
18990     * @see #getForegroundGravity()
18991     *
18992     * @attr ref android.R.styleable#View_foregroundGravity
18993     */
18994    public void setForegroundGravity(int gravity) {
18995        if (mForegroundInfo == null) {
18996            mForegroundInfo = new ForegroundInfo();
18997        }
18998
18999        if (mForegroundInfo.mGravity != gravity) {
19000            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19001                gravity |= Gravity.START;
19002            }
19003
19004            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19005                gravity |= Gravity.TOP;
19006            }
19007
19008            mForegroundInfo.mGravity = gravity;
19009            requestLayout();
19010        }
19011    }
19012
19013    /**
19014     * Applies a tint to the foreground drawable. Does not modify the current tint
19015     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19016     * <p>
19017     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19018     * mutate the drawable and apply the specified tint and tint mode using
19019     * {@link Drawable#setTintList(ColorStateList)}.
19020     *
19021     * @param tint the tint to apply, may be {@code null} to clear tint
19022     *
19023     * @attr ref android.R.styleable#View_foregroundTint
19024     * @see #getForegroundTintList()
19025     * @see Drawable#setTintList(ColorStateList)
19026     */
19027    public void setForegroundTintList(@Nullable ColorStateList tint) {
19028        if (mForegroundInfo == null) {
19029            mForegroundInfo = new ForegroundInfo();
19030        }
19031        if (mForegroundInfo.mTintInfo == null) {
19032            mForegroundInfo.mTintInfo = new TintInfo();
19033        }
19034        mForegroundInfo.mTintInfo.mTintList = tint;
19035        mForegroundInfo.mTintInfo.mHasTintList = true;
19036
19037        applyForegroundTint();
19038    }
19039
19040    /**
19041     * Return the tint applied to the foreground drawable, if specified.
19042     *
19043     * @return the tint applied to the foreground drawable
19044     * @attr ref android.R.styleable#View_foregroundTint
19045     * @see #setForegroundTintList(ColorStateList)
19046     */
19047    @Nullable
19048    public ColorStateList getForegroundTintList() {
19049        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19050                ? mForegroundInfo.mTintInfo.mTintList : null;
19051    }
19052
19053    /**
19054     * Specifies the blending mode used to apply the tint specified by
19055     * {@link #setForegroundTintList(ColorStateList)}} to the background
19056     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19057     *
19058     * @param tintMode the blending mode used to apply the tint, may be
19059     *                 {@code null} to clear tint
19060     * @attr ref android.R.styleable#View_foregroundTintMode
19061     * @see #getForegroundTintMode()
19062     * @see Drawable#setTintMode(PorterDuff.Mode)
19063     */
19064    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19065        if (mForegroundInfo == null) {
19066            mForegroundInfo = new ForegroundInfo();
19067        }
19068        if (mForegroundInfo.mTintInfo == null) {
19069            mForegroundInfo.mTintInfo = new TintInfo();
19070        }
19071        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19072        mForegroundInfo.mTintInfo.mHasTintMode = true;
19073
19074        applyForegroundTint();
19075    }
19076
19077    /**
19078     * Return the blending mode used to apply the tint to the foreground
19079     * drawable, if specified.
19080     *
19081     * @return the blending mode used to apply the tint to the foreground
19082     *         drawable
19083     * @attr ref android.R.styleable#View_foregroundTintMode
19084     * @see #setForegroundTintMode(PorterDuff.Mode)
19085     */
19086    @Nullable
19087    public PorterDuff.Mode getForegroundTintMode() {
19088        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19089                ? mForegroundInfo.mTintInfo.mTintMode : null;
19090    }
19091
19092    private void applyForegroundTint() {
19093        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19094                && mForegroundInfo.mTintInfo != null) {
19095            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19096            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19097                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19098
19099                if (tintInfo.mHasTintList) {
19100                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19101                }
19102
19103                if (tintInfo.mHasTintMode) {
19104                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19105                }
19106
19107                // The drawable (or one of its children) may not have been
19108                // stateful before applying the tint, so let's try again.
19109                if (mForegroundInfo.mDrawable.isStateful()) {
19110                    mForegroundInfo.mDrawable.setState(getDrawableState());
19111                }
19112            }
19113        }
19114    }
19115
19116    /**
19117     * Draw any foreground content for this view.
19118     *
19119     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19120     * drawable or other view-specific decorations. The foreground is drawn on top of the
19121     * primary view content.</p>
19122     *
19123     * @param canvas canvas to draw into
19124     */
19125    public void onDrawForeground(Canvas canvas) {
19126        onDrawScrollIndicators(canvas);
19127        onDrawScrollBars(canvas);
19128
19129        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19130        if (foreground != null) {
19131            if (mForegroundInfo.mBoundsChanged) {
19132                mForegroundInfo.mBoundsChanged = false;
19133                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19134                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19135
19136                if (mForegroundInfo.mInsidePadding) {
19137                    selfBounds.set(0, 0, getWidth(), getHeight());
19138                } else {
19139                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19140                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19141                }
19142
19143                final int ld = getLayoutDirection();
19144                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19145                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19146                foreground.setBounds(overlayBounds);
19147            }
19148
19149            foreground.draw(canvas);
19150        }
19151    }
19152
19153    /**
19154     * Sets the padding. The view may add on the space required to display
19155     * the scrollbars, depending on the style and visibility of the scrollbars.
19156     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19157     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19158     * from the values set in this call.
19159     *
19160     * @attr ref android.R.styleable#View_padding
19161     * @attr ref android.R.styleable#View_paddingBottom
19162     * @attr ref android.R.styleable#View_paddingLeft
19163     * @attr ref android.R.styleable#View_paddingRight
19164     * @attr ref android.R.styleable#View_paddingTop
19165     * @param left the left padding in pixels
19166     * @param top the top padding in pixels
19167     * @param right the right padding in pixels
19168     * @param bottom the bottom padding in pixels
19169     */
19170    public void setPadding(int left, int top, int right, int bottom) {
19171        resetResolvedPaddingInternal();
19172
19173        mUserPaddingStart = UNDEFINED_PADDING;
19174        mUserPaddingEnd = UNDEFINED_PADDING;
19175
19176        mUserPaddingLeftInitial = left;
19177        mUserPaddingRightInitial = right;
19178
19179        mLeftPaddingDefined = true;
19180        mRightPaddingDefined = true;
19181
19182        internalSetPadding(left, top, right, bottom);
19183    }
19184
19185    /**
19186     * @hide
19187     */
19188    protected void internalSetPadding(int left, int top, int right, int bottom) {
19189        mUserPaddingLeft = left;
19190        mUserPaddingRight = right;
19191        mUserPaddingBottom = bottom;
19192
19193        final int viewFlags = mViewFlags;
19194        boolean changed = false;
19195
19196        // Common case is there are no scroll bars.
19197        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19198            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19199                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19200                        ? 0 : getVerticalScrollbarWidth();
19201                switch (mVerticalScrollbarPosition) {
19202                    case SCROLLBAR_POSITION_DEFAULT:
19203                        if (isLayoutRtl()) {
19204                            left += offset;
19205                        } else {
19206                            right += offset;
19207                        }
19208                        break;
19209                    case SCROLLBAR_POSITION_RIGHT:
19210                        right += offset;
19211                        break;
19212                    case SCROLLBAR_POSITION_LEFT:
19213                        left += offset;
19214                        break;
19215                }
19216            }
19217            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19218                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19219                        ? 0 : getHorizontalScrollbarHeight();
19220            }
19221        }
19222
19223        if (mPaddingLeft != left) {
19224            changed = true;
19225            mPaddingLeft = left;
19226        }
19227        if (mPaddingTop != top) {
19228            changed = true;
19229            mPaddingTop = top;
19230        }
19231        if (mPaddingRight != right) {
19232            changed = true;
19233            mPaddingRight = right;
19234        }
19235        if (mPaddingBottom != bottom) {
19236            changed = true;
19237            mPaddingBottom = bottom;
19238        }
19239
19240        if (changed) {
19241            requestLayout();
19242            invalidateOutline();
19243        }
19244    }
19245
19246    /**
19247     * Sets the relative padding. The view may add on the space required to display
19248     * the scrollbars, depending on the style and visibility of the scrollbars.
19249     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19250     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19251     * from the values set in this call.
19252     *
19253     * @attr ref android.R.styleable#View_padding
19254     * @attr ref android.R.styleable#View_paddingBottom
19255     * @attr ref android.R.styleable#View_paddingStart
19256     * @attr ref android.R.styleable#View_paddingEnd
19257     * @attr ref android.R.styleable#View_paddingTop
19258     * @param start the start padding in pixels
19259     * @param top the top padding in pixels
19260     * @param end the end padding in pixels
19261     * @param bottom the bottom padding in pixels
19262     */
19263    public void setPaddingRelative(int start, int top, int end, int bottom) {
19264        resetResolvedPaddingInternal();
19265
19266        mUserPaddingStart = start;
19267        mUserPaddingEnd = end;
19268        mLeftPaddingDefined = true;
19269        mRightPaddingDefined = true;
19270
19271        switch(getLayoutDirection()) {
19272            case LAYOUT_DIRECTION_RTL:
19273                mUserPaddingLeftInitial = end;
19274                mUserPaddingRightInitial = start;
19275                internalSetPadding(end, top, start, bottom);
19276                break;
19277            case LAYOUT_DIRECTION_LTR:
19278            default:
19279                mUserPaddingLeftInitial = start;
19280                mUserPaddingRightInitial = end;
19281                internalSetPadding(start, top, end, bottom);
19282        }
19283    }
19284
19285    /**
19286     * Returns the top padding of this view.
19287     *
19288     * @return the top padding in pixels
19289     */
19290    public int getPaddingTop() {
19291        return mPaddingTop;
19292    }
19293
19294    /**
19295     * Returns the bottom padding of this view. If there are inset and enabled
19296     * scrollbars, this value may include the space required to display the
19297     * scrollbars as well.
19298     *
19299     * @return the bottom padding in pixels
19300     */
19301    public int getPaddingBottom() {
19302        return mPaddingBottom;
19303    }
19304
19305    /**
19306     * Returns the left padding of this view. If there are inset and enabled
19307     * scrollbars, this value may include the space required to display the
19308     * scrollbars as well.
19309     *
19310     * @return the left padding in pixels
19311     */
19312    public int getPaddingLeft() {
19313        if (!isPaddingResolved()) {
19314            resolvePadding();
19315        }
19316        return mPaddingLeft;
19317    }
19318
19319    /**
19320     * Returns the start padding of this view depending on its resolved layout direction.
19321     * If there are inset and enabled scrollbars, this value may include the space
19322     * required to display the scrollbars as well.
19323     *
19324     * @return the start padding in pixels
19325     */
19326    public int getPaddingStart() {
19327        if (!isPaddingResolved()) {
19328            resolvePadding();
19329        }
19330        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19331                mPaddingRight : mPaddingLeft;
19332    }
19333
19334    /**
19335     * Returns the right padding of this view. If there are inset and enabled
19336     * scrollbars, this value may include the space required to display the
19337     * scrollbars as well.
19338     *
19339     * @return the right padding in pixels
19340     */
19341    public int getPaddingRight() {
19342        if (!isPaddingResolved()) {
19343            resolvePadding();
19344        }
19345        return mPaddingRight;
19346    }
19347
19348    /**
19349     * Returns the end padding of this view depending on its resolved layout direction.
19350     * If there are inset and enabled scrollbars, this value may include the space
19351     * required to display the scrollbars as well.
19352     *
19353     * @return the end padding in pixels
19354     */
19355    public int getPaddingEnd() {
19356        if (!isPaddingResolved()) {
19357            resolvePadding();
19358        }
19359        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19360                mPaddingLeft : mPaddingRight;
19361    }
19362
19363    /**
19364     * Return if the padding has been set through relative values
19365     * {@link #setPaddingRelative(int, int, int, int)} or through
19366     * @attr ref android.R.styleable#View_paddingStart or
19367     * @attr ref android.R.styleable#View_paddingEnd
19368     *
19369     * @return true if the padding is relative or false if it is not.
19370     */
19371    public boolean isPaddingRelative() {
19372        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19373    }
19374
19375    Insets computeOpticalInsets() {
19376        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19377    }
19378
19379    /**
19380     * @hide
19381     */
19382    public void resetPaddingToInitialValues() {
19383        if (isRtlCompatibilityMode()) {
19384            mPaddingLeft = mUserPaddingLeftInitial;
19385            mPaddingRight = mUserPaddingRightInitial;
19386            return;
19387        }
19388        if (isLayoutRtl()) {
19389            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19390            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19391        } else {
19392            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19393            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19394        }
19395    }
19396
19397    /**
19398     * @hide
19399     */
19400    public Insets getOpticalInsets() {
19401        if (mLayoutInsets == null) {
19402            mLayoutInsets = computeOpticalInsets();
19403        }
19404        return mLayoutInsets;
19405    }
19406
19407    /**
19408     * Set this view's optical insets.
19409     *
19410     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19411     * property. Views that compute their own optical insets should call it as part of measurement.
19412     * This method does not request layout. If you are setting optical insets outside of
19413     * measure/layout itself you will want to call requestLayout() yourself.
19414     * </p>
19415     * @hide
19416     */
19417    public void setOpticalInsets(Insets insets) {
19418        mLayoutInsets = insets;
19419    }
19420
19421    /**
19422     * Changes the selection state of this view. A view can be selected or not.
19423     * Note that selection is not the same as focus. Views are typically
19424     * selected in the context of an AdapterView like ListView or GridView;
19425     * the selected view is the view that is highlighted.
19426     *
19427     * @param selected true if the view must be selected, false otherwise
19428     */
19429    public void setSelected(boolean selected) {
19430        //noinspection DoubleNegation
19431        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19432            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19433            if (!selected) resetPressedState();
19434            invalidate(true);
19435            refreshDrawableState();
19436            dispatchSetSelected(selected);
19437            if (selected) {
19438                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19439            } else {
19440                notifyViewAccessibilityStateChangedIfNeeded(
19441                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19442            }
19443        }
19444    }
19445
19446    /**
19447     * Dispatch setSelected to all of this View's children.
19448     *
19449     * @see #setSelected(boolean)
19450     *
19451     * @param selected The new selected state
19452     */
19453    protected void dispatchSetSelected(boolean selected) {
19454    }
19455
19456    /**
19457     * Indicates the selection state of this view.
19458     *
19459     * @return true if the view is selected, false otherwise
19460     */
19461    @ViewDebug.ExportedProperty
19462    public boolean isSelected() {
19463        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19464    }
19465
19466    /**
19467     * Changes the activated state of this view. A view can be activated or not.
19468     * Note that activation is not the same as selection.  Selection is
19469     * a transient property, representing the view (hierarchy) the user is
19470     * currently interacting with.  Activation is a longer-term state that the
19471     * user can move views in and out of.  For example, in a list view with
19472     * single or multiple selection enabled, the views in the current selection
19473     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19474     * here.)  The activated state is propagated down to children of the view it
19475     * is set on.
19476     *
19477     * @param activated true if the view must be activated, false otherwise
19478     */
19479    public void setActivated(boolean activated) {
19480        //noinspection DoubleNegation
19481        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19482            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19483            invalidate(true);
19484            refreshDrawableState();
19485            dispatchSetActivated(activated);
19486        }
19487    }
19488
19489    /**
19490     * Dispatch setActivated to all of this View's children.
19491     *
19492     * @see #setActivated(boolean)
19493     *
19494     * @param activated The new activated state
19495     */
19496    protected void dispatchSetActivated(boolean activated) {
19497    }
19498
19499    /**
19500     * Indicates the activation state of this view.
19501     *
19502     * @return true if the view is activated, false otherwise
19503     */
19504    @ViewDebug.ExportedProperty
19505    public boolean isActivated() {
19506        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19507    }
19508
19509    /**
19510     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19511     * observer can be used to get notifications when global events, like
19512     * layout, happen.
19513     *
19514     * The returned ViewTreeObserver observer is not guaranteed to remain
19515     * valid for the lifetime of this View. If the caller of this method keeps
19516     * a long-lived reference to ViewTreeObserver, it should always check for
19517     * the return value of {@link ViewTreeObserver#isAlive()}.
19518     *
19519     * @return The ViewTreeObserver for this view's hierarchy.
19520     */
19521    public ViewTreeObserver getViewTreeObserver() {
19522        if (mAttachInfo != null) {
19523            return mAttachInfo.mTreeObserver;
19524        }
19525        if (mFloatingTreeObserver == null) {
19526            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19527        }
19528        return mFloatingTreeObserver;
19529    }
19530
19531    /**
19532     * <p>Finds the topmost view in the current view hierarchy.</p>
19533     *
19534     * @return the topmost view containing this view
19535     */
19536    public View getRootView() {
19537        if (mAttachInfo != null) {
19538            final View v = mAttachInfo.mRootView;
19539            if (v != null) {
19540                return v;
19541            }
19542        }
19543
19544        View parent = this;
19545
19546        while (parent.mParent != null && parent.mParent instanceof View) {
19547            parent = (View) parent.mParent;
19548        }
19549
19550        return parent;
19551    }
19552
19553    /**
19554     * Transforms a motion event from view-local coordinates to on-screen
19555     * coordinates.
19556     *
19557     * @param ev the view-local motion event
19558     * @return false if the transformation could not be applied
19559     * @hide
19560     */
19561    public boolean toGlobalMotionEvent(MotionEvent ev) {
19562        final AttachInfo info = mAttachInfo;
19563        if (info == null) {
19564            return false;
19565        }
19566
19567        final Matrix m = info.mTmpMatrix;
19568        m.set(Matrix.IDENTITY_MATRIX);
19569        transformMatrixToGlobal(m);
19570        ev.transform(m);
19571        return true;
19572    }
19573
19574    /**
19575     * Transforms a motion event from on-screen coordinates to view-local
19576     * coordinates.
19577     *
19578     * @param ev the on-screen motion event
19579     * @return false if the transformation could not be applied
19580     * @hide
19581     */
19582    public boolean toLocalMotionEvent(MotionEvent ev) {
19583        final AttachInfo info = mAttachInfo;
19584        if (info == null) {
19585            return false;
19586        }
19587
19588        final Matrix m = info.mTmpMatrix;
19589        m.set(Matrix.IDENTITY_MATRIX);
19590        transformMatrixToLocal(m);
19591        ev.transform(m);
19592        return true;
19593    }
19594
19595    /**
19596     * Modifies the input matrix such that it maps view-local coordinates to
19597     * on-screen coordinates.
19598     *
19599     * @param m input matrix to modify
19600     * @hide
19601     */
19602    public void transformMatrixToGlobal(Matrix m) {
19603        final ViewParent parent = mParent;
19604        if (parent instanceof View) {
19605            final View vp = (View) parent;
19606            vp.transformMatrixToGlobal(m);
19607            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19608        } else if (parent instanceof ViewRootImpl) {
19609            final ViewRootImpl vr = (ViewRootImpl) parent;
19610            vr.transformMatrixToGlobal(m);
19611            m.preTranslate(0, -vr.mCurScrollY);
19612        }
19613
19614        m.preTranslate(mLeft, mTop);
19615
19616        if (!hasIdentityMatrix()) {
19617            m.preConcat(getMatrix());
19618        }
19619    }
19620
19621    /**
19622     * Modifies the input matrix such that it maps on-screen coordinates to
19623     * view-local coordinates.
19624     *
19625     * @param m input matrix to modify
19626     * @hide
19627     */
19628    public void transformMatrixToLocal(Matrix m) {
19629        final ViewParent parent = mParent;
19630        if (parent instanceof View) {
19631            final View vp = (View) parent;
19632            vp.transformMatrixToLocal(m);
19633            m.postTranslate(vp.mScrollX, vp.mScrollY);
19634        } else if (parent instanceof ViewRootImpl) {
19635            final ViewRootImpl vr = (ViewRootImpl) parent;
19636            vr.transformMatrixToLocal(m);
19637            m.postTranslate(0, vr.mCurScrollY);
19638        }
19639
19640        m.postTranslate(-mLeft, -mTop);
19641
19642        if (!hasIdentityMatrix()) {
19643            m.postConcat(getInverseMatrix());
19644        }
19645    }
19646
19647    /**
19648     * @hide
19649     */
19650    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19651            @ViewDebug.IntToString(from = 0, to = "x"),
19652            @ViewDebug.IntToString(from = 1, to = "y")
19653    })
19654    public int[] getLocationOnScreen() {
19655        int[] location = new int[2];
19656        getLocationOnScreen(location);
19657        return location;
19658    }
19659
19660    /**
19661     * <p>Computes the coordinates of this view on the screen. The argument
19662     * must be an array of two integers. After the method returns, the array
19663     * contains the x and y location in that order.</p>
19664     *
19665     * @param outLocation an array of two integers in which to hold the coordinates
19666     */
19667    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19668        getLocationInWindow(outLocation);
19669
19670        final AttachInfo info = mAttachInfo;
19671        if (info != null) {
19672            outLocation[0] += info.mWindowLeft;
19673            outLocation[1] += info.mWindowTop;
19674        }
19675    }
19676
19677    /**
19678     * <p>Computes the coordinates of this view in its window. The argument
19679     * must be an array of two integers. After the method returns, the array
19680     * contains the x and y location in that order.</p>
19681     *
19682     * @param outLocation an array of two integers in which to hold the coordinates
19683     */
19684    public void getLocationInWindow(@Size(2) int[] outLocation) {
19685        if (outLocation == null || outLocation.length < 2) {
19686            throw new IllegalArgumentException("outLocation must be an array of two integers");
19687        }
19688
19689        outLocation[0] = 0;
19690        outLocation[1] = 0;
19691
19692        transformFromViewToWindowSpace(outLocation);
19693    }
19694
19695    /** @hide */
19696    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19697        if (inOutLocation == null || inOutLocation.length < 2) {
19698            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19699        }
19700
19701        if (mAttachInfo == null) {
19702            // When the view is not attached to a window, this method does not make sense
19703            inOutLocation[0] = inOutLocation[1] = 0;
19704            return;
19705        }
19706
19707        float position[] = mAttachInfo.mTmpTransformLocation;
19708        position[0] = inOutLocation[0];
19709        position[1] = inOutLocation[1];
19710
19711        if (!hasIdentityMatrix()) {
19712            getMatrix().mapPoints(position);
19713        }
19714
19715        position[0] += mLeft;
19716        position[1] += mTop;
19717
19718        ViewParent viewParent = mParent;
19719        while (viewParent instanceof View) {
19720            final View view = (View) viewParent;
19721
19722            position[0] -= view.mScrollX;
19723            position[1] -= view.mScrollY;
19724
19725            if (!view.hasIdentityMatrix()) {
19726                view.getMatrix().mapPoints(position);
19727            }
19728
19729            position[0] += view.mLeft;
19730            position[1] += view.mTop;
19731
19732            viewParent = view.mParent;
19733         }
19734
19735        if (viewParent instanceof ViewRootImpl) {
19736            // *cough*
19737            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19738            position[1] -= vr.mCurScrollY;
19739        }
19740
19741        inOutLocation[0] = Math.round(position[0]);
19742        inOutLocation[1] = Math.round(position[1]);
19743    }
19744
19745    /**
19746     * {@hide}
19747     * @param id the id of the view to be found
19748     * @return the view of the specified id, null if cannot be found
19749     */
19750    protected View findViewTraversal(@IdRes int id) {
19751        if (id == mID) {
19752            return this;
19753        }
19754        return null;
19755    }
19756
19757    /**
19758     * {@hide}
19759     * @param tag the tag of the view to be found
19760     * @return the view of specified tag, null if cannot be found
19761     */
19762    protected View findViewWithTagTraversal(Object tag) {
19763        if (tag != null && tag.equals(mTag)) {
19764            return this;
19765        }
19766        return null;
19767    }
19768
19769    /**
19770     * {@hide}
19771     * @param predicate The predicate to evaluate.
19772     * @param childToSkip If not null, ignores this child during the recursive traversal.
19773     * @return The first view that matches the predicate or null.
19774     */
19775    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19776        if (predicate.apply(this)) {
19777            return this;
19778        }
19779        return null;
19780    }
19781
19782    /**
19783     * Look for a child view with the given id.  If this view has the given
19784     * id, return this view.
19785     *
19786     * @param id The id to search for.
19787     * @return The view that has the given id in the hierarchy or null
19788     */
19789    @Nullable
19790    public final View findViewById(@IdRes int id) {
19791        if (id < 0) {
19792            return null;
19793        }
19794        return findViewTraversal(id);
19795    }
19796
19797    /**
19798     * Finds a view by its unuque and stable accessibility id.
19799     *
19800     * @param accessibilityId The searched accessibility id.
19801     * @return The found view.
19802     */
19803    final View findViewByAccessibilityId(int accessibilityId) {
19804        if (accessibilityId < 0) {
19805            return null;
19806        }
19807        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19808        if (view != null) {
19809            return view.includeForAccessibility() ? view : null;
19810        }
19811        return null;
19812    }
19813
19814    /**
19815     * Performs the traversal to find a view by its unuque and stable accessibility id.
19816     *
19817     * <strong>Note:</strong>This method does not stop at the root namespace
19818     * boundary since the user can touch the screen at an arbitrary location
19819     * potentially crossing the root namespace bounday which will send an
19820     * accessibility event to accessibility services and they should be able
19821     * to obtain the event source. Also accessibility ids are guaranteed to be
19822     * unique in the window.
19823     *
19824     * @param accessibilityId The accessibility id.
19825     * @return The found view.
19826     *
19827     * @hide
19828     */
19829    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19830        if (getAccessibilityViewId() == accessibilityId) {
19831            return this;
19832        }
19833        return null;
19834    }
19835
19836    /**
19837     * Look for a child view with the given tag.  If this view has the given
19838     * tag, return this view.
19839     *
19840     * @param tag The tag to search for, using "tag.equals(getTag())".
19841     * @return The View that has the given tag in the hierarchy or null
19842     */
19843    public final View findViewWithTag(Object tag) {
19844        if (tag == null) {
19845            return null;
19846        }
19847        return findViewWithTagTraversal(tag);
19848    }
19849
19850    /**
19851     * {@hide}
19852     * Look for a child view that matches the specified predicate.
19853     * If this view matches the predicate, return this view.
19854     *
19855     * @param predicate The predicate to evaluate.
19856     * @return The first view that matches the predicate or null.
19857     */
19858    public final View findViewByPredicate(Predicate<View> predicate) {
19859        return findViewByPredicateTraversal(predicate, null);
19860    }
19861
19862    /**
19863     * {@hide}
19864     * Look for a child view that matches the specified predicate,
19865     * starting with the specified view and its descendents and then
19866     * recusively searching the ancestors and siblings of that view
19867     * until this view is reached.
19868     *
19869     * This method is useful in cases where the predicate does not match
19870     * a single unique view (perhaps multiple views use the same id)
19871     * and we are trying to find the view that is "closest" in scope to the
19872     * starting view.
19873     *
19874     * @param start The view to start from.
19875     * @param predicate The predicate to evaluate.
19876     * @return The first view that matches the predicate or null.
19877     */
19878    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19879        View childToSkip = null;
19880        for (;;) {
19881            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19882            if (view != null || start == this) {
19883                return view;
19884            }
19885
19886            ViewParent parent = start.getParent();
19887            if (parent == null || !(parent instanceof View)) {
19888                return null;
19889            }
19890
19891            childToSkip = start;
19892            start = (View) parent;
19893        }
19894    }
19895
19896    /**
19897     * Sets the identifier for this view. The identifier does not have to be
19898     * unique in this view's hierarchy. The identifier should be a positive
19899     * number.
19900     *
19901     * @see #NO_ID
19902     * @see #getId()
19903     * @see #findViewById(int)
19904     *
19905     * @param id a number used to identify the view
19906     *
19907     * @attr ref android.R.styleable#View_id
19908     */
19909    public void setId(@IdRes int id) {
19910        mID = id;
19911        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19912            mID = generateViewId();
19913        }
19914    }
19915
19916    /**
19917     * {@hide}
19918     *
19919     * @param isRoot true if the view belongs to the root namespace, false
19920     *        otherwise
19921     */
19922    public void setIsRootNamespace(boolean isRoot) {
19923        if (isRoot) {
19924            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19925        } else {
19926            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19927        }
19928    }
19929
19930    /**
19931     * {@hide}
19932     *
19933     * @return true if the view belongs to the root namespace, false otherwise
19934     */
19935    public boolean isRootNamespace() {
19936        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19937    }
19938
19939    /**
19940     * Returns this view's identifier.
19941     *
19942     * @return a positive integer used to identify the view or {@link #NO_ID}
19943     *         if the view has no ID
19944     *
19945     * @see #setId(int)
19946     * @see #findViewById(int)
19947     * @attr ref android.R.styleable#View_id
19948     */
19949    @IdRes
19950    @ViewDebug.CapturedViewProperty
19951    public int getId() {
19952        return mID;
19953    }
19954
19955    /**
19956     * Returns this view's tag.
19957     *
19958     * @return the Object stored in this view as a tag, or {@code null} if not
19959     *         set
19960     *
19961     * @see #setTag(Object)
19962     * @see #getTag(int)
19963     */
19964    @ViewDebug.ExportedProperty
19965    public Object getTag() {
19966        return mTag;
19967    }
19968
19969    /**
19970     * Sets the tag associated with this view. A tag can be used to mark
19971     * a view in its hierarchy and does not have to be unique within the
19972     * hierarchy. Tags can also be used to store data within a view without
19973     * resorting to another data structure.
19974     *
19975     * @param tag an Object to tag the view with
19976     *
19977     * @see #getTag()
19978     * @see #setTag(int, Object)
19979     */
19980    public void setTag(final Object tag) {
19981        mTag = tag;
19982    }
19983
19984    /**
19985     * Returns the tag associated with this view and the specified key.
19986     *
19987     * @param key The key identifying the tag
19988     *
19989     * @return the Object stored in this view as a tag, or {@code null} if not
19990     *         set
19991     *
19992     * @see #setTag(int, Object)
19993     * @see #getTag()
19994     */
19995    public Object getTag(int key) {
19996        if (mKeyedTags != null) return mKeyedTags.get(key);
19997        return null;
19998    }
19999
20000    /**
20001     * Sets a tag associated with this view and a key. A tag can be used
20002     * to mark a view in its hierarchy and does not have to be unique within
20003     * the hierarchy. Tags can also be used to store data within a view
20004     * without resorting to another data structure.
20005     *
20006     * The specified key should be an id declared in the resources of the
20007     * application to ensure it is unique (see the <a
20008     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20009     * Keys identified as belonging to
20010     * the Android framework or not associated with any package will cause
20011     * an {@link IllegalArgumentException} to be thrown.
20012     *
20013     * @param key The key identifying the tag
20014     * @param tag An Object to tag the view with
20015     *
20016     * @throws IllegalArgumentException If they specified key is not valid
20017     *
20018     * @see #setTag(Object)
20019     * @see #getTag(int)
20020     */
20021    public void setTag(int key, final Object tag) {
20022        // If the package id is 0x00 or 0x01, it's either an undefined package
20023        // or a framework id
20024        if ((key >>> 24) < 2) {
20025            throw new IllegalArgumentException("The key must be an application-specific "
20026                    + "resource id.");
20027        }
20028
20029        setKeyedTag(key, tag);
20030    }
20031
20032    /**
20033     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20034     * framework id.
20035     *
20036     * @hide
20037     */
20038    public void setTagInternal(int key, Object tag) {
20039        if ((key >>> 24) != 0x1) {
20040            throw new IllegalArgumentException("The key must be a framework-specific "
20041                    + "resource id.");
20042        }
20043
20044        setKeyedTag(key, tag);
20045    }
20046
20047    private void setKeyedTag(int key, Object tag) {
20048        if (mKeyedTags == null) {
20049            mKeyedTags = new SparseArray<Object>(2);
20050        }
20051
20052        mKeyedTags.put(key, tag);
20053    }
20054
20055    /**
20056     * Prints information about this view in the log output, with the tag
20057     * {@link #VIEW_LOG_TAG}.
20058     *
20059     * @hide
20060     */
20061    public void debug() {
20062        debug(0);
20063    }
20064
20065    /**
20066     * Prints information about this view in the log output, with the tag
20067     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20068     * indentation defined by the <code>depth</code>.
20069     *
20070     * @param depth the indentation level
20071     *
20072     * @hide
20073     */
20074    protected void debug(int depth) {
20075        String output = debugIndent(depth - 1);
20076
20077        output += "+ " + this;
20078        int id = getId();
20079        if (id != -1) {
20080            output += " (id=" + id + ")";
20081        }
20082        Object tag = getTag();
20083        if (tag != null) {
20084            output += " (tag=" + tag + ")";
20085        }
20086        Log.d(VIEW_LOG_TAG, output);
20087
20088        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20089            output = debugIndent(depth) + " FOCUSED";
20090            Log.d(VIEW_LOG_TAG, output);
20091        }
20092
20093        output = debugIndent(depth);
20094        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20095                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20096                + "} ";
20097        Log.d(VIEW_LOG_TAG, output);
20098
20099        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20100                || mPaddingBottom != 0) {
20101            output = debugIndent(depth);
20102            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20103                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20104            Log.d(VIEW_LOG_TAG, output);
20105        }
20106
20107        output = debugIndent(depth);
20108        output += "mMeasureWidth=" + mMeasuredWidth +
20109                " mMeasureHeight=" + mMeasuredHeight;
20110        Log.d(VIEW_LOG_TAG, output);
20111
20112        output = debugIndent(depth);
20113        if (mLayoutParams == null) {
20114            output += "BAD! no layout params";
20115        } else {
20116            output = mLayoutParams.debug(output);
20117        }
20118        Log.d(VIEW_LOG_TAG, output);
20119
20120        output = debugIndent(depth);
20121        output += "flags={";
20122        output += View.printFlags(mViewFlags);
20123        output += "}";
20124        Log.d(VIEW_LOG_TAG, output);
20125
20126        output = debugIndent(depth);
20127        output += "privateFlags={";
20128        output += View.printPrivateFlags(mPrivateFlags);
20129        output += "}";
20130        Log.d(VIEW_LOG_TAG, output);
20131    }
20132
20133    /**
20134     * Creates a string of whitespaces used for indentation.
20135     *
20136     * @param depth the indentation level
20137     * @return a String containing (depth * 2 + 3) * 2 white spaces
20138     *
20139     * @hide
20140     */
20141    protected static String debugIndent(int depth) {
20142        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20143        for (int i = 0; i < (depth * 2) + 3; i++) {
20144            spaces.append(' ').append(' ');
20145        }
20146        return spaces.toString();
20147    }
20148
20149    /**
20150     * <p>Return the offset of the widget's text baseline from the widget's top
20151     * boundary. If this widget does not support baseline alignment, this
20152     * method returns -1. </p>
20153     *
20154     * @return the offset of the baseline within the widget's bounds or -1
20155     *         if baseline alignment is not supported
20156     */
20157    @ViewDebug.ExportedProperty(category = "layout")
20158    public int getBaseline() {
20159        return -1;
20160    }
20161
20162    /**
20163     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20164     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20165     * a layout pass.
20166     *
20167     * @return whether the view hierarchy is currently undergoing a layout pass
20168     */
20169    public boolean isInLayout() {
20170        ViewRootImpl viewRoot = getViewRootImpl();
20171        return (viewRoot != null && viewRoot.isInLayout());
20172    }
20173
20174    /**
20175     * Call this when something has changed which has invalidated the
20176     * layout of this view. This will schedule a layout pass of the view
20177     * tree. This should not be called while the view hierarchy is currently in a layout
20178     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20179     * end of the current layout pass (and then layout will run again) or after the current
20180     * frame is drawn and the next layout occurs.
20181     *
20182     * <p>Subclasses which override this method should call the superclass method to
20183     * handle possible request-during-layout errors correctly.</p>
20184     */
20185    @CallSuper
20186    public void requestLayout() {
20187        if (mMeasureCache != null) mMeasureCache.clear();
20188
20189        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20190            // Only trigger request-during-layout logic if this is the view requesting it,
20191            // not the views in its parent hierarchy
20192            ViewRootImpl viewRoot = getViewRootImpl();
20193            if (viewRoot != null && viewRoot.isInLayout()) {
20194                if (!viewRoot.requestLayoutDuringLayout(this)) {
20195                    return;
20196                }
20197            }
20198            mAttachInfo.mViewRequestingLayout = this;
20199        }
20200
20201        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20202        mPrivateFlags |= PFLAG_INVALIDATED;
20203
20204        if (mParent != null && !mParent.isLayoutRequested()) {
20205            mParent.requestLayout();
20206        }
20207        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20208            mAttachInfo.mViewRequestingLayout = null;
20209        }
20210    }
20211
20212    /**
20213     * Forces this view to be laid out during the next layout pass.
20214     * This method does not call requestLayout() or forceLayout()
20215     * on the parent.
20216     */
20217    public void forceLayout() {
20218        if (mMeasureCache != null) mMeasureCache.clear();
20219
20220        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20221        mPrivateFlags |= PFLAG_INVALIDATED;
20222    }
20223
20224    /**
20225     * <p>
20226     * This is called to find out how big a view should be. The parent
20227     * supplies constraint information in the width and height parameters.
20228     * </p>
20229     *
20230     * <p>
20231     * The actual measurement work of a view is performed in
20232     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20233     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20234     * </p>
20235     *
20236     *
20237     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20238     *        parent
20239     * @param heightMeasureSpec Vertical space requirements as imposed by the
20240     *        parent
20241     *
20242     * @see #onMeasure(int, int)
20243     */
20244    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20245        boolean optical = isLayoutModeOptical(this);
20246        if (optical != isLayoutModeOptical(mParent)) {
20247            Insets insets = getOpticalInsets();
20248            int oWidth  = insets.left + insets.right;
20249            int oHeight = insets.top  + insets.bottom;
20250            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20251            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20252        }
20253
20254        // Suppress sign extension for the low bytes
20255        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20256        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20257
20258        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20259
20260        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20261        // already measured as the correct size. In API 23 and below, this
20262        // extra pass is required to make LinearLayout re-distribute weight.
20263        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20264                || heightMeasureSpec != mOldHeightMeasureSpec;
20265        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20266                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20267        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20268                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20269        final boolean needsLayout = specChanged
20270                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20271
20272        if (forceLayout || needsLayout) {
20273            // first clears the measured dimension flag
20274            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20275
20276            resolveRtlPropertiesIfNeeded();
20277
20278            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20279            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20280                // measure ourselves, this should set the measured dimension flag back
20281                onMeasure(widthMeasureSpec, heightMeasureSpec);
20282                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20283            } else {
20284                long value = mMeasureCache.valueAt(cacheIndex);
20285                // Casting a long to int drops the high 32 bits, no mask needed
20286                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20287                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20288            }
20289
20290            // flag not set, setMeasuredDimension() was not invoked, we raise
20291            // an exception to warn the developer
20292            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20293                throw new IllegalStateException("View with id " + getId() + ": "
20294                        + getClass().getName() + "#onMeasure() did not set the"
20295                        + " measured dimension by calling"
20296                        + " setMeasuredDimension()");
20297            }
20298
20299            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20300        }
20301
20302        mOldWidthMeasureSpec = widthMeasureSpec;
20303        mOldHeightMeasureSpec = heightMeasureSpec;
20304
20305        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20306                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20307    }
20308
20309    /**
20310     * <p>
20311     * Measure the view and its content to determine the measured width and the
20312     * measured height. This method is invoked by {@link #measure(int, int)} and
20313     * should be overridden by subclasses to provide accurate and efficient
20314     * measurement of their contents.
20315     * </p>
20316     *
20317     * <p>
20318     * <strong>CONTRACT:</strong> When overriding this method, you
20319     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20320     * measured width and height of this view. Failure to do so will trigger an
20321     * <code>IllegalStateException</code>, thrown by
20322     * {@link #measure(int, int)}. Calling the superclass'
20323     * {@link #onMeasure(int, int)} is a valid use.
20324     * </p>
20325     *
20326     * <p>
20327     * The base class implementation of measure defaults to the background size,
20328     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20329     * override {@link #onMeasure(int, int)} to provide better measurements of
20330     * their content.
20331     * </p>
20332     *
20333     * <p>
20334     * If this method is overridden, it is the subclass's responsibility to make
20335     * sure the measured height and width are at least the view's minimum height
20336     * and width ({@link #getSuggestedMinimumHeight()} and
20337     * {@link #getSuggestedMinimumWidth()}).
20338     * </p>
20339     *
20340     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20341     *                         The requirements are encoded with
20342     *                         {@link android.view.View.MeasureSpec}.
20343     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20344     *                         The requirements are encoded with
20345     *                         {@link android.view.View.MeasureSpec}.
20346     *
20347     * @see #getMeasuredWidth()
20348     * @see #getMeasuredHeight()
20349     * @see #setMeasuredDimension(int, int)
20350     * @see #getSuggestedMinimumHeight()
20351     * @see #getSuggestedMinimumWidth()
20352     * @see android.view.View.MeasureSpec#getMode(int)
20353     * @see android.view.View.MeasureSpec#getSize(int)
20354     */
20355    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20356        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20357                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20358    }
20359
20360    /**
20361     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20362     * measured width and measured height. Failing to do so will trigger an
20363     * exception at measurement time.</p>
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    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20373        boolean optical = isLayoutModeOptical(this);
20374        if (optical != isLayoutModeOptical(mParent)) {
20375            Insets insets = getOpticalInsets();
20376            int opticalWidth  = insets.left + insets.right;
20377            int opticalHeight = insets.top  + insets.bottom;
20378
20379            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20380            measuredHeight += optical ? opticalHeight : -opticalHeight;
20381        }
20382        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20383    }
20384
20385    /**
20386     * Sets the measured dimension without extra processing for things like optical bounds.
20387     * Useful for reapplying consistent values that have already been cooked with adjustments
20388     * for optical bounds, etc. such as those from the measurement cache.
20389     *
20390     * @param measuredWidth The measured width of this view.  May be a complex
20391     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20392     * {@link #MEASURED_STATE_TOO_SMALL}.
20393     * @param measuredHeight The measured height of this view.  May be a complex
20394     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20395     * {@link #MEASURED_STATE_TOO_SMALL}.
20396     */
20397    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20398        mMeasuredWidth = measuredWidth;
20399        mMeasuredHeight = measuredHeight;
20400
20401        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20402    }
20403
20404    /**
20405     * Merge two states as returned by {@link #getMeasuredState()}.
20406     * @param curState The current state as returned from a view or the result
20407     * of combining multiple views.
20408     * @param newState The new view state to combine.
20409     * @return Returns a new integer reflecting the combination of the two
20410     * states.
20411     */
20412    public static int combineMeasuredStates(int curState, int newState) {
20413        return curState | newState;
20414    }
20415
20416    /**
20417     * Version of {@link #resolveSizeAndState(int, int, int)}
20418     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20419     */
20420    public static int resolveSize(int size, int measureSpec) {
20421        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20422    }
20423
20424    /**
20425     * Utility to reconcile a desired size and state, with constraints imposed
20426     * by a MeasureSpec. Will take the desired size, unless a different size
20427     * is imposed by the constraints. The returned value is a compound integer,
20428     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20429     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20430     * resulting size is smaller than the size the view wants to be.
20431     *
20432     * @param size How big the view wants to be.
20433     * @param measureSpec Constraints imposed by the parent.
20434     * @param childMeasuredState Size information bit mask for the view's
20435     *                           children.
20436     * @return Size information bit mask as defined by
20437     *         {@link #MEASURED_SIZE_MASK} and
20438     *         {@link #MEASURED_STATE_TOO_SMALL}.
20439     */
20440    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20441        final int specMode = MeasureSpec.getMode(measureSpec);
20442        final int specSize = MeasureSpec.getSize(measureSpec);
20443        final int result;
20444        switch (specMode) {
20445            case MeasureSpec.AT_MOST:
20446                if (specSize < size) {
20447                    result = specSize | MEASURED_STATE_TOO_SMALL;
20448                } else {
20449                    result = size;
20450                }
20451                break;
20452            case MeasureSpec.EXACTLY:
20453                result = specSize;
20454                break;
20455            case MeasureSpec.UNSPECIFIED:
20456            default:
20457                result = size;
20458        }
20459        return result | (childMeasuredState & MEASURED_STATE_MASK);
20460    }
20461
20462    /**
20463     * Utility to return a default size. Uses the supplied size if the
20464     * MeasureSpec imposed no constraints. Will get larger if allowed
20465     * by the MeasureSpec.
20466     *
20467     * @param size Default size for this view
20468     * @param measureSpec Constraints imposed by the parent
20469     * @return The size this view should be.
20470     */
20471    public static int getDefaultSize(int size, int measureSpec) {
20472        int result = size;
20473        int specMode = MeasureSpec.getMode(measureSpec);
20474        int specSize = MeasureSpec.getSize(measureSpec);
20475
20476        switch (specMode) {
20477        case MeasureSpec.UNSPECIFIED:
20478            result = size;
20479            break;
20480        case MeasureSpec.AT_MOST:
20481        case MeasureSpec.EXACTLY:
20482            result = specSize;
20483            break;
20484        }
20485        return result;
20486    }
20487
20488    /**
20489     * Returns the suggested minimum height that the view should use. This
20490     * returns the maximum of the view's minimum height
20491     * and the background's minimum height
20492     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20493     * <p>
20494     * When being used in {@link #onMeasure(int, int)}, the caller should still
20495     * ensure the returned height is within the requirements of the parent.
20496     *
20497     * @return The suggested minimum height of the view.
20498     */
20499    protected int getSuggestedMinimumHeight() {
20500        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20501
20502    }
20503
20504    /**
20505     * Returns the suggested minimum width that the view should use. This
20506     * returns the maximum of the view's minimum width
20507     * and the background's minimum width
20508     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20509     * <p>
20510     * When being used in {@link #onMeasure(int, int)}, the caller should still
20511     * ensure the returned width is within the requirements of the parent.
20512     *
20513     * @return The suggested minimum width of the view.
20514     */
20515    protected int getSuggestedMinimumWidth() {
20516        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20517    }
20518
20519    /**
20520     * Returns the minimum height of the view.
20521     *
20522     * @return the minimum height the view will try to be, in pixels
20523     *
20524     * @see #setMinimumHeight(int)
20525     *
20526     * @attr ref android.R.styleable#View_minHeight
20527     */
20528    public int getMinimumHeight() {
20529        return mMinHeight;
20530    }
20531
20532    /**
20533     * Sets the minimum height of the view. It is not guaranteed the view will
20534     * be able to achieve this minimum height (for example, if its parent layout
20535     * constrains it with less available height).
20536     *
20537     * @param minHeight The minimum height the view will try to be, in pixels
20538     *
20539     * @see #getMinimumHeight()
20540     *
20541     * @attr ref android.R.styleable#View_minHeight
20542     */
20543    @RemotableViewMethod
20544    public void setMinimumHeight(int minHeight) {
20545        mMinHeight = minHeight;
20546        requestLayout();
20547    }
20548
20549    /**
20550     * Returns the minimum width of the view.
20551     *
20552     * @return the minimum width the view will try to be, in pixels
20553     *
20554     * @see #setMinimumWidth(int)
20555     *
20556     * @attr ref android.R.styleable#View_minWidth
20557     */
20558    public int getMinimumWidth() {
20559        return mMinWidth;
20560    }
20561
20562    /**
20563     * Sets the minimum width of the view. It is not guaranteed the view will
20564     * be able to achieve this minimum width (for example, if its parent layout
20565     * constrains it with less available width).
20566     *
20567     * @param minWidth The minimum width the view will try to be, in pixels
20568     *
20569     * @see #getMinimumWidth()
20570     *
20571     * @attr ref android.R.styleable#View_minWidth
20572     */
20573    public void setMinimumWidth(int minWidth) {
20574        mMinWidth = minWidth;
20575        requestLayout();
20576
20577    }
20578
20579    /**
20580     * Get the animation currently associated with this view.
20581     *
20582     * @return The animation that is currently playing or
20583     *         scheduled to play for this view.
20584     */
20585    public Animation getAnimation() {
20586        return mCurrentAnimation;
20587    }
20588
20589    /**
20590     * Start the specified animation now.
20591     *
20592     * @param animation the animation to start now
20593     */
20594    public void startAnimation(Animation animation) {
20595        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20596        setAnimation(animation);
20597        invalidateParentCaches();
20598        invalidate(true);
20599    }
20600
20601    /**
20602     * Cancels any animations for this view.
20603     */
20604    public void clearAnimation() {
20605        if (mCurrentAnimation != null) {
20606            mCurrentAnimation.detach();
20607        }
20608        mCurrentAnimation = null;
20609        invalidateParentIfNeeded();
20610    }
20611
20612    /**
20613     * Sets the next animation to play for this view.
20614     * If you want the animation to play immediately, use
20615     * {@link #startAnimation(android.view.animation.Animation)} instead.
20616     * This method provides allows fine-grained
20617     * control over the start time and invalidation, but you
20618     * must make sure that 1) the animation has a start time set, and
20619     * 2) the view's parent (which controls animations on its children)
20620     * will be invalidated when the animation is supposed to
20621     * start.
20622     *
20623     * @param animation The next animation, or null.
20624     */
20625    public void setAnimation(Animation animation) {
20626        mCurrentAnimation = animation;
20627
20628        if (animation != null) {
20629            // If the screen is off assume the animation start time is now instead of
20630            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20631            // would cause the animation to start when the screen turns back on
20632            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20633                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20634                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20635            }
20636            animation.reset();
20637        }
20638    }
20639
20640    /**
20641     * Invoked by a parent ViewGroup to notify the start of the animation
20642     * currently associated with this view. If you override this method,
20643     * always call super.onAnimationStart();
20644     *
20645     * @see #setAnimation(android.view.animation.Animation)
20646     * @see #getAnimation()
20647     */
20648    @CallSuper
20649    protected void onAnimationStart() {
20650        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20651    }
20652
20653    /**
20654     * Invoked by a parent ViewGroup to notify the end of the animation
20655     * currently associated with this view. If you override this method,
20656     * always call super.onAnimationEnd();
20657     *
20658     * @see #setAnimation(android.view.animation.Animation)
20659     * @see #getAnimation()
20660     */
20661    @CallSuper
20662    protected void onAnimationEnd() {
20663        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20664    }
20665
20666    /**
20667     * Invoked if there is a Transform that involves alpha. Subclass that can
20668     * draw themselves with the specified alpha should return true, and then
20669     * respect that alpha when their onDraw() is called. If this returns false
20670     * then the view may be redirected to draw into an offscreen buffer to
20671     * fulfill the request, which will look fine, but may be slower than if the
20672     * subclass handles it internally. The default implementation returns false.
20673     *
20674     * @param alpha The alpha (0..255) to apply to the view's drawing
20675     * @return true if the view can draw with the specified alpha.
20676     */
20677    protected boolean onSetAlpha(int alpha) {
20678        return false;
20679    }
20680
20681    /**
20682     * This is used by the RootView to perform an optimization when
20683     * the view hierarchy contains one or several SurfaceView.
20684     * SurfaceView is always considered transparent, but its children are not,
20685     * therefore all View objects remove themselves from the global transparent
20686     * region (passed as a parameter to this function).
20687     *
20688     * @param region The transparent region for this ViewAncestor (window).
20689     *
20690     * @return Returns true if the effective visibility of the view at this
20691     * point is opaque, regardless of the transparent region; returns false
20692     * if it is possible for underlying windows to be seen behind the view.
20693     *
20694     * {@hide}
20695     */
20696    public boolean gatherTransparentRegion(Region region) {
20697        final AttachInfo attachInfo = mAttachInfo;
20698        if (region != null && attachInfo != null) {
20699            final int pflags = mPrivateFlags;
20700            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20701                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20702                // remove it from the transparent region.
20703                final int[] location = attachInfo.mTransparentLocation;
20704                getLocationInWindow(location);
20705                // When a view has Z value, then it will be better to leave some area below the view
20706                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20707                // the bottom part needs more offset than the left, top and right parts due to the
20708                // spot light effects.
20709                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20710                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20711                        location[0] + mRight - mLeft + shadowOffset,
20712                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20713            } else {
20714                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20715                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20716                    // the background drawable's non-transparent parts from this transparent region.
20717                    applyDrawableToTransparentRegion(mBackground, region);
20718                }
20719                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20720                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20721                    // Similarly, we remove the foreground drawable's non-transparent parts.
20722                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20723                }
20724            }
20725        }
20726        return true;
20727    }
20728
20729    /**
20730     * Play a sound effect for this view.
20731     *
20732     * <p>The framework will play sound effects for some built in actions, such as
20733     * clicking, but you may wish to play these effects in your widget,
20734     * for instance, for internal navigation.
20735     *
20736     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20737     * {@link #isSoundEffectsEnabled()} is true.
20738     *
20739     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20740     */
20741    public void playSoundEffect(int soundConstant) {
20742        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20743            return;
20744        }
20745        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20746    }
20747
20748    /**
20749     * BZZZTT!!1!
20750     *
20751     * <p>Provide haptic feedback to the user for this view.
20752     *
20753     * <p>The framework will provide haptic feedback for some built in actions,
20754     * such as long presses, but you may wish to provide feedback for your
20755     * own widget.
20756     *
20757     * <p>The feedback will only be performed if
20758     * {@link #isHapticFeedbackEnabled()} is true.
20759     *
20760     * @param feedbackConstant One of the constants defined in
20761     * {@link HapticFeedbackConstants}
20762     */
20763    public boolean performHapticFeedback(int feedbackConstant) {
20764        return performHapticFeedback(feedbackConstant, 0);
20765    }
20766
20767    /**
20768     * BZZZTT!!1!
20769     *
20770     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20771     *
20772     * @param feedbackConstant One of the constants defined in
20773     * {@link HapticFeedbackConstants}
20774     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20775     */
20776    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20777        if (mAttachInfo == null) {
20778            return false;
20779        }
20780        //noinspection SimplifiableIfStatement
20781        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20782                && !isHapticFeedbackEnabled()) {
20783            return false;
20784        }
20785        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20786                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20787    }
20788
20789    /**
20790     * Request that the visibility of the status bar or other screen/window
20791     * decorations be changed.
20792     *
20793     * <p>This method is used to put the over device UI into temporary modes
20794     * where the user's attention is focused more on the application content,
20795     * by dimming or hiding surrounding system affordances.  This is typically
20796     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20797     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20798     * to be placed behind the action bar (and with these flags other system
20799     * affordances) so that smooth transitions between hiding and showing them
20800     * can be done.
20801     *
20802     * <p>Two representative examples of the use of system UI visibility is
20803     * implementing a content browsing application (like a magazine reader)
20804     * and a video playing application.
20805     *
20806     * <p>The first code shows a typical implementation of a View in a content
20807     * browsing application.  In this implementation, the application goes
20808     * into a content-oriented mode by hiding the status bar and action bar,
20809     * and putting the navigation elements into lights out mode.  The user can
20810     * then interact with content while in this mode.  Such an application should
20811     * provide an easy way for the user to toggle out of the mode (such as to
20812     * check information in the status bar or access notifications).  In the
20813     * implementation here, this is done simply by tapping on the content.
20814     *
20815     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20816     *      content}
20817     *
20818     * <p>This second code sample shows a typical implementation of a View
20819     * in a video playing application.  In this situation, while the video is
20820     * playing the application would like to go into a complete full-screen mode,
20821     * to use as much of the display as possible for the video.  When in this state
20822     * the user can not interact with the application; the system intercepts
20823     * touching on the screen to pop the UI out of full screen mode.  See
20824     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20825     *
20826     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20827     *      content}
20828     *
20829     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20830     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20831     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20832     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20833     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20834     */
20835    public void setSystemUiVisibility(int visibility) {
20836        if (visibility != mSystemUiVisibility) {
20837            mSystemUiVisibility = visibility;
20838            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20839                mParent.recomputeViewAttributes(this);
20840            }
20841        }
20842    }
20843
20844    /**
20845     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20846     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20847     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20848     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20849     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20850     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20851     */
20852    public int getSystemUiVisibility() {
20853        return mSystemUiVisibility;
20854    }
20855
20856    /**
20857     * Returns the current system UI visibility that is currently set for
20858     * the entire window.  This is the combination of the
20859     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20860     * views in the window.
20861     */
20862    public int getWindowSystemUiVisibility() {
20863        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20864    }
20865
20866    /**
20867     * Override to find out when the window's requested system UI visibility
20868     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20869     * This is different from the callbacks received through
20870     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20871     * in that this is only telling you about the local request of the window,
20872     * not the actual values applied by the system.
20873     */
20874    public void onWindowSystemUiVisibilityChanged(int visible) {
20875    }
20876
20877    /**
20878     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20879     * the view hierarchy.
20880     */
20881    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20882        onWindowSystemUiVisibilityChanged(visible);
20883    }
20884
20885    /**
20886     * Set a listener to receive callbacks when the visibility of the system bar changes.
20887     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20888     */
20889    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20890        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20891        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20892            mParent.recomputeViewAttributes(this);
20893        }
20894    }
20895
20896    /**
20897     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20898     * the view hierarchy.
20899     */
20900    public void dispatchSystemUiVisibilityChanged(int visibility) {
20901        ListenerInfo li = mListenerInfo;
20902        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20903            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20904                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20905        }
20906    }
20907
20908    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20909        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20910        if (val != mSystemUiVisibility) {
20911            setSystemUiVisibility(val);
20912            return true;
20913        }
20914        return false;
20915    }
20916
20917    /** @hide */
20918    public void setDisabledSystemUiVisibility(int flags) {
20919        if (mAttachInfo != null) {
20920            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20921                mAttachInfo.mDisabledSystemUiVisibility = flags;
20922                if (mParent != null) {
20923                    mParent.recomputeViewAttributes(this);
20924                }
20925            }
20926        }
20927    }
20928
20929    /**
20930     * Creates an image that the system displays during the drag and drop
20931     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20932     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20933     * appearance as the given View. The default also positions the center of the drag shadow
20934     * directly under the touch point. If no View is provided (the constructor with no parameters
20935     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20936     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20937     * default is an invisible drag shadow.
20938     * <p>
20939     * You are not required to use the View you provide to the constructor as the basis of the
20940     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20941     * anything you want as the drag shadow.
20942     * </p>
20943     * <p>
20944     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20945     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20946     *  size and position of the drag shadow. It uses this data to construct a
20947     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20948     *  so that your application can draw the shadow image in the Canvas.
20949     * </p>
20950     *
20951     * <div class="special reference">
20952     * <h3>Developer Guides</h3>
20953     * <p>For a guide to implementing drag and drop features, read the
20954     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20955     * </div>
20956     */
20957    public static class DragShadowBuilder {
20958        private final WeakReference<View> mView;
20959
20960        /**
20961         * Constructs a shadow image builder based on a View. By default, the resulting drag
20962         * shadow will have the same appearance and dimensions as the View, with the touch point
20963         * over the center of the View.
20964         * @param view A View. Any View in scope can be used.
20965         */
20966        public DragShadowBuilder(View view) {
20967            mView = new WeakReference<View>(view);
20968        }
20969
20970        /**
20971         * Construct a shadow builder object with no associated View.  This
20972         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20973         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20974         * to supply the drag shadow's dimensions and appearance without
20975         * reference to any View object. If they are not overridden, then the result is an
20976         * invisible drag shadow.
20977         */
20978        public DragShadowBuilder() {
20979            mView = new WeakReference<View>(null);
20980        }
20981
20982        /**
20983         * Returns the View object that had been passed to the
20984         * {@link #View.DragShadowBuilder(View)}
20985         * constructor.  If that View parameter was {@code null} or if the
20986         * {@link #View.DragShadowBuilder()}
20987         * constructor was used to instantiate the builder object, this method will return
20988         * null.
20989         *
20990         * @return The View object associate with this builder object.
20991         */
20992        @SuppressWarnings({"JavadocReference"})
20993        final public View getView() {
20994            return mView.get();
20995        }
20996
20997        /**
20998         * Provides the metrics for the shadow image. These include the dimensions of
20999         * the shadow image, and the point within that shadow that should
21000         * be centered under the touch location while dragging.
21001         * <p>
21002         * The default implementation sets the dimensions of the shadow to be the
21003         * same as the dimensions of the View itself and centers the shadow under
21004         * the touch point.
21005         * </p>
21006         *
21007         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21008         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21009         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21010         * image.
21011         *
21012         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21013         * shadow image that should be underneath the touch point during the drag and drop
21014         * operation. Your application must set {@link android.graphics.Point#x} to the
21015         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21016         */
21017        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21018            final View view = mView.get();
21019            if (view != null) {
21020                outShadowSize.set(view.getWidth(), view.getHeight());
21021                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21022            } else {
21023                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21024            }
21025        }
21026
21027        /**
21028         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21029         * based on the dimensions it received from the
21030         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21031         *
21032         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21033         */
21034        public void onDrawShadow(Canvas canvas) {
21035            final View view = mView.get();
21036            if (view != null) {
21037                view.draw(canvas);
21038            } else {
21039                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21040            }
21041        }
21042    }
21043
21044    /**
21045     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21046     * startDragAndDrop()} for newer platform versions.
21047     */
21048    @Deprecated
21049    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21050                                   Object myLocalState, int flags) {
21051        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21052    }
21053
21054    /**
21055     * Starts a drag and drop operation. When your application calls this method, it passes a
21056     * {@link android.view.View.DragShadowBuilder} object to the system. The
21057     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21058     * to get metrics for the drag shadow, and then calls the object's
21059     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21060     * <p>
21061     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21062     *  drag events to all the View objects in your application that are currently visible. It does
21063     *  this either by calling the View object's drag listener (an implementation of
21064     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21065     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21066     *  Both are passed a {@link android.view.DragEvent} object that has a
21067     *  {@link android.view.DragEvent#getAction()} value of
21068     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21069     * </p>
21070     * <p>
21071     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21072     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21073     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21074     * to the View the user selected for dragging.
21075     * </p>
21076     * @param data A {@link android.content.ClipData} object pointing to the data to be
21077     * transferred by the drag and drop operation.
21078     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21079     * drag shadow.
21080     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21081     * drop operation. When dispatching drag events to views in the same activity this object
21082     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21083     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21084     * will return null).
21085     * <p>
21086     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21087     * to the target Views. For example, it can contain flags that differentiate between a
21088     * a copy operation and a move operation.
21089     * </p>
21090     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21091     * flags, or any combination of the following:
21092     *     <ul>
21093     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21094     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21095     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21096     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21097     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21098     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21099     *     </ul>
21100     * @return {@code true} if the method completes successfully, or
21101     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21102     * do a drag, and so no drag operation is in progress.
21103     */
21104    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21105            Object myLocalState, int flags) {
21106        if (ViewDebug.DEBUG_DRAG) {
21107            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21108        }
21109        if (mAttachInfo == null) {
21110            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21111            return false;
21112        }
21113
21114        if (data != null) {
21115            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21116        }
21117
21118        boolean okay = false;
21119
21120        Point shadowSize = new Point();
21121        Point shadowTouchPoint = new Point();
21122        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21123
21124        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21125                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21126            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21127        }
21128
21129        if (ViewDebug.DEBUG_DRAG) {
21130            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21131                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21132        }
21133        if (mAttachInfo.mDragSurface != null) {
21134            mAttachInfo.mDragSurface.release();
21135        }
21136        mAttachInfo.mDragSurface = new Surface();
21137        try {
21138            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21139                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21140            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21141                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21142            if (mAttachInfo.mDragToken != null) {
21143                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21144                try {
21145                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21146                    shadowBuilder.onDrawShadow(canvas);
21147                } finally {
21148                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21149                }
21150
21151                final ViewRootImpl root = getViewRootImpl();
21152
21153                // Cache the local state object for delivery with DragEvents
21154                root.setLocalDragState(myLocalState);
21155
21156                // repurpose 'shadowSize' for the last touch point
21157                root.getLastTouchPoint(shadowSize);
21158
21159                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21160                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21161                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21162                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21163            }
21164        } catch (Exception e) {
21165            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21166            mAttachInfo.mDragSurface.destroy();
21167            mAttachInfo.mDragSurface = null;
21168        }
21169
21170        return okay;
21171    }
21172
21173    /**
21174     * Cancels an ongoing drag and drop operation.
21175     * <p>
21176     * A {@link android.view.DragEvent} object with
21177     * {@link android.view.DragEvent#getAction()} value of
21178     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21179     * {@link android.view.DragEvent#getResult()} value of {@code false}
21180     * will be sent to every
21181     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21182     * even if they are not currently visible.
21183     * </p>
21184     * <p>
21185     * This method can be called on any View in the same window as the View on which
21186     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21187     * was called.
21188     * </p>
21189     */
21190    public final void cancelDragAndDrop() {
21191        if (ViewDebug.DEBUG_DRAG) {
21192            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21193        }
21194        if (mAttachInfo == null) {
21195            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21196            return;
21197        }
21198        if (mAttachInfo.mDragToken != null) {
21199            try {
21200                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21201            } catch (Exception e) {
21202                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21203            }
21204            mAttachInfo.mDragToken = null;
21205        } else {
21206            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21207        }
21208    }
21209
21210    /**
21211     * Updates the drag shadow for the ongoing drag and drop operation.
21212     *
21213     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21214     * new drag shadow.
21215     */
21216    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21217        if (ViewDebug.DEBUG_DRAG) {
21218            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21219        }
21220        if (mAttachInfo == null) {
21221            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21222            return;
21223        }
21224        if (mAttachInfo.mDragToken != null) {
21225            try {
21226                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21227                try {
21228                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21229                    shadowBuilder.onDrawShadow(canvas);
21230                } finally {
21231                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21232                }
21233            } catch (Exception e) {
21234                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21235            }
21236        } else {
21237            Log.e(VIEW_LOG_TAG, "No active drag");
21238        }
21239    }
21240
21241    /**
21242     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21243     * between {startX, startY} and the new cursor positon.
21244     * @param startX horizontal coordinate where the move started.
21245     * @param startY vertical coordinate where the move started.
21246     * @return whether moving was started successfully.
21247     * @hide
21248     */
21249    public final boolean startMovingTask(float startX, float startY) {
21250        if (ViewDebug.DEBUG_POSITIONING) {
21251            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21252        }
21253        try {
21254            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21255        } catch (RemoteException e) {
21256            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21257        }
21258        return false;
21259    }
21260
21261    /**
21262     * Handles drag events sent by the system following a call to
21263     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21264     * startDragAndDrop()}.
21265     *<p>
21266     * When the system calls this method, it passes a
21267     * {@link android.view.DragEvent} object. A call to
21268     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21269     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21270     * operation.
21271     * @param event The {@link android.view.DragEvent} sent by the system.
21272     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21273     * in DragEvent, indicating the type of drag event represented by this object.
21274     * @return {@code true} if the method was successful, otherwise {@code false}.
21275     * <p>
21276     *  The method should return {@code true} in response to an action type of
21277     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21278     *  operation.
21279     * </p>
21280     * <p>
21281     *  The method should also return {@code true} in response to an action type of
21282     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21283     *  {@code false} if it didn't.
21284     * </p>
21285     * <p>
21286     *  For all other events, the return value is ignored.
21287     * </p>
21288     */
21289    public boolean onDragEvent(DragEvent event) {
21290        return false;
21291    }
21292
21293    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21294    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21295        return callDragEventHandler(event);
21296    }
21297
21298    /**
21299     * Detects if this View is enabled and has a drag event listener.
21300     * If both are true, then it calls the drag event listener with the
21301     * {@link android.view.DragEvent} it received. If the drag event listener returns
21302     * {@code true}, then dispatchDragEvent() returns {@code true}.
21303     * <p>
21304     * For all other cases, the method calls the
21305     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21306     * method and returns its result.
21307     * </p>
21308     * <p>
21309     * This ensures that a drag event is always consumed, even if the View does not have a drag
21310     * event listener. However, if the View has a listener and the listener returns true, then
21311     * onDragEvent() is not called.
21312     * </p>
21313     */
21314    public boolean dispatchDragEvent(DragEvent event) {
21315        event.mEventHandlerWasCalled = true;
21316        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21317            event.mAction == DragEvent.ACTION_DROP) {
21318            // About to deliver an event with coordinates to this view. Notify that now this view
21319            // has drag focus. This will send exit/enter events as needed.
21320            getViewRootImpl().setDragFocus(this, event);
21321        }
21322        return callDragEventHandler(event);
21323    }
21324
21325    final boolean callDragEventHandler(DragEvent event) {
21326        final boolean result;
21327
21328        ListenerInfo li = mListenerInfo;
21329        //noinspection SimplifiableIfStatement
21330        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21331                && li.mOnDragListener.onDrag(this, event)) {
21332            result = true;
21333        } else {
21334            result = onDragEvent(event);
21335        }
21336
21337        switch (event.mAction) {
21338            case DragEvent.ACTION_DRAG_ENTERED: {
21339                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21340                refreshDrawableState();
21341            } break;
21342            case DragEvent.ACTION_DRAG_EXITED: {
21343                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21344                refreshDrawableState();
21345            } break;
21346            case DragEvent.ACTION_DRAG_ENDED: {
21347                mPrivateFlags2 &= ~View.DRAG_MASK;
21348                refreshDrawableState();
21349            } break;
21350        }
21351
21352        return result;
21353    }
21354
21355    boolean canAcceptDrag() {
21356        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21357    }
21358
21359    /**
21360     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21361     * it is ever exposed at all.
21362     * @hide
21363     */
21364    public void onCloseSystemDialogs(String reason) {
21365    }
21366
21367    /**
21368     * Given a Drawable whose bounds have been set to draw into this view,
21369     * update a Region being computed for
21370     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21371     * that any non-transparent parts of the Drawable are removed from the
21372     * given transparent region.
21373     *
21374     * @param dr The Drawable whose transparency is to be applied to the region.
21375     * @param region A Region holding the current transparency information,
21376     * where any parts of the region that are set are considered to be
21377     * transparent.  On return, this region will be modified to have the
21378     * transparency information reduced by the corresponding parts of the
21379     * Drawable that are not transparent.
21380     * {@hide}
21381     */
21382    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21383        if (DBG) {
21384            Log.i("View", "Getting transparent region for: " + this);
21385        }
21386        final Region r = dr.getTransparentRegion();
21387        final Rect db = dr.getBounds();
21388        final AttachInfo attachInfo = mAttachInfo;
21389        if (r != null && attachInfo != null) {
21390            final int w = getRight()-getLeft();
21391            final int h = getBottom()-getTop();
21392            if (db.left > 0) {
21393                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21394                r.op(0, 0, db.left, h, Region.Op.UNION);
21395            }
21396            if (db.right < w) {
21397                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21398                r.op(db.right, 0, w, h, Region.Op.UNION);
21399            }
21400            if (db.top > 0) {
21401                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21402                r.op(0, 0, w, db.top, Region.Op.UNION);
21403            }
21404            if (db.bottom < h) {
21405                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21406                r.op(0, db.bottom, w, h, Region.Op.UNION);
21407            }
21408            final int[] location = attachInfo.mTransparentLocation;
21409            getLocationInWindow(location);
21410            r.translate(location[0], location[1]);
21411            region.op(r, Region.Op.INTERSECT);
21412        } else {
21413            region.op(db, Region.Op.DIFFERENCE);
21414        }
21415    }
21416
21417    private void checkForLongClick(int delayOffset, float x, float y) {
21418        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21419            mHasPerformedLongPress = false;
21420
21421            if (mPendingCheckForLongPress == null) {
21422                mPendingCheckForLongPress = new CheckForLongPress();
21423            }
21424            mPendingCheckForLongPress.setAnchor(x, y);
21425            mPendingCheckForLongPress.rememberWindowAttachCount();
21426            mPendingCheckForLongPress.rememberPressedState();
21427            postDelayed(mPendingCheckForLongPress,
21428                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21429        }
21430    }
21431
21432    /**
21433     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21434     * LayoutInflater} class, which provides a full range of options for view inflation.
21435     *
21436     * @param context The Context object for your activity or application.
21437     * @param resource The resource ID to inflate
21438     * @param root A view group that will be the parent.  Used to properly inflate the
21439     * layout_* parameters.
21440     * @see LayoutInflater
21441     */
21442    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21443        LayoutInflater factory = LayoutInflater.from(context);
21444        return factory.inflate(resource, root);
21445    }
21446
21447    /**
21448     * Scroll the view with standard behavior for scrolling beyond the normal
21449     * content boundaries. Views that call this method should override
21450     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21451     * results of an over-scroll operation.
21452     *
21453     * Views can use this method to handle any touch or fling-based scrolling.
21454     *
21455     * @param deltaX Change in X in pixels
21456     * @param deltaY Change in Y in pixels
21457     * @param scrollX Current X scroll value in pixels before applying deltaX
21458     * @param scrollY Current Y scroll value in pixels before applying deltaY
21459     * @param scrollRangeX Maximum content scroll range along the X axis
21460     * @param scrollRangeY Maximum content scroll range along the Y axis
21461     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21462     *          along the X axis.
21463     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21464     *          along the Y axis.
21465     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21466     * @return true if scrolling was clamped to an over-scroll boundary along either
21467     *          axis, false otherwise.
21468     */
21469    @SuppressWarnings({"UnusedParameters"})
21470    protected boolean overScrollBy(int deltaX, int deltaY,
21471            int scrollX, int scrollY,
21472            int scrollRangeX, int scrollRangeY,
21473            int maxOverScrollX, int maxOverScrollY,
21474            boolean isTouchEvent) {
21475        final int overScrollMode = mOverScrollMode;
21476        final boolean canScrollHorizontal =
21477                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21478        final boolean canScrollVertical =
21479                computeVerticalScrollRange() > computeVerticalScrollExtent();
21480        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21481                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21482        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21483                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21484
21485        int newScrollX = scrollX + deltaX;
21486        if (!overScrollHorizontal) {
21487            maxOverScrollX = 0;
21488        }
21489
21490        int newScrollY = scrollY + deltaY;
21491        if (!overScrollVertical) {
21492            maxOverScrollY = 0;
21493        }
21494
21495        // Clamp values if at the limits and record
21496        final int left = -maxOverScrollX;
21497        final int right = maxOverScrollX + scrollRangeX;
21498        final int top = -maxOverScrollY;
21499        final int bottom = maxOverScrollY + scrollRangeY;
21500
21501        boolean clampedX = false;
21502        if (newScrollX > right) {
21503            newScrollX = right;
21504            clampedX = true;
21505        } else if (newScrollX < left) {
21506            newScrollX = left;
21507            clampedX = true;
21508        }
21509
21510        boolean clampedY = false;
21511        if (newScrollY > bottom) {
21512            newScrollY = bottom;
21513            clampedY = true;
21514        } else if (newScrollY < top) {
21515            newScrollY = top;
21516            clampedY = true;
21517        }
21518
21519        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21520
21521        return clampedX || clampedY;
21522    }
21523
21524    /**
21525     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21526     * respond to the results of an over-scroll operation.
21527     *
21528     * @param scrollX New X scroll value in pixels
21529     * @param scrollY New Y scroll value in pixels
21530     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21531     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21532     */
21533    protected void onOverScrolled(int scrollX, int scrollY,
21534            boolean clampedX, boolean clampedY) {
21535        // Intentionally empty.
21536    }
21537
21538    /**
21539     * Returns the over-scroll mode for this view. The result will be
21540     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21541     * (allow over-scrolling only if the view content is larger than the container),
21542     * or {@link #OVER_SCROLL_NEVER}.
21543     *
21544     * @return This view's over-scroll mode.
21545     */
21546    public int getOverScrollMode() {
21547        return mOverScrollMode;
21548    }
21549
21550    /**
21551     * Set the over-scroll mode for this view. Valid over-scroll modes are
21552     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21553     * (allow over-scrolling only if the view content is larger than the container),
21554     * or {@link #OVER_SCROLL_NEVER}.
21555     *
21556     * Setting the over-scroll mode of a view will have an effect only if the
21557     * view is capable of scrolling.
21558     *
21559     * @param overScrollMode The new over-scroll mode for this view.
21560     */
21561    public void setOverScrollMode(int overScrollMode) {
21562        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21563                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21564                overScrollMode != OVER_SCROLL_NEVER) {
21565            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21566        }
21567        mOverScrollMode = overScrollMode;
21568    }
21569
21570    /**
21571     * Enable or disable nested scrolling for this view.
21572     *
21573     * <p>If this property is set to true the view will be permitted to initiate nested
21574     * scrolling operations with a compatible parent view in the current hierarchy. If this
21575     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21576     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21577     * the nested scroll.</p>
21578     *
21579     * @param enabled true to enable nested scrolling, false to disable
21580     *
21581     * @see #isNestedScrollingEnabled()
21582     */
21583    public void setNestedScrollingEnabled(boolean enabled) {
21584        if (enabled) {
21585            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21586        } else {
21587            stopNestedScroll();
21588            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21589        }
21590    }
21591
21592    /**
21593     * Returns true if nested scrolling is enabled for this view.
21594     *
21595     * <p>If nested scrolling is enabled and this View class implementation supports it,
21596     * this view will act as a nested scrolling child view when applicable, forwarding data
21597     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21598     * parent.</p>
21599     *
21600     * @return true if nested scrolling is enabled
21601     *
21602     * @see #setNestedScrollingEnabled(boolean)
21603     */
21604    public boolean isNestedScrollingEnabled() {
21605        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21606                PFLAG3_NESTED_SCROLLING_ENABLED;
21607    }
21608
21609    /**
21610     * Begin a nestable scroll operation along the given axes.
21611     *
21612     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21613     *
21614     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21615     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21616     * In the case of touch scrolling the nested scroll will be terminated automatically in
21617     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21618     * In the event of programmatic scrolling the caller must explicitly call
21619     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21620     *
21621     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21622     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21623     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21624     *
21625     * <p>At each incremental step of the scroll the caller should invoke
21626     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21627     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21628     * parent at least partially consumed the scroll and the caller should adjust the amount it
21629     * scrolls by.</p>
21630     *
21631     * <p>After applying the remainder of the scroll delta the caller should invoke
21632     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21633     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21634     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21635     * </p>
21636     *
21637     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21638     *             {@link #SCROLL_AXIS_VERTICAL}.
21639     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21640     *         the current gesture.
21641     *
21642     * @see #stopNestedScroll()
21643     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21644     * @see #dispatchNestedScroll(int, int, int, int, int[])
21645     */
21646    public boolean startNestedScroll(int axes) {
21647        if (hasNestedScrollingParent()) {
21648            // Already in progress
21649            return true;
21650        }
21651        if (isNestedScrollingEnabled()) {
21652            ViewParent p = getParent();
21653            View child = this;
21654            while (p != null) {
21655                try {
21656                    if (p.onStartNestedScroll(child, this, axes)) {
21657                        mNestedScrollingParent = p;
21658                        p.onNestedScrollAccepted(child, this, axes);
21659                        return true;
21660                    }
21661                } catch (AbstractMethodError e) {
21662                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21663                            "method onStartNestedScroll", e);
21664                    // Allow the search upward to continue
21665                }
21666                if (p instanceof View) {
21667                    child = (View) p;
21668                }
21669                p = p.getParent();
21670            }
21671        }
21672        return false;
21673    }
21674
21675    /**
21676     * Stop a nested scroll in progress.
21677     *
21678     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21679     *
21680     * @see #startNestedScroll(int)
21681     */
21682    public void stopNestedScroll() {
21683        if (mNestedScrollingParent != null) {
21684            mNestedScrollingParent.onStopNestedScroll(this);
21685            mNestedScrollingParent = null;
21686        }
21687    }
21688
21689    /**
21690     * Returns true if this view has a nested scrolling parent.
21691     *
21692     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21693     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21694     *
21695     * @return whether this view has a nested scrolling parent
21696     */
21697    public boolean hasNestedScrollingParent() {
21698        return mNestedScrollingParent != null;
21699    }
21700
21701    /**
21702     * Dispatch one step of a nested scroll in progress.
21703     *
21704     * <p>Implementations of views that support nested scrolling should call this to report
21705     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21706     * is not currently in progress or nested scrolling is not
21707     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21708     *
21709     * <p>Compatible View implementations should also call
21710     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21711     * consuming a component of the scroll event themselves.</p>
21712     *
21713     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21714     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21715     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21716     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21717     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21718     *                       in local view coordinates of this view from before this operation
21719     *                       to after it completes. View implementations may use this to adjust
21720     *                       expected input coordinate tracking.
21721     * @return true if the event was dispatched, false if it could not be dispatched.
21722     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21723     */
21724    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21725            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21726        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21727            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21728                int startX = 0;
21729                int startY = 0;
21730                if (offsetInWindow != null) {
21731                    getLocationInWindow(offsetInWindow);
21732                    startX = offsetInWindow[0];
21733                    startY = offsetInWindow[1];
21734                }
21735
21736                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21737                        dxUnconsumed, dyUnconsumed);
21738
21739                if (offsetInWindow != null) {
21740                    getLocationInWindow(offsetInWindow);
21741                    offsetInWindow[0] -= startX;
21742                    offsetInWindow[1] -= startY;
21743                }
21744                return true;
21745            } else if (offsetInWindow != null) {
21746                // No motion, no dispatch. Keep offsetInWindow up to date.
21747                offsetInWindow[0] = 0;
21748                offsetInWindow[1] = 0;
21749            }
21750        }
21751        return false;
21752    }
21753
21754    /**
21755     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21756     *
21757     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21758     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21759     * scrolling operation to consume some or all of the scroll operation before the child view
21760     * consumes it.</p>
21761     *
21762     * @param dx Horizontal scroll distance in pixels
21763     * @param dy Vertical scroll distance in pixels
21764     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21765     *                 and consumed[1] the consumed dy.
21766     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21767     *                       in local view coordinates of this view from before this operation
21768     *                       to after it completes. View implementations may use this to adjust
21769     *                       expected input coordinate tracking.
21770     * @return true if the parent consumed some or all of the scroll delta
21771     * @see #dispatchNestedScroll(int, int, int, int, int[])
21772     */
21773    public boolean dispatchNestedPreScroll(int dx, int dy,
21774            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21775        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21776            if (dx != 0 || dy != 0) {
21777                int startX = 0;
21778                int startY = 0;
21779                if (offsetInWindow != null) {
21780                    getLocationInWindow(offsetInWindow);
21781                    startX = offsetInWindow[0];
21782                    startY = offsetInWindow[1];
21783                }
21784
21785                if (consumed == null) {
21786                    if (mTempNestedScrollConsumed == null) {
21787                        mTempNestedScrollConsumed = new int[2];
21788                    }
21789                    consumed = mTempNestedScrollConsumed;
21790                }
21791                consumed[0] = 0;
21792                consumed[1] = 0;
21793                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21794
21795                if (offsetInWindow != null) {
21796                    getLocationInWindow(offsetInWindow);
21797                    offsetInWindow[0] -= startX;
21798                    offsetInWindow[1] -= startY;
21799                }
21800                return consumed[0] != 0 || consumed[1] != 0;
21801            } else if (offsetInWindow != null) {
21802                offsetInWindow[0] = 0;
21803                offsetInWindow[1] = 0;
21804            }
21805        }
21806        return false;
21807    }
21808
21809    /**
21810     * Dispatch a fling to a nested scrolling parent.
21811     *
21812     * <p>This method should be used to indicate that a nested scrolling child has detected
21813     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21814     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21815     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21816     * along a scrollable axis.</p>
21817     *
21818     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21819     * its own content, it can use this method to delegate the fling to its nested scrolling
21820     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21821     *
21822     * @param velocityX Horizontal fling velocity in pixels per second
21823     * @param velocityY Vertical fling velocity in pixels per second
21824     * @param consumed true if the child consumed the fling, false otherwise
21825     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21826     */
21827    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21828        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21829            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21830        }
21831        return false;
21832    }
21833
21834    /**
21835     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21836     *
21837     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21838     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21839     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21840     * before the child view consumes it. If this method returns <code>true</code>, a nested
21841     * parent view consumed the fling and this view should not scroll as a result.</p>
21842     *
21843     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21844     * the fling at a time. If a parent view consumed the fling this method will return false.
21845     * Custom view implementations should account for this in two ways:</p>
21846     *
21847     * <ul>
21848     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21849     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21850     *     position regardless.</li>
21851     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21852     *     even to settle back to a valid idle position.</li>
21853     * </ul>
21854     *
21855     * <p>Views should also not offer fling velocities to nested parent views along an axis
21856     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21857     * should not offer a horizontal fling velocity to its parents since scrolling along that
21858     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21859     *
21860     * @param velocityX Horizontal fling velocity in pixels per second
21861     * @param velocityY Vertical fling velocity in pixels per second
21862     * @return true if a nested scrolling parent consumed the fling
21863     */
21864    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21865        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21866            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21867        }
21868        return false;
21869    }
21870
21871    /**
21872     * Gets a scale factor that determines the distance the view should scroll
21873     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21874     * @return The vertical scroll scale factor.
21875     * @hide
21876     */
21877    protected float getVerticalScrollFactor() {
21878        if (mVerticalScrollFactor == 0) {
21879            TypedValue outValue = new TypedValue();
21880            if (!mContext.getTheme().resolveAttribute(
21881                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21882                throw new IllegalStateException(
21883                        "Expected theme to define listPreferredItemHeight.");
21884            }
21885            mVerticalScrollFactor = outValue.getDimension(
21886                    mContext.getResources().getDisplayMetrics());
21887        }
21888        return mVerticalScrollFactor;
21889    }
21890
21891    /**
21892     * Gets a scale factor that determines the distance the view should scroll
21893     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21894     * @return The horizontal scroll scale factor.
21895     * @hide
21896     */
21897    protected float getHorizontalScrollFactor() {
21898        // TODO: Should use something else.
21899        return getVerticalScrollFactor();
21900    }
21901
21902    /**
21903     * Return the value specifying the text direction or policy that was set with
21904     * {@link #setTextDirection(int)}.
21905     *
21906     * @return the defined text direction. It can be one of:
21907     *
21908     * {@link #TEXT_DIRECTION_INHERIT},
21909     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21910     * {@link #TEXT_DIRECTION_ANY_RTL},
21911     * {@link #TEXT_DIRECTION_LTR},
21912     * {@link #TEXT_DIRECTION_RTL},
21913     * {@link #TEXT_DIRECTION_LOCALE},
21914     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21915     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21916     *
21917     * @attr ref android.R.styleable#View_textDirection
21918     *
21919     * @hide
21920     */
21921    @ViewDebug.ExportedProperty(category = "text", mapping = {
21922            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21923            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21924            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21925            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21926            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21927            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21928            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21929            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21930    })
21931    public int getRawTextDirection() {
21932        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21933    }
21934
21935    /**
21936     * Set the text direction.
21937     *
21938     * @param textDirection the direction to set. Should be one of:
21939     *
21940     * {@link #TEXT_DIRECTION_INHERIT},
21941     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21942     * {@link #TEXT_DIRECTION_ANY_RTL},
21943     * {@link #TEXT_DIRECTION_LTR},
21944     * {@link #TEXT_DIRECTION_RTL},
21945     * {@link #TEXT_DIRECTION_LOCALE}
21946     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21947     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21948     *
21949     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21950     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21951     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21952     *
21953     * @attr ref android.R.styleable#View_textDirection
21954     */
21955    public void setTextDirection(int textDirection) {
21956        if (getRawTextDirection() != textDirection) {
21957            // Reset the current text direction and the resolved one
21958            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21959            resetResolvedTextDirection();
21960            // Set the new text direction
21961            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21962            // Do resolution
21963            resolveTextDirection();
21964            // Notify change
21965            onRtlPropertiesChanged(getLayoutDirection());
21966            // Refresh
21967            requestLayout();
21968            invalidate(true);
21969        }
21970    }
21971
21972    /**
21973     * Return the resolved text direction.
21974     *
21975     * @return the resolved text direction. Returns one of:
21976     *
21977     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21978     * {@link #TEXT_DIRECTION_ANY_RTL},
21979     * {@link #TEXT_DIRECTION_LTR},
21980     * {@link #TEXT_DIRECTION_RTL},
21981     * {@link #TEXT_DIRECTION_LOCALE},
21982     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21983     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21984     *
21985     * @attr ref android.R.styleable#View_textDirection
21986     */
21987    @ViewDebug.ExportedProperty(category = "text", mapping = {
21988            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21989            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21990            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21991            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21992            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21993            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21994            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21995            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21996    })
21997    public int getTextDirection() {
21998        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21999    }
22000
22001    /**
22002     * Resolve the text direction.
22003     *
22004     * @return true if resolution has been done, false otherwise.
22005     *
22006     * @hide
22007     */
22008    public boolean resolveTextDirection() {
22009        // Reset any previous text direction resolution
22010        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22011
22012        if (hasRtlSupport()) {
22013            // Set resolved text direction flag depending on text direction flag
22014            final int textDirection = getRawTextDirection();
22015            switch(textDirection) {
22016                case TEXT_DIRECTION_INHERIT:
22017                    if (!canResolveTextDirection()) {
22018                        // We cannot do the resolution if there is no parent, so use the default one
22019                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22020                        // Resolution will need to happen again later
22021                        return false;
22022                    }
22023
22024                    // Parent has not yet resolved, so we still return the default
22025                    try {
22026                        if (!mParent.isTextDirectionResolved()) {
22027                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22028                            // Resolution will need to happen again later
22029                            return false;
22030                        }
22031                    } catch (AbstractMethodError e) {
22032                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22033                                " does not fully implement ViewParent", e);
22034                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22035                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22036                        return true;
22037                    }
22038
22039                    // Set current resolved direction to the same value as the parent's one
22040                    int parentResolvedDirection;
22041                    try {
22042                        parentResolvedDirection = mParent.getTextDirection();
22043                    } catch (AbstractMethodError e) {
22044                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22045                                " does not fully implement ViewParent", e);
22046                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22047                    }
22048                    switch (parentResolvedDirection) {
22049                        case TEXT_DIRECTION_FIRST_STRONG:
22050                        case TEXT_DIRECTION_ANY_RTL:
22051                        case TEXT_DIRECTION_LTR:
22052                        case TEXT_DIRECTION_RTL:
22053                        case TEXT_DIRECTION_LOCALE:
22054                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22055                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22056                            mPrivateFlags2 |=
22057                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22058                            break;
22059                        default:
22060                            // Default resolved direction is "first strong" heuristic
22061                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22062                    }
22063                    break;
22064                case TEXT_DIRECTION_FIRST_STRONG:
22065                case TEXT_DIRECTION_ANY_RTL:
22066                case TEXT_DIRECTION_LTR:
22067                case TEXT_DIRECTION_RTL:
22068                case TEXT_DIRECTION_LOCALE:
22069                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22070                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22071                    // Resolved direction is the same as text direction
22072                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22073                    break;
22074                default:
22075                    // Default resolved direction is "first strong" heuristic
22076                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22077            }
22078        } else {
22079            // Default resolved direction is "first strong" heuristic
22080            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22081        }
22082
22083        // Set to resolved
22084        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22085        return true;
22086    }
22087
22088    /**
22089     * Check if text direction resolution can be done.
22090     *
22091     * @return true if text direction resolution can be done otherwise return false.
22092     */
22093    public boolean canResolveTextDirection() {
22094        switch (getRawTextDirection()) {
22095            case TEXT_DIRECTION_INHERIT:
22096                if (mParent != null) {
22097                    try {
22098                        return mParent.canResolveTextDirection();
22099                    } catch (AbstractMethodError e) {
22100                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22101                                " does not fully implement ViewParent", e);
22102                    }
22103                }
22104                return false;
22105
22106            default:
22107                return true;
22108        }
22109    }
22110
22111    /**
22112     * Reset resolved text direction. Text direction will be resolved during a call to
22113     * {@link #onMeasure(int, int)}.
22114     *
22115     * @hide
22116     */
22117    public void resetResolvedTextDirection() {
22118        // Reset any previous text direction resolution
22119        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22120        // Set to default value
22121        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22122    }
22123
22124    /**
22125     * @return true if text direction is inherited.
22126     *
22127     * @hide
22128     */
22129    public boolean isTextDirectionInherited() {
22130        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22131    }
22132
22133    /**
22134     * @return true if text direction is resolved.
22135     */
22136    public boolean isTextDirectionResolved() {
22137        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22138    }
22139
22140    /**
22141     * Return the value specifying the text alignment or policy that was set with
22142     * {@link #setTextAlignment(int)}.
22143     *
22144     * @return the defined text alignment. It can be one of:
22145     *
22146     * {@link #TEXT_ALIGNMENT_INHERIT},
22147     * {@link #TEXT_ALIGNMENT_GRAVITY},
22148     * {@link #TEXT_ALIGNMENT_CENTER},
22149     * {@link #TEXT_ALIGNMENT_TEXT_START},
22150     * {@link #TEXT_ALIGNMENT_TEXT_END},
22151     * {@link #TEXT_ALIGNMENT_VIEW_START},
22152     * {@link #TEXT_ALIGNMENT_VIEW_END}
22153     *
22154     * @attr ref android.R.styleable#View_textAlignment
22155     *
22156     * @hide
22157     */
22158    @ViewDebug.ExportedProperty(category = "text", mapping = {
22159            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22160            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22161            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22162            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22163            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22164            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22165            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22166    })
22167    @TextAlignment
22168    public int getRawTextAlignment() {
22169        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22170    }
22171
22172    /**
22173     * Set the text alignment.
22174     *
22175     * @param textAlignment The text alignment to set. Should be one of
22176     *
22177     * {@link #TEXT_ALIGNMENT_INHERIT},
22178     * {@link #TEXT_ALIGNMENT_GRAVITY},
22179     * {@link #TEXT_ALIGNMENT_CENTER},
22180     * {@link #TEXT_ALIGNMENT_TEXT_START},
22181     * {@link #TEXT_ALIGNMENT_TEXT_END},
22182     * {@link #TEXT_ALIGNMENT_VIEW_START},
22183     * {@link #TEXT_ALIGNMENT_VIEW_END}
22184     *
22185     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22186     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22187     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22188     *
22189     * @attr ref android.R.styleable#View_textAlignment
22190     */
22191    public void setTextAlignment(@TextAlignment int textAlignment) {
22192        if (textAlignment != getRawTextAlignment()) {
22193            // Reset the current and resolved text alignment
22194            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22195            resetResolvedTextAlignment();
22196            // Set the new text alignment
22197            mPrivateFlags2 |=
22198                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22199            // Do resolution
22200            resolveTextAlignment();
22201            // Notify change
22202            onRtlPropertiesChanged(getLayoutDirection());
22203            // Refresh
22204            requestLayout();
22205            invalidate(true);
22206        }
22207    }
22208
22209    /**
22210     * Return the resolved text alignment.
22211     *
22212     * @return the resolved text alignment. Returns one of:
22213     *
22214     * {@link #TEXT_ALIGNMENT_GRAVITY},
22215     * {@link #TEXT_ALIGNMENT_CENTER},
22216     * {@link #TEXT_ALIGNMENT_TEXT_START},
22217     * {@link #TEXT_ALIGNMENT_TEXT_END},
22218     * {@link #TEXT_ALIGNMENT_VIEW_START},
22219     * {@link #TEXT_ALIGNMENT_VIEW_END}
22220     *
22221     * @attr ref android.R.styleable#View_textAlignment
22222     */
22223    @ViewDebug.ExportedProperty(category = "text", mapping = {
22224            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22225            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22226            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22227            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22228            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22229            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22230            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22231    })
22232    @TextAlignment
22233    public int getTextAlignment() {
22234        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22235                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22236    }
22237
22238    /**
22239     * Resolve the text alignment.
22240     *
22241     * @return true if resolution has been done, false otherwise.
22242     *
22243     * @hide
22244     */
22245    public boolean resolveTextAlignment() {
22246        // Reset any previous text alignment resolution
22247        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22248
22249        if (hasRtlSupport()) {
22250            // Set resolved text alignment flag depending on text alignment flag
22251            final int textAlignment = getRawTextAlignment();
22252            switch (textAlignment) {
22253                case TEXT_ALIGNMENT_INHERIT:
22254                    // Check if we can resolve the text alignment
22255                    if (!canResolveTextAlignment()) {
22256                        // We cannot do the resolution if there is no parent so use the default
22257                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22258                        // Resolution will need to happen again later
22259                        return false;
22260                    }
22261
22262                    // Parent has not yet resolved, so we still return the default
22263                    try {
22264                        if (!mParent.isTextAlignmentResolved()) {
22265                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22266                            // Resolution will need to happen again later
22267                            return false;
22268                        }
22269                    } catch (AbstractMethodError e) {
22270                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22271                                " does not fully implement ViewParent", e);
22272                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22273                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22274                        return true;
22275                    }
22276
22277                    int parentResolvedTextAlignment;
22278                    try {
22279                        parentResolvedTextAlignment = mParent.getTextAlignment();
22280                    } catch (AbstractMethodError e) {
22281                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22282                                " does not fully implement ViewParent", e);
22283                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22284                    }
22285                    switch (parentResolvedTextAlignment) {
22286                        case TEXT_ALIGNMENT_GRAVITY:
22287                        case TEXT_ALIGNMENT_TEXT_START:
22288                        case TEXT_ALIGNMENT_TEXT_END:
22289                        case TEXT_ALIGNMENT_CENTER:
22290                        case TEXT_ALIGNMENT_VIEW_START:
22291                        case TEXT_ALIGNMENT_VIEW_END:
22292                            // Resolved text alignment is the same as the parent resolved
22293                            // text alignment
22294                            mPrivateFlags2 |=
22295                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22296                            break;
22297                        default:
22298                            // Use default resolved text alignment
22299                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22300                    }
22301                    break;
22302                case TEXT_ALIGNMENT_GRAVITY:
22303                case TEXT_ALIGNMENT_TEXT_START:
22304                case TEXT_ALIGNMENT_TEXT_END:
22305                case TEXT_ALIGNMENT_CENTER:
22306                case TEXT_ALIGNMENT_VIEW_START:
22307                case TEXT_ALIGNMENT_VIEW_END:
22308                    // Resolved text alignment is the same as text alignment
22309                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22310                    break;
22311                default:
22312                    // Use default resolved text alignment
22313                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22314            }
22315        } else {
22316            // Use default resolved text alignment
22317            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22318        }
22319
22320        // Set the resolved
22321        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22322        return true;
22323    }
22324
22325    /**
22326     * Check if text alignment resolution can be done.
22327     *
22328     * @return true if text alignment resolution can be done otherwise return false.
22329     */
22330    public boolean canResolveTextAlignment() {
22331        switch (getRawTextAlignment()) {
22332            case TEXT_DIRECTION_INHERIT:
22333                if (mParent != null) {
22334                    try {
22335                        return mParent.canResolveTextAlignment();
22336                    } catch (AbstractMethodError e) {
22337                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22338                                " does not fully implement ViewParent", e);
22339                    }
22340                }
22341                return false;
22342
22343            default:
22344                return true;
22345        }
22346    }
22347
22348    /**
22349     * Reset resolved text alignment. Text alignment will be resolved during a call to
22350     * {@link #onMeasure(int, int)}.
22351     *
22352     * @hide
22353     */
22354    public void resetResolvedTextAlignment() {
22355        // Reset any previous text alignment resolution
22356        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22357        // Set to default
22358        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22359    }
22360
22361    /**
22362     * @return true if text alignment is inherited.
22363     *
22364     * @hide
22365     */
22366    public boolean isTextAlignmentInherited() {
22367        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22368    }
22369
22370    /**
22371     * @return true if text alignment is resolved.
22372     */
22373    public boolean isTextAlignmentResolved() {
22374        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22375    }
22376
22377    /**
22378     * Generate a value suitable for use in {@link #setId(int)}.
22379     * This value will not collide with ID values generated at build time by aapt for R.id.
22380     *
22381     * @return a generated ID value
22382     */
22383    public static int generateViewId() {
22384        for (;;) {
22385            final int result = sNextGeneratedId.get();
22386            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22387            int newValue = result + 1;
22388            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22389            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22390                return result;
22391            }
22392        }
22393    }
22394
22395    /**
22396     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22397     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22398     *                           a normal View or a ViewGroup with
22399     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22400     * @hide
22401     */
22402    public void captureTransitioningViews(List<View> transitioningViews) {
22403        if (getVisibility() == View.VISIBLE) {
22404            transitioningViews.add(this);
22405        }
22406    }
22407
22408    /**
22409     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22410     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22411     * @hide
22412     */
22413    public void findNamedViews(Map<String, View> namedElements) {
22414        if (getVisibility() == VISIBLE || mGhostView != null) {
22415            String transitionName = getTransitionName();
22416            if (transitionName != null) {
22417                namedElements.put(transitionName, this);
22418            }
22419        }
22420    }
22421
22422    /**
22423     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22424     * The default implementation does not care the location or event types, but some subclasses
22425     * may use it (such as WebViews).
22426     * @param event The MotionEvent from a mouse
22427     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22428     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22429     * @see PointerIcon
22430     */
22431    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22432        final float x = event.getX(pointerIndex);
22433        final float y = event.getY(pointerIndex);
22434        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22435            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22436        }
22437        return mPointerIcon;
22438    }
22439
22440    /**
22441     * Set the pointer icon for the current view.
22442     * Passing {@code null} will restore the pointer icon to its default value.
22443     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22444     */
22445    public void setPointerIcon(PointerIcon pointerIcon) {
22446        mPointerIcon = pointerIcon;
22447        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22448            return;
22449        }
22450        try {
22451            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22452        } catch (RemoteException e) {
22453        }
22454    }
22455
22456    /**
22457     * Gets the pointer icon for the current view.
22458     */
22459    public PointerIcon getPointerIcon() {
22460        return mPointerIcon;
22461    }
22462
22463    //
22464    // Properties
22465    //
22466    /**
22467     * A Property wrapper around the <code>alpha</code> functionality handled by the
22468     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22469     */
22470    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22471        @Override
22472        public void setValue(View object, float value) {
22473            object.setAlpha(value);
22474        }
22475
22476        @Override
22477        public Float get(View object) {
22478            return object.getAlpha();
22479        }
22480    };
22481
22482    /**
22483     * A Property wrapper around the <code>translationX</code> functionality handled by the
22484     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22485     */
22486    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22487        @Override
22488        public void setValue(View object, float value) {
22489            object.setTranslationX(value);
22490        }
22491
22492                @Override
22493        public Float get(View object) {
22494            return object.getTranslationX();
22495        }
22496    };
22497
22498    /**
22499     * A Property wrapper around the <code>translationY</code> functionality handled by the
22500     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22501     */
22502    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22503        @Override
22504        public void setValue(View object, float value) {
22505            object.setTranslationY(value);
22506        }
22507
22508        @Override
22509        public Float get(View object) {
22510            return object.getTranslationY();
22511        }
22512    };
22513
22514    /**
22515     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22516     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22517     */
22518    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22519        @Override
22520        public void setValue(View object, float value) {
22521            object.setTranslationZ(value);
22522        }
22523
22524        @Override
22525        public Float get(View object) {
22526            return object.getTranslationZ();
22527        }
22528    };
22529
22530    /**
22531     * A Property wrapper around the <code>x</code> functionality handled by the
22532     * {@link View#setX(float)} and {@link View#getX()} methods.
22533     */
22534    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22535        @Override
22536        public void setValue(View object, float value) {
22537            object.setX(value);
22538        }
22539
22540        @Override
22541        public Float get(View object) {
22542            return object.getX();
22543        }
22544    };
22545
22546    /**
22547     * A Property wrapper around the <code>y</code> functionality handled by the
22548     * {@link View#setY(float)} and {@link View#getY()} methods.
22549     */
22550    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22551        @Override
22552        public void setValue(View object, float value) {
22553            object.setY(value);
22554        }
22555
22556        @Override
22557        public Float get(View object) {
22558            return object.getY();
22559        }
22560    };
22561
22562    /**
22563     * A Property wrapper around the <code>z</code> functionality handled by the
22564     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22565     */
22566    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22567        @Override
22568        public void setValue(View object, float value) {
22569            object.setZ(value);
22570        }
22571
22572        @Override
22573        public Float get(View object) {
22574            return object.getZ();
22575        }
22576    };
22577
22578    /**
22579     * A Property wrapper around the <code>rotation</code> functionality handled by the
22580     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22581     */
22582    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22583        @Override
22584        public void setValue(View object, float value) {
22585            object.setRotation(value);
22586        }
22587
22588        @Override
22589        public Float get(View object) {
22590            return object.getRotation();
22591        }
22592    };
22593
22594    /**
22595     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22596     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22597     */
22598    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22599        @Override
22600        public void setValue(View object, float value) {
22601            object.setRotationX(value);
22602        }
22603
22604        @Override
22605        public Float get(View object) {
22606            return object.getRotationX();
22607        }
22608    };
22609
22610    /**
22611     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22612     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22613     */
22614    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22615        @Override
22616        public void setValue(View object, float value) {
22617            object.setRotationY(value);
22618        }
22619
22620        @Override
22621        public Float get(View object) {
22622            return object.getRotationY();
22623        }
22624    };
22625
22626    /**
22627     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22628     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22629     */
22630    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22631        @Override
22632        public void setValue(View object, float value) {
22633            object.setScaleX(value);
22634        }
22635
22636        @Override
22637        public Float get(View object) {
22638            return object.getScaleX();
22639        }
22640    };
22641
22642    /**
22643     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22644     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22645     */
22646    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22647        @Override
22648        public void setValue(View object, float value) {
22649            object.setScaleY(value);
22650        }
22651
22652        @Override
22653        public Float get(View object) {
22654            return object.getScaleY();
22655        }
22656    };
22657
22658    /**
22659     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22660     * Each MeasureSpec represents a requirement for either the width or the height.
22661     * A MeasureSpec is comprised of a size and a mode. There are three possible
22662     * modes:
22663     * <dl>
22664     * <dt>UNSPECIFIED</dt>
22665     * <dd>
22666     * The parent has not imposed any constraint on the child. It can be whatever size
22667     * it wants.
22668     * </dd>
22669     *
22670     * <dt>EXACTLY</dt>
22671     * <dd>
22672     * The parent has determined an exact size for the child. The child is going to be
22673     * given those bounds regardless of how big it wants to be.
22674     * </dd>
22675     *
22676     * <dt>AT_MOST</dt>
22677     * <dd>
22678     * The child can be as large as it wants up to the specified size.
22679     * </dd>
22680     * </dl>
22681     *
22682     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22683     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22684     */
22685    public static class MeasureSpec {
22686        private static final int MODE_SHIFT = 30;
22687        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22688
22689        /** @hide */
22690        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22691        @Retention(RetentionPolicy.SOURCE)
22692        public @interface MeasureSpecMode {}
22693
22694        /**
22695         * Measure specification mode: The parent has not imposed any constraint
22696         * on the child. It can be whatever size it wants.
22697         */
22698        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22699
22700        /**
22701         * Measure specification mode: The parent has determined an exact size
22702         * for the child. The child is going to be given those bounds regardless
22703         * of how big it wants to be.
22704         */
22705        public static final int EXACTLY     = 1 << MODE_SHIFT;
22706
22707        /**
22708         * Measure specification mode: The child can be as large as it wants up
22709         * to the specified size.
22710         */
22711        public static final int AT_MOST     = 2 << MODE_SHIFT;
22712
22713        /**
22714         * Creates a measure specification based on the supplied size and mode.
22715         *
22716         * The mode must always be one of the following:
22717         * <ul>
22718         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22719         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22720         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22721         * </ul>
22722         *
22723         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22724         * implementation was such that the order of arguments did not matter
22725         * and overflow in either value could impact the resulting MeasureSpec.
22726         * {@link android.widget.RelativeLayout} was affected by this bug.
22727         * Apps targeting API levels greater than 17 will get the fixed, more strict
22728         * behavior.</p>
22729         *
22730         * @param size the size of the measure specification
22731         * @param mode the mode of the measure specification
22732         * @return the measure specification based on size and mode
22733         */
22734        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22735                                          @MeasureSpecMode int mode) {
22736            if (sUseBrokenMakeMeasureSpec) {
22737                return size + mode;
22738            } else {
22739                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22740            }
22741        }
22742
22743        /**
22744         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22745         * will automatically get a size of 0. Older apps expect this.
22746         *
22747         * @hide internal use only for compatibility with system widgets and older apps
22748         */
22749        public static int makeSafeMeasureSpec(int size, int mode) {
22750            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22751                return 0;
22752            }
22753            return makeMeasureSpec(size, mode);
22754        }
22755
22756        /**
22757         * Extracts the mode from the supplied measure specification.
22758         *
22759         * @param measureSpec the measure specification to extract the mode from
22760         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22761         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22762         *         {@link android.view.View.MeasureSpec#EXACTLY}
22763         */
22764        @MeasureSpecMode
22765        public static int getMode(int measureSpec) {
22766            //noinspection ResourceType
22767            return (measureSpec & MODE_MASK);
22768        }
22769
22770        /**
22771         * Extracts the size from the supplied measure specification.
22772         *
22773         * @param measureSpec the measure specification to extract the size from
22774         * @return the size in pixels defined in the supplied measure specification
22775         */
22776        public static int getSize(int measureSpec) {
22777            return (measureSpec & ~MODE_MASK);
22778        }
22779
22780        static int adjust(int measureSpec, int delta) {
22781            final int mode = getMode(measureSpec);
22782            int size = getSize(measureSpec);
22783            if (mode == UNSPECIFIED) {
22784                // No need to adjust size for UNSPECIFIED mode.
22785                return makeMeasureSpec(size, UNSPECIFIED);
22786            }
22787            size += delta;
22788            if (size < 0) {
22789                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22790                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22791                size = 0;
22792            }
22793            return makeMeasureSpec(size, mode);
22794        }
22795
22796        /**
22797         * Returns a String representation of the specified measure
22798         * specification.
22799         *
22800         * @param measureSpec the measure specification to convert to a String
22801         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22802         */
22803        public static String toString(int measureSpec) {
22804            int mode = getMode(measureSpec);
22805            int size = getSize(measureSpec);
22806
22807            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22808
22809            if (mode == UNSPECIFIED)
22810                sb.append("UNSPECIFIED ");
22811            else if (mode == EXACTLY)
22812                sb.append("EXACTLY ");
22813            else if (mode == AT_MOST)
22814                sb.append("AT_MOST ");
22815            else
22816                sb.append(mode).append(" ");
22817
22818            sb.append(size);
22819            return sb.toString();
22820        }
22821    }
22822
22823    private final class CheckForLongPress implements Runnable {
22824        private int mOriginalWindowAttachCount;
22825        private float mX;
22826        private float mY;
22827        private boolean mOriginalPressedState;
22828
22829        @Override
22830        public void run() {
22831            if ((mOriginalPressedState == isPressed()) && (mParent != null)
22832                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22833                if (performLongClick(mX, mY)) {
22834                    mHasPerformedLongPress = true;
22835                }
22836            }
22837        }
22838
22839        public void setAnchor(float x, float y) {
22840            mX = x;
22841            mY = y;
22842        }
22843
22844        public void rememberWindowAttachCount() {
22845            mOriginalWindowAttachCount = mWindowAttachCount;
22846        }
22847
22848        public void rememberPressedState() {
22849            mOriginalPressedState = isPressed();
22850        }
22851    }
22852
22853    private final class CheckForTap implements Runnable {
22854        public float x;
22855        public float y;
22856
22857        @Override
22858        public void run() {
22859            mPrivateFlags &= ~PFLAG_PREPRESSED;
22860            setPressed(true, x, y);
22861            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22862        }
22863    }
22864
22865    private final class PerformClick implements Runnable {
22866        @Override
22867        public void run() {
22868            performClick();
22869        }
22870    }
22871
22872    /**
22873     * This method returns a ViewPropertyAnimator object, which can be used to animate
22874     * specific properties on this View.
22875     *
22876     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22877     */
22878    public ViewPropertyAnimator animate() {
22879        if (mAnimator == null) {
22880            mAnimator = new ViewPropertyAnimator(this);
22881        }
22882        return mAnimator;
22883    }
22884
22885    /**
22886     * Sets the name of the View to be used to identify Views in Transitions.
22887     * Names should be unique in the View hierarchy.
22888     *
22889     * @param transitionName The name of the View to uniquely identify it for Transitions.
22890     */
22891    public final void setTransitionName(String transitionName) {
22892        mTransitionName = transitionName;
22893    }
22894
22895    /**
22896     * Returns the name of the View to be used to identify Views in Transitions.
22897     * Names should be unique in the View hierarchy.
22898     *
22899     * <p>This returns null if the View has not been given a name.</p>
22900     *
22901     * @return The name used of the View to be used to identify Views in Transitions or null
22902     * if no name has been given.
22903     */
22904    @ViewDebug.ExportedProperty
22905    public String getTransitionName() {
22906        return mTransitionName;
22907    }
22908
22909    /**
22910     * @hide
22911     */
22912    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22913        // Do nothing.
22914    }
22915
22916    /**
22917     * Interface definition for a callback to be invoked when a hardware key event is
22918     * dispatched to this view. The callback will be invoked before the key event is
22919     * given to the view. This is only useful for hardware keyboards; a software input
22920     * method has no obligation to trigger this listener.
22921     */
22922    public interface OnKeyListener {
22923        /**
22924         * Called when a hardware key is dispatched to a view. This allows listeners to
22925         * get a chance to respond before the target view.
22926         * <p>Key presses in software keyboards will generally NOT trigger this method,
22927         * although some may elect to do so in some situations. Do not assume a
22928         * software input method has to be key-based; even if it is, it may use key presses
22929         * in a different way than you expect, so there is no way to reliably catch soft
22930         * input key presses.
22931         *
22932         * @param v The view the key has been dispatched to.
22933         * @param keyCode The code for the physical key that was pressed
22934         * @param event The KeyEvent object containing full information about
22935         *        the event.
22936         * @return True if the listener has consumed the event, false otherwise.
22937         */
22938        boolean onKey(View v, int keyCode, KeyEvent event);
22939    }
22940
22941    /**
22942     * Interface definition for a callback to be invoked when a touch event is
22943     * dispatched to this view. The callback will be invoked before the touch
22944     * event is given to the view.
22945     */
22946    public interface OnTouchListener {
22947        /**
22948         * Called when a touch event is dispatched to a view. This allows listeners to
22949         * get a chance to respond before the target view.
22950         *
22951         * @param v The view the touch event has been dispatched to.
22952         * @param event The MotionEvent object containing full information about
22953         *        the event.
22954         * @return True if the listener has consumed the event, false otherwise.
22955         */
22956        boolean onTouch(View v, MotionEvent event);
22957    }
22958
22959    /**
22960     * Interface definition for a callback to be invoked when a hover event is
22961     * dispatched to this view. The callback will be invoked before the hover
22962     * event is given to the view.
22963     */
22964    public interface OnHoverListener {
22965        /**
22966         * Called when a hover event is dispatched to a view. This allows listeners to
22967         * get a chance to respond before the target view.
22968         *
22969         * @param v The view the hover event has been dispatched to.
22970         * @param event The MotionEvent object containing full information about
22971         *        the event.
22972         * @return True if the listener has consumed the event, false otherwise.
22973         */
22974        boolean onHover(View v, MotionEvent event);
22975    }
22976
22977    /**
22978     * Interface definition for a callback to be invoked when a generic motion event is
22979     * dispatched to this view. The callback will be invoked before the generic motion
22980     * event is given to the view.
22981     */
22982    public interface OnGenericMotionListener {
22983        /**
22984         * Called when a generic motion event is dispatched to a view. This allows listeners to
22985         * get a chance to respond before the target view.
22986         *
22987         * @param v The view the generic motion event has been dispatched to.
22988         * @param event The MotionEvent object containing full information about
22989         *        the event.
22990         * @return True if the listener has consumed the event, false otherwise.
22991         */
22992        boolean onGenericMotion(View v, MotionEvent event);
22993    }
22994
22995    /**
22996     * Interface definition for a callback to be invoked when a view has been clicked and held.
22997     */
22998    public interface OnLongClickListener {
22999        /**
23000         * Called when a view has been clicked and held.
23001         *
23002         * @param v The view that was clicked and held.
23003         *
23004         * @return true if the callback consumed the long click, false otherwise.
23005         */
23006        boolean onLongClick(View v);
23007    }
23008
23009    /**
23010     * Interface definition for a callback to be invoked when a drag is being dispatched
23011     * to this view.  The callback will be invoked before the hosting view's own
23012     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23013     * onDrag(event) behavior, it should return 'false' from this callback.
23014     *
23015     * <div class="special reference">
23016     * <h3>Developer Guides</h3>
23017     * <p>For a guide to implementing drag and drop features, read the
23018     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23019     * </div>
23020     */
23021    public interface OnDragListener {
23022        /**
23023         * Called when a drag event is dispatched to a view. This allows listeners
23024         * to get a chance to override base View behavior.
23025         *
23026         * @param v The View that received the drag event.
23027         * @param event The {@link android.view.DragEvent} object for the drag event.
23028         * @return {@code true} if the drag event was handled successfully, or {@code false}
23029         * if the drag event was not handled. Note that {@code false} will trigger the View
23030         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23031         */
23032        boolean onDrag(View v, DragEvent event);
23033    }
23034
23035    /**
23036     * Interface definition for a callback to be invoked when the focus state of
23037     * a view changed.
23038     */
23039    public interface OnFocusChangeListener {
23040        /**
23041         * Called when the focus state of a view has changed.
23042         *
23043         * @param v The view whose state has changed.
23044         * @param hasFocus The new focus state of v.
23045         */
23046        void onFocusChange(View v, boolean hasFocus);
23047    }
23048
23049    /**
23050     * Interface definition for a callback to be invoked when a view is clicked.
23051     */
23052    public interface OnClickListener {
23053        /**
23054         * Called when a view has been clicked.
23055         *
23056         * @param v The view that was clicked.
23057         */
23058        void onClick(View v);
23059    }
23060
23061    /**
23062     * Interface definition for a callback to be invoked when a view is context clicked.
23063     */
23064    public interface OnContextClickListener {
23065        /**
23066         * Called when a view is context clicked.
23067         *
23068         * @param v The view that has been context clicked.
23069         * @return true if the callback consumed the context click, false otherwise.
23070         */
23071        boolean onContextClick(View v);
23072    }
23073
23074    /**
23075     * Interface definition for a callback to be invoked when the context menu
23076     * for this view is being built.
23077     */
23078    public interface OnCreateContextMenuListener {
23079        /**
23080         * Called when the context menu for this view is being built. It is not
23081         * safe to hold onto the menu after this method returns.
23082         *
23083         * @param menu The context menu that is being built
23084         * @param v The view for which the context menu is being built
23085         * @param menuInfo Extra information about the item for which the
23086         *            context menu should be shown. This information will vary
23087         *            depending on the class of v.
23088         */
23089        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23090    }
23091
23092    /**
23093     * Interface definition for a callback to be invoked when the status bar changes
23094     * visibility.  This reports <strong>global</strong> changes to the system UI
23095     * state, not what the application is requesting.
23096     *
23097     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23098     */
23099    public interface OnSystemUiVisibilityChangeListener {
23100        /**
23101         * Called when the status bar changes visibility because of a call to
23102         * {@link View#setSystemUiVisibility(int)}.
23103         *
23104         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23105         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23106         * This tells you the <strong>global</strong> state of these UI visibility
23107         * flags, not what your app is currently applying.
23108         */
23109        public void onSystemUiVisibilityChange(int visibility);
23110    }
23111
23112    /**
23113     * Interface definition for a callback to be invoked when this view is attached
23114     * or detached from its window.
23115     */
23116    public interface OnAttachStateChangeListener {
23117        /**
23118         * Called when the view is attached to a window.
23119         * @param v The view that was attached
23120         */
23121        public void onViewAttachedToWindow(View v);
23122        /**
23123         * Called when the view is detached from a window.
23124         * @param v The view that was detached
23125         */
23126        public void onViewDetachedFromWindow(View v);
23127    }
23128
23129    /**
23130     * Listener for applying window insets on a view in a custom way.
23131     *
23132     * <p>Apps may choose to implement this interface if they want to apply custom policy
23133     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23134     * is set, its
23135     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23136     * method will be called instead of the View's own
23137     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23138     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23139     * the View's normal behavior as part of its own.</p>
23140     */
23141    public interface OnApplyWindowInsetsListener {
23142        /**
23143         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23144         * on a View, this listener method will be called instead of the view's own
23145         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23146         *
23147         * @param v The view applying window insets
23148         * @param insets The insets to apply
23149         * @return The insets supplied, minus any insets that were consumed
23150         */
23151        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23152    }
23153
23154    private final class UnsetPressedState implements Runnable {
23155        @Override
23156        public void run() {
23157            setPressed(false);
23158        }
23159    }
23160
23161    /**
23162     * Base class for derived classes that want to save and restore their own
23163     * state in {@link android.view.View#onSaveInstanceState()}.
23164     */
23165    public static class BaseSavedState extends AbsSavedState {
23166        String mStartActivityRequestWhoSaved;
23167
23168        /**
23169         * Constructor used when reading from a parcel. Reads the state of the superclass.
23170         *
23171         * @param source parcel to read from
23172         */
23173        public BaseSavedState(Parcel source) {
23174            this(source, null);
23175        }
23176
23177        /**
23178         * Constructor used when reading from a parcel using a given class loader.
23179         * Reads the state of the superclass.
23180         *
23181         * @param source parcel to read from
23182         * @param loader ClassLoader to use for reading
23183         */
23184        public BaseSavedState(Parcel source, ClassLoader loader) {
23185            super(source, loader);
23186            mStartActivityRequestWhoSaved = source.readString();
23187        }
23188
23189        /**
23190         * Constructor called by derived classes when creating their SavedState objects
23191         *
23192         * @param superState The state of the superclass of this view
23193         */
23194        public BaseSavedState(Parcelable superState) {
23195            super(superState);
23196        }
23197
23198        @Override
23199        public void writeToParcel(Parcel out, int flags) {
23200            super.writeToParcel(out, flags);
23201            out.writeString(mStartActivityRequestWhoSaved);
23202        }
23203
23204        public static final Parcelable.Creator<BaseSavedState> CREATOR
23205                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23206            @Override
23207            public BaseSavedState createFromParcel(Parcel in) {
23208                return new BaseSavedState(in);
23209            }
23210
23211            @Override
23212            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23213                return new BaseSavedState(in, loader);
23214            }
23215
23216            @Override
23217            public BaseSavedState[] newArray(int size) {
23218                return new BaseSavedState[size];
23219            }
23220        };
23221    }
23222
23223    /**
23224     * A set of information given to a view when it is attached to its parent
23225     * window.
23226     */
23227    final static class AttachInfo {
23228        interface Callbacks {
23229            void playSoundEffect(int effectId);
23230            boolean performHapticFeedback(int effectId, boolean always);
23231        }
23232
23233        /**
23234         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23235         * to a Handler. This class contains the target (View) to invalidate and
23236         * the coordinates of the dirty rectangle.
23237         *
23238         * For performance purposes, this class also implements a pool of up to
23239         * POOL_LIMIT objects that get reused. This reduces memory allocations
23240         * whenever possible.
23241         */
23242        static class InvalidateInfo {
23243            private static final int POOL_LIMIT = 10;
23244
23245            private static final SynchronizedPool<InvalidateInfo> sPool =
23246                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23247
23248            View target;
23249
23250            int left;
23251            int top;
23252            int right;
23253            int bottom;
23254
23255            public static InvalidateInfo obtain() {
23256                InvalidateInfo instance = sPool.acquire();
23257                return (instance != null) ? instance : new InvalidateInfo();
23258            }
23259
23260            public void recycle() {
23261                target = null;
23262                sPool.release(this);
23263            }
23264        }
23265
23266        final IWindowSession mSession;
23267
23268        final IWindow mWindow;
23269
23270        final IBinder mWindowToken;
23271
23272        final Display mDisplay;
23273
23274        final Callbacks mRootCallbacks;
23275
23276        IWindowId mIWindowId;
23277        WindowId mWindowId;
23278
23279        /**
23280         * The top view of the hierarchy.
23281         */
23282        View mRootView;
23283
23284        IBinder mPanelParentWindowToken;
23285
23286        boolean mHardwareAccelerated;
23287        boolean mHardwareAccelerationRequested;
23288        ThreadedRenderer mThreadedRenderer;
23289        List<RenderNode> mPendingAnimatingRenderNodes;
23290
23291        /**
23292         * The state of the display to which the window is attached, as reported
23293         * by {@link Display#getState()}.  Note that the display state constants
23294         * declared by {@link Display} do not exactly line up with the screen state
23295         * constants declared by {@link View} (there are more display states than
23296         * screen states).
23297         */
23298        int mDisplayState = Display.STATE_UNKNOWN;
23299
23300        /**
23301         * Scale factor used by the compatibility mode
23302         */
23303        float mApplicationScale;
23304
23305        /**
23306         * Indicates whether the application is in compatibility mode
23307         */
23308        boolean mScalingRequired;
23309
23310        /**
23311         * Left position of this view's window
23312         */
23313        int mWindowLeft;
23314
23315        /**
23316         * Top position of this view's window
23317         */
23318        int mWindowTop;
23319
23320        /**
23321         * Indicates whether views need to use 32-bit drawing caches
23322         */
23323        boolean mUse32BitDrawingCache;
23324
23325        /**
23326         * For windows that are full-screen but using insets to layout inside
23327         * of the screen areas, these are the current insets to appear inside
23328         * the overscan area of the display.
23329         */
23330        final Rect mOverscanInsets = new Rect();
23331
23332        /**
23333         * For windows that are full-screen but using insets to layout inside
23334         * of the screen decorations, these are the current insets for the
23335         * content of the window.
23336         */
23337        final Rect mContentInsets = new Rect();
23338
23339        /**
23340         * For windows that are full-screen but using insets to layout inside
23341         * of the screen decorations, these are the current insets for the
23342         * actual visible parts of the window.
23343         */
23344        final Rect mVisibleInsets = new Rect();
23345
23346        /**
23347         * For windows that are full-screen but using insets to layout inside
23348         * of the screen decorations, these are the current insets for the
23349         * stable system windows.
23350         */
23351        final Rect mStableInsets = new Rect();
23352
23353        /**
23354         * For windows that include areas that are not covered by real surface these are the outsets
23355         * for real surface.
23356         */
23357        final Rect mOutsets = new Rect();
23358
23359        /**
23360         * In multi-window we force show the navigation bar. Because we don't want that the surface
23361         * size changes in this mode, we instead have a flag whether the navigation bar size should
23362         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23363         */
23364        boolean mAlwaysConsumeNavBar;
23365
23366        /**
23367         * The internal insets given by this window.  This value is
23368         * supplied by the client (through
23369         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23370         * be given to the window manager when changed to be used in laying
23371         * out windows behind it.
23372         */
23373        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23374                = new ViewTreeObserver.InternalInsetsInfo();
23375
23376        /**
23377         * Set to true when mGivenInternalInsets is non-empty.
23378         */
23379        boolean mHasNonEmptyGivenInternalInsets;
23380
23381        /**
23382         * All views in the window's hierarchy that serve as scroll containers,
23383         * used to determine if the window can be resized or must be panned
23384         * to adjust for a soft input area.
23385         */
23386        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23387
23388        final KeyEvent.DispatcherState mKeyDispatchState
23389                = new KeyEvent.DispatcherState();
23390
23391        /**
23392         * Indicates whether the view's window currently has the focus.
23393         */
23394        boolean mHasWindowFocus;
23395
23396        /**
23397         * The current visibility of the window.
23398         */
23399        int mWindowVisibility;
23400
23401        /**
23402         * Indicates the time at which drawing started to occur.
23403         */
23404        long mDrawingTime;
23405
23406        /**
23407         * Indicates whether or not ignoring the DIRTY_MASK flags.
23408         */
23409        boolean mIgnoreDirtyState;
23410
23411        /**
23412         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23413         * to avoid clearing that flag prematurely.
23414         */
23415        boolean mSetIgnoreDirtyState = false;
23416
23417        /**
23418         * Indicates whether the view's window is currently in touch mode.
23419         */
23420        boolean mInTouchMode;
23421
23422        /**
23423         * Indicates whether the view has requested unbuffered input dispatching for the current
23424         * event stream.
23425         */
23426        boolean mUnbufferedDispatchRequested;
23427
23428        /**
23429         * Indicates that ViewAncestor should trigger a global layout change
23430         * the next time it performs a traversal
23431         */
23432        boolean mRecomputeGlobalAttributes;
23433
23434        /**
23435         * Always report new attributes at next traversal.
23436         */
23437        boolean mForceReportNewAttributes;
23438
23439        /**
23440         * Set during a traveral if any views want to keep the screen on.
23441         */
23442        boolean mKeepScreenOn;
23443
23444        /**
23445         * Set during a traveral if the light center needs to be updated.
23446         */
23447        boolean mNeedsUpdateLightCenter;
23448
23449        /**
23450         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23451         */
23452        int mSystemUiVisibility;
23453
23454        /**
23455         * Hack to force certain system UI visibility flags to be cleared.
23456         */
23457        int mDisabledSystemUiVisibility;
23458
23459        /**
23460         * Last global system UI visibility reported by the window manager.
23461         */
23462        int mGlobalSystemUiVisibility = -1;
23463
23464        /**
23465         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23466         * attached.
23467         */
23468        boolean mHasSystemUiListeners;
23469
23470        /**
23471         * Set if the window has requested to extend into the overscan region
23472         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23473         */
23474        boolean mOverscanRequested;
23475
23476        /**
23477         * Set if the visibility of any views has changed.
23478         */
23479        boolean mViewVisibilityChanged;
23480
23481        /**
23482         * Set to true if a view has been scrolled.
23483         */
23484        boolean mViewScrollChanged;
23485
23486        /**
23487         * Set to true if high contrast mode enabled
23488         */
23489        boolean mHighContrastText;
23490
23491        /**
23492         * Set to true if a pointer event is currently being handled.
23493         */
23494        boolean mHandlingPointerEvent;
23495
23496        /**
23497         * Global to the view hierarchy used as a temporary for dealing with
23498         * x/y points in the transparent region computations.
23499         */
23500        final int[] mTransparentLocation = new int[2];
23501
23502        /**
23503         * Global to the view hierarchy used as a temporary for dealing with
23504         * x/y points in the ViewGroup.invalidateChild implementation.
23505         */
23506        final int[] mInvalidateChildLocation = new int[2];
23507
23508        /**
23509         * Global to the view hierarchy used as a temporary for dealing with
23510         * computing absolute on-screen location.
23511         */
23512        final int[] mTmpLocation = new int[2];
23513
23514        /**
23515         * Global to the view hierarchy used as a temporary for dealing with
23516         * x/y location when view is transformed.
23517         */
23518        final float[] mTmpTransformLocation = new float[2];
23519
23520        /**
23521         * The view tree observer used to dispatch global events like
23522         * layout, pre-draw, touch mode change, etc.
23523         */
23524        final ViewTreeObserver mTreeObserver;
23525
23526        /**
23527         * A Canvas used by the view hierarchy to perform bitmap caching.
23528         */
23529        Canvas mCanvas;
23530
23531        /**
23532         * The view root impl.
23533         */
23534        final ViewRootImpl mViewRootImpl;
23535
23536        /**
23537         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23538         * handler can be used to pump events in the UI events queue.
23539         */
23540        final Handler mHandler;
23541
23542        /**
23543         * Temporary for use in computing invalidate rectangles while
23544         * calling up the hierarchy.
23545         */
23546        final Rect mTmpInvalRect = new Rect();
23547
23548        /**
23549         * Temporary for use in computing hit areas with transformed views
23550         */
23551        final RectF mTmpTransformRect = new RectF();
23552
23553        /**
23554         * Temporary for use in computing hit areas with transformed views
23555         */
23556        final RectF mTmpTransformRect1 = new RectF();
23557
23558        /**
23559         * Temporary list of rectanges.
23560         */
23561        final List<RectF> mTmpRectList = new ArrayList<>();
23562
23563        /**
23564         * Temporary for use in transforming invalidation rect
23565         */
23566        final Matrix mTmpMatrix = new Matrix();
23567
23568        /**
23569         * Temporary for use in transforming invalidation rect
23570         */
23571        final Transformation mTmpTransformation = new Transformation();
23572
23573        /**
23574         * Temporary for use in querying outlines from OutlineProviders
23575         */
23576        final Outline mTmpOutline = new Outline();
23577
23578        /**
23579         * Temporary list for use in collecting focusable descendents of a view.
23580         */
23581        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23582
23583        /**
23584         * The id of the window for accessibility purposes.
23585         */
23586        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23587
23588        /**
23589         * Flags related to accessibility processing.
23590         *
23591         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23592         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23593         */
23594        int mAccessibilityFetchFlags;
23595
23596        /**
23597         * The drawable for highlighting accessibility focus.
23598         */
23599        Drawable mAccessibilityFocusDrawable;
23600
23601        /**
23602         * Show where the margins, bounds and layout bounds are for each view.
23603         */
23604        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23605
23606        /**
23607         * Point used to compute visible regions.
23608         */
23609        final Point mPoint = new Point();
23610
23611        /**
23612         * Used to track which View originated a requestLayout() call, used when
23613         * requestLayout() is called during layout.
23614         */
23615        View mViewRequestingLayout;
23616
23617        /**
23618         * Used to track views that need (at least) a partial relayout at their current size
23619         * during the next traversal.
23620         */
23621        List<View> mPartialLayoutViews = new ArrayList<>();
23622
23623        /**
23624         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23625         * modification. Lazily assigned during ViewRootImpl layout.
23626         */
23627        List<View> mEmptyPartialLayoutViews;
23628
23629        /**
23630         * Used to track the identity of the current drag operation.
23631         */
23632        IBinder mDragToken;
23633
23634        /**
23635         * The drag shadow surface for the current drag operation.
23636         */
23637        public Surface mDragSurface;
23638
23639
23640        /**
23641         * The view that currently has a tooltip displayed.
23642         */
23643        View mTooltipHost;
23644
23645        /**
23646         * Creates a new set of attachment information with the specified
23647         * events handler and thread.
23648         *
23649         * @param handler the events handler the view must use
23650         */
23651        AttachInfo(IWindowSession session, IWindow window, Display display,
23652                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
23653                Context context) {
23654            mSession = session;
23655            mWindow = window;
23656            mWindowToken = window.asBinder();
23657            mDisplay = display;
23658            mViewRootImpl = viewRootImpl;
23659            mHandler = handler;
23660            mRootCallbacks = effectPlayer;
23661            mTreeObserver = new ViewTreeObserver(context);
23662        }
23663    }
23664
23665    /**
23666     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23667     * is supported. This avoids keeping too many unused fields in most
23668     * instances of View.</p>
23669     */
23670    private static class ScrollabilityCache implements Runnable {
23671
23672        /**
23673         * Scrollbars are not visible
23674         */
23675        public static final int OFF = 0;
23676
23677        /**
23678         * Scrollbars are visible
23679         */
23680        public static final int ON = 1;
23681
23682        /**
23683         * Scrollbars are fading away
23684         */
23685        public static final int FADING = 2;
23686
23687        public boolean fadeScrollBars;
23688
23689        public int fadingEdgeLength;
23690        public int scrollBarDefaultDelayBeforeFade;
23691        public int scrollBarFadeDuration;
23692
23693        public int scrollBarSize;
23694        public ScrollBarDrawable scrollBar;
23695        public float[] interpolatorValues;
23696        public View host;
23697
23698        public final Paint paint;
23699        public final Matrix matrix;
23700        public Shader shader;
23701
23702        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23703
23704        private static final float[] OPAQUE = { 255 };
23705        private static final float[] TRANSPARENT = { 0.0f };
23706
23707        /**
23708         * When fading should start. This time moves into the future every time
23709         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23710         */
23711        public long fadeStartTime;
23712
23713
23714        /**
23715         * The current state of the scrollbars: ON, OFF, or FADING
23716         */
23717        public int state = OFF;
23718
23719        private int mLastColor;
23720
23721        public final Rect mScrollBarBounds = new Rect();
23722
23723        public static final int NOT_DRAGGING = 0;
23724        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23725        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23726        public int mScrollBarDraggingState = NOT_DRAGGING;
23727
23728        public float mScrollBarDraggingPos = 0;
23729
23730        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23731            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23732            scrollBarSize = configuration.getScaledScrollBarSize();
23733            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23734            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23735
23736            paint = new Paint();
23737            matrix = new Matrix();
23738            // use use a height of 1, and then wack the matrix each time we
23739            // actually use it.
23740            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23741            paint.setShader(shader);
23742            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23743
23744            this.host = host;
23745        }
23746
23747        public void setFadeColor(int color) {
23748            if (color != mLastColor) {
23749                mLastColor = color;
23750
23751                if (color != 0) {
23752                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23753                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23754                    paint.setShader(shader);
23755                    // Restore the default transfer mode (src_over)
23756                    paint.setXfermode(null);
23757                } else {
23758                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23759                    paint.setShader(shader);
23760                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23761                }
23762            }
23763        }
23764
23765        public void run() {
23766            long now = AnimationUtils.currentAnimationTimeMillis();
23767            if (now >= fadeStartTime) {
23768
23769                // the animation fades the scrollbars out by changing
23770                // the opacity (alpha) from fully opaque to fully
23771                // transparent
23772                int nextFrame = (int) now;
23773                int framesCount = 0;
23774
23775                Interpolator interpolator = scrollBarInterpolator;
23776
23777                // Start opaque
23778                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23779
23780                // End transparent
23781                nextFrame += scrollBarFadeDuration;
23782                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23783
23784                state = FADING;
23785
23786                // Kick off the fade animation
23787                host.invalidate(true);
23788            }
23789        }
23790    }
23791
23792    /**
23793     * Resuable callback for sending
23794     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23795     */
23796    private class SendViewScrolledAccessibilityEvent implements Runnable {
23797        public volatile boolean mIsPending;
23798
23799        public void run() {
23800            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23801            mIsPending = false;
23802        }
23803    }
23804
23805    /**
23806     * <p>
23807     * This class represents a delegate that can be registered in a {@link View}
23808     * to enhance accessibility support via composition rather via inheritance.
23809     * It is specifically targeted to widget developers that extend basic View
23810     * classes i.e. classes in package android.view, that would like their
23811     * applications to be backwards compatible.
23812     * </p>
23813     * <div class="special reference">
23814     * <h3>Developer Guides</h3>
23815     * <p>For more information about making applications accessible, read the
23816     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23817     * developer guide.</p>
23818     * </div>
23819     * <p>
23820     * A scenario in which a developer would like to use an accessibility delegate
23821     * is overriding a method introduced in a later API version than the minimal API
23822     * version supported by the application. For example, the method
23823     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23824     * in API version 4 when the accessibility APIs were first introduced. If a
23825     * developer would like his application to run on API version 4 devices (assuming
23826     * all other APIs used by the application are version 4 or lower) and take advantage
23827     * of this method, instead of overriding the method which would break the application's
23828     * backwards compatibility, he can override the corresponding method in this
23829     * delegate and register the delegate in the target View if the API version of
23830     * the system is high enough, i.e. the API version is the same as or higher than the API
23831     * version that introduced
23832     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23833     * </p>
23834     * <p>
23835     * Here is an example implementation:
23836     * </p>
23837     * <code><pre><p>
23838     * if (Build.VERSION.SDK_INT >= 14) {
23839     *     // If the API version is equal of higher than the version in
23840     *     // which onInitializeAccessibilityNodeInfo was introduced we
23841     *     // register a delegate with a customized implementation.
23842     *     View view = findViewById(R.id.view_id);
23843     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23844     *         public void onInitializeAccessibilityNodeInfo(View host,
23845     *                 AccessibilityNodeInfo info) {
23846     *             // Let the default implementation populate the info.
23847     *             super.onInitializeAccessibilityNodeInfo(host, info);
23848     *             // Set some other information.
23849     *             info.setEnabled(host.isEnabled());
23850     *         }
23851     *     });
23852     * }
23853     * </code></pre></p>
23854     * <p>
23855     * This delegate contains methods that correspond to the accessibility methods
23856     * in View. If a delegate has been specified the implementation in View hands
23857     * off handling to the corresponding method in this delegate. The default
23858     * implementation the delegate methods behaves exactly as the corresponding
23859     * method in View for the case of no accessibility delegate been set. Hence,
23860     * to customize the behavior of a View method, clients can override only the
23861     * corresponding delegate method without altering the behavior of the rest
23862     * accessibility related methods of the host view.
23863     * </p>
23864     * <p>
23865     * <strong>Note:</strong> On platform versions prior to
23866     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23867     * views in the {@code android.widget.*} package are called <i>before</i>
23868     * host methods. This prevents certain properties such as class name from
23869     * being modified by overriding
23870     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23871     * as any changes will be overwritten by the host class.
23872     * <p>
23873     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23874     * methods are called <i>after</i> host methods, which all properties to be
23875     * modified without being overwritten by the host class.
23876     */
23877    public static class AccessibilityDelegate {
23878
23879        /**
23880         * Sends an accessibility event of the given type. If accessibility is not
23881         * enabled this method has no effect.
23882         * <p>
23883         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23884         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23885         * been set.
23886         * </p>
23887         *
23888         * @param host The View hosting the delegate.
23889         * @param eventType The type of the event to send.
23890         *
23891         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23892         */
23893        public void sendAccessibilityEvent(View host, int eventType) {
23894            host.sendAccessibilityEventInternal(eventType);
23895        }
23896
23897        /**
23898         * Performs the specified accessibility action on the view. For
23899         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23900         * <p>
23901         * The default implementation behaves as
23902         * {@link View#performAccessibilityAction(int, Bundle)
23903         *  View#performAccessibilityAction(int, Bundle)} for the case of
23904         *  no accessibility delegate been set.
23905         * </p>
23906         *
23907         * @param action The action to perform.
23908         * @return Whether the action was performed.
23909         *
23910         * @see View#performAccessibilityAction(int, Bundle)
23911         *      View#performAccessibilityAction(int, Bundle)
23912         */
23913        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23914            return host.performAccessibilityActionInternal(action, args);
23915        }
23916
23917        /**
23918         * Sends an accessibility event. This method behaves exactly as
23919         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23920         * empty {@link AccessibilityEvent} and does not perform a check whether
23921         * accessibility is enabled.
23922         * <p>
23923         * The default implementation behaves as
23924         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23925         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23926         * the case of no accessibility delegate been set.
23927         * </p>
23928         *
23929         * @param host The View hosting the delegate.
23930         * @param event The event to send.
23931         *
23932         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23933         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23934         */
23935        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23936            host.sendAccessibilityEventUncheckedInternal(event);
23937        }
23938
23939        /**
23940         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23941         * to its children for adding their text content to the event.
23942         * <p>
23943         * The default implementation behaves as
23944         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23945         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23946         * the case of no accessibility delegate been set.
23947         * </p>
23948         *
23949         * @param host The View hosting the delegate.
23950         * @param event The event.
23951         * @return True if the event population was completed.
23952         *
23953         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23954         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23955         */
23956        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23957            return host.dispatchPopulateAccessibilityEventInternal(event);
23958        }
23959
23960        /**
23961         * Gives a chance to the host View to populate the accessibility event with its
23962         * text content.
23963         * <p>
23964         * The default implementation behaves as
23965         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23966         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23967         * the case of no accessibility delegate been set.
23968         * </p>
23969         *
23970         * @param host The View hosting the delegate.
23971         * @param event The accessibility event which to populate.
23972         *
23973         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23974         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23975         */
23976        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23977            host.onPopulateAccessibilityEventInternal(event);
23978        }
23979
23980        /**
23981         * Initializes an {@link AccessibilityEvent} with information about the
23982         * the host View which is the event source.
23983         * <p>
23984         * The default implementation behaves as
23985         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23986         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23987         * the case of no accessibility delegate been set.
23988         * </p>
23989         *
23990         * @param host The View hosting the delegate.
23991         * @param event The event to initialize.
23992         *
23993         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23994         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23995         */
23996        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23997            host.onInitializeAccessibilityEventInternal(event);
23998        }
23999
24000        /**
24001         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24002         * <p>
24003         * The default implementation behaves as
24004         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24005         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24006         * the case of no accessibility delegate been set.
24007         * </p>
24008         *
24009         * @param host The View hosting the delegate.
24010         * @param info The instance to initialize.
24011         *
24012         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24013         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24014         */
24015        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24016            host.onInitializeAccessibilityNodeInfoInternal(info);
24017        }
24018
24019        /**
24020         * Called when a child of the host View has requested sending an
24021         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24022         * to augment the event.
24023         * <p>
24024         * The default implementation behaves as
24025         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24026         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24027         * the case of no accessibility delegate been set.
24028         * </p>
24029         *
24030         * @param host The View hosting the delegate.
24031         * @param child The child which requests sending the event.
24032         * @param event The event to be sent.
24033         * @return True if the event should be sent
24034         *
24035         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24036         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24037         */
24038        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24039                AccessibilityEvent event) {
24040            return host.onRequestSendAccessibilityEventInternal(child, event);
24041        }
24042
24043        /**
24044         * Gets the provider for managing a virtual view hierarchy rooted at this View
24045         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24046         * that explore the window content.
24047         * <p>
24048         * The default implementation behaves as
24049         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24050         * the case of no accessibility delegate been set.
24051         * </p>
24052         *
24053         * @return The provider.
24054         *
24055         * @see AccessibilityNodeProvider
24056         */
24057        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24058            return null;
24059        }
24060
24061        /**
24062         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24063         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24064         * This method is responsible for obtaining an accessibility node info from a
24065         * pool of reusable instances and calling
24066         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24067         * view to initialize the former.
24068         * <p>
24069         * <strong>Note:</strong> The client is responsible for recycling the obtained
24070         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24071         * creation.
24072         * </p>
24073         * <p>
24074         * The default implementation behaves as
24075         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24076         * the case of no accessibility delegate been set.
24077         * </p>
24078         * @return A populated {@link AccessibilityNodeInfo}.
24079         *
24080         * @see AccessibilityNodeInfo
24081         *
24082         * @hide
24083         */
24084        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24085            return host.createAccessibilityNodeInfoInternal();
24086        }
24087    }
24088
24089    private class MatchIdPredicate implements Predicate<View> {
24090        public int mId;
24091
24092        @Override
24093        public boolean apply(View view) {
24094            return (view.mID == mId);
24095        }
24096    }
24097
24098    private class MatchLabelForPredicate implements Predicate<View> {
24099        private int mLabeledId;
24100
24101        @Override
24102        public boolean apply(View view) {
24103            return (view.mLabelForId == mLabeledId);
24104        }
24105    }
24106
24107    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24108        private int mChangeTypes = 0;
24109        private boolean mPosted;
24110        private boolean mPostedWithDelay;
24111        private long mLastEventTimeMillis;
24112
24113        @Override
24114        public void run() {
24115            mPosted = false;
24116            mPostedWithDelay = false;
24117            mLastEventTimeMillis = SystemClock.uptimeMillis();
24118            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24119                final AccessibilityEvent event = AccessibilityEvent.obtain();
24120                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24121                event.setContentChangeTypes(mChangeTypes);
24122                sendAccessibilityEventUnchecked(event);
24123            }
24124            mChangeTypes = 0;
24125        }
24126
24127        public void runOrPost(int changeType) {
24128            mChangeTypes |= changeType;
24129
24130            // If this is a live region or the child of a live region, collect
24131            // all events from this frame and send them on the next frame.
24132            if (inLiveRegion()) {
24133                // If we're already posted with a delay, remove that.
24134                if (mPostedWithDelay) {
24135                    removeCallbacks(this);
24136                    mPostedWithDelay = false;
24137                }
24138                // Only post if we're not already posted.
24139                if (!mPosted) {
24140                    post(this);
24141                    mPosted = true;
24142                }
24143                return;
24144            }
24145
24146            if (mPosted) {
24147                return;
24148            }
24149
24150            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24151            final long minEventIntevalMillis =
24152                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24153            if (timeSinceLastMillis >= minEventIntevalMillis) {
24154                removeCallbacks(this);
24155                run();
24156            } else {
24157                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24158                mPostedWithDelay = true;
24159            }
24160        }
24161    }
24162
24163    private boolean inLiveRegion() {
24164        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24165            return true;
24166        }
24167
24168        ViewParent parent = getParent();
24169        while (parent instanceof View) {
24170            if (((View) parent).getAccessibilityLiveRegion()
24171                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24172                return true;
24173            }
24174            parent = parent.getParent();
24175        }
24176
24177        return false;
24178    }
24179
24180    /**
24181     * Dump all private flags in readable format, useful for documentation and
24182     * sanity checking.
24183     */
24184    private static void dumpFlags() {
24185        final HashMap<String, String> found = Maps.newHashMap();
24186        try {
24187            for (Field field : View.class.getDeclaredFields()) {
24188                final int modifiers = field.getModifiers();
24189                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24190                    if (field.getType().equals(int.class)) {
24191                        final int value = field.getInt(null);
24192                        dumpFlag(found, field.getName(), value);
24193                    } else if (field.getType().equals(int[].class)) {
24194                        final int[] values = (int[]) field.get(null);
24195                        for (int i = 0; i < values.length; i++) {
24196                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24197                        }
24198                    }
24199                }
24200            }
24201        } catch (IllegalAccessException e) {
24202            throw new RuntimeException(e);
24203        }
24204
24205        final ArrayList<String> keys = Lists.newArrayList();
24206        keys.addAll(found.keySet());
24207        Collections.sort(keys);
24208        for (String key : keys) {
24209            Log.d(VIEW_LOG_TAG, found.get(key));
24210        }
24211    }
24212
24213    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24214        // Sort flags by prefix, then by bits, always keeping unique keys
24215        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24216        final int prefix = name.indexOf('_');
24217        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24218        final String output = bits + " " + name;
24219        found.put(key, output);
24220    }
24221
24222    /** {@hide} */
24223    public void encode(@NonNull ViewHierarchyEncoder stream) {
24224        stream.beginObject(this);
24225        encodeProperties(stream);
24226        stream.endObject();
24227    }
24228
24229    /** {@hide} */
24230    @CallSuper
24231    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24232        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24233        if (resolveId instanceof String) {
24234            stream.addProperty("id", (String) resolveId);
24235        } else {
24236            stream.addProperty("id", mID);
24237        }
24238
24239        stream.addProperty("misc:transformation.alpha",
24240                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24241        stream.addProperty("misc:transitionName", getTransitionName());
24242
24243        // layout
24244        stream.addProperty("layout:left", mLeft);
24245        stream.addProperty("layout:right", mRight);
24246        stream.addProperty("layout:top", mTop);
24247        stream.addProperty("layout:bottom", mBottom);
24248        stream.addProperty("layout:width", getWidth());
24249        stream.addProperty("layout:height", getHeight());
24250        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24251        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24252        stream.addProperty("layout:hasTransientState", hasTransientState());
24253        stream.addProperty("layout:baseline", getBaseline());
24254
24255        // layout params
24256        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24257        if (layoutParams != null) {
24258            stream.addPropertyKey("layoutParams");
24259            layoutParams.encode(stream);
24260        }
24261
24262        // scrolling
24263        stream.addProperty("scrolling:scrollX", mScrollX);
24264        stream.addProperty("scrolling:scrollY", mScrollY);
24265
24266        // padding
24267        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24268        stream.addProperty("padding:paddingRight", mPaddingRight);
24269        stream.addProperty("padding:paddingTop", mPaddingTop);
24270        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24271        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24272        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24273        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24274        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24275        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24276
24277        // measurement
24278        stream.addProperty("measurement:minHeight", mMinHeight);
24279        stream.addProperty("measurement:minWidth", mMinWidth);
24280        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24281        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24282
24283        // drawing
24284        stream.addProperty("drawing:elevation", getElevation());
24285        stream.addProperty("drawing:translationX", getTranslationX());
24286        stream.addProperty("drawing:translationY", getTranslationY());
24287        stream.addProperty("drawing:translationZ", getTranslationZ());
24288        stream.addProperty("drawing:rotation", getRotation());
24289        stream.addProperty("drawing:rotationX", getRotationX());
24290        stream.addProperty("drawing:rotationY", getRotationY());
24291        stream.addProperty("drawing:scaleX", getScaleX());
24292        stream.addProperty("drawing:scaleY", getScaleY());
24293        stream.addProperty("drawing:pivotX", getPivotX());
24294        stream.addProperty("drawing:pivotY", getPivotY());
24295        stream.addProperty("drawing:opaque", isOpaque());
24296        stream.addProperty("drawing:alpha", getAlpha());
24297        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24298        stream.addProperty("drawing:shadow", hasShadow());
24299        stream.addProperty("drawing:solidColor", getSolidColor());
24300        stream.addProperty("drawing:layerType", mLayerType);
24301        stream.addProperty("drawing:willNotDraw", willNotDraw());
24302        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24303        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24304        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24305        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24306
24307        // focus
24308        stream.addProperty("focus:hasFocus", hasFocus());
24309        stream.addProperty("focus:isFocused", isFocused());
24310        stream.addProperty("focus:isFocusable", isFocusable());
24311        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24312
24313        stream.addProperty("misc:clickable", isClickable());
24314        stream.addProperty("misc:pressed", isPressed());
24315        stream.addProperty("misc:selected", isSelected());
24316        stream.addProperty("misc:touchMode", isInTouchMode());
24317        stream.addProperty("misc:hovered", isHovered());
24318        stream.addProperty("misc:activated", isActivated());
24319
24320        stream.addProperty("misc:visibility", getVisibility());
24321        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24322        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24323
24324        stream.addProperty("misc:enabled", isEnabled());
24325        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24326        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24327
24328        // theme attributes
24329        Resources.Theme theme = getContext().getTheme();
24330        if (theme != null) {
24331            stream.addPropertyKey("theme");
24332            theme.encode(stream);
24333        }
24334
24335        // view attribute information
24336        int n = mAttributes != null ? mAttributes.length : 0;
24337        stream.addProperty("meta:__attrCount__", n/2);
24338        for (int i = 0; i < n; i += 2) {
24339            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24340        }
24341
24342        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24343
24344        // text
24345        stream.addProperty("text:textDirection", getTextDirection());
24346        stream.addProperty("text:textAlignment", getTextAlignment());
24347
24348        // accessibility
24349        CharSequence contentDescription = getContentDescription();
24350        stream.addProperty("accessibility:contentDescription",
24351                contentDescription == null ? "" : contentDescription.toString());
24352        stream.addProperty("accessibility:labelFor", getLabelFor());
24353        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24354    }
24355
24356    /**
24357     * Determine if this view is rendered on a round wearable device and is the main view
24358     * on the screen.
24359     */
24360    private boolean shouldDrawRoundScrollbar() {
24361        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24362            return false;
24363        }
24364
24365        final View rootView = getRootView();
24366        final WindowInsets insets = getRootWindowInsets();
24367
24368        int height = getHeight();
24369        int width = getWidth();
24370        int displayHeight = rootView.getHeight();
24371        int displayWidth = rootView.getWidth();
24372
24373        if (height != displayHeight || width != displayWidth) {
24374            return false;
24375        }
24376
24377        getLocationOnScreen(mAttachInfo.mTmpLocation);
24378        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24379                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24380    }
24381
24382    /**
24383     * Sets the tooltip text which will be displayed in a small popup next to the view.
24384     * <p>
24385     * The tooltip will be displayed:
24386     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24387     * menu). </li>
24388     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24389     *
24390     * @param tooltip the tooltip text, or null if no tooltip is required
24391     */
24392    public final void setTooltip(@Nullable CharSequence tooltip) {
24393        if (TextUtils.isEmpty(tooltip)) {
24394            setFlags(0, TOOLTIP);
24395            hideTooltip();
24396            mTooltipInfo = null;
24397        } else {
24398            setFlags(TOOLTIP, TOOLTIP);
24399            if (mTooltipInfo == null) {
24400                mTooltipInfo = new TooltipInfo();
24401                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24402                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24403            }
24404            mTooltipInfo.mTooltip = tooltip;
24405            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24406                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltip);
24407            }
24408        }
24409    }
24410
24411    /**
24412     * Returns the view's tooltip text.
24413     *
24414     * @return the tooltip text
24415     */
24416    @Nullable
24417    public final CharSequence getTooltip() {
24418        return mTooltipInfo != null ? mTooltipInfo.mTooltip : null;
24419    }
24420
24421    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24422        if (mAttachInfo == null) {
24423            return false;
24424        }
24425        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24426            return false;
24427        }
24428        final CharSequence tooltipText = getTooltip();
24429        if (TextUtils.isEmpty(tooltipText)) {
24430            return false;
24431        }
24432        hideTooltip();
24433        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24434        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24435        mTooltipInfo.mTooltipPopup.show(this, x, y, tooltipText);
24436        mAttachInfo.mTooltipHost = this;
24437        return true;
24438    }
24439
24440    void hideTooltip() {
24441        if (mTooltipInfo == null) {
24442            return;
24443        }
24444        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24445        if (mTooltipInfo.mTooltipPopup == null) {
24446            return;
24447        }
24448        mTooltipInfo.mTooltipPopup.hide();
24449        mTooltipInfo.mTooltipPopup = null;
24450        mTooltipInfo.mTooltipFromLongClick = false;
24451        if (mAttachInfo != null) {
24452            mAttachInfo.mTooltipHost = null;
24453        }
24454    }
24455
24456    private boolean showLongClickTooltip(int x, int y) {
24457        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24458        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24459        return showTooltip(x, y, true);
24460    }
24461
24462    private void showHoverTooltip() {
24463        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24464    }
24465
24466    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24467        if (mTooltipInfo == null) {
24468            return false;
24469        }
24470        switch(event.getAction()) {
24471            case MotionEvent.ACTION_HOVER_MOVE:
24472                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24473                    break;
24474                }
24475                if (!mTooltipInfo.mTooltipFromLongClick) {
24476                    if (mTooltipInfo.mTooltipPopup == null) {
24477                        // Schedule showing the tooltip after a timeout.
24478                        mTooltipInfo.mAnchorX = (int) event.getX();
24479                        mTooltipInfo.mAnchorY = (int) event.getY();
24480                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24481                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24482                                ViewConfiguration.getHoverTooltipShowTimeout());
24483                    }
24484
24485                    // Hide hover-triggered tooltip after a period of inactivity.
24486                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24487                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24488                    final int timeout;
24489                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24490                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24491                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24492                    } else {
24493                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24494                    }
24495                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24496                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24497                }
24498                return true;
24499
24500            case MotionEvent.ACTION_HOVER_EXIT:
24501                if (!mTooltipInfo.mTooltipFromLongClick) {
24502                    hideTooltip();
24503                }
24504                break;
24505        }
24506        return false;
24507    }
24508
24509    void handleTooltipKey(KeyEvent event) {
24510        switch (event.getAction()) {
24511            case KeyEvent.ACTION_DOWN:
24512                if (event.getRepeatCount() == 0) {
24513                    hideTooltip();
24514                }
24515                break;
24516
24517            case KeyEvent.ACTION_UP:
24518                handleTooltipUp();
24519                break;
24520        }
24521    }
24522
24523    private void handleTooltipUp() {
24524        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24525            return;
24526        }
24527        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24528        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24529                ViewConfiguration.getLongPressTooltipHideTimeout());
24530    }
24531
24532    /**
24533     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24534     * is not showing.
24535     * @hide
24536     */
24537    @TestApi
24538    public View getTooltipView() {
24539        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24540            return null;
24541        }
24542        return mTooltipInfo.mTooltipPopup.getContentView();
24543    }
24544}
24545