View.java revision 12e182a99ee9d3572043aa77521718b02ed21823
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handle moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
824     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
825     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
826     * check is implemented for backwards compatibility.
827     *
828     * {@hide}
829     */
830    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
831
832    /**
833     * Prior to N, when drag enters into child of a view that has already received an
834     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
835     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
836     * false from its event handler for these events.
837     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
838     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
839     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
840     */
841    static boolean sCascadedDragDrop;
842
843    /**
844     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
845     * calling setFlags.
846     */
847    private static final int NOT_FOCUSABLE = 0x00000000;
848
849    /**
850     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
851     * setFlags.
852     */
853    private static final int FOCUSABLE = 0x00000001;
854
855    /**
856     * Mask for use with setFlags indicating bits used for focus.
857     */
858    private static final int FOCUSABLE_MASK = 0x00000001;
859
860    /**
861     * This view will adjust its padding to fit sytem windows (e.g. status bar)
862     */
863    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
864
865    /** @hide */
866    @IntDef({VISIBLE, INVISIBLE, GONE})
867    @Retention(RetentionPolicy.SOURCE)
868    public @interface Visibility {}
869
870    /**
871     * This view is visible.
872     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
873     * android:visibility}.
874     */
875    public static final int VISIBLE = 0x00000000;
876
877    /**
878     * This view is invisible, but it still takes up space for layout purposes.
879     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
880     * android:visibility}.
881     */
882    public static final int INVISIBLE = 0x00000004;
883
884    /**
885     * This view is invisible, and it doesn't take any space for layout
886     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
887     * android:visibility}.
888     */
889    public static final int GONE = 0x00000008;
890
891    /**
892     * Mask for use with setFlags indicating bits used for visibility.
893     * {@hide}
894     */
895    static final int VISIBILITY_MASK = 0x0000000C;
896
897    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
898
899    /**
900     * This view is enabled. Interpretation varies by subclass.
901     * Use with ENABLED_MASK when calling setFlags.
902     * {@hide}
903     */
904    static final int ENABLED = 0x00000000;
905
906    /**
907     * This view is disabled. Interpretation varies by subclass.
908     * Use with ENABLED_MASK when calling setFlags.
909     * {@hide}
910     */
911    static final int DISABLED = 0x00000020;
912
913   /**
914    * Mask for use with setFlags indicating bits used for indicating whether
915    * this view is enabled
916    * {@hide}
917    */
918    static final int ENABLED_MASK = 0x00000020;
919
920    /**
921     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
922     * called and further optimizations will be performed. It is okay to have
923     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
924     * {@hide}
925     */
926    static final int WILL_NOT_DRAW = 0x00000080;
927
928    /**
929     * Mask for use with setFlags indicating bits used for indicating whether
930     * this view is will draw
931     * {@hide}
932     */
933    static final int DRAW_MASK = 0x00000080;
934
935    /**
936     * <p>This view doesn't show scrollbars.</p>
937     * {@hide}
938     */
939    static final int SCROLLBARS_NONE = 0x00000000;
940
941    /**
942     * <p>This view shows horizontal scrollbars.</p>
943     * {@hide}
944     */
945    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
946
947    /**
948     * <p>This view shows vertical scrollbars.</p>
949     * {@hide}
950     */
951    static final int SCROLLBARS_VERTICAL = 0x00000200;
952
953    /**
954     * <p>Mask for use with setFlags indicating bits used for indicating which
955     * scrollbars are enabled.</p>
956     * {@hide}
957     */
958    static final int SCROLLBARS_MASK = 0x00000300;
959
960    /**
961     * Indicates that the view should filter touches when its window is obscured.
962     * Refer to the class comments for more information about this security feature.
963     * {@hide}
964     */
965    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
966
967    /**
968     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
969     * that they are optional and should be skipped if the window has
970     * requested system UI flags that ignore those insets for layout.
971     */
972    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
973
974    /**
975     * <p>This view doesn't show fading edges.</p>
976     * {@hide}
977     */
978    static final int FADING_EDGE_NONE = 0x00000000;
979
980    /**
981     * <p>This view shows horizontal fading edges.</p>
982     * {@hide}
983     */
984    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
985
986    /**
987     * <p>This view shows vertical fading edges.</p>
988     * {@hide}
989     */
990    static final int FADING_EDGE_VERTICAL = 0x00002000;
991
992    /**
993     * <p>Mask for use with setFlags indicating bits used for indicating which
994     * fading edges are enabled.</p>
995     * {@hide}
996     */
997    static final int FADING_EDGE_MASK = 0x00003000;
998
999    /**
1000     * <p>Indicates this view can be clicked. When clickable, a View reacts
1001     * to clicks by notifying the OnClickListener.<p>
1002     * {@hide}
1003     */
1004    static final int CLICKABLE = 0x00004000;
1005
1006    /**
1007     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1008     * {@hide}
1009     */
1010    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1011
1012    /**
1013     * <p>Indicates that no icicle should be saved for this view.<p>
1014     * {@hide}
1015     */
1016    static final int SAVE_DISABLED = 0x000010000;
1017
1018    /**
1019     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1020     * property.</p>
1021     * {@hide}
1022     */
1023    static final int SAVE_DISABLED_MASK = 0x000010000;
1024
1025    /**
1026     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1027     * {@hide}
1028     */
1029    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1030
1031    /**
1032     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1033     * {@hide}
1034     */
1035    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1036
1037    /** @hide */
1038    @Retention(RetentionPolicy.SOURCE)
1039    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1040    public @interface DrawingCacheQuality {}
1041
1042    /**
1043     * <p>Enables low quality mode for the drawing cache.</p>
1044     */
1045    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1046
1047    /**
1048     * <p>Enables high quality mode for the drawing cache.</p>
1049     */
1050    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1051
1052    /**
1053     * <p>Enables automatic quality mode for the drawing cache.</p>
1054     */
1055    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1056
1057    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1058            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1059    };
1060
1061    /**
1062     * <p>Mask for use with setFlags indicating bits used for the cache
1063     * quality property.</p>
1064     * {@hide}
1065     */
1066    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1067
1068    /**
1069     * <p>
1070     * Indicates this view can be long clicked. When long clickable, a View
1071     * reacts to long clicks by notifying the OnLongClickListener or showing a
1072     * context menu.
1073     * </p>
1074     * {@hide}
1075     */
1076    static final int LONG_CLICKABLE = 0x00200000;
1077
1078    /**
1079     * <p>Indicates that this view gets its drawable states from its direct parent
1080     * and ignores its original internal states.</p>
1081     *
1082     * @hide
1083     */
1084    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1085
1086    /**
1087     * <p>
1088     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1089     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1090     * OnContextClickListener.
1091     * </p>
1092     * {@hide}
1093     */
1094    static final int CONTEXT_CLICKABLE = 0x00800000;
1095
1096
1097    /** @hide */
1098    @IntDef({
1099        SCROLLBARS_INSIDE_OVERLAY,
1100        SCROLLBARS_INSIDE_INSET,
1101        SCROLLBARS_OUTSIDE_OVERLAY,
1102        SCROLLBARS_OUTSIDE_INSET
1103    })
1104    @Retention(RetentionPolicy.SOURCE)
1105    public @interface ScrollBarStyle {}
1106
1107    /**
1108     * The scrollbar style to display the scrollbars inside the content area,
1109     * without increasing the padding. The scrollbars will be overlaid with
1110     * translucency on the view's content.
1111     */
1112    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1113
1114    /**
1115     * The scrollbar style to display the scrollbars inside the padded area,
1116     * increasing the padding of the view. The scrollbars will not overlap the
1117     * content area of the view.
1118     */
1119    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1120
1121    /**
1122     * The scrollbar style to display the scrollbars at the edge of the view,
1123     * without increasing the padding. The scrollbars will be overlaid with
1124     * translucency.
1125     */
1126    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1127
1128    /**
1129     * The scrollbar style to display the scrollbars at the edge of the view,
1130     * increasing the padding of the view. The scrollbars will only overlap the
1131     * background, if any.
1132     */
1133    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1134
1135    /**
1136     * Mask to check if the scrollbar style is overlay or inset.
1137     * {@hide}
1138     */
1139    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1140
1141    /**
1142     * Mask to check if the scrollbar style is inside or outside.
1143     * {@hide}
1144     */
1145    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1146
1147    /**
1148     * Mask for scrollbar style.
1149     * {@hide}
1150     */
1151    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1152
1153    /**
1154     * View flag indicating that the screen should remain on while the
1155     * window containing this view is visible to the user.  This effectively
1156     * takes care of automatically setting the WindowManager's
1157     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1158     */
1159    public static final int KEEP_SCREEN_ON = 0x04000000;
1160
1161    /**
1162     * View flag indicating whether this view should have sound effects enabled
1163     * for events such as clicking and touching.
1164     */
1165    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1166
1167    /**
1168     * View flag indicating whether this view should have haptic feedback
1169     * enabled for events such as long presses.
1170     */
1171    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1172
1173    /**
1174     * <p>Indicates that the view hierarchy should stop saving state when
1175     * it reaches this view.  If state saving is initiated immediately at
1176     * the view, it will be allowed.
1177     * {@hide}
1178     */
1179    static final int PARENT_SAVE_DISABLED = 0x20000000;
1180
1181    /**
1182     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1183     * {@hide}
1184     */
1185    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1186
1187    /** @hide */
1188    @IntDef(flag = true,
1189            value = {
1190                FOCUSABLES_ALL,
1191                FOCUSABLES_TOUCH_MODE
1192            })
1193    @Retention(RetentionPolicy.SOURCE)
1194    public @interface FocusableMode {}
1195
1196    /**
1197     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1198     * should add all focusable Views regardless if they are focusable in touch mode.
1199     */
1200    public static final int FOCUSABLES_ALL = 0x00000000;
1201
1202    /**
1203     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1204     * should add only Views focusable in touch mode.
1205     */
1206    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1207
1208    /** @hide */
1209    @IntDef({
1210            FOCUS_BACKWARD,
1211            FOCUS_FORWARD,
1212            FOCUS_LEFT,
1213            FOCUS_UP,
1214            FOCUS_RIGHT,
1215            FOCUS_DOWN
1216    })
1217    @Retention(RetentionPolicy.SOURCE)
1218    public @interface FocusDirection {}
1219
1220    /** @hide */
1221    @IntDef({
1222            FOCUS_LEFT,
1223            FOCUS_UP,
1224            FOCUS_RIGHT,
1225            FOCUS_DOWN
1226    })
1227    @Retention(RetentionPolicy.SOURCE)
1228    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1229
1230    /**
1231     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1232     * item.
1233     */
1234    public static final int FOCUS_BACKWARD = 0x00000001;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1238     * item.
1239     */
1240    public static final int FOCUS_FORWARD = 0x00000002;
1241
1242    /**
1243     * Use with {@link #focusSearch(int)}. Move focus to the left.
1244     */
1245    public static final int FOCUS_LEFT = 0x00000011;
1246
1247    /**
1248     * Use with {@link #focusSearch(int)}. Move focus up.
1249     */
1250    public static final int FOCUS_UP = 0x00000021;
1251
1252    /**
1253     * Use with {@link #focusSearch(int)}. Move focus to the right.
1254     */
1255    public static final int FOCUS_RIGHT = 0x00000042;
1256
1257    /**
1258     * Use with {@link #focusSearch(int)}. Move focus down.
1259     */
1260    public static final int FOCUS_DOWN = 0x00000082;
1261
1262    /**
1263     * Bits of {@link #getMeasuredWidthAndState()} and
1264     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1265     */
1266    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1267
1268    /**
1269     * Bits of {@link #getMeasuredWidthAndState()} and
1270     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1271     */
1272    public static final int MEASURED_STATE_MASK = 0xff000000;
1273
1274    /**
1275     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1276     * for functions that combine both width and height into a single int,
1277     * such as {@link #getMeasuredState()} and the childState argument of
1278     * {@link #resolveSizeAndState(int, int, int)}.
1279     */
1280    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1281
1282    /**
1283     * Bit of {@link #getMeasuredWidthAndState()} and
1284     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1285     * is smaller that the space the view would like to have.
1286     */
1287    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1288
1289    /**
1290     * Base View state sets
1291     */
1292    // Singles
1293    /**
1294     * Indicates the view has no states set. States are used with
1295     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1296     * view depending on its state.
1297     *
1298     * @see android.graphics.drawable.Drawable
1299     * @see #getDrawableState()
1300     */
1301    protected static final int[] EMPTY_STATE_SET;
1302    /**
1303     * Indicates the view is enabled. States are used with
1304     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1305     * view depending on its state.
1306     *
1307     * @see android.graphics.drawable.Drawable
1308     * @see #getDrawableState()
1309     */
1310    protected static final int[] ENABLED_STATE_SET;
1311    /**
1312     * Indicates the view is focused. States are used with
1313     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1314     * view depending on its state.
1315     *
1316     * @see android.graphics.drawable.Drawable
1317     * @see #getDrawableState()
1318     */
1319    protected static final int[] FOCUSED_STATE_SET;
1320    /**
1321     * Indicates the view is selected. States are used with
1322     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1323     * view depending on its state.
1324     *
1325     * @see android.graphics.drawable.Drawable
1326     * @see #getDrawableState()
1327     */
1328    protected static final int[] SELECTED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed. States are used with
1331     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1332     * view depending on its state.
1333     *
1334     * @see android.graphics.drawable.Drawable
1335     * @see #getDrawableState()
1336     */
1337    protected static final int[] PRESSED_STATE_SET;
1338    /**
1339     * Indicates the view's window has focus. States are used with
1340     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1341     * view depending on its state.
1342     *
1343     * @see android.graphics.drawable.Drawable
1344     * @see #getDrawableState()
1345     */
1346    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1347    // Doubles
1348    /**
1349     * Indicates the view is enabled and has the focus.
1350     *
1351     * @see #ENABLED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     */
1354    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1355    /**
1356     * Indicates the view is enabled and selected.
1357     *
1358     * @see #ENABLED_STATE_SET
1359     * @see #SELECTED_STATE_SET
1360     */
1361    protected static final int[] ENABLED_SELECTED_STATE_SET;
1362    /**
1363     * Indicates the view is enabled and that its window has focus.
1364     *
1365     * @see #ENABLED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1369    /**
1370     * Indicates the view is focused and selected.
1371     *
1372     * @see #FOCUSED_STATE_SET
1373     * @see #SELECTED_STATE_SET
1374     */
1375    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1376    /**
1377     * Indicates the view has the focus and that its window has the focus.
1378     *
1379     * @see #FOCUSED_STATE_SET
1380     * @see #WINDOW_FOCUSED_STATE_SET
1381     */
1382    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1383    /**
1384     * Indicates the view is selected and that its window has the focus.
1385     *
1386     * @see #SELECTED_STATE_SET
1387     * @see #WINDOW_FOCUSED_STATE_SET
1388     */
1389    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1390    // Triples
1391    /**
1392     * Indicates the view is enabled, focused and selected.
1393     *
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     * @see #SELECTED_STATE_SET
1397     */
1398    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1399    /**
1400     * Indicates the view is enabled, focused and its window has the focus.
1401     *
1402     * @see #ENABLED_STATE_SET
1403     * @see #FOCUSED_STATE_SET
1404     * @see #WINDOW_FOCUSED_STATE_SET
1405     */
1406    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1407    /**
1408     * Indicates the view is enabled, selected and its window has the focus.
1409     *
1410     * @see #ENABLED_STATE_SET
1411     * @see #SELECTED_STATE_SET
1412     * @see #WINDOW_FOCUSED_STATE_SET
1413     */
1414    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1415    /**
1416     * Indicates the view is focused, selected and its window has the focus.
1417     *
1418     * @see #FOCUSED_STATE_SET
1419     * @see #SELECTED_STATE_SET
1420     * @see #WINDOW_FOCUSED_STATE_SET
1421     */
1422    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1423    /**
1424     * Indicates the view is enabled, focused, selected and its window
1425     * has the focus.
1426     *
1427     * @see #ENABLED_STATE_SET
1428     * @see #FOCUSED_STATE_SET
1429     * @see #SELECTED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1433    /**
1434     * Indicates the view is pressed and its window has the focus.
1435     *
1436     * @see #PRESSED_STATE_SET
1437     * @see #WINDOW_FOCUSED_STATE_SET
1438     */
1439    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1440    /**
1441     * Indicates the view is pressed and selected.
1442     *
1443     * @see #PRESSED_STATE_SET
1444     * @see #SELECTED_STATE_SET
1445     */
1446    protected static final int[] PRESSED_SELECTED_STATE_SET;
1447    /**
1448     * Indicates the view is pressed, selected and its window has the focus.
1449     *
1450     * @see #PRESSED_STATE_SET
1451     * @see #SELECTED_STATE_SET
1452     * @see #WINDOW_FOCUSED_STATE_SET
1453     */
1454    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1455    /**
1456     * Indicates the view is pressed and focused.
1457     *
1458     * @see #PRESSED_STATE_SET
1459     * @see #FOCUSED_STATE_SET
1460     */
1461    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1462    /**
1463     * Indicates the view is pressed, focused and its window has the focus.
1464     *
1465     * @see #PRESSED_STATE_SET
1466     * @see #FOCUSED_STATE_SET
1467     * @see #WINDOW_FOCUSED_STATE_SET
1468     */
1469    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1470    /**
1471     * Indicates the view is pressed, focused and selected.
1472     *
1473     * @see #PRESSED_STATE_SET
1474     * @see #SELECTED_STATE_SET
1475     * @see #FOCUSED_STATE_SET
1476     */
1477    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1478    /**
1479     * Indicates the view is pressed, focused, selected and its window has the focus.
1480     *
1481     * @see #PRESSED_STATE_SET
1482     * @see #FOCUSED_STATE_SET
1483     * @see #SELECTED_STATE_SET
1484     * @see #WINDOW_FOCUSED_STATE_SET
1485     */
1486    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1487    /**
1488     * Indicates the view is pressed and enabled.
1489     *
1490     * @see #PRESSED_STATE_SET
1491     * @see #ENABLED_STATE_SET
1492     */
1493    protected static final int[] PRESSED_ENABLED_STATE_SET;
1494    /**
1495     * Indicates the view is pressed, enabled and its window has the focus.
1496     *
1497     * @see #PRESSED_STATE_SET
1498     * @see #ENABLED_STATE_SET
1499     * @see #WINDOW_FOCUSED_STATE_SET
1500     */
1501    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1502    /**
1503     * Indicates the view is pressed, enabled and selected.
1504     *
1505     * @see #PRESSED_STATE_SET
1506     * @see #ENABLED_STATE_SET
1507     * @see #SELECTED_STATE_SET
1508     */
1509    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1510    /**
1511     * Indicates the view is pressed, enabled, selected and its window has the
1512     * focus.
1513     *
1514     * @see #PRESSED_STATE_SET
1515     * @see #ENABLED_STATE_SET
1516     * @see #SELECTED_STATE_SET
1517     * @see #WINDOW_FOCUSED_STATE_SET
1518     */
1519    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1520    /**
1521     * Indicates the view is pressed, enabled and focused.
1522     *
1523     * @see #PRESSED_STATE_SET
1524     * @see #ENABLED_STATE_SET
1525     * @see #FOCUSED_STATE_SET
1526     */
1527    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1528    /**
1529     * Indicates the view is pressed, enabled, focused and its window has the
1530     * focus.
1531     *
1532     * @see #PRESSED_STATE_SET
1533     * @see #ENABLED_STATE_SET
1534     * @see #FOCUSED_STATE_SET
1535     * @see #WINDOW_FOCUSED_STATE_SET
1536     */
1537    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1538    /**
1539     * Indicates the view is pressed, enabled, focused and selected.
1540     *
1541     * @see #PRESSED_STATE_SET
1542     * @see #ENABLED_STATE_SET
1543     * @see #SELECTED_STATE_SET
1544     * @see #FOCUSED_STATE_SET
1545     */
1546    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1547    /**
1548     * Indicates the view is pressed, enabled, focused, selected and its window
1549     * has the focus.
1550     *
1551     * @see #PRESSED_STATE_SET
1552     * @see #ENABLED_STATE_SET
1553     * @see #SELECTED_STATE_SET
1554     * @see #FOCUSED_STATE_SET
1555     * @see #WINDOW_FOCUSED_STATE_SET
1556     */
1557    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1558
1559    static {
1560        EMPTY_STATE_SET = StateSet.get(0);
1561
1562        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1563
1564        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1565        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1566                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1567
1568        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1569        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1571        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1572                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1573        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1574                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1575                        | StateSet.VIEW_STATE_FOCUSED);
1576
1577        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1578        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1579                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1580        ENABLED_SELECTED_STATE_SET = StateSet.get(
1581                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1582        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1583                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1584                        | StateSet.VIEW_STATE_ENABLED);
1585        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1586                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1587        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1588                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1589                        | StateSet.VIEW_STATE_ENABLED);
1590        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1591                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1592                        | StateSet.VIEW_STATE_ENABLED);
1593        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1594                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1595                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1596
1597        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1598        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1599                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1600        PRESSED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1602        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1603                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1604                        | StateSet.VIEW_STATE_PRESSED);
1605        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1606                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1607        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1608                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1609                        | StateSet.VIEW_STATE_PRESSED);
1610        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1611                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1612                        | StateSet.VIEW_STATE_PRESSED);
1613        PRESSED_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_PRESSED);
1616        PRESSED_ENABLED_STATE_SET = StateSet.get(
1617                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1618        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1619                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1620                        | StateSet.VIEW_STATE_PRESSED);
1621        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1622                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1623                        | StateSet.VIEW_STATE_PRESSED);
1624        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1625                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1626                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1627        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1628                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1629                        | StateSet.VIEW_STATE_PRESSED);
1630        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1631                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1632                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1633        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1634                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1635                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1636        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1637                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1638                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1639                        | StateSet.VIEW_STATE_PRESSED);
1640    }
1641
1642    /**
1643     * Accessibility event types that are dispatched for text population.
1644     */
1645    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1646            AccessibilityEvent.TYPE_VIEW_CLICKED
1647            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1648            | AccessibilityEvent.TYPE_VIEW_SELECTED
1649            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1650            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1651            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1652            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1653            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1654            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1655            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1656            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1657
1658    /**
1659     * Temporary Rect currently for use in setBackground().  This will probably
1660     * be extended in the future to hold our own class with more than just
1661     * a Rect. :)
1662     */
1663    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1664
1665    /**
1666     * Map used to store views' tags.
1667     */
1668    private SparseArray<Object> mKeyedTags;
1669
1670    /**
1671     * The next available accessibility id.
1672     */
1673    private static int sNextAccessibilityViewId;
1674
1675    /**
1676     * The animation currently associated with this view.
1677     * @hide
1678     */
1679    protected Animation mCurrentAnimation = null;
1680
1681    /**
1682     * Width as measured during measure pass.
1683     * {@hide}
1684     */
1685    @ViewDebug.ExportedProperty(category = "measurement")
1686    int mMeasuredWidth;
1687
1688    /**
1689     * Height as measured during measure pass.
1690     * {@hide}
1691     */
1692    @ViewDebug.ExportedProperty(category = "measurement")
1693    int mMeasuredHeight;
1694
1695    /**
1696     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1697     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1698     * its display list. This flag, used only when hw accelerated, allows us to clear the
1699     * flag while retaining this information until it's needed (at getDisplayList() time and
1700     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1701     *
1702     * {@hide}
1703     */
1704    boolean mRecreateDisplayList = false;
1705
1706    /**
1707     * The view's identifier.
1708     * {@hide}
1709     *
1710     * @see #setId(int)
1711     * @see #getId()
1712     */
1713    @IdRes
1714    @ViewDebug.ExportedProperty(resolveId = true)
1715    int mID = NO_ID;
1716
1717    /**
1718     * The stable ID of this view for accessibility purposes.
1719     */
1720    int mAccessibilityViewId = NO_ID;
1721
1722    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1723
1724    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1725
1726    /**
1727     * The view's tag.
1728     * {@hide}
1729     *
1730     * @see #setTag(Object)
1731     * @see #getTag()
1732     */
1733    protected Object mTag = null;
1734
1735    // for mPrivateFlags:
1736    /** {@hide} */
1737    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1738    /** {@hide} */
1739    static final int PFLAG_FOCUSED                     = 0x00000002;
1740    /** {@hide} */
1741    static final int PFLAG_SELECTED                    = 0x00000004;
1742    /** {@hide} */
1743    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1744    /** {@hide} */
1745    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1746    /** {@hide} */
1747    static final int PFLAG_DRAWN                       = 0x00000020;
1748    /**
1749     * When this flag is set, this view is running an animation on behalf of its
1750     * children and should therefore not cancel invalidate requests, even if they
1751     * lie outside of this view's bounds.
1752     *
1753     * {@hide}
1754     */
1755    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1756    /** {@hide} */
1757    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1758    /** {@hide} */
1759    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1760    /** {@hide} */
1761    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1762    /** {@hide} */
1763    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1764    /** {@hide} */
1765    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1766    /** {@hide} */
1767    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1768
1769    private static final int PFLAG_PRESSED             = 0x00004000;
1770
1771    /** {@hide} */
1772    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1773    /**
1774     * Flag used to indicate that this view should be drawn once more (and only once
1775     * more) after its animation has completed.
1776     * {@hide}
1777     */
1778    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1779
1780    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1781
1782    /**
1783     * Indicates that the View returned true when onSetAlpha() was called and that
1784     * the alpha must be restored.
1785     * {@hide}
1786     */
1787    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1788
1789    /**
1790     * Set by {@link #setScrollContainer(boolean)}.
1791     */
1792    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1793
1794    /**
1795     * Set by {@link #setScrollContainer(boolean)}.
1796     */
1797    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1798
1799    /**
1800     * View flag indicating whether this view was invalidated (fully or partially.)
1801     *
1802     * @hide
1803     */
1804    static final int PFLAG_DIRTY                       = 0x00200000;
1805
1806    /**
1807     * View flag indicating whether this view was invalidated by an opaque
1808     * invalidate request.
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1813
1814    /**
1815     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1820
1821    /**
1822     * Indicates whether the background is opaque.
1823     *
1824     * @hide
1825     */
1826    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1827
1828    /**
1829     * Indicates whether the scrollbars are opaque.
1830     *
1831     * @hide
1832     */
1833    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1834
1835    /**
1836     * Indicates whether the view is opaque.
1837     *
1838     * @hide
1839     */
1840    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1841
1842    /**
1843     * Indicates a prepressed state;
1844     * the short time between ACTION_DOWN and recognizing
1845     * a 'real' press. Prepressed is used to recognize quick taps
1846     * even when they are shorter than ViewConfiguration.getTapTimeout().
1847     *
1848     * @hide
1849     */
1850    private static final int PFLAG_PREPRESSED          = 0x02000000;
1851
1852    /**
1853     * Indicates whether the view is temporarily detached.
1854     *
1855     * @hide
1856     */
1857    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1858
1859    /**
1860     * Indicates that we should awaken scroll bars once attached
1861     *
1862     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1863     * during window attachment and it is no longer needed. Feel free to repurpose it.
1864     *
1865     * @hide
1866     */
1867    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1868
1869    /**
1870     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1871     * @hide
1872     */
1873    private static final int PFLAG_HOVERED             = 0x10000000;
1874
1875    /**
1876     * no longer needed, should be reused
1877     */
1878    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1879
1880    /** {@hide} */
1881    static final int PFLAG_ACTIVATED                   = 0x40000000;
1882
1883    /**
1884     * Indicates that this view was specifically invalidated, not just dirtied because some
1885     * child view was invalidated. The flag is used to determine when we need to recreate
1886     * a view's display list (as opposed to just returning a reference to its existing
1887     * display list).
1888     *
1889     * @hide
1890     */
1891    static final int PFLAG_INVALIDATED                 = 0x80000000;
1892
1893    /**
1894     * Masks for mPrivateFlags2, as generated by dumpFlags():
1895     *
1896     * |-------|-------|-------|-------|
1897     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1898     *                                1  PFLAG2_DRAG_HOVERED
1899     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1900     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1901     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1902     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1903     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1904     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1905     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1906     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1907     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1908     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1909     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1910     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1911     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1912     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1913     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1914     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1915     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1916     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1917     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1918     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1919     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1920     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1921     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1922     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1923     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1924     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1925     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1926     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1927     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1928     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1929     *    1                              PFLAG2_PADDING_RESOLVED
1930     *   1                               PFLAG2_DRAWABLE_RESOLVED
1931     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1932     * |-------|-------|-------|-------|
1933     */
1934
1935    /**
1936     * Indicates that this view has reported that it can accept the current drag's content.
1937     * Cleared when the drag operation concludes.
1938     * @hide
1939     */
1940    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1941
1942    /**
1943     * Indicates that this view is currently directly under the drag location in a
1944     * drag-and-drop operation involving content that it can accept.  Cleared when
1945     * the drag exits the view, or when the drag operation concludes.
1946     * @hide
1947     */
1948    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1949
1950    /** @hide */
1951    @IntDef({
1952        LAYOUT_DIRECTION_LTR,
1953        LAYOUT_DIRECTION_RTL,
1954        LAYOUT_DIRECTION_INHERIT,
1955        LAYOUT_DIRECTION_LOCALE
1956    })
1957    @Retention(RetentionPolicy.SOURCE)
1958    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1959    public @interface LayoutDir {}
1960
1961    /** @hide */
1962    @IntDef({
1963        LAYOUT_DIRECTION_LTR,
1964        LAYOUT_DIRECTION_RTL
1965    })
1966    @Retention(RetentionPolicy.SOURCE)
1967    public @interface ResolvedLayoutDir {}
1968
1969    /**
1970     * A flag to indicate that the layout direction of this view has not been defined yet.
1971     * @hide
1972     */
1973    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1974
1975    /**
1976     * Horizontal layout direction of this view is from Left to Right.
1977     * Use with {@link #setLayoutDirection}.
1978     */
1979    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1980
1981    /**
1982     * Horizontal layout direction of this view is from Right to Left.
1983     * Use with {@link #setLayoutDirection}.
1984     */
1985    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1986
1987    /**
1988     * Horizontal layout direction of this view is inherited from its parent.
1989     * Use with {@link #setLayoutDirection}.
1990     */
1991    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1992
1993    /**
1994     * Horizontal layout direction of this view is from deduced from the default language
1995     * script for the locale. Use with {@link #setLayoutDirection}.
1996     */
1997    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1998
1999    /**
2000     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2001     * @hide
2002     */
2003    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2004
2005    /**
2006     * Mask for use with private flags indicating bits used for horizontal layout direction.
2007     * @hide
2008     */
2009    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2010
2011    /**
2012     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2013     * right-to-left direction.
2014     * @hide
2015     */
2016    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2017
2018    /**
2019     * Indicates whether the view horizontal layout direction has been resolved.
2020     * @hide
2021     */
2022    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2023
2024    /**
2025     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2026     * @hide
2027     */
2028    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2029            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2030
2031    /*
2032     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2033     * flag value.
2034     * @hide
2035     */
2036    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2037            LAYOUT_DIRECTION_LTR,
2038            LAYOUT_DIRECTION_RTL,
2039            LAYOUT_DIRECTION_INHERIT,
2040            LAYOUT_DIRECTION_LOCALE
2041    };
2042
2043    /**
2044     * Default horizontal layout direction.
2045     */
2046    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2047
2048    /**
2049     * Default horizontal layout direction.
2050     * @hide
2051     */
2052    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2053
2054    /**
2055     * Text direction is inherited through {@link ViewGroup}
2056     */
2057    public static final int TEXT_DIRECTION_INHERIT = 0;
2058
2059    /**
2060     * Text direction is using "first strong algorithm". The first strong directional character
2061     * determines the paragraph direction. If there is no strong directional character, the
2062     * paragraph direction is the view's resolved layout direction.
2063     */
2064    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2065
2066    /**
2067     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2068     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2069     * If there are neither, the paragraph direction is the view's resolved layout direction.
2070     */
2071    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2072
2073    /**
2074     * Text direction is forced to LTR.
2075     */
2076    public static final int TEXT_DIRECTION_LTR = 3;
2077
2078    /**
2079     * Text direction is forced to RTL.
2080     */
2081    public static final int TEXT_DIRECTION_RTL = 4;
2082
2083    /**
2084     * Text direction is coming from the system Locale.
2085     */
2086    public static final int TEXT_DIRECTION_LOCALE = 5;
2087
2088    /**
2089     * Text direction is using "first strong algorithm". The first strong directional character
2090     * determines the paragraph direction. If there is no strong directional character, the
2091     * paragraph direction is LTR.
2092     */
2093    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2094
2095    /**
2096     * Text direction is using "first strong algorithm". The first strong directional character
2097     * determines the paragraph direction. If there is no strong directional character, the
2098     * paragraph direction is RTL.
2099     */
2100    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2101
2102    /**
2103     * Default text direction is inherited
2104     */
2105    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2106
2107    /**
2108     * Default resolved text direction
2109     * @hide
2110     */
2111    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2112
2113    /**
2114     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2115     * @hide
2116     */
2117    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2118
2119    /**
2120     * Mask for use with private flags indicating bits used for text direction.
2121     * @hide
2122     */
2123    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2124            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2125
2126    /**
2127     * Array of text direction flags for mapping attribute "textDirection" to correct
2128     * flag value.
2129     * @hide
2130     */
2131    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2132            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2133            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2134            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2135            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2136            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2137            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2138            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2139            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2140    };
2141
2142    /**
2143     * Indicates whether the view text direction has been resolved.
2144     * @hide
2145     */
2146    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2147            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2148
2149    /**
2150     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2151     * @hide
2152     */
2153    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2154
2155    /**
2156     * Mask for use with private flags indicating bits used for resolved text direction.
2157     * @hide
2158     */
2159    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2160            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2161
2162    /**
2163     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2164     * @hide
2165     */
2166    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2167            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2168
2169    /** @hide */
2170    @IntDef({
2171        TEXT_ALIGNMENT_INHERIT,
2172        TEXT_ALIGNMENT_GRAVITY,
2173        TEXT_ALIGNMENT_CENTER,
2174        TEXT_ALIGNMENT_TEXT_START,
2175        TEXT_ALIGNMENT_TEXT_END,
2176        TEXT_ALIGNMENT_VIEW_START,
2177        TEXT_ALIGNMENT_VIEW_END
2178    })
2179    @Retention(RetentionPolicy.SOURCE)
2180    public @interface TextAlignment {}
2181
2182    /**
2183     * Default text alignment. The text alignment of this View is inherited from its parent.
2184     * Use with {@link #setTextAlignment(int)}
2185     */
2186    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2187
2188    /**
2189     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2190     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2191     *
2192     * Use with {@link #setTextAlignment(int)}
2193     */
2194    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2195
2196    /**
2197     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2198     *
2199     * Use with {@link #setTextAlignment(int)}
2200     */
2201    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2202
2203    /**
2204     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2205     *
2206     * Use with {@link #setTextAlignment(int)}
2207     */
2208    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2209
2210    /**
2211     * Center the paragraph, e.g. ALIGN_CENTER.
2212     *
2213     * Use with {@link #setTextAlignment(int)}
2214     */
2215    public static final int TEXT_ALIGNMENT_CENTER = 4;
2216
2217    /**
2218     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2219     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2220     *
2221     * Use with {@link #setTextAlignment(int)}
2222     */
2223    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2224
2225    /**
2226     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2227     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2228     *
2229     * Use with {@link #setTextAlignment(int)}
2230     */
2231    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2232
2233    /**
2234     * Default text alignment is inherited
2235     */
2236    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2237
2238    /**
2239     * Default resolved text alignment
2240     * @hide
2241     */
2242    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2243
2244    /**
2245      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2246      * @hide
2247      */
2248    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2249
2250    /**
2251      * Mask for use with private flags indicating bits used for text alignment.
2252      * @hide
2253      */
2254    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2255
2256    /**
2257     * Array of text direction flags for mapping attribute "textAlignment" to correct
2258     * flag value.
2259     * @hide
2260     */
2261    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2262            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2263            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2264            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2265            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2266            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2267            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2268            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2269    };
2270
2271    /**
2272     * Indicates whether the view text alignment has been resolved.
2273     * @hide
2274     */
2275    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2276
2277    /**
2278     * Bit shift to get the resolved text alignment.
2279     * @hide
2280     */
2281    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2282
2283    /**
2284     * Mask for use with private flags indicating bits used for text alignment.
2285     * @hide
2286     */
2287    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2288            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2289
2290    /**
2291     * Indicates whether if the view text alignment has been resolved to gravity
2292     */
2293    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2294            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2295
2296    // Accessiblity constants for mPrivateFlags2
2297
2298    /**
2299     * Shift for the bits in {@link #mPrivateFlags2} related to the
2300     * "importantForAccessibility" attribute.
2301     */
2302    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2303
2304    /**
2305     * Automatically determine whether a view is important for accessibility.
2306     */
2307    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2308
2309    /**
2310     * The view is important for accessibility.
2311     */
2312    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2313
2314    /**
2315     * The view is not important for accessibility.
2316     */
2317    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2318
2319    /**
2320     * The view is not important for accessibility, nor are any of its
2321     * descendant views.
2322     */
2323    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2324
2325    /**
2326     * The default whether the view is important for accessibility.
2327     */
2328    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2329
2330    /**
2331     * Mask for obtaining the bits which specify how to determine
2332     * whether a view is important for accessibility.
2333     */
2334    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2335        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2336        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2337        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2338
2339    /**
2340     * Shift for the bits in {@link #mPrivateFlags2} related to the
2341     * "accessibilityLiveRegion" attribute.
2342     */
2343    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2344
2345    /**
2346     * Live region mode specifying that accessibility services should not
2347     * automatically announce changes to this view. This is the default live
2348     * region mode for most views.
2349     * <p>
2350     * Use with {@link #setAccessibilityLiveRegion(int)}.
2351     */
2352    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2353
2354    /**
2355     * Live region mode specifying that accessibility services should announce
2356     * changes to this view.
2357     * <p>
2358     * Use with {@link #setAccessibilityLiveRegion(int)}.
2359     */
2360    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2361
2362    /**
2363     * Live region mode specifying that accessibility services should interrupt
2364     * ongoing speech to immediately announce changes to this view.
2365     * <p>
2366     * Use with {@link #setAccessibilityLiveRegion(int)}.
2367     */
2368    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2369
2370    /**
2371     * The default whether the view is important for accessibility.
2372     */
2373    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2374
2375    /**
2376     * Mask for obtaining the bits which specify a view's accessibility live
2377     * region mode.
2378     */
2379    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2380            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2381            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2382
2383    /**
2384     * Flag indicating whether a view has accessibility focus.
2385     */
2386    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2387
2388    /**
2389     * Flag whether the accessibility state of the subtree rooted at this view changed.
2390     */
2391    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2392
2393    /**
2394     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2395     * is used to check whether later changes to the view's transform should invalidate the
2396     * view to force the quickReject test to run again.
2397     */
2398    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2399
2400    /**
2401     * Flag indicating that start/end padding has been resolved into left/right padding
2402     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2403     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2404     * during measurement. In some special cases this is required such as when an adapter-based
2405     * view measures prospective children without attaching them to a window.
2406     */
2407    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2408
2409    /**
2410     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2411     */
2412    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2413
2414    /**
2415     * Indicates that the view is tracking some sort of transient state
2416     * that the app should not need to be aware of, but that the framework
2417     * should take special care to preserve.
2418     */
2419    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2420
2421    /**
2422     * Group of bits indicating that RTL properties resolution is done.
2423     */
2424    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2425            PFLAG2_TEXT_DIRECTION_RESOLVED |
2426            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2427            PFLAG2_PADDING_RESOLVED |
2428            PFLAG2_DRAWABLE_RESOLVED;
2429
2430    // There are a couple of flags left in mPrivateFlags2
2431
2432    /* End of masks for mPrivateFlags2 */
2433
2434    /**
2435     * Masks for mPrivateFlags3, as generated by dumpFlags():
2436     *
2437     * |-------|-------|-------|-------|
2438     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2439     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2440     *                               1   PFLAG3_IS_LAID_OUT
2441     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2442     *                             1     PFLAG3_CALLED_SUPER
2443     *                            1      PFLAG3_APPLYING_INSETS
2444     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2445     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2446     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2447     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2448     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2449     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2450     *                     1             PFLAG3_SCROLL_INDICATOR_START
2451     *                    1              PFLAG3_SCROLL_INDICATOR_END
2452     *                   1               PFLAG3_ASSIST_BLOCKED
2453     *                  1                PFLAG3_POINTER_ICON_NULL
2454     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2455     *           11111111                PFLAG3_POINTER_ICON_MASK
2456     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2457     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2458     *        1                          PFLAG3_TEMPORARY_DETACH
2459     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2460     * |-------|-------|-------|-------|
2461     */
2462
2463    /**
2464     * Flag indicating that view has a transform animation set on it. This is used to track whether
2465     * an animation is cleared between successive frames, in order to tell the associated
2466     * DisplayList to clear its animation matrix.
2467     */
2468    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2469
2470    /**
2471     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2472     * animation is cleared between successive frames, in order to tell the associated
2473     * DisplayList to restore its alpha value.
2474     */
2475    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2476
2477    /**
2478     * Flag indicating that the view has been through at least one layout since it
2479     * was last attached to a window.
2480     */
2481    static final int PFLAG3_IS_LAID_OUT = 0x4;
2482
2483    /**
2484     * Flag indicating that a call to measure() was skipped and should be done
2485     * instead when layout() is invoked.
2486     */
2487    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2488
2489    /**
2490     * Flag indicating that an overridden method correctly called down to
2491     * the superclass implementation as required by the API spec.
2492     */
2493    static final int PFLAG3_CALLED_SUPER = 0x10;
2494
2495    /**
2496     * Flag indicating that we're in the process of applying window insets.
2497     */
2498    static final int PFLAG3_APPLYING_INSETS = 0x20;
2499
2500    /**
2501     * Flag indicating that we're in the process of fitting system windows using the old method.
2502     */
2503    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2504
2505    /**
2506     * Flag indicating that nested scrolling is enabled for this view.
2507     * The view will optionally cooperate with views up its parent chain to allow for
2508     * integrated nested scrolling along the same axis.
2509     */
2510    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2511
2512    /**
2513     * Flag indicating that the bottom scroll indicator should be displayed
2514     * when this view can scroll up.
2515     */
2516    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2517
2518    /**
2519     * Flag indicating that the bottom scroll indicator should be displayed
2520     * when this view can scroll down.
2521     */
2522    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2523
2524    /**
2525     * Flag indicating that the left scroll indicator should be displayed
2526     * when this view can scroll left.
2527     */
2528    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2529
2530    /**
2531     * Flag indicating that the right scroll indicator should be displayed
2532     * when this view can scroll right.
2533     */
2534    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2535
2536    /**
2537     * Flag indicating that the start scroll indicator should be displayed
2538     * when this view can scroll in the start direction.
2539     */
2540    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2541
2542    /**
2543     * Flag indicating that the end scroll indicator should be displayed
2544     * when this view can scroll in the end direction.
2545     */
2546    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2547
2548    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2549
2550    static final int SCROLL_INDICATORS_NONE = 0x0000;
2551
2552    /**
2553     * Mask for use with setFlags indicating bits used for indicating which
2554     * scroll indicators are enabled.
2555     */
2556    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2557            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2558            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2559            | PFLAG3_SCROLL_INDICATOR_END;
2560
2561    /**
2562     * Left-shift required to translate between public scroll indicator flags
2563     * and internal PFLAGS3 flags. When used as a right-shift, translates
2564     * PFLAGS3 flags to public flags.
2565     */
2566    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2567
2568    /** @hide */
2569    @Retention(RetentionPolicy.SOURCE)
2570    @IntDef(flag = true,
2571            value = {
2572                    SCROLL_INDICATOR_TOP,
2573                    SCROLL_INDICATOR_BOTTOM,
2574                    SCROLL_INDICATOR_LEFT,
2575                    SCROLL_INDICATOR_RIGHT,
2576                    SCROLL_INDICATOR_START,
2577                    SCROLL_INDICATOR_END,
2578            })
2579    public @interface ScrollIndicators {}
2580
2581    /**
2582     * Scroll indicator direction for the top edge of the view.
2583     *
2584     * @see #setScrollIndicators(int)
2585     * @see #setScrollIndicators(int, int)
2586     * @see #getScrollIndicators()
2587     */
2588    public static final int SCROLL_INDICATOR_TOP =
2589            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2590
2591    /**
2592     * Scroll indicator direction for the bottom edge of the view.
2593     *
2594     * @see #setScrollIndicators(int)
2595     * @see #setScrollIndicators(int, int)
2596     * @see #getScrollIndicators()
2597     */
2598    public static final int SCROLL_INDICATOR_BOTTOM =
2599            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2600
2601    /**
2602     * Scroll indicator direction for the left edge of the view.
2603     *
2604     * @see #setScrollIndicators(int)
2605     * @see #setScrollIndicators(int, int)
2606     * @see #getScrollIndicators()
2607     */
2608    public static final int SCROLL_INDICATOR_LEFT =
2609            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2610
2611    /**
2612     * Scroll indicator direction for the right edge of the view.
2613     *
2614     * @see #setScrollIndicators(int)
2615     * @see #setScrollIndicators(int, int)
2616     * @see #getScrollIndicators()
2617     */
2618    public static final int SCROLL_INDICATOR_RIGHT =
2619            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2620
2621    /**
2622     * Scroll indicator direction for the starting edge of the view.
2623     * <p>
2624     * Resolved according to the view's layout direction, see
2625     * {@link #getLayoutDirection()} for more information.
2626     *
2627     * @see #setScrollIndicators(int)
2628     * @see #setScrollIndicators(int, int)
2629     * @see #getScrollIndicators()
2630     */
2631    public static final int SCROLL_INDICATOR_START =
2632            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2633
2634    /**
2635     * Scroll indicator direction for the ending edge of the view.
2636     * <p>
2637     * Resolved according to the view's layout direction, see
2638     * {@link #getLayoutDirection()} for more information.
2639     *
2640     * @see #setScrollIndicators(int)
2641     * @see #setScrollIndicators(int, int)
2642     * @see #getScrollIndicators()
2643     */
2644    public static final int SCROLL_INDICATOR_END =
2645            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2646
2647    /**
2648     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2649     * into this view.<p>
2650     */
2651    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2652
2653    /**
2654     * The mask for use with private flags indicating bits used for pointer icon shapes.
2655     */
2656    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2657
2658    /**
2659     * Left-shift used for pointer icon shape values in private flags.
2660     */
2661    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2662
2663    /**
2664     * Value indicating no specific pointer icons.
2665     */
2666    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2667
2668    /**
2669     * Value indicating {@link PointerIcon.TYPE_NULL}.
2670     */
2671    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2672
2673    /**
2674     * The base value for other pointer icon shapes.
2675     */
2676    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2677
2678    /**
2679     * Whether this view has rendered elements that overlap (see {@link
2680     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2681     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2682     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2683     * determined by whatever {@link #hasOverlappingRendering()} returns.
2684     */
2685    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2686
2687    /**
2688     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2689     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2690     */
2691    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2692
2693    /**
2694     * Flag indicating that the view is temporarily detached from the parent view.
2695     *
2696     * @see #onStartTemporaryDetach()
2697     * @see #onFinishTemporaryDetach()
2698     */
2699    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2700
2701    /**
2702     * Flag indicating that the view does not wish to be revealed within its parent
2703     * hierarchy when it gains focus. Expressed in the negative since the historical
2704     * default behavior is to reveal on focus; this flag suppresses that behavior.
2705     *
2706     * @see #setRevealOnFocusHint(boolean)
2707     * @see #getRevealOnFocusHint()
2708     */
2709    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2710
2711    /* End of masks for mPrivateFlags3 */
2712
2713    /**
2714     * Always allow a user to over-scroll this view, provided it is a
2715     * view that can scroll.
2716     *
2717     * @see #getOverScrollMode()
2718     * @see #setOverScrollMode(int)
2719     */
2720    public static final int OVER_SCROLL_ALWAYS = 0;
2721
2722    /**
2723     * Allow a user to over-scroll this view only if the content is large
2724     * enough to meaningfully scroll, provided it is a view that can scroll.
2725     *
2726     * @see #getOverScrollMode()
2727     * @see #setOverScrollMode(int)
2728     */
2729    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2730
2731    /**
2732     * Never allow a user to over-scroll this view.
2733     *
2734     * @see #getOverScrollMode()
2735     * @see #setOverScrollMode(int)
2736     */
2737    public static final int OVER_SCROLL_NEVER = 2;
2738
2739    /**
2740     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2741     * requested the system UI (status bar) to be visible (the default).
2742     *
2743     * @see #setSystemUiVisibility(int)
2744     */
2745    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2746
2747    /**
2748     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2749     * system UI to enter an unobtrusive "low profile" mode.
2750     *
2751     * <p>This is for use in games, book readers, video players, or any other
2752     * "immersive" application where the usual system chrome is deemed too distracting.
2753     *
2754     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2755     *
2756     * @see #setSystemUiVisibility(int)
2757     */
2758    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2759
2760    /**
2761     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2762     * system navigation be temporarily hidden.
2763     *
2764     * <p>This is an even less obtrusive state than that called for by
2765     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2766     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2767     * those to disappear. This is useful (in conjunction with the
2768     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2769     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2770     * window flags) for displaying content using every last pixel on the display.
2771     *
2772     * <p>There is a limitation: because navigation controls are so important, the least user
2773     * interaction will cause them to reappear immediately.  When this happens, both
2774     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2775     * so that both elements reappear at the same time.
2776     *
2777     * @see #setSystemUiVisibility(int)
2778     */
2779    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2780
2781    /**
2782     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2783     * into the normal fullscreen mode so that its content can take over the screen
2784     * while still allowing the user to interact with the application.
2785     *
2786     * <p>This has the same visual effect as
2787     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2788     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2789     * meaning that non-critical screen decorations (such as the status bar) will be
2790     * hidden while the user is in the View's window, focusing the experience on
2791     * that content.  Unlike the window flag, if you are using ActionBar in
2792     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2793     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2794     * hide the action bar.
2795     *
2796     * <p>This approach to going fullscreen is best used over the window flag when
2797     * it is a transient state -- that is, the application does this at certain
2798     * points in its user interaction where it wants to allow the user to focus
2799     * on content, but not as a continuous state.  For situations where the application
2800     * would like to simply stay full screen the entire time (such as a game that
2801     * wants to take over the screen), the
2802     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2803     * is usually a better approach.  The state set here will be removed by the system
2804     * in various situations (such as the user moving to another application) like
2805     * the other system UI states.
2806     *
2807     * <p>When using this flag, the application should provide some easy facility
2808     * for the user to go out of it.  A common example would be in an e-book
2809     * reader, where tapping on the screen brings back whatever screen and UI
2810     * decorations that had been hidden while the user was immersed in reading
2811     * the book.
2812     *
2813     * @see #setSystemUiVisibility(int)
2814     */
2815    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2816
2817    /**
2818     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2819     * flags, we would like a stable view of the content insets given to
2820     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2821     * will always represent the worst case that the application can expect
2822     * as a continuous state.  In the stock Android UI this is the space for
2823     * the system bar, nav bar, and status bar, but not more transient elements
2824     * such as an input method.
2825     *
2826     * The stable layout your UI sees is based on the system UI modes you can
2827     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2828     * then you will get a stable layout for changes of the
2829     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2830     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2831     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2832     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2833     * with a stable layout.  (Note that you should avoid using
2834     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2835     *
2836     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2837     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2838     * then a hidden status bar will be considered a "stable" state for purposes
2839     * here.  This allows your UI to continually hide the status bar, while still
2840     * using the system UI flags to hide the action bar while still retaining
2841     * a stable layout.  Note that changing the window fullscreen flag will never
2842     * provide a stable layout for a clean transition.
2843     *
2844     * <p>If you are using ActionBar in
2845     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2846     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2847     * insets it adds to those given to the application.
2848     */
2849    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2850
2851    /**
2852     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2853     * to be laid out as if it has requested
2854     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2855     * allows it to avoid artifacts when switching in and out of that mode, at
2856     * the expense that some of its user interface may be covered by screen
2857     * decorations when they are shown.  You can perform layout of your inner
2858     * UI elements to account for the navigation system UI through the
2859     * {@link #fitSystemWindows(Rect)} method.
2860     */
2861    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2862
2863    /**
2864     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2865     * to be laid out as if it has requested
2866     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2867     * allows it to avoid artifacts when switching in and out of that mode, at
2868     * the expense that some of its user interface may be covered by screen
2869     * decorations when they are shown.  You can perform layout of your inner
2870     * UI elements to account for non-fullscreen system UI through the
2871     * {@link #fitSystemWindows(Rect)} method.
2872     */
2873    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2874
2875    /**
2876     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2877     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2878     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2879     * user interaction.
2880     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2881     * has an effect when used in combination with that flag.</p>
2882     */
2883    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2884
2885    /**
2886     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2887     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2888     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2889     * experience while also hiding the system bars.  If this flag is not set,
2890     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2891     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2892     * if the user swipes from the top of the screen.
2893     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2894     * system gestures, such as swiping from the top of the screen.  These transient system bars
2895     * will overlay app’s content, may have some degree of transparency, and will automatically
2896     * hide after a short timeout.
2897     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2898     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2899     * with one or both of those flags.</p>
2900     */
2901    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2902
2903    /**
2904     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2905     * is compatible with light status bar backgrounds.
2906     *
2907     * <p>For this to take effect, the window must request
2908     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2909     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2910     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2911     *         FLAG_TRANSLUCENT_STATUS}.
2912     *
2913     * @see android.R.attr#windowLightStatusBar
2914     */
2915    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2916
2917    /**
2918     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2919     */
2920    @Deprecated
2921    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2922
2923    /**
2924     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2925     */
2926    @Deprecated
2927    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2928
2929    /**
2930     * @hide
2931     *
2932     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2933     * out of the public fields to keep the undefined bits out of the developer's way.
2934     *
2935     * Flag to make the status bar not expandable.  Unless you also
2936     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2937     */
2938    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2939
2940    /**
2941     * @hide
2942     *
2943     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2944     * out of the public fields to keep the undefined bits out of the developer's way.
2945     *
2946     * Flag to hide notification icons and scrolling ticker text.
2947     */
2948    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2949
2950    /**
2951     * @hide
2952     *
2953     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2954     * out of the public fields to keep the undefined bits out of the developer's way.
2955     *
2956     * Flag to disable incoming notification alerts.  This will not block
2957     * icons, but it will block sound, vibrating and other visual or aural notifications.
2958     */
2959    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2960
2961    /**
2962     * @hide
2963     *
2964     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2965     * out of the public fields to keep the undefined bits out of the developer's way.
2966     *
2967     * Flag to hide only the scrolling ticker.  Note that
2968     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2969     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2970     */
2971    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2972
2973    /**
2974     * @hide
2975     *
2976     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2977     * out of the public fields to keep the undefined bits out of the developer's way.
2978     *
2979     * Flag to hide the center system info area.
2980     */
2981    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2982
2983    /**
2984     * @hide
2985     *
2986     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2987     * out of the public fields to keep the undefined bits out of the developer's way.
2988     *
2989     * Flag to hide only the home button.  Don't use this
2990     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2991     */
2992    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2993
2994    /**
2995     * @hide
2996     *
2997     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2998     * out of the public fields to keep the undefined bits out of the developer's way.
2999     *
3000     * Flag to hide only the back button. Don't use this
3001     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3002     */
3003    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3004
3005    /**
3006     * @hide
3007     *
3008     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3009     * out of the public fields to keep the undefined bits out of the developer's way.
3010     *
3011     * Flag to hide only the clock.  You might use this if your activity has
3012     * its own clock making the status bar's clock redundant.
3013     */
3014    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3015
3016    /**
3017     * @hide
3018     *
3019     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3020     * out of the public fields to keep the undefined bits out of the developer's way.
3021     *
3022     * Flag to hide only the recent apps button. Don't use this
3023     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3024     */
3025    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3026
3027    /**
3028     * @hide
3029     *
3030     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3031     * out of the public fields to keep the undefined bits out of the developer's way.
3032     *
3033     * Flag to disable the global search gesture. Don't use this
3034     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3035     */
3036    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3037
3038    /**
3039     * @hide
3040     *
3041     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3042     * out of the public fields to keep the undefined bits out of the developer's way.
3043     *
3044     * Flag to specify that the status bar is displayed in transient mode.
3045     */
3046    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3047
3048    /**
3049     * @hide
3050     *
3051     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3052     * out of the public fields to keep the undefined bits out of the developer's way.
3053     *
3054     * Flag to specify that the navigation bar is displayed in transient mode.
3055     */
3056    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3057
3058    /**
3059     * @hide
3060     *
3061     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3062     * out of the public fields to keep the undefined bits out of the developer's way.
3063     *
3064     * Flag to specify that the hidden status bar would like to be shown.
3065     */
3066    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3067
3068    /**
3069     * @hide
3070     *
3071     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3072     * out of the public fields to keep the undefined bits out of the developer's way.
3073     *
3074     * Flag to specify that the hidden navigation bar would like to be shown.
3075     */
3076    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3077
3078    /**
3079     * @hide
3080     *
3081     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3082     * out of the public fields to keep the undefined bits out of the developer's way.
3083     *
3084     * Flag to specify that the status bar is displayed in translucent mode.
3085     */
3086    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3087
3088    /**
3089     * @hide
3090     *
3091     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3092     * out of the public fields to keep the undefined bits out of the developer's way.
3093     *
3094     * Flag to specify that the navigation bar is displayed in translucent mode.
3095     */
3096    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3097
3098    /**
3099     * @hide
3100     *
3101     * Makes navigation bar transparent (but not the status bar).
3102     */
3103    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3104
3105    /**
3106     * @hide
3107     *
3108     * Makes status bar transparent (but not the navigation bar).
3109     */
3110    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3111
3112    /**
3113     * @hide
3114     *
3115     * Makes both status bar and navigation bar transparent.
3116     */
3117    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3118            | STATUS_BAR_TRANSPARENT;
3119
3120    /**
3121     * @hide
3122     */
3123    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3124
3125    /**
3126     * These are the system UI flags that can be cleared by events outside
3127     * of an application.  Currently this is just the ability to tap on the
3128     * screen while hiding the navigation bar to have it return.
3129     * @hide
3130     */
3131    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3132            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3133            | SYSTEM_UI_FLAG_FULLSCREEN;
3134
3135    /**
3136     * Flags that can impact the layout in relation to system UI.
3137     */
3138    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3139            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3140            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3141
3142    /** @hide */
3143    @IntDef(flag = true,
3144            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3145    @Retention(RetentionPolicy.SOURCE)
3146    public @interface FindViewFlags {}
3147
3148    /**
3149     * Find views that render the specified text.
3150     *
3151     * @see #findViewsWithText(ArrayList, CharSequence, int)
3152     */
3153    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3154
3155    /**
3156     * Find find views that contain the specified content description.
3157     *
3158     * @see #findViewsWithText(ArrayList, CharSequence, int)
3159     */
3160    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3161
3162    /**
3163     * Find views that contain {@link AccessibilityNodeProvider}. Such
3164     * a View is a root of virtual view hierarchy and may contain the searched
3165     * text. If this flag is set Views with providers are automatically
3166     * added and it is a responsibility of the client to call the APIs of
3167     * the provider to determine whether the virtual tree rooted at this View
3168     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3169     * representing the virtual views with this text.
3170     *
3171     * @see #findViewsWithText(ArrayList, CharSequence, int)
3172     *
3173     * @hide
3174     */
3175    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3176
3177    /**
3178     * The undefined cursor position.
3179     *
3180     * @hide
3181     */
3182    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3183
3184    /**
3185     * Indicates that the screen has changed state and is now off.
3186     *
3187     * @see #onScreenStateChanged(int)
3188     */
3189    public static final int SCREEN_STATE_OFF = 0x0;
3190
3191    /**
3192     * Indicates that the screen has changed state and is now on.
3193     *
3194     * @see #onScreenStateChanged(int)
3195     */
3196    public static final int SCREEN_STATE_ON = 0x1;
3197
3198    /**
3199     * Indicates no axis of view scrolling.
3200     */
3201    public static final int SCROLL_AXIS_NONE = 0;
3202
3203    /**
3204     * Indicates scrolling along the horizontal axis.
3205     */
3206    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3207
3208    /**
3209     * Indicates scrolling along the vertical axis.
3210     */
3211    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3212
3213    /**
3214     * Controls the over-scroll mode for this view.
3215     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3216     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3217     * and {@link #OVER_SCROLL_NEVER}.
3218     */
3219    private int mOverScrollMode;
3220
3221    /**
3222     * The parent this view is attached to.
3223     * {@hide}
3224     *
3225     * @see #getParent()
3226     */
3227    protected ViewParent mParent;
3228
3229    /**
3230     * {@hide}
3231     */
3232    AttachInfo mAttachInfo;
3233
3234    /**
3235     * {@hide}
3236     */
3237    @ViewDebug.ExportedProperty(flagMapping = {
3238        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3239                name = "FORCE_LAYOUT"),
3240        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3241                name = "LAYOUT_REQUIRED"),
3242        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3243            name = "DRAWING_CACHE_INVALID", outputIf = false),
3244        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3245        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3246        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3247        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3248    }, formatToHexString = true)
3249    int mPrivateFlags;
3250    int mPrivateFlags2;
3251    int mPrivateFlags3;
3252
3253    /**
3254     * This view's request for the visibility of the status bar.
3255     * @hide
3256     */
3257    @ViewDebug.ExportedProperty(flagMapping = {
3258        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3259                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3260                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3261        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3262                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3263                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3264        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3265                                equals = SYSTEM_UI_FLAG_VISIBLE,
3266                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3267    }, formatToHexString = true)
3268    int mSystemUiVisibility;
3269
3270    /**
3271     * Reference count for transient state.
3272     * @see #setHasTransientState(boolean)
3273     */
3274    int mTransientStateCount = 0;
3275
3276    /**
3277     * Count of how many windows this view has been attached to.
3278     */
3279    int mWindowAttachCount;
3280
3281    /**
3282     * The layout parameters associated with this view and used by the parent
3283     * {@link android.view.ViewGroup} to determine how this view should be
3284     * laid out.
3285     * {@hide}
3286     */
3287    protected ViewGroup.LayoutParams mLayoutParams;
3288
3289    /**
3290     * The view flags hold various views states.
3291     * {@hide}
3292     */
3293    @ViewDebug.ExportedProperty(formatToHexString = true)
3294    int mViewFlags;
3295
3296    static class TransformationInfo {
3297        /**
3298         * The transform matrix for the View. This transform is calculated internally
3299         * based on the translation, rotation, and scale properties.
3300         *
3301         * Do *not* use this variable directly; instead call getMatrix(), which will
3302         * load the value from the View's RenderNode.
3303         */
3304        private final Matrix mMatrix = new Matrix();
3305
3306        /**
3307         * The inverse transform matrix for the View. This transform is calculated
3308         * internally based on the translation, rotation, and scale properties.
3309         *
3310         * Do *not* use this variable directly; instead call getInverseMatrix(),
3311         * which will load the value from the View's RenderNode.
3312         */
3313        private Matrix mInverseMatrix;
3314
3315        /**
3316         * The opacity of the View. This is a value from 0 to 1, where 0 means
3317         * completely transparent and 1 means completely opaque.
3318         */
3319        @ViewDebug.ExportedProperty
3320        float mAlpha = 1f;
3321
3322        /**
3323         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3324         * property only used by transitions, which is composited with the other alpha
3325         * values to calculate the final visual alpha value.
3326         */
3327        float mTransitionAlpha = 1f;
3328    }
3329
3330    TransformationInfo mTransformationInfo;
3331
3332    /**
3333     * Current clip bounds. to which all drawing of this view are constrained.
3334     */
3335    Rect mClipBounds = null;
3336
3337    private boolean mLastIsOpaque;
3338
3339    /**
3340     * The distance in pixels from the left edge of this view's parent
3341     * to the left edge of this view.
3342     * {@hide}
3343     */
3344    @ViewDebug.ExportedProperty(category = "layout")
3345    protected int mLeft;
3346    /**
3347     * The distance in pixels from the left edge of this view's parent
3348     * to the right edge of this view.
3349     * {@hide}
3350     */
3351    @ViewDebug.ExportedProperty(category = "layout")
3352    protected int mRight;
3353    /**
3354     * The distance in pixels from the top edge of this view's parent
3355     * to the top edge of this view.
3356     * {@hide}
3357     */
3358    @ViewDebug.ExportedProperty(category = "layout")
3359    protected int mTop;
3360    /**
3361     * The distance in pixels from the top edge of this view's parent
3362     * to the bottom edge of this view.
3363     * {@hide}
3364     */
3365    @ViewDebug.ExportedProperty(category = "layout")
3366    protected int mBottom;
3367
3368    /**
3369     * The offset, in pixels, by which the content of this view is scrolled
3370     * horizontally.
3371     * {@hide}
3372     */
3373    @ViewDebug.ExportedProperty(category = "scrolling")
3374    protected int mScrollX;
3375    /**
3376     * The offset, in pixels, by which the content of this view is scrolled
3377     * vertically.
3378     * {@hide}
3379     */
3380    @ViewDebug.ExportedProperty(category = "scrolling")
3381    protected int mScrollY;
3382
3383    /**
3384     * The left padding in pixels, that is the distance in pixels between the
3385     * left edge of this view and the left edge of its content.
3386     * {@hide}
3387     */
3388    @ViewDebug.ExportedProperty(category = "padding")
3389    protected int mPaddingLeft = 0;
3390    /**
3391     * The right padding in pixels, that is the distance in pixels between the
3392     * right edge of this view and the right edge of its content.
3393     * {@hide}
3394     */
3395    @ViewDebug.ExportedProperty(category = "padding")
3396    protected int mPaddingRight = 0;
3397    /**
3398     * The top padding in pixels, that is the distance in pixels between the
3399     * top edge of this view and the top edge of its content.
3400     * {@hide}
3401     */
3402    @ViewDebug.ExportedProperty(category = "padding")
3403    protected int mPaddingTop;
3404    /**
3405     * The bottom padding in pixels, that is the distance in pixels between the
3406     * bottom edge of this view and the bottom edge of its content.
3407     * {@hide}
3408     */
3409    @ViewDebug.ExportedProperty(category = "padding")
3410    protected int mPaddingBottom;
3411
3412    /**
3413     * The layout insets in pixels, that is the distance in pixels between the
3414     * visible edges of this view its bounds.
3415     */
3416    private Insets mLayoutInsets;
3417
3418    /**
3419     * Briefly describes the view and is primarily used for accessibility support.
3420     */
3421    private CharSequence mContentDescription;
3422
3423    /**
3424     * Specifies the id of a view for which this view serves as a label for
3425     * accessibility purposes.
3426     */
3427    private int mLabelForId = View.NO_ID;
3428
3429    /**
3430     * Predicate for matching labeled view id with its label for
3431     * accessibility purposes.
3432     */
3433    private MatchLabelForPredicate mMatchLabelForPredicate;
3434
3435    /**
3436     * Specifies a view before which this one is visited in accessibility traversal.
3437     */
3438    private int mAccessibilityTraversalBeforeId = NO_ID;
3439
3440    /**
3441     * Specifies a view after which this one is visited in accessibility traversal.
3442     */
3443    private int mAccessibilityTraversalAfterId = NO_ID;
3444
3445    /**
3446     * Predicate for matching a view by its id.
3447     */
3448    private MatchIdPredicate mMatchIdPredicate;
3449
3450    /**
3451     * Cache the paddingRight set by the user to append to the scrollbar's size.
3452     *
3453     * @hide
3454     */
3455    @ViewDebug.ExportedProperty(category = "padding")
3456    protected int mUserPaddingRight;
3457
3458    /**
3459     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3460     *
3461     * @hide
3462     */
3463    @ViewDebug.ExportedProperty(category = "padding")
3464    protected int mUserPaddingBottom;
3465
3466    /**
3467     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3468     *
3469     * @hide
3470     */
3471    @ViewDebug.ExportedProperty(category = "padding")
3472    protected int mUserPaddingLeft;
3473
3474    /**
3475     * Cache the paddingStart set by the user to append to the scrollbar's size.
3476     *
3477     */
3478    @ViewDebug.ExportedProperty(category = "padding")
3479    int mUserPaddingStart;
3480
3481    /**
3482     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3483     *
3484     */
3485    @ViewDebug.ExportedProperty(category = "padding")
3486    int mUserPaddingEnd;
3487
3488    /**
3489     * Cache initial left padding.
3490     *
3491     * @hide
3492     */
3493    int mUserPaddingLeftInitial;
3494
3495    /**
3496     * Cache initial right padding.
3497     *
3498     * @hide
3499     */
3500    int mUserPaddingRightInitial;
3501
3502    /**
3503     * Default undefined padding
3504     */
3505    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3506
3507    /**
3508     * Cache if a left padding has been defined
3509     */
3510    private boolean mLeftPaddingDefined = false;
3511
3512    /**
3513     * Cache if a right padding has been defined
3514     */
3515    private boolean mRightPaddingDefined = false;
3516
3517    /**
3518     * @hide
3519     */
3520    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3521    /**
3522     * @hide
3523     */
3524    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3525
3526    private LongSparseLongArray mMeasureCache;
3527
3528    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3529    private Drawable mBackground;
3530    private TintInfo mBackgroundTint;
3531
3532    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3533    private ForegroundInfo mForegroundInfo;
3534
3535    private Drawable mScrollIndicatorDrawable;
3536
3537    /**
3538     * RenderNode used for backgrounds.
3539     * <p>
3540     * When non-null and valid, this is expected to contain an up-to-date copy
3541     * of the background drawable. It is cleared on temporary detach, and reset
3542     * on cleanup.
3543     */
3544    private RenderNode mBackgroundRenderNode;
3545
3546    private int mBackgroundResource;
3547    private boolean mBackgroundSizeChanged;
3548
3549    private String mTransitionName;
3550
3551    static class TintInfo {
3552        ColorStateList mTintList;
3553        PorterDuff.Mode mTintMode;
3554        boolean mHasTintMode;
3555        boolean mHasTintList;
3556    }
3557
3558    private static class ForegroundInfo {
3559        private Drawable mDrawable;
3560        private TintInfo mTintInfo;
3561        private int mGravity = Gravity.FILL;
3562        private boolean mInsidePadding = true;
3563        private boolean mBoundsChanged = true;
3564        private final Rect mSelfBounds = new Rect();
3565        private final Rect mOverlayBounds = new Rect();
3566    }
3567
3568    static class ListenerInfo {
3569        /**
3570         * Listener used to dispatch focus change events.
3571         * This field should be made private, so it is hidden from the SDK.
3572         * {@hide}
3573         */
3574        protected OnFocusChangeListener mOnFocusChangeListener;
3575
3576        /**
3577         * Listeners for layout change events.
3578         */
3579        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3580
3581        protected OnScrollChangeListener mOnScrollChangeListener;
3582
3583        /**
3584         * Listeners for attach events.
3585         */
3586        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3587
3588        /**
3589         * Listener used to dispatch click events.
3590         * This field should be made private, so it is hidden from the SDK.
3591         * {@hide}
3592         */
3593        public OnClickListener mOnClickListener;
3594
3595        /**
3596         * Listener used to dispatch long click events.
3597         * This field should be made private, so it is hidden from the SDK.
3598         * {@hide}
3599         */
3600        protected OnLongClickListener mOnLongClickListener;
3601
3602        /**
3603         * Listener used to dispatch context click events. This field should be made private, so it
3604         * is hidden from the SDK.
3605         * {@hide}
3606         */
3607        protected OnContextClickListener mOnContextClickListener;
3608
3609        /**
3610         * Listener used to build the context menu.
3611         * This field should be made private, so it is hidden from the SDK.
3612         * {@hide}
3613         */
3614        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3615
3616        private OnKeyListener mOnKeyListener;
3617
3618        private OnTouchListener mOnTouchListener;
3619
3620        private OnHoverListener mOnHoverListener;
3621
3622        private OnGenericMotionListener mOnGenericMotionListener;
3623
3624        private OnDragListener mOnDragListener;
3625
3626        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3627
3628        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3629    }
3630
3631    ListenerInfo mListenerInfo;
3632
3633    // Temporary values used to hold (x,y) coordinates when delegating from the
3634    // two-arg performLongClick() method to the legacy no-arg version.
3635    private float mLongClickX = Float.NaN;
3636    private float mLongClickY = Float.NaN;
3637
3638    /**
3639     * The application environment this view lives in.
3640     * This field should be made private, so it is hidden from the SDK.
3641     * {@hide}
3642     */
3643    @ViewDebug.ExportedProperty(deepExport = true)
3644    protected Context mContext;
3645
3646    private final Resources mResources;
3647
3648    private ScrollabilityCache mScrollCache;
3649
3650    private int[] mDrawableState = null;
3651
3652    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3653
3654    /**
3655     * Animator that automatically runs based on state changes.
3656     */
3657    private StateListAnimator mStateListAnimator;
3658
3659    /**
3660     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3661     * the user may specify which view to go to next.
3662     */
3663    private int mNextFocusLeftId = View.NO_ID;
3664
3665    /**
3666     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3667     * the user may specify which view to go to next.
3668     */
3669    private int mNextFocusRightId = View.NO_ID;
3670
3671    /**
3672     * When this view has focus and the next focus is {@link #FOCUS_UP},
3673     * the user may specify which view to go to next.
3674     */
3675    private int mNextFocusUpId = View.NO_ID;
3676
3677    /**
3678     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3679     * the user may specify which view to go to next.
3680     */
3681    private int mNextFocusDownId = View.NO_ID;
3682
3683    /**
3684     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3685     * the user may specify which view to go to next.
3686     */
3687    int mNextFocusForwardId = View.NO_ID;
3688
3689    private CheckForLongPress mPendingCheckForLongPress;
3690    private CheckForTap mPendingCheckForTap = null;
3691    private PerformClick mPerformClick;
3692    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3693
3694    private UnsetPressedState mUnsetPressedState;
3695
3696    /**
3697     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3698     * up event while a long press is invoked as soon as the long press duration is reached, so
3699     * a long press could be performed before the tap is checked, in which case the tap's action
3700     * should not be invoked.
3701     */
3702    private boolean mHasPerformedLongPress;
3703
3704    /**
3705     * Whether a context click button is currently pressed down. This is true when the stylus is
3706     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3707     * pressed. This is false once the button is released or if the stylus has been lifted.
3708     */
3709    private boolean mInContextButtonPress;
3710
3711    /**
3712     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3713     * true after a stylus button press has occured, when the next up event should not be recognized
3714     * as a tap.
3715     */
3716    private boolean mIgnoreNextUpEvent;
3717
3718    /**
3719     * The minimum height of the view. We'll try our best to have the height
3720     * of this view to at least this amount.
3721     */
3722    @ViewDebug.ExportedProperty(category = "measurement")
3723    private int mMinHeight;
3724
3725    /**
3726     * The minimum width of the view. We'll try our best to have the width
3727     * of this view to at least this amount.
3728     */
3729    @ViewDebug.ExportedProperty(category = "measurement")
3730    private int mMinWidth;
3731
3732    /**
3733     * The delegate to handle touch events that are physically in this view
3734     * but should be handled by another view.
3735     */
3736    private TouchDelegate mTouchDelegate = null;
3737
3738    /**
3739     * Solid color to use as a background when creating the drawing cache. Enables
3740     * the cache to use 16 bit bitmaps instead of 32 bit.
3741     */
3742    private int mDrawingCacheBackgroundColor = 0;
3743
3744    /**
3745     * Special tree observer used when mAttachInfo is null.
3746     */
3747    private ViewTreeObserver mFloatingTreeObserver;
3748
3749    /**
3750     * Cache the touch slop from the context that created the view.
3751     */
3752    private int mTouchSlop;
3753
3754    /**
3755     * Object that handles automatic animation of view properties.
3756     */
3757    private ViewPropertyAnimator mAnimator = null;
3758
3759    /**
3760     * List of registered FrameMetricsObservers.
3761     */
3762    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3763
3764    /**
3765     * Flag indicating that a drag can cross window boundaries.  When
3766     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3767     * with this flag set, all visible applications with targetSdkVersion >=
3768     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3769     * in the drag operation and receive the dragged content.
3770     *
3771     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3772     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3773     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3774     */
3775    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3776
3777    /**
3778     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3779     * request read access to the content URI(s) contained in the {@link ClipData} object.
3780     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3781     */
3782    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3783
3784    /**
3785     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3786     * request write access to the content URI(s) contained in the {@link ClipData} object.
3787     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3788     */
3789    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3790
3791    /**
3792     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3793     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3794     * reboots until explicitly revoked with
3795     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3796     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3797     */
3798    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3799            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3800
3801    /**
3802     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3803     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3804     * match against the original granted URI.
3805     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3806     */
3807    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3808            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3809
3810    /**
3811     * Flag indicating that the drag shadow will be opaque.  When
3812     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3813     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3814     */
3815    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3816
3817    /**
3818     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3819     */
3820    private float mVerticalScrollFactor;
3821
3822    /**
3823     * Position of the vertical scroll bar.
3824     */
3825    private int mVerticalScrollbarPosition;
3826
3827    /**
3828     * Position the scroll bar at the default position as determined by the system.
3829     */
3830    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3831
3832    /**
3833     * Position the scroll bar along the left edge.
3834     */
3835    public static final int SCROLLBAR_POSITION_LEFT = 1;
3836
3837    /**
3838     * Position the scroll bar along the right edge.
3839     */
3840    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3841
3842    /**
3843     * Indicates that the view does not have a layer.
3844     *
3845     * @see #getLayerType()
3846     * @see #setLayerType(int, android.graphics.Paint)
3847     * @see #LAYER_TYPE_SOFTWARE
3848     * @see #LAYER_TYPE_HARDWARE
3849     */
3850    public static final int LAYER_TYPE_NONE = 0;
3851
3852    /**
3853     * <p>Indicates that the view has a software layer. A software layer is backed
3854     * by a bitmap and causes the view to be rendered using Android's software
3855     * rendering pipeline, even if hardware acceleration is enabled.</p>
3856     *
3857     * <p>Software layers have various usages:</p>
3858     * <p>When the application is not using hardware acceleration, a software layer
3859     * is useful to apply a specific color filter and/or blending mode and/or
3860     * translucency to a view and all its children.</p>
3861     * <p>When the application is using hardware acceleration, a software layer
3862     * is useful to render drawing primitives not supported by the hardware
3863     * accelerated pipeline. It can also be used to cache a complex view tree
3864     * into a texture and reduce the complexity of drawing operations. For instance,
3865     * when animating a complex view tree with a translation, a software layer can
3866     * be used to render the view tree only once.</p>
3867     * <p>Software layers should be avoided when the affected view tree updates
3868     * often. Every update will require to re-render the software layer, which can
3869     * potentially be slow (particularly when hardware acceleration is turned on
3870     * since the layer will have to be uploaded into a hardware texture after every
3871     * update.)</p>
3872     *
3873     * @see #getLayerType()
3874     * @see #setLayerType(int, android.graphics.Paint)
3875     * @see #LAYER_TYPE_NONE
3876     * @see #LAYER_TYPE_HARDWARE
3877     */
3878    public static final int LAYER_TYPE_SOFTWARE = 1;
3879
3880    /**
3881     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3882     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3883     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3884     * rendering pipeline, but only if hardware acceleration is turned on for the
3885     * view hierarchy. When hardware acceleration is turned off, hardware layers
3886     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3887     *
3888     * <p>A hardware layer is useful to apply a specific color filter and/or
3889     * blending mode and/or translucency to a view and all its children.</p>
3890     * <p>A hardware layer can be used to cache a complex view tree into a
3891     * texture and reduce the complexity of drawing operations. For instance,
3892     * when animating a complex view tree with a translation, a hardware layer can
3893     * be used to render the view tree only once.</p>
3894     * <p>A hardware layer can also be used to increase the rendering quality when
3895     * rotation transformations are applied on a view. It can also be used to
3896     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3897     *
3898     * @see #getLayerType()
3899     * @see #setLayerType(int, android.graphics.Paint)
3900     * @see #LAYER_TYPE_NONE
3901     * @see #LAYER_TYPE_SOFTWARE
3902     */
3903    public static final int LAYER_TYPE_HARDWARE = 2;
3904
3905    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3906            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3907            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3908            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3909    })
3910    int mLayerType = LAYER_TYPE_NONE;
3911    Paint mLayerPaint;
3912
3913    /**
3914     * Set to true when drawing cache is enabled and cannot be created.
3915     *
3916     * @hide
3917     */
3918    public boolean mCachingFailed;
3919    private Bitmap mDrawingCache;
3920    private Bitmap mUnscaledDrawingCache;
3921
3922    /**
3923     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3924     * <p>
3925     * When non-null and valid, this is expected to contain an up-to-date copy
3926     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3927     * cleanup.
3928     */
3929    final RenderNode mRenderNode;
3930
3931    /**
3932     * Set to true when the view is sending hover accessibility events because it
3933     * is the innermost hovered view.
3934     */
3935    private boolean mSendingHoverAccessibilityEvents;
3936
3937    /**
3938     * Delegate for injecting accessibility functionality.
3939     */
3940    AccessibilityDelegate mAccessibilityDelegate;
3941
3942    /**
3943     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3944     * and add/remove objects to/from the overlay directly through the Overlay methods.
3945     */
3946    ViewOverlay mOverlay;
3947
3948    /**
3949     * The currently active parent view for receiving delegated nested scrolling events.
3950     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3951     * by {@link #stopNestedScroll()} at the same point where we clear
3952     * requestDisallowInterceptTouchEvent.
3953     */
3954    private ViewParent mNestedScrollingParent;
3955
3956    /**
3957     * Consistency verifier for debugging purposes.
3958     * @hide
3959     */
3960    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3961            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3962                    new InputEventConsistencyVerifier(this, 0) : null;
3963
3964    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3965
3966    private int[] mTempNestedScrollConsumed;
3967
3968    /**
3969     * An overlay is going to draw this View instead of being drawn as part of this
3970     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3971     * when this view is invalidated.
3972     */
3973    GhostView mGhostView;
3974
3975    /**
3976     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3977     * @hide
3978     */
3979    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3980    public String[] mAttributes;
3981
3982    /**
3983     * Maps a Resource id to its name.
3984     */
3985    private static SparseArray<String> mAttributeMap;
3986
3987    /**
3988     * Queue of pending runnables. Used to postpone calls to post() until this
3989     * view is attached and has a handler.
3990     */
3991    private HandlerActionQueue mRunQueue;
3992
3993    /**
3994     * The pointer icon when the mouse hovers on this view. The default is null.
3995     */
3996    private PointerIcon mPointerIcon;
3997
3998    /**
3999     * @hide
4000     */
4001    String mStartActivityRequestWho;
4002
4003    @Nullable
4004    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4005
4006    /**
4007     * Simple constructor to use when creating a view from code.
4008     *
4009     * @param context The Context the view is running in, through which it can
4010     *        access the current theme, resources, etc.
4011     */
4012    public View(Context context) {
4013        mContext = context;
4014        mResources = context != null ? context.getResources() : null;
4015        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
4016        // Set some flags defaults
4017        mPrivateFlags2 =
4018                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4019                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4020                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4021                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4022                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4023                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4024        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4025        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4026        mUserPaddingStart = UNDEFINED_PADDING;
4027        mUserPaddingEnd = UNDEFINED_PADDING;
4028        mRenderNode = RenderNode.create(getClass().getName(), this);
4029
4030        if (!sCompatibilityDone && context != null) {
4031            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4032
4033            // Older apps may need this compatibility hack for measurement.
4034            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4035
4036            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4037            // of whether a layout was requested on that View.
4038            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4039
4040            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4041
4042            // In M and newer, our widgets can pass a "hint" value in the size
4043            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4044            // know what the expected parent size is going to be, so e.g. list items can size
4045            // themselves at 1/3 the size of their container. It breaks older apps though,
4046            // specifically apps that use some popular open source libraries.
4047            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4048
4049            // Old versions of the platform would give different results from
4050            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4051            // modes, so we always need to run an additional EXACTLY pass.
4052            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4053
4054            // Prior to N, layout params could change without requiring a
4055            // subsequent call to setLayoutParams() and they would usually
4056            // work. Partial layout breaks this assumption.
4057            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4058
4059            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4060            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4061            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4062
4063            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4064            // in apps so we target check it to avoid breaking existing apps.
4065            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4066
4067            sCascadedDragDrop = targetSdkVersion < N;
4068
4069            sCompatibilityDone = true;
4070        }
4071    }
4072
4073    /**
4074     * Constructor that is called when inflating a view from XML. This is called
4075     * when a view is being constructed from an XML file, supplying attributes
4076     * that were specified in the XML file. This version uses a default style of
4077     * 0, so the only attribute values applied are those in the Context's Theme
4078     * and the given AttributeSet.
4079     *
4080     * <p>
4081     * The method onFinishInflate() will be called after all children have been
4082     * added.
4083     *
4084     * @param context The Context the view is running in, through which it can
4085     *        access the current theme, resources, etc.
4086     * @param attrs The attributes of the XML tag that is inflating the view.
4087     * @see #View(Context, AttributeSet, int)
4088     */
4089    public View(Context context, @Nullable AttributeSet attrs) {
4090        this(context, attrs, 0);
4091    }
4092
4093    /**
4094     * Perform inflation from XML and apply a class-specific base style from a
4095     * theme attribute. This constructor of View allows subclasses to use their
4096     * own base style when they are inflating. For example, a Button class's
4097     * constructor would call this version of the super class constructor and
4098     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4099     * allows the theme's button style to modify all of the base view attributes
4100     * (in particular its background) as well as the Button class's attributes.
4101     *
4102     * @param context The Context the view is running in, through which it can
4103     *        access the current theme, resources, etc.
4104     * @param attrs The attributes of the XML tag that is inflating the view.
4105     * @param defStyleAttr An attribute in the current theme that contains a
4106     *        reference to a style resource that supplies default values for
4107     *        the view. Can be 0 to not look for defaults.
4108     * @see #View(Context, AttributeSet)
4109     */
4110    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4111        this(context, attrs, defStyleAttr, 0);
4112    }
4113
4114    /**
4115     * Perform inflation from XML and apply a class-specific base style from a
4116     * theme attribute or style resource. This constructor of View allows
4117     * subclasses to use their own base style when they are inflating.
4118     * <p>
4119     * When determining the final value of a particular attribute, there are
4120     * four inputs that come into play:
4121     * <ol>
4122     * <li>Any attribute values in the given AttributeSet.
4123     * <li>The style resource specified in the AttributeSet (named "style").
4124     * <li>The default style specified by <var>defStyleAttr</var>.
4125     * <li>The default style specified by <var>defStyleRes</var>.
4126     * <li>The base values in this theme.
4127     * </ol>
4128     * <p>
4129     * Each of these inputs is considered in-order, with the first listed taking
4130     * precedence over the following ones. In other words, if in the
4131     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4132     * , then the button's text will <em>always</em> be black, regardless of
4133     * what is specified in any of the styles.
4134     *
4135     * @param context The Context the view is running in, through which it can
4136     *        access the current theme, resources, etc.
4137     * @param attrs The attributes of the XML tag that is inflating the view.
4138     * @param defStyleAttr An attribute in the current theme that contains a
4139     *        reference to a style resource that supplies default values for
4140     *        the view. Can be 0 to not look for defaults.
4141     * @param defStyleRes A resource identifier of a style resource that
4142     *        supplies default values for the view, used only if
4143     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4144     *        to not look for defaults.
4145     * @see #View(Context, AttributeSet, int)
4146     */
4147    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4148        this(context);
4149
4150        final TypedArray a = context.obtainStyledAttributes(
4151                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4152
4153        if (mDebugViewAttributes) {
4154            saveAttributeData(attrs, a);
4155        }
4156
4157        Drawable background = null;
4158
4159        int leftPadding = -1;
4160        int topPadding = -1;
4161        int rightPadding = -1;
4162        int bottomPadding = -1;
4163        int startPadding = UNDEFINED_PADDING;
4164        int endPadding = UNDEFINED_PADDING;
4165
4166        int padding = -1;
4167
4168        int viewFlagValues = 0;
4169        int viewFlagMasks = 0;
4170
4171        boolean setScrollContainer = false;
4172
4173        int x = 0;
4174        int y = 0;
4175
4176        float tx = 0;
4177        float ty = 0;
4178        float tz = 0;
4179        float elevation = 0;
4180        float rotation = 0;
4181        float rotationX = 0;
4182        float rotationY = 0;
4183        float sx = 1f;
4184        float sy = 1f;
4185        boolean transformSet = false;
4186
4187        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4188        int overScrollMode = mOverScrollMode;
4189        boolean initializeScrollbars = false;
4190        boolean initializeScrollIndicators = false;
4191
4192        boolean startPaddingDefined = false;
4193        boolean endPaddingDefined = false;
4194        boolean leftPaddingDefined = false;
4195        boolean rightPaddingDefined = false;
4196
4197        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4198
4199        final int N = a.getIndexCount();
4200        for (int i = 0; i < N; i++) {
4201            int attr = a.getIndex(i);
4202            switch (attr) {
4203                case com.android.internal.R.styleable.View_background:
4204                    background = a.getDrawable(attr);
4205                    break;
4206                case com.android.internal.R.styleable.View_padding:
4207                    padding = a.getDimensionPixelSize(attr, -1);
4208                    mUserPaddingLeftInitial = padding;
4209                    mUserPaddingRightInitial = padding;
4210                    leftPaddingDefined = true;
4211                    rightPaddingDefined = true;
4212                    break;
4213                 case com.android.internal.R.styleable.View_paddingLeft:
4214                    leftPadding = a.getDimensionPixelSize(attr, -1);
4215                    mUserPaddingLeftInitial = leftPadding;
4216                    leftPaddingDefined = true;
4217                    break;
4218                case com.android.internal.R.styleable.View_paddingTop:
4219                    topPadding = a.getDimensionPixelSize(attr, -1);
4220                    break;
4221                case com.android.internal.R.styleable.View_paddingRight:
4222                    rightPadding = a.getDimensionPixelSize(attr, -1);
4223                    mUserPaddingRightInitial = rightPadding;
4224                    rightPaddingDefined = true;
4225                    break;
4226                case com.android.internal.R.styleable.View_paddingBottom:
4227                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4228                    break;
4229                case com.android.internal.R.styleable.View_paddingStart:
4230                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4231                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4232                    break;
4233                case com.android.internal.R.styleable.View_paddingEnd:
4234                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4235                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4236                    break;
4237                case com.android.internal.R.styleable.View_scrollX:
4238                    x = a.getDimensionPixelOffset(attr, 0);
4239                    break;
4240                case com.android.internal.R.styleable.View_scrollY:
4241                    y = a.getDimensionPixelOffset(attr, 0);
4242                    break;
4243                case com.android.internal.R.styleable.View_alpha:
4244                    setAlpha(a.getFloat(attr, 1f));
4245                    break;
4246                case com.android.internal.R.styleable.View_transformPivotX:
4247                    setPivotX(a.getDimension(attr, 0));
4248                    break;
4249                case com.android.internal.R.styleable.View_transformPivotY:
4250                    setPivotY(a.getDimension(attr, 0));
4251                    break;
4252                case com.android.internal.R.styleable.View_translationX:
4253                    tx = a.getDimension(attr, 0);
4254                    transformSet = true;
4255                    break;
4256                case com.android.internal.R.styleable.View_translationY:
4257                    ty = a.getDimension(attr, 0);
4258                    transformSet = true;
4259                    break;
4260                case com.android.internal.R.styleable.View_translationZ:
4261                    tz = a.getDimension(attr, 0);
4262                    transformSet = true;
4263                    break;
4264                case com.android.internal.R.styleable.View_elevation:
4265                    elevation = a.getDimension(attr, 0);
4266                    transformSet = true;
4267                    break;
4268                case com.android.internal.R.styleable.View_rotation:
4269                    rotation = a.getFloat(attr, 0);
4270                    transformSet = true;
4271                    break;
4272                case com.android.internal.R.styleable.View_rotationX:
4273                    rotationX = a.getFloat(attr, 0);
4274                    transformSet = true;
4275                    break;
4276                case com.android.internal.R.styleable.View_rotationY:
4277                    rotationY = a.getFloat(attr, 0);
4278                    transformSet = true;
4279                    break;
4280                case com.android.internal.R.styleable.View_scaleX:
4281                    sx = a.getFloat(attr, 1f);
4282                    transformSet = true;
4283                    break;
4284                case com.android.internal.R.styleable.View_scaleY:
4285                    sy = a.getFloat(attr, 1f);
4286                    transformSet = true;
4287                    break;
4288                case com.android.internal.R.styleable.View_id:
4289                    mID = a.getResourceId(attr, NO_ID);
4290                    break;
4291                case com.android.internal.R.styleable.View_tag:
4292                    mTag = a.getText(attr);
4293                    break;
4294                case com.android.internal.R.styleable.View_fitsSystemWindows:
4295                    if (a.getBoolean(attr, false)) {
4296                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4297                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4298                    }
4299                    break;
4300                case com.android.internal.R.styleable.View_focusable:
4301                    if (a.getBoolean(attr, false)) {
4302                        viewFlagValues |= FOCUSABLE;
4303                        viewFlagMasks |= FOCUSABLE_MASK;
4304                    }
4305                    break;
4306                case com.android.internal.R.styleable.View_focusableInTouchMode:
4307                    if (a.getBoolean(attr, false)) {
4308                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4309                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4310                    }
4311                    break;
4312                case com.android.internal.R.styleable.View_clickable:
4313                    if (a.getBoolean(attr, false)) {
4314                        viewFlagValues |= CLICKABLE;
4315                        viewFlagMasks |= CLICKABLE;
4316                    }
4317                    break;
4318                case com.android.internal.R.styleable.View_longClickable:
4319                    if (a.getBoolean(attr, false)) {
4320                        viewFlagValues |= LONG_CLICKABLE;
4321                        viewFlagMasks |= LONG_CLICKABLE;
4322                    }
4323                    break;
4324                case com.android.internal.R.styleable.View_contextClickable:
4325                    if (a.getBoolean(attr, false)) {
4326                        viewFlagValues |= CONTEXT_CLICKABLE;
4327                        viewFlagMasks |= CONTEXT_CLICKABLE;
4328                    }
4329                    break;
4330                case com.android.internal.R.styleable.View_saveEnabled:
4331                    if (!a.getBoolean(attr, true)) {
4332                        viewFlagValues |= SAVE_DISABLED;
4333                        viewFlagMasks |= SAVE_DISABLED_MASK;
4334                    }
4335                    break;
4336                case com.android.internal.R.styleable.View_duplicateParentState:
4337                    if (a.getBoolean(attr, false)) {
4338                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4339                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4340                    }
4341                    break;
4342                case com.android.internal.R.styleable.View_visibility:
4343                    final int visibility = a.getInt(attr, 0);
4344                    if (visibility != 0) {
4345                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4346                        viewFlagMasks |= VISIBILITY_MASK;
4347                    }
4348                    break;
4349                case com.android.internal.R.styleable.View_layoutDirection:
4350                    // Clear any layout direction flags (included resolved bits) already set
4351                    mPrivateFlags2 &=
4352                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4353                    // Set the layout direction flags depending on the value of the attribute
4354                    final int layoutDirection = a.getInt(attr, -1);
4355                    final int value = (layoutDirection != -1) ?
4356                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4357                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4358                    break;
4359                case com.android.internal.R.styleable.View_drawingCacheQuality:
4360                    final int cacheQuality = a.getInt(attr, 0);
4361                    if (cacheQuality != 0) {
4362                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4363                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4364                    }
4365                    break;
4366                case com.android.internal.R.styleable.View_contentDescription:
4367                    setContentDescription(a.getString(attr));
4368                    break;
4369                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4370                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4371                    break;
4372                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4373                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4374                    break;
4375                case com.android.internal.R.styleable.View_labelFor:
4376                    setLabelFor(a.getResourceId(attr, NO_ID));
4377                    break;
4378                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4379                    if (!a.getBoolean(attr, true)) {
4380                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4381                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4382                    }
4383                    break;
4384                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4385                    if (!a.getBoolean(attr, true)) {
4386                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4387                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4388                    }
4389                    break;
4390                case R.styleable.View_scrollbars:
4391                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4392                    if (scrollbars != SCROLLBARS_NONE) {
4393                        viewFlagValues |= scrollbars;
4394                        viewFlagMasks |= SCROLLBARS_MASK;
4395                        initializeScrollbars = true;
4396                    }
4397                    break;
4398                //noinspection deprecation
4399                case R.styleable.View_fadingEdge:
4400                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4401                        // Ignore the attribute starting with ICS
4402                        break;
4403                    }
4404                    // With builds < ICS, fall through and apply fading edges
4405                case R.styleable.View_requiresFadingEdge:
4406                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4407                    if (fadingEdge != FADING_EDGE_NONE) {
4408                        viewFlagValues |= fadingEdge;
4409                        viewFlagMasks |= FADING_EDGE_MASK;
4410                        initializeFadingEdgeInternal(a);
4411                    }
4412                    break;
4413                case R.styleable.View_scrollbarStyle:
4414                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4415                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4416                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4417                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4418                    }
4419                    break;
4420                case R.styleable.View_isScrollContainer:
4421                    setScrollContainer = true;
4422                    if (a.getBoolean(attr, false)) {
4423                        setScrollContainer(true);
4424                    }
4425                    break;
4426                case com.android.internal.R.styleable.View_keepScreenOn:
4427                    if (a.getBoolean(attr, false)) {
4428                        viewFlagValues |= KEEP_SCREEN_ON;
4429                        viewFlagMasks |= KEEP_SCREEN_ON;
4430                    }
4431                    break;
4432                case R.styleable.View_filterTouchesWhenObscured:
4433                    if (a.getBoolean(attr, false)) {
4434                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4435                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4436                    }
4437                    break;
4438                case R.styleable.View_nextFocusLeft:
4439                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4440                    break;
4441                case R.styleable.View_nextFocusRight:
4442                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4443                    break;
4444                case R.styleable.View_nextFocusUp:
4445                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4446                    break;
4447                case R.styleable.View_nextFocusDown:
4448                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4449                    break;
4450                case R.styleable.View_nextFocusForward:
4451                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4452                    break;
4453                case R.styleable.View_minWidth:
4454                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4455                    break;
4456                case R.styleable.View_minHeight:
4457                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4458                    break;
4459                case R.styleable.View_onClick:
4460                    if (context.isRestricted()) {
4461                        throw new IllegalStateException("The android:onClick attribute cannot "
4462                                + "be used within a restricted context");
4463                    }
4464
4465                    final String handlerName = a.getString(attr);
4466                    if (handlerName != null) {
4467                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4468                    }
4469                    break;
4470                case R.styleable.View_overScrollMode:
4471                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4472                    break;
4473                case R.styleable.View_verticalScrollbarPosition:
4474                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4475                    break;
4476                case R.styleable.View_layerType:
4477                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4478                    break;
4479                case R.styleable.View_textDirection:
4480                    // Clear any text direction flag already set
4481                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4482                    // Set the text direction flags depending on the value of the attribute
4483                    final int textDirection = a.getInt(attr, -1);
4484                    if (textDirection != -1) {
4485                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4486                    }
4487                    break;
4488                case R.styleable.View_textAlignment:
4489                    // Clear any text alignment flag already set
4490                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4491                    // Set the text alignment flag depending on the value of the attribute
4492                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4493                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4494                    break;
4495                case R.styleable.View_importantForAccessibility:
4496                    setImportantForAccessibility(a.getInt(attr,
4497                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4498                    break;
4499                case R.styleable.View_accessibilityLiveRegion:
4500                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4501                    break;
4502                case R.styleable.View_transitionName:
4503                    setTransitionName(a.getString(attr));
4504                    break;
4505                case R.styleable.View_nestedScrollingEnabled:
4506                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4507                    break;
4508                case R.styleable.View_stateListAnimator:
4509                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4510                            a.getResourceId(attr, 0)));
4511                    break;
4512                case R.styleable.View_backgroundTint:
4513                    // This will get applied later during setBackground().
4514                    if (mBackgroundTint == null) {
4515                        mBackgroundTint = new TintInfo();
4516                    }
4517                    mBackgroundTint.mTintList = a.getColorStateList(
4518                            R.styleable.View_backgroundTint);
4519                    mBackgroundTint.mHasTintList = true;
4520                    break;
4521                case R.styleable.View_backgroundTintMode:
4522                    // This will get applied later during setBackground().
4523                    if (mBackgroundTint == null) {
4524                        mBackgroundTint = new TintInfo();
4525                    }
4526                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4527                            R.styleable.View_backgroundTintMode, -1), null);
4528                    mBackgroundTint.mHasTintMode = true;
4529                    break;
4530                case R.styleable.View_outlineProvider:
4531                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4532                            PROVIDER_BACKGROUND));
4533                    break;
4534                case R.styleable.View_foreground:
4535                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4536                        setForeground(a.getDrawable(attr));
4537                    }
4538                    break;
4539                case R.styleable.View_foregroundGravity:
4540                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4541                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4542                    }
4543                    break;
4544                case R.styleable.View_foregroundTintMode:
4545                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4546                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4547                    }
4548                    break;
4549                case R.styleable.View_foregroundTint:
4550                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4551                        setForegroundTintList(a.getColorStateList(attr));
4552                    }
4553                    break;
4554                case R.styleable.View_foregroundInsidePadding:
4555                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4556                        if (mForegroundInfo == null) {
4557                            mForegroundInfo = new ForegroundInfo();
4558                        }
4559                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4560                                mForegroundInfo.mInsidePadding);
4561                    }
4562                    break;
4563                case R.styleable.View_scrollIndicators:
4564                    final int scrollIndicators =
4565                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4566                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4567                    if (scrollIndicators != 0) {
4568                        mPrivateFlags3 |= scrollIndicators;
4569                        initializeScrollIndicators = true;
4570                    }
4571                    break;
4572                case R.styleable.View_pointerIcon:
4573                    final int resourceId = a.getResourceId(attr, 0);
4574                    if (resourceId != 0) {
4575                        setPointerIcon(PointerIcon.load(
4576                                context.getResources(), resourceId));
4577                    } else {
4578                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4579                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4580                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4581                        }
4582                    }
4583                    break;
4584                case R.styleable.View_forceHasOverlappingRendering:
4585                    if (a.peekValue(attr) != null) {
4586                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4587                    }
4588                    break;
4589
4590            }
4591        }
4592
4593        setOverScrollMode(overScrollMode);
4594
4595        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4596        // the resolved layout direction). Those cached values will be used later during padding
4597        // resolution.
4598        mUserPaddingStart = startPadding;
4599        mUserPaddingEnd = endPadding;
4600
4601        if (background != null) {
4602            setBackground(background);
4603        }
4604
4605        // setBackground above will record that padding is currently provided by the background.
4606        // If we have padding specified via xml, record that here instead and use it.
4607        mLeftPaddingDefined = leftPaddingDefined;
4608        mRightPaddingDefined = rightPaddingDefined;
4609
4610        if (padding >= 0) {
4611            leftPadding = padding;
4612            topPadding = padding;
4613            rightPadding = padding;
4614            bottomPadding = padding;
4615            mUserPaddingLeftInitial = padding;
4616            mUserPaddingRightInitial = padding;
4617        }
4618
4619        if (isRtlCompatibilityMode()) {
4620            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4621            // left / right padding are used if defined (meaning here nothing to do). If they are not
4622            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4623            // start / end and resolve them as left / right (layout direction is not taken into account).
4624            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4625            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4626            // defined.
4627            if (!mLeftPaddingDefined && startPaddingDefined) {
4628                leftPadding = startPadding;
4629            }
4630            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4631            if (!mRightPaddingDefined && endPaddingDefined) {
4632                rightPadding = endPadding;
4633            }
4634            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4635        } else {
4636            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4637            // values defined. Otherwise, left /right values are used.
4638            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4639            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4640            // defined.
4641            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4642
4643            if (mLeftPaddingDefined && !hasRelativePadding) {
4644                mUserPaddingLeftInitial = leftPadding;
4645            }
4646            if (mRightPaddingDefined && !hasRelativePadding) {
4647                mUserPaddingRightInitial = rightPadding;
4648            }
4649        }
4650
4651        internalSetPadding(
4652                mUserPaddingLeftInitial,
4653                topPadding >= 0 ? topPadding : mPaddingTop,
4654                mUserPaddingRightInitial,
4655                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4656
4657        if (viewFlagMasks != 0) {
4658            setFlags(viewFlagValues, viewFlagMasks);
4659        }
4660
4661        if (initializeScrollbars) {
4662            initializeScrollbarsInternal(a);
4663        }
4664
4665        if (initializeScrollIndicators) {
4666            initializeScrollIndicatorsInternal();
4667        }
4668
4669        a.recycle();
4670
4671        // Needs to be called after mViewFlags is set
4672        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4673            recomputePadding();
4674        }
4675
4676        if (x != 0 || y != 0) {
4677            scrollTo(x, y);
4678        }
4679
4680        if (transformSet) {
4681            setTranslationX(tx);
4682            setTranslationY(ty);
4683            setTranslationZ(tz);
4684            setElevation(elevation);
4685            setRotation(rotation);
4686            setRotationX(rotationX);
4687            setRotationY(rotationY);
4688            setScaleX(sx);
4689            setScaleY(sy);
4690        }
4691
4692        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4693            setScrollContainer(true);
4694        }
4695
4696        computeOpaqueFlags();
4697    }
4698
4699    /**
4700     * An implementation of OnClickListener that attempts to lazily load a
4701     * named click handling method from a parent or ancestor context.
4702     */
4703    private static class DeclaredOnClickListener implements OnClickListener {
4704        private final View mHostView;
4705        private final String mMethodName;
4706
4707        private Method mResolvedMethod;
4708        private Context mResolvedContext;
4709
4710        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4711            mHostView = hostView;
4712            mMethodName = methodName;
4713        }
4714
4715        @Override
4716        public void onClick(@NonNull View v) {
4717            if (mResolvedMethod == null) {
4718                resolveMethod(mHostView.getContext(), mMethodName);
4719            }
4720
4721            try {
4722                mResolvedMethod.invoke(mResolvedContext, v);
4723            } catch (IllegalAccessException e) {
4724                throw new IllegalStateException(
4725                        "Could not execute non-public method for android:onClick", e);
4726            } catch (InvocationTargetException e) {
4727                throw new IllegalStateException(
4728                        "Could not execute method for android:onClick", e);
4729            }
4730        }
4731
4732        @NonNull
4733        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4734            while (context != null) {
4735                try {
4736                    if (!context.isRestricted()) {
4737                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4738                        if (method != null) {
4739                            mResolvedMethod = method;
4740                            mResolvedContext = context;
4741                            return;
4742                        }
4743                    }
4744                } catch (NoSuchMethodException e) {
4745                    // Failed to find method, keep searching up the hierarchy.
4746                }
4747
4748                if (context instanceof ContextWrapper) {
4749                    context = ((ContextWrapper) context).getBaseContext();
4750                } else {
4751                    // Can't search up the hierarchy, null out and fail.
4752                    context = null;
4753                }
4754            }
4755
4756            final int id = mHostView.getId();
4757            final String idText = id == NO_ID ? "" : " with id '"
4758                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4759            throw new IllegalStateException("Could not find method " + mMethodName
4760                    + "(View) in a parent or ancestor Context for android:onClick "
4761                    + "attribute defined on view " + mHostView.getClass() + idText);
4762        }
4763    }
4764
4765    /**
4766     * Non-public constructor for use in testing
4767     */
4768    View() {
4769        mResources = null;
4770        mRenderNode = RenderNode.create(getClass().getName(), this);
4771    }
4772
4773    private static SparseArray<String> getAttributeMap() {
4774        if (mAttributeMap == null) {
4775            mAttributeMap = new SparseArray<>();
4776        }
4777        return mAttributeMap;
4778    }
4779
4780    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4781        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4782        final int indexCount = t.getIndexCount();
4783        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4784
4785        int i = 0;
4786
4787        // Store raw XML attributes.
4788        for (int j = 0; j < attrsCount; ++j) {
4789            attributes[i] = attrs.getAttributeName(j);
4790            attributes[i + 1] = attrs.getAttributeValue(j);
4791            i += 2;
4792        }
4793
4794        // Store resolved styleable attributes.
4795        final Resources res = t.getResources();
4796        final SparseArray<String> attributeMap = getAttributeMap();
4797        for (int j = 0; j < indexCount; ++j) {
4798            final int index = t.getIndex(j);
4799            if (!t.hasValueOrEmpty(index)) {
4800                // Value is undefined. Skip it.
4801                continue;
4802            }
4803
4804            final int resourceId = t.getResourceId(index, 0);
4805            if (resourceId == 0) {
4806                // Value is not a reference. Skip it.
4807                continue;
4808            }
4809
4810            String resourceName = attributeMap.get(resourceId);
4811            if (resourceName == null) {
4812                try {
4813                    resourceName = res.getResourceName(resourceId);
4814                } catch (Resources.NotFoundException e) {
4815                    resourceName = "0x" + Integer.toHexString(resourceId);
4816                }
4817                attributeMap.put(resourceId, resourceName);
4818            }
4819
4820            attributes[i] = resourceName;
4821            attributes[i + 1] = t.getString(index);
4822            i += 2;
4823        }
4824
4825        // Trim to fit contents.
4826        final String[] trimmed = new String[i];
4827        System.arraycopy(attributes, 0, trimmed, 0, i);
4828        mAttributes = trimmed;
4829    }
4830
4831    public String toString() {
4832        StringBuilder out = new StringBuilder(128);
4833        out.append(getClass().getName());
4834        out.append('{');
4835        out.append(Integer.toHexString(System.identityHashCode(this)));
4836        out.append(' ');
4837        switch (mViewFlags&VISIBILITY_MASK) {
4838            case VISIBLE: out.append('V'); break;
4839            case INVISIBLE: out.append('I'); break;
4840            case GONE: out.append('G'); break;
4841            default: out.append('.'); break;
4842        }
4843        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4844        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4845        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4846        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4847        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4848        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4849        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4850        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4851        out.append(' ');
4852        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4853        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4854        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4855        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4856            out.append('p');
4857        } else {
4858            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4859        }
4860        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4861        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4862        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4863        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4864        out.append(' ');
4865        out.append(mLeft);
4866        out.append(',');
4867        out.append(mTop);
4868        out.append('-');
4869        out.append(mRight);
4870        out.append(',');
4871        out.append(mBottom);
4872        final int id = getId();
4873        if (id != NO_ID) {
4874            out.append(" #");
4875            out.append(Integer.toHexString(id));
4876            final Resources r = mResources;
4877            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4878                try {
4879                    String pkgname;
4880                    switch (id&0xff000000) {
4881                        case 0x7f000000:
4882                            pkgname="app";
4883                            break;
4884                        case 0x01000000:
4885                            pkgname="android";
4886                            break;
4887                        default:
4888                            pkgname = r.getResourcePackageName(id);
4889                            break;
4890                    }
4891                    String typename = r.getResourceTypeName(id);
4892                    String entryname = r.getResourceEntryName(id);
4893                    out.append(" ");
4894                    out.append(pkgname);
4895                    out.append(":");
4896                    out.append(typename);
4897                    out.append("/");
4898                    out.append(entryname);
4899                } catch (Resources.NotFoundException e) {
4900                }
4901            }
4902        }
4903        out.append("}");
4904        return out.toString();
4905    }
4906
4907    /**
4908     * <p>
4909     * Initializes the fading edges from a given set of styled attributes. This
4910     * method should be called by subclasses that need fading edges and when an
4911     * instance of these subclasses is created programmatically rather than
4912     * being inflated from XML. This method is automatically called when the XML
4913     * is inflated.
4914     * </p>
4915     *
4916     * @param a the styled attributes set to initialize the fading edges from
4917     *
4918     * @removed
4919     */
4920    protected void initializeFadingEdge(TypedArray a) {
4921        // This method probably shouldn't have been included in the SDK to begin with.
4922        // It relies on 'a' having been initialized using an attribute filter array that is
4923        // not publicly available to the SDK. The old method has been renamed
4924        // to initializeFadingEdgeInternal and hidden for framework use only;
4925        // this one initializes using defaults to make it safe to call for apps.
4926
4927        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4928
4929        initializeFadingEdgeInternal(arr);
4930
4931        arr.recycle();
4932    }
4933
4934    /**
4935     * <p>
4936     * Initializes the fading edges from a given set of styled attributes. This
4937     * method should be called by subclasses that need fading edges and when an
4938     * instance of these subclasses is created programmatically rather than
4939     * being inflated from XML. This method is automatically called when the XML
4940     * is inflated.
4941     * </p>
4942     *
4943     * @param a the styled attributes set to initialize the fading edges from
4944     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4945     */
4946    protected void initializeFadingEdgeInternal(TypedArray a) {
4947        initScrollCache();
4948
4949        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4950                R.styleable.View_fadingEdgeLength,
4951                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4952    }
4953
4954    /**
4955     * Returns the size of the vertical faded edges used to indicate that more
4956     * content in this view is visible.
4957     *
4958     * @return The size in pixels of the vertical faded edge or 0 if vertical
4959     *         faded edges are not enabled for this view.
4960     * @attr ref android.R.styleable#View_fadingEdgeLength
4961     */
4962    public int getVerticalFadingEdgeLength() {
4963        if (isVerticalFadingEdgeEnabled()) {
4964            ScrollabilityCache cache = mScrollCache;
4965            if (cache != null) {
4966                return cache.fadingEdgeLength;
4967            }
4968        }
4969        return 0;
4970    }
4971
4972    /**
4973     * Set the size of the faded edge used to indicate that more content in this
4974     * view is available.  Will not change whether the fading edge is enabled; use
4975     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4976     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4977     * for the vertical or horizontal fading edges.
4978     *
4979     * @param length The size in pixels of the faded edge used to indicate that more
4980     *        content in this view is visible.
4981     */
4982    public void setFadingEdgeLength(int length) {
4983        initScrollCache();
4984        mScrollCache.fadingEdgeLength = length;
4985    }
4986
4987    /**
4988     * Returns the size of the horizontal faded edges used to indicate that more
4989     * content in this view is visible.
4990     *
4991     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4992     *         faded edges are not enabled for this view.
4993     * @attr ref android.R.styleable#View_fadingEdgeLength
4994     */
4995    public int getHorizontalFadingEdgeLength() {
4996        if (isHorizontalFadingEdgeEnabled()) {
4997            ScrollabilityCache cache = mScrollCache;
4998            if (cache != null) {
4999                return cache.fadingEdgeLength;
5000            }
5001        }
5002        return 0;
5003    }
5004
5005    /**
5006     * Returns the width of the vertical scrollbar.
5007     *
5008     * @return The width in pixels of the vertical scrollbar or 0 if there
5009     *         is no vertical scrollbar.
5010     */
5011    public int getVerticalScrollbarWidth() {
5012        ScrollabilityCache cache = mScrollCache;
5013        if (cache != null) {
5014            ScrollBarDrawable scrollBar = cache.scrollBar;
5015            if (scrollBar != null) {
5016                int size = scrollBar.getSize(true);
5017                if (size <= 0) {
5018                    size = cache.scrollBarSize;
5019                }
5020                return size;
5021            }
5022            return 0;
5023        }
5024        return 0;
5025    }
5026
5027    /**
5028     * Returns the height of the horizontal scrollbar.
5029     *
5030     * @return The height in pixels of the horizontal scrollbar or 0 if
5031     *         there is no horizontal scrollbar.
5032     */
5033    protected int getHorizontalScrollbarHeight() {
5034        ScrollabilityCache cache = mScrollCache;
5035        if (cache != null) {
5036            ScrollBarDrawable scrollBar = cache.scrollBar;
5037            if (scrollBar != null) {
5038                int size = scrollBar.getSize(false);
5039                if (size <= 0) {
5040                    size = cache.scrollBarSize;
5041                }
5042                return size;
5043            }
5044            return 0;
5045        }
5046        return 0;
5047    }
5048
5049    /**
5050     * <p>
5051     * Initializes the scrollbars from a given set of styled attributes. This
5052     * method should be called by subclasses that need scrollbars 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 scrollbars from
5059     *
5060     * @removed
5061     */
5062    protected void initializeScrollbars(TypedArray a) {
5063        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5064        // using the View filter array which is not available to the SDK. As such, internal
5065        // framework usage now uses initializeScrollbarsInternal and we grab a default
5066        // TypedArray with the right filter instead here.
5067        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5068
5069        initializeScrollbarsInternal(arr);
5070
5071        // We ignored the method parameter. Recycle the one we actually did use.
5072        arr.recycle();
5073    }
5074
5075    /**
5076     * <p>
5077     * Initializes the scrollbars from a given set of styled attributes. This
5078     * method should be called by subclasses that need scrollbars and when an
5079     * instance of these subclasses is created programmatically rather than
5080     * being inflated from XML. This method is automatically called when the XML
5081     * is inflated.
5082     * </p>
5083     *
5084     * @param a the styled attributes set to initialize the scrollbars from
5085     * @hide
5086     */
5087    protected void initializeScrollbarsInternal(TypedArray a) {
5088        initScrollCache();
5089
5090        final ScrollabilityCache scrollabilityCache = mScrollCache;
5091
5092        if (scrollabilityCache.scrollBar == null) {
5093            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5094            scrollabilityCache.scrollBar.setState(getDrawableState());
5095            scrollabilityCache.scrollBar.setCallback(this);
5096        }
5097
5098        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5099
5100        if (!fadeScrollbars) {
5101            scrollabilityCache.state = ScrollabilityCache.ON;
5102        }
5103        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5104
5105
5106        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5107                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5108                        .getScrollBarFadeDuration());
5109        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5110                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5111                ViewConfiguration.getScrollDefaultDelay());
5112
5113
5114        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5115                com.android.internal.R.styleable.View_scrollbarSize,
5116                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5117
5118        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5119        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5120
5121        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5122        if (thumb != null) {
5123            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5124        }
5125
5126        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5127                false);
5128        if (alwaysDraw) {
5129            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5130        }
5131
5132        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5133        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5134
5135        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5136        if (thumb != null) {
5137            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5138        }
5139
5140        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5141                false);
5142        if (alwaysDraw) {
5143            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5144        }
5145
5146        // Apply layout direction to the new Drawables if needed
5147        final int layoutDirection = getLayoutDirection();
5148        if (track != null) {
5149            track.setLayoutDirection(layoutDirection);
5150        }
5151        if (thumb != null) {
5152            thumb.setLayoutDirection(layoutDirection);
5153        }
5154
5155        // Re-apply user/background padding so that scrollbar(s) get added
5156        resolvePadding();
5157    }
5158
5159    private void initializeScrollIndicatorsInternal() {
5160        // Some day maybe we'll break this into top/left/start/etc. and let the
5161        // client control it. Until then, you can have any scroll indicator you
5162        // want as long as it's a 1dp foreground-colored rectangle.
5163        if (mScrollIndicatorDrawable == null) {
5164            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5165        }
5166    }
5167
5168    /**
5169     * <p>
5170     * Initalizes the scrollability cache if necessary.
5171     * </p>
5172     */
5173    private void initScrollCache() {
5174        if (mScrollCache == null) {
5175            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5176        }
5177    }
5178
5179    private ScrollabilityCache getScrollCache() {
5180        initScrollCache();
5181        return mScrollCache;
5182    }
5183
5184    /**
5185     * Set the position of the vertical scroll bar. Should be one of
5186     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5187     * {@link #SCROLLBAR_POSITION_RIGHT}.
5188     *
5189     * @param position Where the vertical scroll bar should be positioned.
5190     */
5191    public void setVerticalScrollbarPosition(int position) {
5192        if (mVerticalScrollbarPosition != position) {
5193            mVerticalScrollbarPosition = position;
5194            computeOpaqueFlags();
5195            resolvePadding();
5196        }
5197    }
5198
5199    /**
5200     * @return The position where the vertical scroll bar will show, if applicable.
5201     * @see #setVerticalScrollbarPosition(int)
5202     */
5203    public int getVerticalScrollbarPosition() {
5204        return mVerticalScrollbarPosition;
5205    }
5206
5207    boolean isOnScrollbar(float x, float y) {
5208        if (mScrollCache == null) {
5209            return false;
5210        }
5211        x += getScrollX();
5212        y += getScrollY();
5213        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5214            final Rect bounds = mScrollCache.mScrollBarBounds;
5215            getVerticalScrollBarBounds(bounds);
5216            if (bounds.contains((int)x, (int)y)) {
5217                return true;
5218            }
5219        }
5220        if (isHorizontalScrollBarEnabled()) {
5221            final Rect bounds = mScrollCache.mScrollBarBounds;
5222            getHorizontalScrollBarBounds(bounds);
5223            if (bounds.contains((int)x, (int)y)) {
5224                return true;
5225            }
5226        }
5227        return false;
5228    }
5229
5230    boolean isOnScrollbarThumb(float x, float y) {
5231        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5232    }
5233
5234    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5235        if (mScrollCache == null) {
5236            return false;
5237        }
5238        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5239            x += getScrollX();
5240            y += getScrollY();
5241            final Rect bounds = mScrollCache.mScrollBarBounds;
5242            getVerticalScrollBarBounds(bounds);
5243            final int range = computeVerticalScrollRange();
5244            final int offset = computeVerticalScrollOffset();
5245            final int extent = computeVerticalScrollExtent();
5246            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5247                    extent, range);
5248            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5249                    extent, range, offset);
5250            final int thumbTop = bounds.top + thumbOffset;
5251            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5252                    && y <= thumbTop + thumbLength) {
5253                return true;
5254            }
5255        }
5256        return false;
5257    }
5258
5259    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5260        if (mScrollCache == null) {
5261            return false;
5262        }
5263        if (isHorizontalScrollBarEnabled()) {
5264            x += getScrollX();
5265            y += getScrollY();
5266            final Rect bounds = mScrollCache.mScrollBarBounds;
5267            getHorizontalScrollBarBounds(bounds);
5268            final int range = computeHorizontalScrollRange();
5269            final int offset = computeHorizontalScrollOffset();
5270            final int extent = computeHorizontalScrollExtent();
5271            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5272                    extent, range);
5273            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5274                    extent, range, offset);
5275            final int thumbLeft = bounds.left + thumbOffset;
5276            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5277                    && y <= bounds.bottom) {
5278                return true;
5279            }
5280        }
5281        return false;
5282    }
5283
5284    boolean isDraggingScrollBar() {
5285        return mScrollCache != null
5286                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5287    }
5288
5289    /**
5290     * Sets the state of all scroll indicators.
5291     * <p>
5292     * See {@link #setScrollIndicators(int, int)} for usage information.
5293     *
5294     * @param indicators a bitmask of indicators that should be enabled, or
5295     *                   {@code 0} to disable all indicators
5296     * @see #setScrollIndicators(int, int)
5297     * @see #getScrollIndicators()
5298     * @attr ref android.R.styleable#View_scrollIndicators
5299     */
5300    public void setScrollIndicators(@ScrollIndicators int indicators) {
5301        setScrollIndicators(indicators,
5302                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5303    }
5304
5305    /**
5306     * Sets the state of the scroll indicators specified by the mask. To change
5307     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5308     * <p>
5309     * When a scroll indicator is enabled, it will be displayed if the view
5310     * can scroll in the direction of the indicator.
5311     * <p>
5312     * Multiple indicator types may be enabled or disabled by passing the
5313     * logical OR of the desired types. If multiple types are specified, they
5314     * will all be set to the same enabled state.
5315     * <p>
5316     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5317     *
5318     * @param indicators the indicator direction, or the logical OR of multiple
5319     *             indicator directions. One or more of:
5320     *             <ul>
5321     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5322     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5323     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5324     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5325     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5326     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5327     *             </ul>
5328     * @see #setScrollIndicators(int)
5329     * @see #getScrollIndicators()
5330     * @attr ref android.R.styleable#View_scrollIndicators
5331     */
5332    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5333        // Shift and sanitize mask.
5334        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5335        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5336
5337        // Shift and mask indicators.
5338        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5339        indicators &= mask;
5340
5341        // Merge with non-masked flags.
5342        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5343
5344        if (mPrivateFlags3 != updatedFlags) {
5345            mPrivateFlags3 = updatedFlags;
5346
5347            if (indicators != 0) {
5348                initializeScrollIndicatorsInternal();
5349            }
5350            invalidate();
5351        }
5352    }
5353
5354    /**
5355     * Returns a bitmask representing the enabled scroll indicators.
5356     * <p>
5357     * For example, if the top and left scroll indicators are enabled and all
5358     * other indicators are disabled, the return value will be
5359     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5360     * <p>
5361     * To check whether the bottom scroll indicator is enabled, use the value
5362     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5363     *
5364     * @return a bitmask representing the enabled scroll indicators
5365     */
5366    @ScrollIndicators
5367    public int getScrollIndicators() {
5368        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5369                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5370    }
5371
5372    ListenerInfo getListenerInfo() {
5373        if (mListenerInfo != null) {
5374            return mListenerInfo;
5375        }
5376        mListenerInfo = new ListenerInfo();
5377        return mListenerInfo;
5378    }
5379
5380    /**
5381     * Register a callback to be invoked when the scroll X or Y positions of
5382     * this view change.
5383     * <p>
5384     * <b>Note:</b> Some views handle scrolling independently from View and may
5385     * have their own separate listeners for scroll-type events. For example,
5386     * {@link android.widget.ListView ListView} allows clients to register an
5387     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5388     * to listen for changes in list scroll position.
5389     *
5390     * @param l The listener to notify when the scroll X or Y position changes.
5391     * @see android.view.View#getScrollX()
5392     * @see android.view.View#getScrollY()
5393     */
5394    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5395        getListenerInfo().mOnScrollChangeListener = l;
5396    }
5397
5398    /**
5399     * Register a callback to be invoked when focus of this view changed.
5400     *
5401     * @param l The callback that will run.
5402     */
5403    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5404        getListenerInfo().mOnFocusChangeListener = l;
5405    }
5406
5407    /**
5408     * Add a listener that will be called when the bounds of the view change due to
5409     * layout processing.
5410     *
5411     * @param listener The listener that will be called when layout bounds change.
5412     */
5413    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5414        ListenerInfo li = getListenerInfo();
5415        if (li.mOnLayoutChangeListeners == null) {
5416            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5417        }
5418        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5419            li.mOnLayoutChangeListeners.add(listener);
5420        }
5421    }
5422
5423    /**
5424     * Remove a listener for layout changes.
5425     *
5426     * @param listener The listener for layout bounds change.
5427     */
5428    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5429        ListenerInfo li = mListenerInfo;
5430        if (li == null || li.mOnLayoutChangeListeners == null) {
5431            return;
5432        }
5433        li.mOnLayoutChangeListeners.remove(listener);
5434    }
5435
5436    /**
5437     * Add a listener for attach state changes.
5438     *
5439     * This listener will be called whenever this view is attached or detached
5440     * from a window. Remove the listener using
5441     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5442     *
5443     * @param listener Listener to attach
5444     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5445     */
5446    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5447        ListenerInfo li = getListenerInfo();
5448        if (li.mOnAttachStateChangeListeners == null) {
5449            li.mOnAttachStateChangeListeners
5450                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5451        }
5452        li.mOnAttachStateChangeListeners.add(listener);
5453    }
5454
5455    /**
5456     * Remove a listener for attach state changes. The listener will receive no further
5457     * notification of window attach/detach events.
5458     *
5459     * @param listener Listener to remove
5460     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5461     */
5462    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5463        ListenerInfo li = mListenerInfo;
5464        if (li == null || li.mOnAttachStateChangeListeners == null) {
5465            return;
5466        }
5467        li.mOnAttachStateChangeListeners.remove(listener);
5468    }
5469
5470    /**
5471     * Returns the focus-change callback registered for this view.
5472     *
5473     * @return The callback, or null if one is not registered.
5474     */
5475    public OnFocusChangeListener getOnFocusChangeListener() {
5476        ListenerInfo li = mListenerInfo;
5477        return li != null ? li.mOnFocusChangeListener : null;
5478    }
5479
5480    /**
5481     * Register a callback to be invoked when this view is clicked. If this view is not
5482     * clickable, it becomes clickable.
5483     *
5484     * @param l The callback that will run
5485     *
5486     * @see #setClickable(boolean)
5487     */
5488    public void setOnClickListener(@Nullable OnClickListener l) {
5489        if (!isClickable()) {
5490            setClickable(true);
5491        }
5492        getListenerInfo().mOnClickListener = l;
5493    }
5494
5495    /**
5496     * Return whether this view has an attached OnClickListener.  Returns
5497     * true if there is a listener, false if there is none.
5498     */
5499    public boolean hasOnClickListeners() {
5500        ListenerInfo li = mListenerInfo;
5501        return (li != null && li.mOnClickListener != null);
5502    }
5503
5504    /**
5505     * Register a callback to be invoked when this view is clicked and held. If this view is not
5506     * long clickable, it becomes long clickable.
5507     *
5508     * @param l The callback that will run
5509     *
5510     * @see #setLongClickable(boolean)
5511     */
5512    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5513        if (!isLongClickable()) {
5514            setLongClickable(true);
5515        }
5516        getListenerInfo().mOnLongClickListener = l;
5517    }
5518
5519    /**
5520     * Register a callback to be invoked when this view is context clicked. If the view is not
5521     * context clickable, it becomes context clickable.
5522     *
5523     * @param l The callback that will run
5524     * @see #setContextClickable(boolean)
5525     */
5526    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5527        if (!isContextClickable()) {
5528            setContextClickable(true);
5529        }
5530        getListenerInfo().mOnContextClickListener = l;
5531    }
5532
5533    /**
5534     * Register a callback to be invoked when the context menu for this view is
5535     * being built. If this view is not long clickable, it becomes long clickable.
5536     *
5537     * @param l The callback that will run
5538     *
5539     */
5540    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5541        if (!isLongClickable()) {
5542            setLongClickable(true);
5543        }
5544        getListenerInfo().mOnCreateContextMenuListener = l;
5545    }
5546
5547    /**
5548     * Set an observer to collect stats for each frame rendered for this view.
5549     *
5550     * @hide
5551     */
5552    public void addFrameMetricsListener(Window window,
5553            Window.OnFrameMetricsAvailableListener listener,
5554            Handler handler) {
5555        if (mAttachInfo != null) {
5556            if (mAttachInfo.mThreadedRenderer != null) {
5557                if (mFrameMetricsObservers == null) {
5558                    mFrameMetricsObservers = new ArrayList<>();
5559                }
5560
5561                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5562                        handler.getLooper(), listener);
5563                mFrameMetricsObservers.add(fmo);
5564                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5565            } else {
5566                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5567            }
5568        } else {
5569            if (mFrameMetricsObservers == null) {
5570                mFrameMetricsObservers = new ArrayList<>();
5571            }
5572
5573            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5574                    handler.getLooper(), listener);
5575            mFrameMetricsObservers.add(fmo);
5576        }
5577    }
5578
5579    /**
5580     * Remove observer configured to collect frame stats for this view.
5581     *
5582     * @hide
5583     */
5584    public void removeFrameMetricsListener(
5585            Window.OnFrameMetricsAvailableListener listener) {
5586        ThreadedRenderer renderer = getThreadedRenderer();
5587        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5588        if (fmo == null) {
5589            throw new IllegalArgumentException(
5590                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5591        }
5592
5593        if (mFrameMetricsObservers != null) {
5594            mFrameMetricsObservers.remove(fmo);
5595            if (renderer != null) {
5596                renderer.removeFrameMetricsObserver(fmo);
5597            }
5598        }
5599    }
5600
5601    private void registerPendingFrameMetricsObservers() {
5602        if (mFrameMetricsObservers != null) {
5603            ThreadedRenderer renderer = getThreadedRenderer();
5604            if (renderer != null) {
5605                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5606                    renderer.addFrameMetricsObserver(fmo);
5607                }
5608            } else {
5609                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5610            }
5611        }
5612    }
5613
5614    private FrameMetricsObserver findFrameMetricsObserver(
5615            Window.OnFrameMetricsAvailableListener listener) {
5616        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5617            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5618            if (observer.mListener == listener) {
5619                return observer;
5620            }
5621        }
5622
5623        return null;
5624    }
5625
5626    /**
5627     * Call this view's OnClickListener, if it is defined.  Performs all normal
5628     * actions associated with clicking: reporting accessibility event, playing
5629     * a sound, etc.
5630     *
5631     * @return True there was an assigned OnClickListener that was called, false
5632     *         otherwise is returned.
5633     */
5634    public boolean performClick() {
5635        final boolean result;
5636        final ListenerInfo li = mListenerInfo;
5637        if (li != null && li.mOnClickListener != null) {
5638            playSoundEffect(SoundEffectConstants.CLICK);
5639            li.mOnClickListener.onClick(this);
5640            result = true;
5641        } else {
5642            result = false;
5643        }
5644
5645        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5646        return result;
5647    }
5648
5649    /**
5650     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5651     * this only calls the listener, and does not do any associated clicking
5652     * actions like reporting an accessibility event.
5653     *
5654     * @return True there was an assigned OnClickListener that was called, false
5655     *         otherwise is returned.
5656     */
5657    public boolean callOnClick() {
5658        ListenerInfo li = mListenerInfo;
5659        if (li != null && li.mOnClickListener != null) {
5660            li.mOnClickListener.onClick(this);
5661            return true;
5662        }
5663        return false;
5664    }
5665
5666    /**
5667     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5668     * context menu if the OnLongClickListener did not consume the event.
5669     *
5670     * @return {@code true} if one of the above receivers consumed the event,
5671     *         {@code false} otherwise
5672     */
5673    public boolean performLongClick() {
5674        return performLongClickInternal(mLongClickX, mLongClickY);
5675    }
5676
5677    /**
5678     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5679     * context menu if the OnLongClickListener did not consume the event,
5680     * anchoring it to an (x,y) coordinate.
5681     *
5682     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5683     *          to disable anchoring
5684     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5685     *          to disable anchoring
5686     * @return {@code true} if one of the above receivers consumed the event,
5687     *         {@code false} otherwise
5688     */
5689    public boolean performLongClick(float x, float y) {
5690        mLongClickX = x;
5691        mLongClickY = y;
5692        final boolean handled = performLongClick();
5693        mLongClickX = Float.NaN;
5694        mLongClickY = Float.NaN;
5695        return handled;
5696    }
5697
5698    /**
5699     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5700     * context menu if the OnLongClickListener did not consume the event,
5701     * optionally anchoring it to an (x,y) coordinate.
5702     *
5703     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5704     *          to disable anchoring
5705     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5706     *          to disable anchoring
5707     * @return {@code true} if one of the above receivers consumed the event,
5708     *         {@code false} otherwise
5709     */
5710    private boolean performLongClickInternal(float x, float y) {
5711        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5712
5713        boolean handled = false;
5714        final ListenerInfo li = mListenerInfo;
5715        if (li != null && li.mOnLongClickListener != null) {
5716            handled = li.mOnLongClickListener.onLongClick(View.this);
5717        }
5718        if (!handled) {
5719            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5720            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5721        }
5722        if (handled) {
5723            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5724        }
5725        return handled;
5726    }
5727
5728    /**
5729     * Call this view's OnContextClickListener, if it is defined.
5730     *
5731     * @param x the x coordinate of the context click
5732     * @param y the y coordinate of the context click
5733     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5734     *         otherwise.
5735     */
5736    public boolean performContextClick(float x, float y) {
5737        return performContextClick();
5738    }
5739
5740    /**
5741     * Call this view's OnContextClickListener, if it is defined.
5742     *
5743     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5744     *         otherwise.
5745     */
5746    public boolean performContextClick() {
5747        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5748
5749        boolean handled = false;
5750        ListenerInfo li = mListenerInfo;
5751        if (li != null && li.mOnContextClickListener != null) {
5752            handled = li.mOnContextClickListener.onContextClick(View.this);
5753        }
5754        if (handled) {
5755            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5756        }
5757        return handled;
5758    }
5759
5760    /**
5761     * Performs button-related actions during a touch down event.
5762     *
5763     * @param event The event.
5764     * @return True if the down was consumed.
5765     *
5766     * @hide
5767     */
5768    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5769        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5770            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5771            showContextMenu(event.getX(), event.getY());
5772            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5773            return true;
5774        }
5775        return false;
5776    }
5777
5778    /**
5779     * Shows the context menu for this view.
5780     *
5781     * @return {@code true} if the context menu was shown, {@code false}
5782     *         otherwise
5783     * @see #showContextMenu(float, float)
5784     */
5785    public boolean showContextMenu() {
5786        return getParent().showContextMenuForChild(this);
5787    }
5788
5789    /**
5790     * Shows the context menu for this view anchored to the specified
5791     * view-relative coordinate.
5792     *
5793     * @param x the X coordinate in pixels relative to the view to which the
5794     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5795     * @param y the Y coordinate in pixels relative to the view to which the
5796     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5797     * @return {@code true} if the context menu was shown, {@code false}
5798     *         otherwise
5799     */
5800    public boolean showContextMenu(float x, float y) {
5801        return getParent().showContextMenuForChild(this, x, y);
5802    }
5803
5804    /**
5805     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5806     *
5807     * @param callback Callback that will control the lifecycle of the action mode
5808     * @return The new action mode if it is started, null otherwise
5809     *
5810     * @see ActionMode
5811     * @see #startActionMode(android.view.ActionMode.Callback, int)
5812     */
5813    public ActionMode startActionMode(ActionMode.Callback callback) {
5814        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5815    }
5816
5817    /**
5818     * Start an action mode with the given type.
5819     *
5820     * @param callback Callback that will control the lifecycle of the action mode
5821     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5822     * @return The new action mode if it is started, null otherwise
5823     *
5824     * @see ActionMode
5825     */
5826    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5827        ViewParent parent = getParent();
5828        if (parent == null) return null;
5829        try {
5830            return parent.startActionModeForChild(this, callback, type);
5831        } catch (AbstractMethodError ame) {
5832            // Older implementations of custom views might not implement this.
5833            return parent.startActionModeForChild(this, callback);
5834        }
5835    }
5836
5837    /**
5838     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5839     * Context, creating a unique View identifier to retrieve the result.
5840     *
5841     * @param intent The Intent to be started.
5842     * @param requestCode The request code to use.
5843     * @hide
5844     */
5845    public void startActivityForResult(Intent intent, int requestCode) {
5846        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5847        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5848    }
5849
5850    /**
5851     * If this View corresponds to the calling who, dispatches the activity result.
5852     * @param who The identifier for the targeted View to receive the result.
5853     * @param requestCode The integer request code originally supplied to
5854     *                    startActivityForResult(), allowing you to identify who this
5855     *                    result came from.
5856     * @param resultCode The integer result code returned by the child activity
5857     *                   through its setResult().
5858     * @param data An Intent, which can return result data to the caller
5859     *               (various data can be attached to Intent "extras").
5860     * @return {@code true} if the activity result was dispatched.
5861     * @hide
5862     */
5863    public boolean dispatchActivityResult(
5864            String who, int requestCode, int resultCode, Intent data) {
5865        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5866            onActivityResult(requestCode, resultCode, data);
5867            mStartActivityRequestWho = null;
5868            return true;
5869        }
5870        return false;
5871    }
5872
5873    /**
5874     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5875     *
5876     * @param requestCode The integer request code originally supplied to
5877     *                    startActivityForResult(), allowing you to identify who this
5878     *                    result came from.
5879     * @param resultCode The integer result code returned by the child activity
5880     *                   through its setResult().
5881     * @param data An Intent, which can return result data to the caller
5882     *               (various data can be attached to Intent "extras").
5883     * @hide
5884     */
5885    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5886        // Do nothing.
5887    }
5888
5889    /**
5890     * Register a callback to be invoked when a hardware key is pressed in this view.
5891     * Key presses in software input methods will generally not trigger the methods of
5892     * this listener.
5893     * @param l the key listener to attach to this view
5894     */
5895    public void setOnKeyListener(OnKeyListener l) {
5896        getListenerInfo().mOnKeyListener = l;
5897    }
5898
5899    /**
5900     * Register a callback to be invoked when a touch event is sent to this view.
5901     * @param l the touch listener to attach to this view
5902     */
5903    public void setOnTouchListener(OnTouchListener l) {
5904        getListenerInfo().mOnTouchListener = l;
5905    }
5906
5907    /**
5908     * Register a callback to be invoked when a generic motion event is sent to this view.
5909     * @param l the generic motion listener to attach to this view
5910     */
5911    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5912        getListenerInfo().mOnGenericMotionListener = l;
5913    }
5914
5915    /**
5916     * Register a callback to be invoked when a hover event is sent to this view.
5917     * @param l the hover listener to attach to this view
5918     */
5919    public void setOnHoverListener(OnHoverListener l) {
5920        getListenerInfo().mOnHoverListener = l;
5921    }
5922
5923    /**
5924     * Register a drag event listener callback object for this View. The parameter is
5925     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5926     * View, the system calls the
5927     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5928     * @param l An implementation of {@link android.view.View.OnDragListener}.
5929     */
5930    public void setOnDragListener(OnDragListener l) {
5931        getListenerInfo().mOnDragListener = l;
5932    }
5933
5934    /**
5935     * Give this view focus. This will cause
5936     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5937     *
5938     * Note: this does not check whether this {@link View} should get focus, it just
5939     * gives it focus no matter what.  It should only be called internally by framework
5940     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5941     *
5942     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5943     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5944     *        focus moved when requestFocus() is called. It may not always
5945     *        apply, in which case use the default View.FOCUS_DOWN.
5946     * @param previouslyFocusedRect The rectangle of the view that had focus
5947     *        prior in this View's coordinate system.
5948     */
5949    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5950        if (DBG) {
5951            System.out.println(this + " requestFocus()");
5952        }
5953
5954        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5955            mPrivateFlags |= PFLAG_FOCUSED;
5956
5957            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5958
5959            if (mParent != null) {
5960                mParent.requestChildFocus(this, this);
5961            }
5962
5963            if (mAttachInfo != null) {
5964                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5965            }
5966
5967            onFocusChanged(true, direction, previouslyFocusedRect);
5968            refreshDrawableState();
5969        }
5970    }
5971
5972    /**
5973     * Sets this view's preference for reveal behavior when it gains focus.
5974     *
5975     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
5976     * this view would prefer to be brought fully into view when it gains focus.
5977     * For example, a text field that a user is meant to type into. Other views such
5978     * as scrolling containers may prefer to opt-out of this behavior.</p>
5979     *
5980     * <p>The default value for views is true, though subclasses may change this
5981     * based on their preferred behavior.</p>
5982     *
5983     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
5984     *
5985     * @see #getRevealOnFocusHint()
5986     */
5987    public final void setRevealOnFocusHint(boolean revealOnFocus) {
5988        if (revealOnFocus) {
5989            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
5990        } else {
5991            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
5992        }
5993    }
5994
5995    /**
5996     * Returns this view's preference for reveal behavior when it gains focus.
5997     *
5998     * <p>When this method returns true for a child view requesting focus, ancestor
5999     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6000     * should make a best effort to make the newly focused child fully visible to the user.
6001     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6002     * other properties affecting visibility to the user as part of the focus change.</p>
6003     *
6004     * @return true if this view would prefer to become fully visible when it gains focus,
6005     *         false if it would prefer not to disrupt scroll positioning
6006     *
6007     * @see #setRevealOnFocusHint(boolean)
6008     */
6009    public final boolean getRevealOnFocusHint() {
6010        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6011    }
6012
6013    /**
6014     * Populates <code>outRect</code> with the hotspot bounds. By default,
6015     * the hotspot bounds are identical to the screen bounds.
6016     *
6017     * @param outRect rect to populate with hotspot bounds
6018     * @hide Only for internal use by views and widgets.
6019     */
6020    public void getHotspotBounds(Rect outRect) {
6021        final Drawable background = getBackground();
6022        if (background != null) {
6023            background.getHotspotBounds(outRect);
6024        } else {
6025            getBoundsOnScreen(outRect);
6026        }
6027    }
6028
6029    /**
6030     * Request that a rectangle of this view be visible on the screen,
6031     * scrolling if necessary just enough.
6032     *
6033     * <p>A View should call this if it maintains some notion of which part
6034     * of its content is interesting.  For example, a text editing view
6035     * should call this when its cursor moves.
6036     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6037     * It should not be affected by which part of the View is currently visible or its scroll
6038     * position.
6039     *
6040     * @param rectangle The rectangle in the View's content coordinate space
6041     * @return Whether any parent scrolled.
6042     */
6043    public boolean requestRectangleOnScreen(Rect rectangle) {
6044        return requestRectangleOnScreen(rectangle, false);
6045    }
6046
6047    /**
6048     * Request that a rectangle of this view be visible on the screen,
6049     * scrolling if necessary just enough.
6050     *
6051     * <p>A View should call this if it maintains some notion of which part
6052     * of its content is interesting.  For example, a text editing view
6053     * should call this when its cursor moves.
6054     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6055     * It should not be affected by which part of the View is currently visible or its scroll
6056     * position.
6057     * <p>When <code>immediate</code> is set to true, scrolling will not be
6058     * animated.
6059     *
6060     * @param rectangle The rectangle in the View's content coordinate space
6061     * @param immediate True to forbid animated scrolling, false otherwise
6062     * @return Whether any parent scrolled.
6063     */
6064    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6065        if (mParent == null) {
6066            return false;
6067        }
6068
6069        View child = this;
6070
6071        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6072        position.set(rectangle);
6073
6074        ViewParent parent = mParent;
6075        boolean scrolled = false;
6076        while (parent != null) {
6077            rectangle.set((int) position.left, (int) position.top,
6078                    (int) position.right, (int) position.bottom);
6079
6080            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6081
6082            if (!(parent instanceof View)) {
6083                break;
6084            }
6085
6086            // move it from child's content coordinate space to parent's content coordinate space
6087            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6088
6089            child = (View) parent;
6090            parent = child.getParent();
6091        }
6092
6093        return scrolled;
6094    }
6095
6096    /**
6097     * Called when this view wants to give up focus. If focus is cleared
6098     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6099     * <p>
6100     * <strong>Note:</strong> When a View clears focus the framework is trying
6101     * to give focus to the first focusable View from the top. Hence, if this
6102     * View is the first from the top that can take focus, then all callbacks
6103     * related to clearing focus will be invoked after which the framework will
6104     * give focus to this view.
6105     * </p>
6106     */
6107    public void clearFocus() {
6108        if (DBG) {
6109            System.out.println(this + " clearFocus()");
6110        }
6111
6112        clearFocusInternal(null, true, true);
6113    }
6114
6115    /**
6116     * Clears focus from the view, optionally propagating the change up through
6117     * the parent hierarchy and requesting that the root view place new focus.
6118     *
6119     * @param propagate whether to propagate the change up through the parent
6120     *            hierarchy
6121     * @param refocus when propagate is true, specifies whether to request the
6122     *            root view place new focus
6123     */
6124    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6125        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6126            mPrivateFlags &= ~PFLAG_FOCUSED;
6127
6128            if (propagate && mParent != null) {
6129                mParent.clearChildFocus(this);
6130            }
6131
6132            onFocusChanged(false, 0, null);
6133            refreshDrawableState();
6134
6135            if (propagate && (!refocus || !rootViewRequestFocus())) {
6136                notifyGlobalFocusCleared(this);
6137            }
6138        }
6139    }
6140
6141    void notifyGlobalFocusCleared(View oldFocus) {
6142        if (oldFocus != null && mAttachInfo != null) {
6143            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6144        }
6145    }
6146
6147    boolean rootViewRequestFocus() {
6148        final View root = getRootView();
6149        return root != null && root.requestFocus();
6150    }
6151
6152    /**
6153     * Called internally by the view system when a new view is getting focus.
6154     * This is what clears the old focus.
6155     * <p>
6156     * <b>NOTE:</b> The parent view's focused child must be updated manually
6157     * after calling this method. Otherwise, the view hierarchy may be left in
6158     * an inconstent state.
6159     */
6160    void unFocus(View focused) {
6161        if (DBG) {
6162            System.out.println(this + " unFocus()");
6163        }
6164
6165        clearFocusInternal(focused, false, false);
6166    }
6167
6168    /**
6169     * Returns true if this view has focus itself, or is the ancestor of the
6170     * view that has focus.
6171     *
6172     * @return True if this view has or contains focus, false otherwise.
6173     */
6174    @ViewDebug.ExportedProperty(category = "focus")
6175    public boolean hasFocus() {
6176        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6177    }
6178
6179    /**
6180     * Returns true if this view is focusable or if it contains a reachable View
6181     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6182     * is a View whose parents do not block descendants focus.
6183     *
6184     * Only {@link #VISIBLE} views are considered focusable.
6185     *
6186     * @return True if the view is focusable or if the view contains a focusable
6187     *         View, false otherwise.
6188     *
6189     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6190     * @see ViewGroup#getTouchscreenBlocksFocus()
6191     */
6192    public boolean hasFocusable() {
6193        if (!isFocusableInTouchMode()) {
6194            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6195                final ViewGroup g = (ViewGroup) p;
6196                if (g.shouldBlockFocusForTouchscreen()) {
6197                    return false;
6198                }
6199            }
6200        }
6201        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6202    }
6203
6204    /**
6205     * Called by the view system when the focus state of this view changes.
6206     * When the focus change event is caused by directional navigation, direction
6207     * and previouslyFocusedRect provide insight into where the focus is coming from.
6208     * When overriding, be sure to call up through to the super class so that
6209     * the standard focus handling will occur.
6210     *
6211     * @param gainFocus True if the View has focus; false otherwise.
6212     * @param direction The direction focus has moved when requestFocus()
6213     *                  is called to give this view focus. Values are
6214     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6215     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6216     *                  It may not always apply, in which case use the default.
6217     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6218     *        system, of the previously focused view.  If applicable, this will be
6219     *        passed in as finer grained information about where the focus is coming
6220     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6221     */
6222    @CallSuper
6223    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6224            @Nullable Rect previouslyFocusedRect) {
6225        if (gainFocus) {
6226            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6227        } else {
6228            notifyViewAccessibilityStateChangedIfNeeded(
6229                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6230        }
6231
6232        InputMethodManager imm = InputMethodManager.peekInstance();
6233        if (!gainFocus) {
6234            if (isPressed()) {
6235                setPressed(false);
6236            }
6237            if (imm != null && mAttachInfo != null
6238                    && mAttachInfo.mHasWindowFocus) {
6239                imm.focusOut(this);
6240            }
6241            onFocusLost();
6242        } else if (imm != null && mAttachInfo != null
6243                && mAttachInfo.mHasWindowFocus) {
6244            imm.focusIn(this);
6245        }
6246
6247        invalidate(true);
6248        ListenerInfo li = mListenerInfo;
6249        if (li != null && li.mOnFocusChangeListener != null) {
6250            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6251        }
6252
6253        if (mAttachInfo != null) {
6254            mAttachInfo.mKeyDispatchState.reset(this);
6255        }
6256    }
6257
6258    /**
6259     * Sends an accessibility event of the given type. If accessibility is
6260     * not enabled this method has no effect. The default implementation calls
6261     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6262     * to populate information about the event source (this View), then calls
6263     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6264     * populate the text content of the event source including its descendants,
6265     * and last calls
6266     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6267     * on its parent to request sending of the event to interested parties.
6268     * <p>
6269     * If an {@link AccessibilityDelegate} has been specified via calling
6270     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6271     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6272     * responsible for handling this call.
6273     * </p>
6274     *
6275     * @param eventType The type of the event to send, as defined by several types from
6276     * {@link android.view.accessibility.AccessibilityEvent}, such as
6277     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6278     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6279     *
6280     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6281     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6282     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6283     * @see AccessibilityDelegate
6284     */
6285    public void sendAccessibilityEvent(int eventType) {
6286        if (mAccessibilityDelegate != null) {
6287            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6288        } else {
6289            sendAccessibilityEventInternal(eventType);
6290        }
6291    }
6292
6293    /**
6294     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6295     * {@link AccessibilityEvent} to make an announcement which is related to some
6296     * sort of a context change for which none of the events representing UI transitions
6297     * is a good fit. For example, announcing a new page in a book. If accessibility
6298     * is not enabled this method does nothing.
6299     *
6300     * @param text The announcement text.
6301     */
6302    public void announceForAccessibility(CharSequence text) {
6303        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6304            AccessibilityEvent event = AccessibilityEvent.obtain(
6305                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6306            onInitializeAccessibilityEvent(event);
6307            event.getText().add(text);
6308            event.setContentDescription(null);
6309            mParent.requestSendAccessibilityEvent(this, event);
6310        }
6311    }
6312
6313    /**
6314     * @see #sendAccessibilityEvent(int)
6315     *
6316     * Note: Called from the default {@link AccessibilityDelegate}.
6317     *
6318     * @hide
6319     */
6320    public void sendAccessibilityEventInternal(int eventType) {
6321        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6322            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6323        }
6324    }
6325
6326    /**
6327     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6328     * takes as an argument an empty {@link AccessibilityEvent} and does not
6329     * perform a check whether accessibility is enabled.
6330     * <p>
6331     * If an {@link AccessibilityDelegate} has been specified via calling
6332     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6333     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6334     * is responsible for handling this call.
6335     * </p>
6336     *
6337     * @param event The event to send.
6338     *
6339     * @see #sendAccessibilityEvent(int)
6340     */
6341    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6342        if (mAccessibilityDelegate != null) {
6343            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6344        } else {
6345            sendAccessibilityEventUncheckedInternal(event);
6346        }
6347    }
6348
6349    /**
6350     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6351     *
6352     * Note: Called from the default {@link AccessibilityDelegate}.
6353     *
6354     * @hide
6355     */
6356    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6357        if (!isShown()) {
6358            return;
6359        }
6360        onInitializeAccessibilityEvent(event);
6361        // Only a subset of accessibility events populates text content.
6362        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6363            dispatchPopulateAccessibilityEvent(event);
6364        }
6365        // In the beginning we called #isShown(), so we know that getParent() is not null.
6366        getParent().requestSendAccessibilityEvent(this, event);
6367    }
6368
6369    /**
6370     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6371     * to its children for adding their text content to the event. Note that the
6372     * event text is populated in a separate dispatch path since we add to the
6373     * event not only the text of the source but also the text of all its descendants.
6374     * A typical implementation will call
6375     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6376     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6377     * on each child. Override this method if custom population of the event text
6378     * content is required.
6379     * <p>
6380     * If an {@link AccessibilityDelegate} has been specified via calling
6381     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6382     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6383     * is responsible for handling this call.
6384     * </p>
6385     * <p>
6386     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6387     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6388     * </p>
6389     *
6390     * @param event The event.
6391     *
6392     * @return True if the event population was completed.
6393     */
6394    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6395        if (mAccessibilityDelegate != null) {
6396            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6397        } else {
6398            return dispatchPopulateAccessibilityEventInternal(event);
6399        }
6400    }
6401
6402    /**
6403     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6404     *
6405     * Note: Called from the default {@link AccessibilityDelegate}.
6406     *
6407     * @hide
6408     */
6409    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6410        onPopulateAccessibilityEvent(event);
6411        return false;
6412    }
6413
6414    /**
6415     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6416     * giving a chance to this View to populate the accessibility event with its
6417     * text content. While this method is free to modify event
6418     * attributes other than text content, doing so should normally be performed in
6419     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6420     * <p>
6421     * Example: Adding formatted date string to an accessibility event in addition
6422     *          to the text added by the super implementation:
6423     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6424     *     super.onPopulateAccessibilityEvent(event);
6425     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6426     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6427     *         mCurrentDate.getTimeInMillis(), flags);
6428     *     event.getText().add(selectedDateUtterance);
6429     * }</pre>
6430     * <p>
6431     * If an {@link AccessibilityDelegate} has been specified via calling
6432     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6433     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6434     * is responsible for handling this call.
6435     * </p>
6436     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6437     * information to the event, in case the default implementation has basic information to add.
6438     * </p>
6439     *
6440     * @param event The accessibility event which to populate.
6441     *
6442     * @see #sendAccessibilityEvent(int)
6443     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6444     */
6445    @CallSuper
6446    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6447        if (mAccessibilityDelegate != null) {
6448            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6449        } else {
6450            onPopulateAccessibilityEventInternal(event);
6451        }
6452    }
6453
6454    /**
6455     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6456     *
6457     * Note: Called from the default {@link AccessibilityDelegate}.
6458     *
6459     * @hide
6460     */
6461    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6462    }
6463
6464    /**
6465     * Initializes an {@link AccessibilityEvent} with information about
6466     * this View which is the event source. In other words, the source of
6467     * an accessibility event is the view whose state change triggered firing
6468     * the event.
6469     * <p>
6470     * Example: Setting the password property of an event in addition
6471     *          to properties set by the super implementation:
6472     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6473     *     super.onInitializeAccessibilityEvent(event);
6474     *     event.setPassword(true);
6475     * }</pre>
6476     * <p>
6477     * If an {@link AccessibilityDelegate} has been specified via calling
6478     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6479     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6480     * is responsible for handling this call.
6481     * </p>
6482     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6483     * information to the event, in case the default implementation has basic information to add.
6484     * </p>
6485     * @param event The event to initialize.
6486     *
6487     * @see #sendAccessibilityEvent(int)
6488     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6489     */
6490    @CallSuper
6491    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6492        if (mAccessibilityDelegate != null) {
6493            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6494        } else {
6495            onInitializeAccessibilityEventInternal(event);
6496        }
6497    }
6498
6499    /**
6500     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6501     *
6502     * Note: Called from the default {@link AccessibilityDelegate}.
6503     *
6504     * @hide
6505     */
6506    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6507        event.setSource(this);
6508        event.setClassName(getAccessibilityClassName());
6509        event.setPackageName(getContext().getPackageName());
6510        event.setEnabled(isEnabled());
6511        event.setContentDescription(mContentDescription);
6512
6513        switch (event.getEventType()) {
6514            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6515                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6516                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6517                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6518                event.setItemCount(focusablesTempList.size());
6519                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6520                if (mAttachInfo != null) {
6521                    focusablesTempList.clear();
6522                }
6523            } break;
6524            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6525                CharSequence text = getIterableTextForAccessibility();
6526                if (text != null && text.length() > 0) {
6527                    event.setFromIndex(getAccessibilitySelectionStart());
6528                    event.setToIndex(getAccessibilitySelectionEnd());
6529                    event.setItemCount(text.length());
6530                }
6531            } break;
6532        }
6533    }
6534
6535    /**
6536     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6537     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6538     * This method is responsible for obtaining an accessibility node info from a
6539     * pool of reusable instances and calling
6540     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6541     * initialize the former.
6542     * <p>
6543     * Note: The client is responsible for recycling the obtained instance by calling
6544     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6545     * </p>
6546     *
6547     * @return A populated {@link AccessibilityNodeInfo}.
6548     *
6549     * @see AccessibilityNodeInfo
6550     */
6551    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6552        if (mAccessibilityDelegate != null) {
6553            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6554        } else {
6555            return createAccessibilityNodeInfoInternal();
6556        }
6557    }
6558
6559    /**
6560     * @see #createAccessibilityNodeInfo()
6561     *
6562     * @hide
6563     */
6564    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6565        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6566        if (provider != null) {
6567            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6568        } else {
6569            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6570            onInitializeAccessibilityNodeInfo(info);
6571            return info;
6572        }
6573    }
6574
6575    /**
6576     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6577     * The base implementation sets:
6578     * <ul>
6579     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6580     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6581     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6582     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6583     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6584     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6585     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6586     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6587     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6588     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6589     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6590     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6591     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6592     * </ul>
6593     * <p>
6594     * Subclasses should override this method, call the super implementation,
6595     * and set additional attributes.
6596     * </p>
6597     * <p>
6598     * If an {@link AccessibilityDelegate} has been specified via calling
6599     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6600     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6601     * is responsible for handling this call.
6602     * </p>
6603     *
6604     * @param info The instance to initialize.
6605     */
6606    @CallSuper
6607    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6608        if (mAccessibilityDelegate != null) {
6609            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6610        } else {
6611            onInitializeAccessibilityNodeInfoInternal(info);
6612        }
6613    }
6614
6615    /**
6616     * Gets the location of this view in screen coordinates.
6617     *
6618     * @param outRect The output location
6619     * @hide
6620     */
6621    public void getBoundsOnScreen(Rect outRect) {
6622        getBoundsOnScreen(outRect, false);
6623    }
6624
6625    /**
6626     * Gets the location of this view in screen coordinates.
6627     *
6628     * @param outRect The output location
6629     * @param clipToParent Whether to clip child bounds to the parent ones.
6630     * @hide
6631     */
6632    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6633        if (mAttachInfo == null) {
6634            return;
6635        }
6636
6637        RectF position = mAttachInfo.mTmpTransformRect;
6638        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6639
6640        if (!hasIdentityMatrix()) {
6641            getMatrix().mapRect(position);
6642        }
6643
6644        position.offset(mLeft, mTop);
6645
6646        ViewParent parent = mParent;
6647        while (parent instanceof View) {
6648            View parentView = (View) parent;
6649
6650            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6651
6652            if (clipToParent) {
6653                position.left = Math.max(position.left, 0);
6654                position.top = Math.max(position.top, 0);
6655                position.right = Math.min(position.right, parentView.getWidth());
6656                position.bottom = Math.min(position.bottom, parentView.getHeight());
6657            }
6658
6659            if (!parentView.hasIdentityMatrix()) {
6660                parentView.getMatrix().mapRect(position);
6661            }
6662
6663            position.offset(parentView.mLeft, parentView.mTop);
6664
6665            parent = parentView.mParent;
6666        }
6667
6668        if (parent instanceof ViewRootImpl) {
6669            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6670            position.offset(0, -viewRootImpl.mCurScrollY);
6671        }
6672
6673        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6674
6675        outRect.set(Math.round(position.left), Math.round(position.top),
6676                Math.round(position.right), Math.round(position.bottom));
6677    }
6678
6679    /**
6680     * Return the class name of this object to be used for accessibility purposes.
6681     * Subclasses should only override this if they are implementing something that
6682     * should be seen as a completely new class of view when used by accessibility,
6683     * unrelated to the class it is deriving from.  This is used to fill in
6684     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6685     */
6686    public CharSequence getAccessibilityClassName() {
6687        return View.class.getName();
6688    }
6689
6690    /**
6691     * Called when assist structure is being retrieved from a view as part of
6692     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6693     * @param structure Fill in with structured view data.  The default implementation
6694     * fills in all data that can be inferred from the view itself.
6695     */
6696    public void onProvideStructure(ViewStructure structure) {
6697        final int id = mID;
6698        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6699                && (id&0x0000ffff) != 0) {
6700            String pkg, type, entry;
6701            try {
6702                final Resources res = getResources();
6703                entry = res.getResourceEntryName(id);
6704                type = res.getResourceTypeName(id);
6705                pkg = res.getResourcePackageName(id);
6706            } catch (Resources.NotFoundException e) {
6707                entry = type = pkg = null;
6708            }
6709            structure.setId(id, pkg, type, entry);
6710        } else {
6711            structure.setId(id, null, null, null);
6712        }
6713        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6714        if (!hasIdentityMatrix()) {
6715            structure.setTransformation(getMatrix());
6716        }
6717        structure.setElevation(getZ());
6718        structure.setVisibility(getVisibility());
6719        structure.setEnabled(isEnabled());
6720        if (isClickable()) {
6721            structure.setClickable(true);
6722        }
6723        if (isFocusable()) {
6724            structure.setFocusable(true);
6725        }
6726        if (isFocused()) {
6727            structure.setFocused(true);
6728        }
6729        if (isAccessibilityFocused()) {
6730            structure.setAccessibilityFocused(true);
6731        }
6732        if (isSelected()) {
6733            structure.setSelected(true);
6734        }
6735        if (isActivated()) {
6736            structure.setActivated(true);
6737        }
6738        if (isLongClickable()) {
6739            structure.setLongClickable(true);
6740        }
6741        if (this instanceof Checkable) {
6742            structure.setCheckable(true);
6743            if (((Checkable)this).isChecked()) {
6744                structure.setChecked(true);
6745            }
6746        }
6747        if (isContextClickable()) {
6748            structure.setContextClickable(true);
6749        }
6750        structure.setClassName(getAccessibilityClassName().toString());
6751        structure.setContentDescription(getContentDescription());
6752    }
6753
6754    /**
6755     * Called when assist structure is being retrieved from a view as part of
6756     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6757     * generate additional virtual structure under this view.  The defaullt implementation
6758     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6759     * view's virtual accessibility nodes, if any.  You can override this for a more
6760     * optimal implementation providing this data.
6761     */
6762    public void onProvideVirtualStructure(ViewStructure structure) {
6763        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6764        if (provider != null) {
6765            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6766            structure.setChildCount(1);
6767            ViewStructure root = structure.newChild(0);
6768            populateVirtualStructure(root, provider, info);
6769            info.recycle();
6770        }
6771    }
6772
6773    private void populateVirtualStructure(ViewStructure structure,
6774            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6775        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6776                null, null, null);
6777        Rect rect = structure.getTempRect();
6778        info.getBoundsInParent(rect);
6779        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6780        structure.setVisibility(VISIBLE);
6781        structure.setEnabled(info.isEnabled());
6782        if (info.isClickable()) {
6783            structure.setClickable(true);
6784        }
6785        if (info.isFocusable()) {
6786            structure.setFocusable(true);
6787        }
6788        if (info.isFocused()) {
6789            structure.setFocused(true);
6790        }
6791        if (info.isAccessibilityFocused()) {
6792            structure.setAccessibilityFocused(true);
6793        }
6794        if (info.isSelected()) {
6795            structure.setSelected(true);
6796        }
6797        if (info.isLongClickable()) {
6798            structure.setLongClickable(true);
6799        }
6800        if (info.isCheckable()) {
6801            structure.setCheckable(true);
6802            if (info.isChecked()) {
6803                structure.setChecked(true);
6804            }
6805        }
6806        if (info.isContextClickable()) {
6807            structure.setContextClickable(true);
6808        }
6809        CharSequence cname = info.getClassName();
6810        structure.setClassName(cname != null ? cname.toString() : null);
6811        structure.setContentDescription(info.getContentDescription());
6812        if (info.getText() != null || info.getError() != null) {
6813            structure.setText(info.getText(), info.getTextSelectionStart(),
6814                    info.getTextSelectionEnd());
6815        }
6816        final int NCHILDREN = info.getChildCount();
6817        if (NCHILDREN > 0) {
6818            structure.setChildCount(NCHILDREN);
6819            for (int i=0; i<NCHILDREN; i++) {
6820                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6821                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6822                ViewStructure child = structure.newChild(i);
6823                populateVirtualStructure(child, provider, cinfo);
6824                cinfo.recycle();
6825            }
6826        }
6827    }
6828
6829    /**
6830     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6831     * implementation calls {@link #onProvideStructure} and
6832     * {@link #onProvideVirtualStructure}.
6833     */
6834    public void dispatchProvideStructure(ViewStructure structure) {
6835        if (!isAssistBlocked()) {
6836            onProvideStructure(structure);
6837            onProvideVirtualStructure(structure);
6838        } else {
6839            structure.setClassName(getAccessibilityClassName().toString());
6840            structure.setAssistBlocked(true);
6841        }
6842    }
6843
6844    /**
6845     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6846     *
6847     * Note: Called from the default {@link AccessibilityDelegate}.
6848     *
6849     * @hide
6850     */
6851    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6852        if (mAttachInfo == null) {
6853            return;
6854        }
6855
6856        Rect bounds = mAttachInfo.mTmpInvalRect;
6857
6858        getDrawingRect(bounds);
6859        info.setBoundsInParent(bounds);
6860
6861        getBoundsOnScreen(bounds, true);
6862        info.setBoundsInScreen(bounds);
6863
6864        ViewParent parent = getParentForAccessibility();
6865        if (parent instanceof View) {
6866            info.setParent((View) parent);
6867        }
6868
6869        if (mID != View.NO_ID) {
6870            View rootView = getRootView();
6871            if (rootView == null) {
6872                rootView = this;
6873            }
6874
6875            View label = rootView.findLabelForView(this, mID);
6876            if (label != null) {
6877                info.setLabeledBy(label);
6878            }
6879
6880            if ((mAttachInfo.mAccessibilityFetchFlags
6881                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6882                    && Resources.resourceHasPackage(mID)) {
6883                try {
6884                    String viewId = getResources().getResourceName(mID);
6885                    info.setViewIdResourceName(viewId);
6886                } catch (Resources.NotFoundException nfe) {
6887                    /* ignore */
6888                }
6889            }
6890        }
6891
6892        if (mLabelForId != View.NO_ID) {
6893            View rootView = getRootView();
6894            if (rootView == null) {
6895                rootView = this;
6896            }
6897            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6898            if (labeled != null) {
6899                info.setLabelFor(labeled);
6900            }
6901        }
6902
6903        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6904            View rootView = getRootView();
6905            if (rootView == null) {
6906                rootView = this;
6907            }
6908            View next = rootView.findViewInsideOutShouldExist(this,
6909                    mAccessibilityTraversalBeforeId);
6910            if (next != null && next.includeForAccessibility()) {
6911                info.setTraversalBefore(next);
6912            }
6913        }
6914
6915        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6916            View rootView = getRootView();
6917            if (rootView == null) {
6918                rootView = this;
6919            }
6920            View next = rootView.findViewInsideOutShouldExist(this,
6921                    mAccessibilityTraversalAfterId);
6922            if (next != null && next.includeForAccessibility()) {
6923                info.setTraversalAfter(next);
6924            }
6925        }
6926
6927        info.setVisibleToUser(isVisibleToUser());
6928
6929        info.setImportantForAccessibility(isImportantForAccessibility());
6930        info.setPackageName(mContext.getPackageName());
6931        info.setClassName(getAccessibilityClassName());
6932        info.setContentDescription(getContentDescription());
6933
6934        info.setEnabled(isEnabled());
6935        info.setClickable(isClickable());
6936        info.setFocusable(isFocusable());
6937        info.setFocused(isFocused());
6938        info.setAccessibilityFocused(isAccessibilityFocused());
6939        info.setSelected(isSelected());
6940        info.setLongClickable(isLongClickable());
6941        info.setContextClickable(isContextClickable());
6942        info.setLiveRegion(getAccessibilityLiveRegion());
6943
6944        // TODO: These make sense only if we are in an AdapterView but all
6945        // views can be selected. Maybe from accessibility perspective
6946        // we should report as selectable view in an AdapterView.
6947        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6948        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6949
6950        if (isFocusable()) {
6951            if (isFocused()) {
6952                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6953            } else {
6954                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6955            }
6956        }
6957
6958        if (!isAccessibilityFocused()) {
6959            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6960        } else {
6961            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6962        }
6963
6964        if (isClickable() && isEnabled()) {
6965            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6966        }
6967
6968        if (isLongClickable() && isEnabled()) {
6969            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6970        }
6971
6972        if (isContextClickable() && isEnabled()) {
6973            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6974        }
6975
6976        CharSequence text = getIterableTextForAccessibility();
6977        if (text != null && text.length() > 0) {
6978            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6979
6980            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6981            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6982            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6983            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6984                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6985                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6986        }
6987
6988        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6989        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6990    }
6991
6992    /**
6993     * Determine the order in which this view will be drawn relative to its siblings for a11y
6994     *
6995     * @param info The info whose drawing order should be populated
6996     */
6997    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6998        /*
6999         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7000         * drawing order may not be well-defined, and some Views with custom drawing order may
7001         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7002         */
7003        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7004            info.setDrawingOrder(0);
7005            return;
7006        }
7007        int drawingOrderInParent = 1;
7008        // Iterate up the hierarchy if parents are not important for a11y
7009        View viewAtDrawingLevel = this;
7010        final ViewParent parent = getParentForAccessibility();
7011        while (viewAtDrawingLevel != parent) {
7012            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7013            if (!(currentParent instanceof ViewGroup)) {
7014                // Should only happen for the Decor
7015                drawingOrderInParent = 0;
7016                break;
7017            } else {
7018                final ViewGroup parentGroup = (ViewGroup) currentParent;
7019                final int childCount = parentGroup.getChildCount();
7020                if (childCount > 1) {
7021                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7022                    if (preorderedList != null) {
7023                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7024                        for (int i = 0; i < childDrawIndex; i++) {
7025                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7026                        }
7027                    } else {
7028                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7029                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7030                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7031                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7032                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7033                        if (childDrawIndex != 0) {
7034                            for (int i = 0; i < numChildrenToIterate; i++) {
7035                                final int otherDrawIndex = (customOrder ?
7036                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7037                                if (otherDrawIndex < childDrawIndex) {
7038                                    drawingOrderInParent +=
7039                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7040                                }
7041                            }
7042                        }
7043                    }
7044                }
7045            }
7046            viewAtDrawingLevel = (View) currentParent;
7047        }
7048        info.setDrawingOrder(drawingOrderInParent);
7049    }
7050
7051    private static int numViewsForAccessibility(View view) {
7052        if (view != null) {
7053            if (view.includeForAccessibility()) {
7054                return 1;
7055            } else if (view instanceof ViewGroup) {
7056                return ((ViewGroup) view).getNumChildrenForAccessibility();
7057            }
7058        }
7059        return 0;
7060    }
7061
7062    private View findLabelForView(View view, int labeledId) {
7063        if (mMatchLabelForPredicate == null) {
7064            mMatchLabelForPredicate = new MatchLabelForPredicate();
7065        }
7066        mMatchLabelForPredicate.mLabeledId = labeledId;
7067        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7068    }
7069
7070    /**
7071     * Computes whether this view is visible to the user. Such a view is
7072     * attached, visible, all its predecessors are visible, it is not clipped
7073     * entirely by its predecessors, and has an alpha greater than zero.
7074     *
7075     * @return Whether the view is visible on the screen.
7076     *
7077     * @hide
7078     */
7079    protected boolean isVisibleToUser() {
7080        return isVisibleToUser(null);
7081    }
7082
7083    /**
7084     * Computes whether the given portion of this view is visible to the user.
7085     * Such a view is attached, visible, all its predecessors are visible,
7086     * has an alpha greater than zero, and the specified portion is not
7087     * clipped entirely by its predecessors.
7088     *
7089     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7090     *                    <code>null</code>, and the entire view will be tested in this case.
7091     *                    When <code>true</code> is returned by the function, the actual visible
7092     *                    region will be stored in this parameter; that is, if boundInView is fully
7093     *                    contained within the view, no modification will be made, otherwise regions
7094     *                    outside of the visible area of the view will be clipped.
7095     *
7096     * @return Whether the specified portion of the view is visible on the screen.
7097     *
7098     * @hide
7099     */
7100    protected boolean isVisibleToUser(Rect boundInView) {
7101        if (mAttachInfo != null) {
7102            // Attached to invisible window means this view is not visible.
7103            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7104                return false;
7105            }
7106            // An invisible predecessor or one with alpha zero means
7107            // that this view is not visible to the user.
7108            Object current = this;
7109            while (current instanceof View) {
7110                View view = (View) current;
7111                // We have attach info so this view is attached and there is no
7112                // need to check whether we reach to ViewRootImpl on the way up.
7113                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7114                        view.getVisibility() != VISIBLE) {
7115                    return false;
7116                }
7117                current = view.mParent;
7118            }
7119            // Check if the view is entirely covered by its predecessors.
7120            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7121            Point offset = mAttachInfo.mPoint;
7122            if (!getGlobalVisibleRect(visibleRect, offset)) {
7123                return false;
7124            }
7125            // Check if the visible portion intersects the rectangle of interest.
7126            if (boundInView != null) {
7127                visibleRect.offset(-offset.x, -offset.y);
7128                return boundInView.intersect(visibleRect);
7129            }
7130            return true;
7131        }
7132        return false;
7133    }
7134
7135    /**
7136     * Returns the delegate for implementing accessibility support via
7137     * composition. For more details see {@link AccessibilityDelegate}.
7138     *
7139     * @return The delegate, or null if none set.
7140     *
7141     * @hide
7142     */
7143    public AccessibilityDelegate getAccessibilityDelegate() {
7144        return mAccessibilityDelegate;
7145    }
7146
7147    /**
7148     * Sets a delegate for implementing accessibility support via composition
7149     * (as opposed to inheritance). For more details, see
7150     * {@link AccessibilityDelegate}.
7151     * <p>
7152     * <strong>Note:</strong> On platform versions prior to
7153     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7154     * views in the {@code android.widget.*} package are called <i>before</i>
7155     * host methods. This prevents certain properties such as class name from
7156     * being modified by overriding
7157     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7158     * as any changes will be overwritten by the host class.
7159     * <p>
7160     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7161     * methods are called <i>after</i> host methods, which all properties to be
7162     * modified without being overwritten by the host class.
7163     *
7164     * @param delegate the object to which accessibility method calls should be
7165     *                 delegated
7166     * @see AccessibilityDelegate
7167     */
7168    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7169        mAccessibilityDelegate = delegate;
7170    }
7171
7172    /**
7173     * Gets the provider for managing a virtual view hierarchy rooted at this View
7174     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7175     * that explore the window content.
7176     * <p>
7177     * If this method returns an instance, this instance is responsible for managing
7178     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7179     * View including the one representing the View itself. Similarly the returned
7180     * instance is responsible for performing accessibility actions on any virtual
7181     * view or the root view itself.
7182     * </p>
7183     * <p>
7184     * If an {@link AccessibilityDelegate} has been specified via calling
7185     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7186     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7187     * is responsible for handling this call.
7188     * </p>
7189     *
7190     * @return The provider.
7191     *
7192     * @see AccessibilityNodeProvider
7193     */
7194    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7195        if (mAccessibilityDelegate != null) {
7196            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7197        } else {
7198            return null;
7199        }
7200    }
7201
7202    /**
7203     * Gets the unique identifier of this view on the screen for accessibility purposes.
7204     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7205     *
7206     * @return The view accessibility id.
7207     *
7208     * @hide
7209     */
7210    public int getAccessibilityViewId() {
7211        if (mAccessibilityViewId == NO_ID) {
7212            mAccessibilityViewId = sNextAccessibilityViewId++;
7213        }
7214        return mAccessibilityViewId;
7215    }
7216
7217    /**
7218     * Gets the unique identifier of the window in which this View reseides.
7219     *
7220     * @return The window accessibility id.
7221     *
7222     * @hide
7223     */
7224    public int getAccessibilityWindowId() {
7225        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7226                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7227    }
7228
7229    /**
7230     * Returns the {@link View}'s content description.
7231     * <p>
7232     * <strong>Note:</strong> Do not override this method, as it will have no
7233     * effect on the content description presented to accessibility services.
7234     * You must call {@link #setContentDescription(CharSequence)} to modify the
7235     * content description.
7236     *
7237     * @return the content description
7238     * @see #setContentDescription(CharSequence)
7239     * @attr ref android.R.styleable#View_contentDescription
7240     */
7241    @ViewDebug.ExportedProperty(category = "accessibility")
7242    public CharSequence getContentDescription() {
7243        return mContentDescription;
7244    }
7245
7246    /**
7247     * Sets the {@link View}'s content description.
7248     * <p>
7249     * A content description briefly describes the view and is primarily used
7250     * for accessibility support to determine how a view should be presented to
7251     * the user. In the case of a view with no textual representation, such as
7252     * {@link android.widget.ImageButton}, a useful content description
7253     * explains what the view does. For example, an image button with a phone
7254     * icon that is used to place a call may use "Call" as its content
7255     * description. An image of a floppy disk that is used to save a file may
7256     * use "Save".
7257     *
7258     * @param contentDescription The content description.
7259     * @see #getContentDescription()
7260     * @attr ref android.R.styleable#View_contentDescription
7261     */
7262    @RemotableViewMethod
7263    public void setContentDescription(CharSequence contentDescription) {
7264        if (mContentDescription == null) {
7265            if (contentDescription == null) {
7266                return;
7267            }
7268        } else if (mContentDescription.equals(contentDescription)) {
7269            return;
7270        }
7271        mContentDescription = contentDescription;
7272        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7273        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7274            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7275            notifySubtreeAccessibilityStateChangedIfNeeded();
7276        } else {
7277            notifyViewAccessibilityStateChangedIfNeeded(
7278                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7279        }
7280    }
7281
7282    /**
7283     * Sets the id of a view before which this one is visited in accessibility traversal.
7284     * A screen-reader must visit the content of this view before the content of the one
7285     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7286     * will traverse the entire content of B before traversing the entire content of A,
7287     * regardles of what traversal strategy it is using.
7288     * <p>
7289     * Views that do not have specified before/after relationships are traversed in order
7290     * determined by the screen-reader.
7291     * </p>
7292     * <p>
7293     * Setting that this view is before a view that is not important for accessibility
7294     * or if this view is not important for accessibility will have no effect as the
7295     * screen-reader is not aware of unimportant views.
7296     * </p>
7297     *
7298     * @param beforeId The id of a view this one precedes in accessibility traversal.
7299     *
7300     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7301     *
7302     * @see #setImportantForAccessibility(int)
7303     */
7304    @RemotableViewMethod
7305    public void setAccessibilityTraversalBefore(int beforeId) {
7306        if (mAccessibilityTraversalBeforeId == beforeId) {
7307            return;
7308        }
7309        mAccessibilityTraversalBeforeId = beforeId;
7310        notifyViewAccessibilityStateChangedIfNeeded(
7311                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7312    }
7313
7314    /**
7315     * Gets the id of a view before which this one is visited in accessibility traversal.
7316     *
7317     * @return The id of a view this one precedes in accessibility traversal if
7318     *         specified, otherwise {@link #NO_ID}.
7319     *
7320     * @see #setAccessibilityTraversalBefore(int)
7321     */
7322    public int getAccessibilityTraversalBefore() {
7323        return mAccessibilityTraversalBeforeId;
7324    }
7325
7326    /**
7327     * Sets the id of a view after which this one is visited in accessibility traversal.
7328     * A screen-reader must visit the content of the other view before the content of this
7329     * one. For example, if view B is set to be after view A, then a screen-reader
7330     * will traverse the entire content of A before traversing the entire content of B,
7331     * regardles of what traversal strategy it is using.
7332     * <p>
7333     * Views that do not have specified before/after relationships are traversed in order
7334     * determined by the screen-reader.
7335     * </p>
7336     * <p>
7337     * Setting that this view is after a view that is not important for accessibility
7338     * or if this view is not important for accessibility will have no effect as the
7339     * screen-reader is not aware of unimportant views.
7340     * </p>
7341     *
7342     * @param afterId The id of a view this one succedees in accessibility traversal.
7343     *
7344     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7345     *
7346     * @see #setImportantForAccessibility(int)
7347     */
7348    @RemotableViewMethod
7349    public void setAccessibilityTraversalAfter(int afterId) {
7350        if (mAccessibilityTraversalAfterId == afterId) {
7351            return;
7352        }
7353        mAccessibilityTraversalAfterId = afterId;
7354        notifyViewAccessibilityStateChangedIfNeeded(
7355                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7356    }
7357
7358    /**
7359     * Gets the id of a view after which this one is visited in accessibility traversal.
7360     *
7361     * @return The id of a view this one succeedes in accessibility traversal if
7362     *         specified, otherwise {@link #NO_ID}.
7363     *
7364     * @see #setAccessibilityTraversalAfter(int)
7365     */
7366    public int getAccessibilityTraversalAfter() {
7367        return mAccessibilityTraversalAfterId;
7368    }
7369
7370    /**
7371     * Gets the id of a view for which this view serves as a label for
7372     * accessibility purposes.
7373     *
7374     * @return The labeled view id.
7375     */
7376    @ViewDebug.ExportedProperty(category = "accessibility")
7377    public int getLabelFor() {
7378        return mLabelForId;
7379    }
7380
7381    /**
7382     * Sets the id of a view for which this view serves as a label for
7383     * accessibility purposes.
7384     *
7385     * @param id The labeled view id.
7386     */
7387    @RemotableViewMethod
7388    public void setLabelFor(@IdRes int id) {
7389        if (mLabelForId == id) {
7390            return;
7391        }
7392        mLabelForId = id;
7393        if (mLabelForId != View.NO_ID
7394                && mID == View.NO_ID) {
7395            mID = generateViewId();
7396        }
7397        notifyViewAccessibilityStateChangedIfNeeded(
7398                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7399    }
7400
7401    /**
7402     * Invoked whenever this view loses focus, either by losing window focus or by losing
7403     * focus within its window. This method can be used to clear any state tied to the
7404     * focus. For instance, if a button is held pressed with the trackball and the window
7405     * loses focus, this method can be used to cancel the press.
7406     *
7407     * Subclasses of View overriding this method should always call super.onFocusLost().
7408     *
7409     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7410     * @see #onWindowFocusChanged(boolean)
7411     *
7412     * @hide pending API council approval
7413     */
7414    @CallSuper
7415    protected void onFocusLost() {
7416        resetPressedState();
7417    }
7418
7419    private void resetPressedState() {
7420        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7421            return;
7422        }
7423
7424        if (isPressed()) {
7425            setPressed(false);
7426
7427            if (!mHasPerformedLongPress) {
7428                removeLongPressCallback();
7429            }
7430        }
7431    }
7432
7433    /**
7434     * Returns true if this view has focus
7435     *
7436     * @return True if this view has focus, false otherwise.
7437     */
7438    @ViewDebug.ExportedProperty(category = "focus")
7439    public boolean isFocused() {
7440        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7441    }
7442
7443    /**
7444     * Find the view in the hierarchy rooted at this view that currently has
7445     * focus.
7446     *
7447     * @return The view that currently has focus, or null if no focused view can
7448     *         be found.
7449     */
7450    public View findFocus() {
7451        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7452    }
7453
7454    /**
7455     * Indicates whether this view is one of the set of scrollable containers in
7456     * its window.
7457     *
7458     * @return whether this view is one of the set of scrollable containers in
7459     * its window
7460     *
7461     * @attr ref android.R.styleable#View_isScrollContainer
7462     */
7463    public boolean isScrollContainer() {
7464        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7465    }
7466
7467    /**
7468     * Change whether this view is one of the set of scrollable containers in
7469     * its window.  This will be used to determine whether the window can
7470     * resize or must pan when a soft input area is open -- scrollable
7471     * containers allow the window to use resize mode since the container
7472     * will appropriately shrink.
7473     *
7474     * @attr ref android.R.styleable#View_isScrollContainer
7475     */
7476    public void setScrollContainer(boolean isScrollContainer) {
7477        if (isScrollContainer) {
7478            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7479                mAttachInfo.mScrollContainers.add(this);
7480                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7481            }
7482            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7483        } else {
7484            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7485                mAttachInfo.mScrollContainers.remove(this);
7486            }
7487            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7488        }
7489    }
7490
7491    /**
7492     * Returns the quality of the drawing cache.
7493     *
7494     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7495     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7496     *
7497     * @see #setDrawingCacheQuality(int)
7498     * @see #setDrawingCacheEnabled(boolean)
7499     * @see #isDrawingCacheEnabled()
7500     *
7501     * @attr ref android.R.styleable#View_drawingCacheQuality
7502     */
7503    @DrawingCacheQuality
7504    public int getDrawingCacheQuality() {
7505        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7506    }
7507
7508    /**
7509     * Set the drawing cache quality of this view. This value is used only when the
7510     * drawing cache is enabled
7511     *
7512     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7513     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7514     *
7515     * @see #getDrawingCacheQuality()
7516     * @see #setDrawingCacheEnabled(boolean)
7517     * @see #isDrawingCacheEnabled()
7518     *
7519     * @attr ref android.R.styleable#View_drawingCacheQuality
7520     */
7521    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7522        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7523    }
7524
7525    /**
7526     * Returns whether the screen should remain on, corresponding to the current
7527     * value of {@link #KEEP_SCREEN_ON}.
7528     *
7529     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7530     *
7531     * @see #setKeepScreenOn(boolean)
7532     *
7533     * @attr ref android.R.styleable#View_keepScreenOn
7534     */
7535    public boolean getKeepScreenOn() {
7536        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7537    }
7538
7539    /**
7540     * Controls whether the screen should remain on, modifying the
7541     * value of {@link #KEEP_SCREEN_ON}.
7542     *
7543     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7544     *
7545     * @see #getKeepScreenOn()
7546     *
7547     * @attr ref android.R.styleable#View_keepScreenOn
7548     */
7549    public void setKeepScreenOn(boolean keepScreenOn) {
7550        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7551    }
7552
7553    /**
7554     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7555     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7556     *
7557     * @attr ref android.R.styleable#View_nextFocusLeft
7558     */
7559    public int getNextFocusLeftId() {
7560        return mNextFocusLeftId;
7561    }
7562
7563    /**
7564     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7565     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7566     * decide automatically.
7567     *
7568     * @attr ref android.R.styleable#View_nextFocusLeft
7569     */
7570    public void setNextFocusLeftId(int nextFocusLeftId) {
7571        mNextFocusLeftId = nextFocusLeftId;
7572    }
7573
7574    /**
7575     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7576     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7577     *
7578     * @attr ref android.R.styleable#View_nextFocusRight
7579     */
7580    public int getNextFocusRightId() {
7581        return mNextFocusRightId;
7582    }
7583
7584    /**
7585     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7586     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7587     * decide automatically.
7588     *
7589     * @attr ref android.R.styleable#View_nextFocusRight
7590     */
7591    public void setNextFocusRightId(int nextFocusRightId) {
7592        mNextFocusRightId = nextFocusRightId;
7593    }
7594
7595    /**
7596     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7597     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7598     *
7599     * @attr ref android.R.styleable#View_nextFocusUp
7600     */
7601    public int getNextFocusUpId() {
7602        return mNextFocusUpId;
7603    }
7604
7605    /**
7606     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7607     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7608     * decide automatically.
7609     *
7610     * @attr ref android.R.styleable#View_nextFocusUp
7611     */
7612    public void setNextFocusUpId(int nextFocusUpId) {
7613        mNextFocusUpId = nextFocusUpId;
7614    }
7615
7616    /**
7617     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7618     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7619     *
7620     * @attr ref android.R.styleable#View_nextFocusDown
7621     */
7622    public int getNextFocusDownId() {
7623        return mNextFocusDownId;
7624    }
7625
7626    /**
7627     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7628     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7629     * decide automatically.
7630     *
7631     * @attr ref android.R.styleable#View_nextFocusDown
7632     */
7633    public void setNextFocusDownId(int nextFocusDownId) {
7634        mNextFocusDownId = nextFocusDownId;
7635    }
7636
7637    /**
7638     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7639     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7640     *
7641     * @attr ref android.R.styleable#View_nextFocusForward
7642     */
7643    public int getNextFocusForwardId() {
7644        return mNextFocusForwardId;
7645    }
7646
7647    /**
7648     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7649     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7650     * decide automatically.
7651     *
7652     * @attr ref android.R.styleable#View_nextFocusForward
7653     */
7654    public void setNextFocusForwardId(int nextFocusForwardId) {
7655        mNextFocusForwardId = nextFocusForwardId;
7656    }
7657
7658    /**
7659     * Returns the visibility of this view and all of its ancestors
7660     *
7661     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7662     */
7663    public boolean isShown() {
7664        View current = this;
7665        //noinspection ConstantConditions
7666        do {
7667            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7668                return false;
7669            }
7670            ViewParent parent = current.mParent;
7671            if (parent == null) {
7672                return false; // We are not attached to the view root
7673            }
7674            if (!(parent instanceof View)) {
7675                return true;
7676            }
7677            current = (View) parent;
7678        } while (current != null);
7679
7680        return false;
7681    }
7682
7683    /**
7684     * Called by the view hierarchy when the content insets for a window have
7685     * changed, to allow it to adjust its content to fit within those windows.
7686     * The content insets tell you the space that the status bar, input method,
7687     * and other system windows infringe on the application's window.
7688     *
7689     * <p>You do not normally need to deal with this function, since the default
7690     * window decoration given to applications takes care of applying it to the
7691     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7692     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7693     * and your content can be placed under those system elements.  You can then
7694     * use this method within your view hierarchy if you have parts of your UI
7695     * which you would like to ensure are not being covered.
7696     *
7697     * <p>The default implementation of this method simply applies the content
7698     * insets to the view's padding, consuming that content (modifying the
7699     * insets to be 0), and returning true.  This behavior is off by default, but can
7700     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7701     *
7702     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7703     * insets object is propagated down the hierarchy, so any changes made to it will
7704     * be seen by all following views (including potentially ones above in
7705     * the hierarchy since this is a depth-first traversal).  The first view
7706     * that returns true will abort the entire traversal.
7707     *
7708     * <p>The default implementation works well for a situation where it is
7709     * used with a container that covers the entire window, allowing it to
7710     * apply the appropriate insets to its content on all edges.  If you need
7711     * a more complicated layout (such as two different views fitting system
7712     * windows, one on the top of the window, and one on the bottom),
7713     * you can override the method and handle the insets however you would like.
7714     * Note that the insets provided by the framework are always relative to the
7715     * far edges of the window, not accounting for the location of the called view
7716     * within that window.  (In fact when this method is called you do not yet know
7717     * where the layout will place the view, as it is done before layout happens.)
7718     *
7719     * <p>Note: unlike many View methods, there is no dispatch phase to this
7720     * call.  If you are overriding it in a ViewGroup and want to allow the
7721     * call to continue to your children, you must be sure to call the super
7722     * implementation.
7723     *
7724     * <p>Here is a sample layout that makes use of fitting system windows
7725     * to have controls for a video view placed inside of the window decorations
7726     * that it hides and shows.  This can be used with code like the second
7727     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7728     *
7729     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7730     *
7731     * @param insets Current content insets of the window.  Prior to
7732     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7733     * the insets or else you and Android will be unhappy.
7734     *
7735     * @return {@code true} if this view applied the insets and it should not
7736     * continue propagating further down the hierarchy, {@code false} otherwise.
7737     * @see #getFitsSystemWindows()
7738     * @see #setFitsSystemWindows(boolean)
7739     * @see #setSystemUiVisibility(int)
7740     *
7741     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7742     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7743     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7744     * to implement handling their own insets.
7745     */
7746    @Deprecated
7747    protected boolean fitSystemWindows(Rect insets) {
7748        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7749            if (insets == null) {
7750                // Null insets by definition have already been consumed.
7751                // This call cannot apply insets since there are none to apply,
7752                // so return false.
7753                return false;
7754            }
7755            // If we're not in the process of dispatching the newer apply insets call,
7756            // that means we're not in the compatibility path. Dispatch into the newer
7757            // apply insets path and take things from there.
7758            try {
7759                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7760                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7761            } finally {
7762                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7763            }
7764        } else {
7765            // We're being called from the newer apply insets path.
7766            // Perform the standard fallback behavior.
7767            return fitSystemWindowsInt(insets);
7768        }
7769    }
7770
7771    private boolean fitSystemWindowsInt(Rect insets) {
7772        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7773            mUserPaddingStart = UNDEFINED_PADDING;
7774            mUserPaddingEnd = UNDEFINED_PADDING;
7775            Rect localInsets = sThreadLocal.get();
7776            if (localInsets == null) {
7777                localInsets = new Rect();
7778                sThreadLocal.set(localInsets);
7779            }
7780            boolean res = computeFitSystemWindows(insets, localInsets);
7781            mUserPaddingLeftInitial = localInsets.left;
7782            mUserPaddingRightInitial = localInsets.right;
7783            internalSetPadding(localInsets.left, localInsets.top,
7784                    localInsets.right, localInsets.bottom);
7785            return res;
7786        }
7787        return false;
7788    }
7789
7790    /**
7791     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7792     *
7793     * <p>This method should be overridden by views that wish to apply a policy different from or
7794     * in addition to the default behavior. Clients that wish to force a view subtree
7795     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7796     *
7797     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7798     * it will be called during dispatch instead of this method. The listener may optionally
7799     * call this method from its own implementation if it wishes to apply the view's default
7800     * insets policy in addition to its own.</p>
7801     *
7802     * <p>Implementations of this method should either return the insets parameter unchanged
7803     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7804     * that this view applied itself. This allows new inset types added in future platform
7805     * versions to pass through existing implementations unchanged without being erroneously
7806     * consumed.</p>
7807     *
7808     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7809     * property is set then the view will consume the system window insets and apply them
7810     * as padding for the view.</p>
7811     *
7812     * @param insets Insets to apply
7813     * @return The supplied insets with any applied insets consumed
7814     */
7815    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7816        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7817            // We weren't called from within a direct call to fitSystemWindows,
7818            // call into it as a fallback in case we're in a class that overrides it
7819            // and has logic to perform.
7820            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7821                return insets.consumeSystemWindowInsets();
7822            }
7823        } else {
7824            // We were called from within a direct call to fitSystemWindows.
7825            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7826                return insets.consumeSystemWindowInsets();
7827            }
7828        }
7829        return insets;
7830    }
7831
7832    /**
7833     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7834     * window insets to this view. The listener's
7835     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7836     * method will be called instead of the view's
7837     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7838     *
7839     * @param listener Listener to set
7840     *
7841     * @see #onApplyWindowInsets(WindowInsets)
7842     */
7843    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7844        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7845    }
7846
7847    /**
7848     * Request to apply the given window insets to this view or another view in its subtree.
7849     *
7850     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7851     * obscured by window decorations or overlays. This can include the status and navigation bars,
7852     * action bars, input methods and more. New inset categories may be added in the future.
7853     * The method returns the insets provided minus any that were applied by this view or its
7854     * children.</p>
7855     *
7856     * <p>Clients wishing to provide custom behavior should override the
7857     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7858     * {@link OnApplyWindowInsetsListener} via the
7859     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7860     * method.</p>
7861     *
7862     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7863     * </p>
7864     *
7865     * @param insets Insets to apply
7866     * @return The provided insets minus the insets that were consumed
7867     */
7868    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7869        try {
7870            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7871            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7872                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7873            } else {
7874                return onApplyWindowInsets(insets);
7875            }
7876        } finally {
7877            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7878        }
7879    }
7880
7881    /**
7882     * Compute the view's coordinate within the surface.
7883     *
7884     * <p>Computes the coordinates of this view in its surface. The argument
7885     * must be an array of two integers. After the method returns, the array
7886     * contains the x and y location in that order.</p>
7887     * @hide
7888     * @param location an array of two integers in which to hold the coordinates
7889     */
7890    public void getLocationInSurface(@Size(2) int[] location) {
7891        getLocationInWindow(location);
7892        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7893            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7894            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7895        }
7896    }
7897
7898    /**
7899     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7900     * only available if the view is attached.
7901     *
7902     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7903     */
7904    public WindowInsets getRootWindowInsets() {
7905        if (mAttachInfo != null) {
7906            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7907        }
7908        return null;
7909    }
7910
7911    /**
7912     * @hide Compute the insets that should be consumed by this view and the ones
7913     * that should propagate to those under it.
7914     */
7915    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7916        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7917                || mAttachInfo == null
7918                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7919                        && !mAttachInfo.mOverscanRequested)) {
7920            outLocalInsets.set(inoutInsets);
7921            inoutInsets.set(0, 0, 0, 0);
7922            return true;
7923        } else {
7924            // The application wants to take care of fitting system window for
7925            // the content...  however we still need to take care of any overscan here.
7926            final Rect overscan = mAttachInfo.mOverscanInsets;
7927            outLocalInsets.set(overscan);
7928            inoutInsets.left -= overscan.left;
7929            inoutInsets.top -= overscan.top;
7930            inoutInsets.right -= overscan.right;
7931            inoutInsets.bottom -= overscan.bottom;
7932            return false;
7933        }
7934    }
7935
7936    /**
7937     * Compute insets that should be consumed by this view and the ones that should propagate
7938     * to those under it.
7939     *
7940     * @param in Insets currently being processed by this View, likely received as a parameter
7941     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7942     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7943     *                       by this view
7944     * @return Insets that should be passed along to views under this one
7945     */
7946    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7947        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7948                || mAttachInfo == null
7949                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7950            outLocalInsets.set(in.getSystemWindowInsets());
7951            return in.consumeSystemWindowInsets();
7952        } else {
7953            outLocalInsets.set(0, 0, 0, 0);
7954            return in;
7955        }
7956    }
7957
7958    /**
7959     * Sets whether or not this view should account for system screen decorations
7960     * such as the status bar and inset its content; that is, controlling whether
7961     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7962     * executed.  See that method for more details.
7963     *
7964     * <p>Note that if you are providing your own implementation of
7965     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7966     * flag to true -- your implementation will be overriding the default
7967     * implementation that checks this flag.
7968     *
7969     * @param fitSystemWindows If true, then the default implementation of
7970     * {@link #fitSystemWindows(Rect)} will be executed.
7971     *
7972     * @attr ref android.R.styleable#View_fitsSystemWindows
7973     * @see #getFitsSystemWindows()
7974     * @see #fitSystemWindows(Rect)
7975     * @see #setSystemUiVisibility(int)
7976     */
7977    public void setFitsSystemWindows(boolean fitSystemWindows) {
7978        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7979    }
7980
7981    /**
7982     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7983     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7984     * will be executed.
7985     *
7986     * @return {@code true} if the default implementation of
7987     * {@link #fitSystemWindows(Rect)} will be executed.
7988     *
7989     * @attr ref android.R.styleable#View_fitsSystemWindows
7990     * @see #setFitsSystemWindows(boolean)
7991     * @see #fitSystemWindows(Rect)
7992     * @see #setSystemUiVisibility(int)
7993     */
7994    @ViewDebug.ExportedProperty
7995    public boolean getFitsSystemWindows() {
7996        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7997    }
7998
7999    /** @hide */
8000    public boolean fitsSystemWindows() {
8001        return getFitsSystemWindows();
8002    }
8003
8004    /**
8005     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8006     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8007     */
8008    @Deprecated
8009    public void requestFitSystemWindows() {
8010        if (mParent != null) {
8011            mParent.requestFitSystemWindows();
8012        }
8013    }
8014
8015    /**
8016     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8017     */
8018    public void requestApplyInsets() {
8019        requestFitSystemWindows();
8020    }
8021
8022    /**
8023     * For use by PhoneWindow to make its own system window fitting optional.
8024     * @hide
8025     */
8026    public void makeOptionalFitsSystemWindows() {
8027        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8028    }
8029
8030    /**
8031     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8032     * treat them as such.
8033     * @hide
8034     */
8035    public void getOutsets(Rect outOutsetRect) {
8036        if (mAttachInfo != null) {
8037            outOutsetRect.set(mAttachInfo.mOutsets);
8038        } else {
8039            outOutsetRect.setEmpty();
8040        }
8041    }
8042
8043    /**
8044     * Returns the visibility status for this view.
8045     *
8046     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8047     * @attr ref android.R.styleable#View_visibility
8048     */
8049    @ViewDebug.ExportedProperty(mapping = {
8050        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8051        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8052        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8053    })
8054    @Visibility
8055    public int getVisibility() {
8056        return mViewFlags & VISIBILITY_MASK;
8057    }
8058
8059    /**
8060     * Set the visibility state of this view.
8061     *
8062     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8063     * @attr ref android.R.styleable#View_visibility
8064     */
8065    @RemotableViewMethod
8066    public void setVisibility(@Visibility int visibility) {
8067        setFlags(visibility, VISIBILITY_MASK);
8068    }
8069
8070    /**
8071     * Returns the enabled status for this view. The interpretation of the
8072     * enabled state varies by subclass.
8073     *
8074     * @return True if this view is enabled, false otherwise.
8075     */
8076    @ViewDebug.ExportedProperty
8077    public boolean isEnabled() {
8078        return (mViewFlags & ENABLED_MASK) == ENABLED;
8079    }
8080
8081    /**
8082     * Set the enabled state of this view. The interpretation of the enabled
8083     * state varies by subclass.
8084     *
8085     * @param enabled True if this view is enabled, false otherwise.
8086     */
8087    @RemotableViewMethod
8088    public void setEnabled(boolean enabled) {
8089        if (enabled == isEnabled()) return;
8090
8091        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8092
8093        /*
8094         * The View most likely has to change its appearance, so refresh
8095         * the drawable state.
8096         */
8097        refreshDrawableState();
8098
8099        // Invalidate too, since the default behavior for views is to be
8100        // be drawn at 50% alpha rather than to change the drawable.
8101        invalidate(true);
8102
8103        if (!enabled) {
8104            cancelPendingInputEvents();
8105        }
8106    }
8107
8108    /**
8109     * Set whether this view can receive the focus.
8110     *
8111     * Setting this to false will also ensure that this view is not focusable
8112     * in touch mode.
8113     *
8114     * @param focusable If true, this view can receive the focus.
8115     *
8116     * @see #setFocusableInTouchMode(boolean)
8117     * @attr ref android.R.styleable#View_focusable
8118     */
8119    public void setFocusable(boolean focusable) {
8120        if (!focusable) {
8121            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8122        }
8123        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8124    }
8125
8126    /**
8127     * Set whether this view can receive focus while in touch mode.
8128     *
8129     * Setting this to true will also ensure that this view is focusable.
8130     *
8131     * @param focusableInTouchMode If true, this view can receive the focus while
8132     *   in touch mode.
8133     *
8134     * @see #setFocusable(boolean)
8135     * @attr ref android.R.styleable#View_focusableInTouchMode
8136     */
8137    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8138        // Focusable in touch mode should always be set before the focusable flag
8139        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8140        // which, in touch mode, will not successfully request focus on this view
8141        // because the focusable in touch mode flag is not set
8142        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8143        if (focusableInTouchMode) {
8144            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8145        }
8146    }
8147
8148    /**
8149     * Set whether this view should have sound effects enabled for events such as
8150     * clicking and touching.
8151     *
8152     * <p>You may wish to disable sound effects for a view if you already play sounds,
8153     * for instance, a dial key that plays dtmf tones.
8154     *
8155     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8156     * @see #isSoundEffectsEnabled()
8157     * @see #playSoundEffect(int)
8158     * @attr ref android.R.styleable#View_soundEffectsEnabled
8159     */
8160    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8161        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8162    }
8163
8164    /**
8165     * @return whether this view should have sound effects enabled for events such as
8166     *     clicking and touching.
8167     *
8168     * @see #setSoundEffectsEnabled(boolean)
8169     * @see #playSoundEffect(int)
8170     * @attr ref android.R.styleable#View_soundEffectsEnabled
8171     */
8172    @ViewDebug.ExportedProperty
8173    public boolean isSoundEffectsEnabled() {
8174        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8175    }
8176
8177    /**
8178     * Set whether this view should have haptic feedback for events such as
8179     * long presses.
8180     *
8181     * <p>You may wish to disable haptic feedback if your view already controls
8182     * its own haptic feedback.
8183     *
8184     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8185     * @see #isHapticFeedbackEnabled()
8186     * @see #performHapticFeedback(int)
8187     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8188     */
8189    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8190        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8191    }
8192
8193    /**
8194     * @return whether this view should have haptic feedback enabled for events
8195     * long presses.
8196     *
8197     * @see #setHapticFeedbackEnabled(boolean)
8198     * @see #performHapticFeedback(int)
8199     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8200     */
8201    @ViewDebug.ExportedProperty
8202    public boolean isHapticFeedbackEnabled() {
8203        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8204    }
8205
8206    /**
8207     * Returns the layout direction for this view.
8208     *
8209     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8210     *   {@link #LAYOUT_DIRECTION_RTL},
8211     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8212     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8213     *
8214     * @attr ref android.R.styleable#View_layoutDirection
8215     *
8216     * @hide
8217     */
8218    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8219        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8220        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8221        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8222        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8223    })
8224    @LayoutDir
8225    public int getRawLayoutDirection() {
8226        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8227    }
8228
8229    /**
8230     * Set the layout direction for this view. This will propagate a reset of layout direction
8231     * resolution to the view's children and resolve layout direction for this view.
8232     *
8233     * @param layoutDirection the layout direction to set. Should be one of:
8234     *
8235     * {@link #LAYOUT_DIRECTION_LTR},
8236     * {@link #LAYOUT_DIRECTION_RTL},
8237     * {@link #LAYOUT_DIRECTION_INHERIT},
8238     * {@link #LAYOUT_DIRECTION_LOCALE}.
8239     *
8240     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8241     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8242     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8243     *
8244     * @attr ref android.R.styleable#View_layoutDirection
8245     */
8246    @RemotableViewMethod
8247    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8248        if (getRawLayoutDirection() != layoutDirection) {
8249            // Reset the current layout direction and the resolved one
8250            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8251            resetRtlProperties();
8252            // Set the new layout direction (filtered)
8253            mPrivateFlags2 |=
8254                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8255            // We need to resolve all RTL properties as they all depend on layout direction
8256            resolveRtlPropertiesIfNeeded();
8257            requestLayout();
8258            invalidate(true);
8259        }
8260    }
8261
8262    /**
8263     * Returns the resolved layout direction for this view.
8264     *
8265     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8266     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8267     *
8268     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8269     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8270     *
8271     * @attr ref android.R.styleable#View_layoutDirection
8272     */
8273    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8274        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8275        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8276    })
8277    @ResolvedLayoutDir
8278    public int getLayoutDirection() {
8279        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8280        if (targetSdkVersion < JELLY_BEAN_MR1) {
8281            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8282            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8283        }
8284        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8285                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8286    }
8287
8288    /**
8289     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8290     * layout attribute and/or the inherited value from the parent
8291     *
8292     * @return true if the layout is right-to-left.
8293     *
8294     * @hide
8295     */
8296    @ViewDebug.ExportedProperty(category = "layout")
8297    public boolean isLayoutRtl() {
8298        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8299    }
8300
8301    /**
8302     * Indicates whether the view is currently tracking transient state that the
8303     * app should not need to concern itself with saving and restoring, but that
8304     * the framework should take special note to preserve when possible.
8305     *
8306     * <p>A view with transient state cannot be trivially rebound from an external
8307     * data source, such as an adapter binding item views in a list. This may be
8308     * because the view is performing an animation, tracking user selection
8309     * of content, or similar.</p>
8310     *
8311     * @return true if the view has transient state
8312     */
8313    @ViewDebug.ExportedProperty(category = "layout")
8314    public boolean hasTransientState() {
8315        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8316    }
8317
8318    /**
8319     * Set whether this view is currently tracking transient state that the
8320     * framework should attempt to preserve when possible. This flag is reference counted,
8321     * so every call to setHasTransientState(true) should be paired with a later call
8322     * to setHasTransientState(false).
8323     *
8324     * <p>A view with transient state cannot be trivially rebound from an external
8325     * data source, such as an adapter binding item views in a list. This may be
8326     * because the view is performing an animation, tracking user selection
8327     * of content, or similar.</p>
8328     *
8329     * @param hasTransientState true if this view has transient state
8330     */
8331    public void setHasTransientState(boolean hasTransientState) {
8332        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8333                mTransientStateCount - 1;
8334        if (mTransientStateCount < 0) {
8335            mTransientStateCount = 0;
8336            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8337                    "unmatched pair of setHasTransientState calls");
8338        } else if ((hasTransientState && mTransientStateCount == 1) ||
8339                (!hasTransientState && mTransientStateCount == 0)) {
8340            // update flag if we've just incremented up from 0 or decremented down to 0
8341            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8342                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8343            if (mParent != null) {
8344                try {
8345                    mParent.childHasTransientStateChanged(this, hasTransientState);
8346                } catch (AbstractMethodError e) {
8347                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8348                            " does not fully implement ViewParent", e);
8349                }
8350            }
8351        }
8352    }
8353
8354    /**
8355     * Returns true if this view is currently attached to a window.
8356     */
8357    public boolean isAttachedToWindow() {
8358        return mAttachInfo != null;
8359    }
8360
8361    /**
8362     * Returns true if this view has been through at least one layout since it
8363     * was last attached to or detached from a window.
8364     */
8365    public boolean isLaidOut() {
8366        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8367    }
8368
8369    /**
8370     * If this view doesn't do any drawing on its own, set this flag to
8371     * allow further optimizations. By default, this flag is not set on
8372     * View, but could be set on some View subclasses such as ViewGroup.
8373     *
8374     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8375     * you should clear this flag.
8376     *
8377     * @param willNotDraw whether or not this View draw on its own
8378     */
8379    public void setWillNotDraw(boolean willNotDraw) {
8380        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8381    }
8382
8383    /**
8384     * Returns whether or not this View draws on its own.
8385     *
8386     * @return true if this view has nothing to draw, false otherwise
8387     */
8388    @ViewDebug.ExportedProperty(category = "drawing")
8389    public boolean willNotDraw() {
8390        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8391    }
8392
8393    /**
8394     * When a View's drawing cache is enabled, drawing is redirected to an
8395     * offscreen bitmap. Some views, like an ImageView, must be able to
8396     * bypass this mechanism if they already draw a single bitmap, to avoid
8397     * unnecessary usage of the memory.
8398     *
8399     * @param willNotCacheDrawing true if this view does not cache its
8400     *        drawing, false otherwise
8401     */
8402    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8403        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8404    }
8405
8406    /**
8407     * Returns whether or not this View can cache its drawing or not.
8408     *
8409     * @return true if this view does not cache its drawing, false otherwise
8410     */
8411    @ViewDebug.ExportedProperty(category = "drawing")
8412    public boolean willNotCacheDrawing() {
8413        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8414    }
8415
8416    /**
8417     * Indicates whether this view reacts to click events or not.
8418     *
8419     * @return true if the view is clickable, false otherwise
8420     *
8421     * @see #setClickable(boolean)
8422     * @attr ref android.R.styleable#View_clickable
8423     */
8424    @ViewDebug.ExportedProperty
8425    public boolean isClickable() {
8426        return (mViewFlags & CLICKABLE) == CLICKABLE;
8427    }
8428
8429    /**
8430     * Enables or disables click events for this view. When a view
8431     * is clickable it will change its state to "pressed" on every click.
8432     * Subclasses should set the view clickable to visually react to
8433     * user's clicks.
8434     *
8435     * @param clickable true to make the view clickable, false otherwise
8436     *
8437     * @see #isClickable()
8438     * @attr ref android.R.styleable#View_clickable
8439     */
8440    public void setClickable(boolean clickable) {
8441        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8442    }
8443
8444    /**
8445     * Indicates whether this view reacts to long click events or not.
8446     *
8447     * @return true if the view is long clickable, false otherwise
8448     *
8449     * @see #setLongClickable(boolean)
8450     * @attr ref android.R.styleable#View_longClickable
8451     */
8452    public boolean isLongClickable() {
8453        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8454    }
8455
8456    /**
8457     * Enables or disables long click events for this view. When a view is long
8458     * clickable it reacts to the user holding down the button for a longer
8459     * duration than a tap. This event can either launch the listener or a
8460     * context menu.
8461     *
8462     * @param longClickable true to make the view long clickable, false otherwise
8463     * @see #isLongClickable()
8464     * @attr ref android.R.styleable#View_longClickable
8465     */
8466    public void setLongClickable(boolean longClickable) {
8467        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8468    }
8469
8470    /**
8471     * Indicates whether this view reacts to context clicks or not.
8472     *
8473     * @return true if the view is context clickable, false otherwise
8474     * @see #setContextClickable(boolean)
8475     * @attr ref android.R.styleable#View_contextClickable
8476     */
8477    public boolean isContextClickable() {
8478        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8479    }
8480
8481    /**
8482     * Enables or disables context clicking for this view. This event can launch the listener.
8483     *
8484     * @param contextClickable true to make the view react to a context click, false otherwise
8485     * @see #isContextClickable()
8486     * @attr ref android.R.styleable#View_contextClickable
8487     */
8488    public void setContextClickable(boolean contextClickable) {
8489        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8490    }
8491
8492    /**
8493     * Sets the pressed state for this view and provides a touch coordinate for
8494     * animation hinting.
8495     *
8496     * @param pressed Pass true to set the View's internal state to "pressed",
8497     *            or false to reverts the View's internal state from a
8498     *            previously set "pressed" state.
8499     * @param x The x coordinate of the touch that caused the press
8500     * @param y The y coordinate of the touch that caused the press
8501     */
8502    private void setPressed(boolean pressed, float x, float y) {
8503        if (pressed) {
8504            drawableHotspotChanged(x, y);
8505        }
8506
8507        setPressed(pressed);
8508    }
8509
8510    /**
8511     * Sets the pressed state for this view.
8512     *
8513     * @see #isClickable()
8514     * @see #setClickable(boolean)
8515     *
8516     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8517     *        the View's internal state from a previously set "pressed" state.
8518     */
8519    public void setPressed(boolean pressed) {
8520        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8521
8522        if (pressed) {
8523            mPrivateFlags |= PFLAG_PRESSED;
8524        } else {
8525            mPrivateFlags &= ~PFLAG_PRESSED;
8526        }
8527
8528        if (needsRefresh) {
8529            refreshDrawableState();
8530        }
8531        dispatchSetPressed(pressed);
8532    }
8533
8534    /**
8535     * Dispatch setPressed to all of this View's children.
8536     *
8537     * @see #setPressed(boolean)
8538     *
8539     * @param pressed The new pressed state
8540     */
8541    protected void dispatchSetPressed(boolean pressed) {
8542    }
8543
8544    /**
8545     * Indicates whether the view is currently in pressed state. Unless
8546     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8547     * the pressed state.
8548     *
8549     * @see #setPressed(boolean)
8550     * @see #isClickable()
8551     * @see #setClickable(boolean)
8552     *
8553     * @return true if the view is currently pressed, false otherwise
8554     */
8555    @ViewDebug.ExportedProperty
8556    public boolean isPressed() {
8557        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8558    }
8559
8560    /**
8561     * @hide
8562     * Indicates whether this view will participate in data collection through
8563     * {@link ViewStructure}.  If true, it will not provide any data
8564     * for itself or its children.  If false, the normal data collection will be allowed.
8565     *
8566     * @return Returns false if assist data collection is not blocked, else true.
8567     *
8568     * @see #setAssistBlocked(boolean)
8569     * @attr ref android.R.styleable#View_assistBlocked
8570     */
8571    public boolean isAssistBlocked() {
8572        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8573    }
8574
8575    /**
8576     * @hide
8577     * Controls whether assist data collection from this view and its children is enabled
8578     * (that is, whether {@link #onProvideStructure} and
8579     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8580     * allowing normal assist collection.  Setting this to false will disable assist collection.
8581     *
8582     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8583     * (the default) to allow it.
8584     *
8585     * @see #isAssistBlocked()
8586     * @see #onProvideStructure
8587     * @see #onProvideVirtualStructure
8588     * @attr ref android.R.styleable#View_assistBlocked
8589     */
8590    public void setAssistBlocked(boolean enabled) {
8591        if (enabled) {
8592            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8593        } else {
8594            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8595        }
8596    }
8597
8598    /**
8599     * Indicates whether this view will save its state (that is,
8600     * whether its {@link #onSaveInstanceState} method will be called).
8601     *
8602     * @return Returns true if the view state saving is enabled, else false.
8603     *
8604     * @see #setSaveEnabled(boolean)
8605     * @attr ref android.R.styleable#View_saveEnabled
8606     */
8607    public boolean isSaveEnabled() {
8608        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8609    }
8610
8611    /**
8612     * Controls whether the saving of this view's state is
8613     * enabled (that is, whether its {@link #onSaveInstanceState} method
8614     * will be called).  Note that even if freezing is enabled, the
8615     * view still must have an id assigned to it (via {@link #setId(int)})
8616     * for its state to be saved.  This flag can only disable the
8617     * saving of this view; any child views may still have their state saved.
8618     *
8619     * @param enabled Set to false to <em>disable</em> state saving, or true
8620     * (the default) to allow it.
8621     *
8622     * @see #isSaveEnabled()
8623     * @see #setId(int)
8624     * @see #onSaveInstanceState()
8625     * @attr ref android.R.styleable#View_saveEnabled
8626     */
8627    public void setSaveEnabled(boolean enabled) {
8628        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8629    }
8630
8631    /**
8632     * Gets whether the framework should discard touches when the view's
8633     * window is obscured by another visible window.
8634     * Refer to the {@link View} security documentation for more details.
8635     *
8636     * @return True if touch filtering is enabled.
8637     *
8638     * @see #setFilterTouchesWhenObscured(boolean)
8639     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8640     */
8641    @ViewDebug.ExportedProperty
8642    public boolean getFilterTouchesWhenObscured() {
8643        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8644    }
8645
8646    /**
8647     * Sets whether the framework should discard touches when the view's
8648     * window is obscured by another visible window.
8649     * Refer to the {@link View} security documentation for more details.
8650     *
8651     * @param enabled True if touch filtering should be enabled.
8652     *
8653     * @see #getFilterTouchesWhenObscured
8654     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8655     */
8656    public void setFilterTouchesWhenObscured(boolean enabled) {
8657        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8658                FILTER_TOUCHES_WHEN_OBSCURED);
8659    }
8660
8661    /**
8662     * Indicates whether the entire hierarchy under this view will save its
8663     * state when a state saving traversal occurs from its parent.  The default
8664     * is true; if false, these views will not be saved unless
8665     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8666     *
8667     * @return Returns true if the view state saving from parent is enabled, else false.
8668     *
8669     * @see #setSaveFromParentEnabled(boolean)
8670     */
8671    public boolean isSaveFromParentEnabled() {
8672        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8673    }
8674
8675    /**
8676     * Controls whether the entire hierarchy under this view will save its
8677     * state when a state saving traversal occurs from its parent.  The default
8678     * is true; if false, these views will not be saved unless
8679     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8680     *
8681     * @param enabled Set to false to <em>disable</em> state saving, or true
8682     * (the default) to allow it.
8683     *
8684     * @see #isSaveFromParentEnabled()
8685     * @see #setId(int)
8686     * @see #onSaveInstanceState()
8687     */
8688    public void setSaveFromParentEnabled(boolean enabled) {
8689        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8690    }
8691
8692
8693    /**
8694     * Returns whether this View is able to take focus.
8695     *
8696     * @return True if this view can take focus, or false otherwise.
8697     * @attr ref android.R.styleable#View_focusable
8698     */
8699    @ViewDebug.ExportedProperty(category = "focus")
8700    public final boolean isFocusable() {
8701        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8702    }
8703
8704    /**
8705     * When a view is focusable, it may not want to take focus when in touch mode.
8706     * For example, a button would like focus when the user is navigating via a D-pad
8707     * so that the user can click on it, but once the user starts touching the screen,
8708     * the button shouldn't take focus
8709     * @return Whether the view is focusable in touch mode.
8710     * @attr ref android.R.styleable#View_focusableInTouchMode
8711     */
8712    @ViewDebug.ExportedProperty
8713    public final boolean isFocusableInTouchMode() {
8714        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8715    }
8716
8717    /**
8718     * Find the nearest view in the specified direction that can take focus.
8719     * This does not actually give focus to that view.
8720     *
8721     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8722     *
8723     * @return The nearest focusable in the specified direction, or null if none
8724     *         can be found.
8725     */
8726    public View focusSearch(@FocusRealDirection int direction) {
8727        if (mParent != null) {
8728            return mParent.focusSearch(this, direction);
8729        } else {
8730            return null;
8731        }
8732    }
8733
8734    /**
8735     * This method is the last chance for the focused view and its ancestors to
8736     * respond to an arrow key. This is called when the focused view did not
8737     * consume the key internally, nor could the view system find a new view in
8738     * the requested direction to give focus to.
8739     *
8740     * @param focused The currently focused view.
8741     * @param direction The direction focus wants to move. One of FOCUS_UP,
8742     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8743     * @return True if the this view consumed this unhandled move.
8744     */
8745    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8746        return false;
8747    }
8748
8749    /**
8750     * If a user manually specified the next view id for a particular direction,
8751     * use the root to look up the view.
8752     * @param root The root view of the hierarchy containing this view.
8753     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8754     * or FOCUS_BACKWARD.
8755     * @return The user specified next view, or null if there is none.
8756     */
8757    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8758        switch (direction) {
8759            case FOCUS_LEFT:
8760                if (mNextFocusLeftId == View.NO_ID) return null;
8761                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8762            case FOCUS_RIGHT:
8763                if (mNextFocusRightId == View.NO_ID) return null;
8764                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8765            case FOCUS_UP:
8766                if (mNextFocusUpId == View.NO_ID) return null;
8767                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8768            case FOCUS_DOWN:
8769                if (mNextFocusDownId == View.NO_ID) return null;
8770                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8771            case FOCUS_FORWARD:
8772                if (mNextFocusForwardId == View.NO_ID) return null;
8773                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8774            case FOCUS_BACKWARD: {
8775                if (mID == View.NO_ID) return null;
8776                final int id = mID;
8777                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8778                    @Override
8779                    public boolean apply(View t) {
8780                        return t.mNextFocusForwardId == id;
8781                    }
8782                });
8783            }
8784        }
8785        return null;
8786    }
8787
8788    private View findViewInsideOutShouldExist(View root, int id) {
8789        if (mMatchIdPredicate == null) {
8790            mMatchIdPredicate = new MatchIdPredicate();
8791        }
8792        mMatchIdPredicate.mId = id;
8793        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8794        if (result == null) {
8795            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8796        }
8797        return result;
8798    }
8799
8800    /**
8801     * Find and return all focusable views that are descendants of this view,
8802     * possibly including this view if it is focusable itself.
8803     *
8804     * @param direction The direction of the focus
8805     * @return A list of focusable views
8806     */
8807    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8808        ArrayList<View> result = new ArrayList<View>(24);
8809        addFocusables(result, direction);
8810        return result;
8811    }
8812
8813    /**
8814     * Add any focusable views that are descendants of this view (possibly
8815     * including this view if it is focusable itself) to views.  If we are in touch mode,
8816     * only add views that are also focusable in touch mode.
8817     *
8818     * @param views Focusable views found so far
8819     * @param direction The direction of the focus
8820     */
8821    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8822        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
8823    }
8824
8825    /**
8826     * Adds any focusable views that are descendants of this view (possibly
8827     * including this view if it is focusable itself) to views. This method
8828     * adds all focusable views regardless if we are in touch mode or
8829     * only views focusable in touch mode if we are in touch mode or
8830     * only views that can take accessibility focus if accessibility is enabled
8831     * depending on the focusable mode parameter.
8832     *
8833     * @param views Focusable views found so far or null if all we are interested is
8834     *        the number of focusables.
8835     * @param direction The direction of the focus.
8836     * @param focusableMode The type of focusables to be added.
8837     *
8838     * @see #FOCUSABLES_ALL
8839     * @see #FOCUSABLES_TOUCH_MODE
8840     */
8841    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8842            @FocusableMode int focusableMode) {
8843        if (views == null) {
8844            return;
8845        }
8846        if (!isFocusable()) {
8847            return;
8848        }
8849        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8850                && !isFocusableInTouchMode()) {
8851            return;
8852        }
8853        views.add(this);
8854    }
8855
8856    /**
8857     * Finds the Views that contain given text. The containment is case insensitive.
8858     * The search is performed by either the text that the View renders or the content
8859     * description that describes the view for accessibility purposes and the view does
8860     * not render or both. Clients can specify how the search is to be performed via
8861     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8862     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8863     *
8864     * @param outViews The output list of matching Views.
8865     * @param searched The text to match against.
8866     *
8867     * @see #FIND_VIEWS_WITH_TEXT
8868     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8869     * @see #setContentDescription(CharSequence)
8870     */
8871    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8872            @FindViewFlags int flags) {
8873        if (getAccessibilityNodeProvider() != null) {
8874            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8875                outViews.add(this);
8876            }
8877        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8878                && (searched != null && searched.length() > 0)
8879                && (mContentDescription != null && mContentDescription.length() > 0)) {
8880            String searchedLowerCase = searched.toString().toLowerCase();
8881            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8882            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8883                outViews.add(this);
8884            }
8885        }
8886    }
8887
8888    /**
8889     * Find and return all touchable views that are descendants of this view,
8890     * possibly including this view if it is touchable itself.
8891     *
8892     * @return A list of touchable views
8893     */
8894    public ArrayList<View> getTouchables() {
8895        ArrayList<View> result = new ArrayList<View>();
8896        addTouchables(result);
8897        return result;
8898    }
8899
8900    /**
8901     * Add any touchable views that are descendants of this view (possibly
8902     * including this view if it is touchable itself) to views.
8903     *
8904     * @param views Touchable views found so far
8905     */
8906    public void addTouchables(ArrayList<View> views) {
8907        final int viewFlags = mViewFlags;
8908
8909        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8910                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8911                && (viewFlags & ENABLED_MASK) == ENABLED) {
8912            views.add(this);
8913        }
8914    }
8915
8916    /**
8917     * Returns whether this View is accessibility focused.
8918     *
8919     * @return True if this View is accessibility focused.
8920     */
8921    public boolean isAccessibilityFocused() {
8922        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8923    }
8924
8925    /**
8926     * Call this to try to give accessibility focus to this view.
8927     *
8928     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8929     * returns false or the view is no visible or the view already has accessibility
8930     * focus.
8931     *
8932     * See also {@link #focusSearch(int)}, which is what you call to say that you
8933     * have focus, and you want your parent to look for the next one.
8934     *
8935     * @return Whether this view actually took accessibility focus.
8936     *
8937     * @hide
8938     */
8939    public boolean requestAccessibilityFocus() {
8940        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8941        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8942            return false;
8943        }
8944        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8945            return false;
8946        }
8947        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8948            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8949            ViewRootImpl viewRootImpl = getViewRootImpl();
8950            if (viewRootImpl != null) {
8951                viewRootImpl.setAccessibilityFocus(this, null);
8952            }
8953            invalidate();
8954            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8955            return true;
8956        }
8957        return false;
8958    }
8959
8960    /**
8961     * Call this to try to clear accessibility focus of this view.
8962     *
8963     * See also {@link #focusSearch(int)}, which is what you call to say that you
8964     * have focus, and you want your parent to look for the next one.
8965     *
8966     * @hide
8967     */
8968    public void clearAccessibilityFocus() {
8969        clearAccessibilityFocusNoCallbacks(0);
8970
8971        // Clear the global reference of accessibility focus if this view or
8972        // any of its descendants had accessibility focus. This will NOT send
8973        // an event or update internal state if focus is cleared from a
8974        // descendant view, which may leave views in inconsistent states.
8975        final ViewRootImpl viewRootImpl = getViewRootImpl();
8976        if (viewRootImpl != null) {
8977            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8978            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8979                viewRootImpl.setAccessibilityFocus(null, null);
8980            }
8981        }
8982    }
8983
8984    private void sendAccessibilityHoverEvent(int eventType) {
8985        // Since we are not delivering to a client accessibility events from not
8986        // important views (unless the clinet request that) we need to fire the
8987        // event from the deepest view exposed to the client. As a consequence if
8988        // the user crosses a not exposed view the client will see enter and exit
8989        // of the exposed predecessor followed by and enter and exit of that same
8990        // predecessor when entering and exiting the not exposed descendant. This
8991        // is fine since the client has a clear idea which view is hovered at the
8992        // price of a couple more events being sent. This is a simple and
8993        // working solution.
8994        View source = this;
8995        while (true) {
8996            if (source.includeForAccessibility()) {
8997                source.sendAccessibilityEvent(eventType);
8998                return;
8999            }
9000            ViewParent parent = source.getParent();
9001            if (parent instanceof View) {
9002                source = (View) parent;
9003            } else {
9004                return;
9005            }
9006        }
9007    }
9008
9009    /**
9010     * Clears accessibility focus without calling any callback methods
9011     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9012     * is used separately from that one for clearing accessibility focus when
9013     * giving this focus to another view.
9014     *
9015     * @param action The action, if any, that led to focus being cleared. Set to
9016     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9017     * the window.
9018     */
9019    void clearAccessibilityFocusNoCallbacks(int action) {
9020        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9021            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9022            invalidate();
9023            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9024                AccessibilityEvent event = AccessibilityEvent.obtain(
9025                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9026                event.setAction(action);
9027                if (mAccessibilityDelegate != null) {
9028                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9029                } else {
9030                    sendAccessibilityEventUnchecked(event);
9031                }
9032            }
9033        }
9034    }
9035
9036    /**
9037     * Call this to try to give focus to a specific view or to one of its
9038     * descendants.
9039     *
9040     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9041     * false), or if it is focusable and it is not focusable in touch mode
9042     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9043     *
9044     * See also {@link #focusSearch(int)}, which is what you call to say that you
9045     * have focus, and you want your parent to look for the next one.
9046     *
9047     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9048     * {@link #FOCUS_DOWN} and <code>null</code>.
9049     *
9050     * @return Whether this view or one of its descendants actually took focus.
9051     */
9052    public final boolean requestFocus() {
9053        return requestFocus(View.FOCUS_DOWN);
9054    }
9055
9056    /**
9057     * Call this to try to give focus to a specific view or to one of its
9058     * descendants and give it a hint about what direction focus is heading.
9059     *
9060     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9061     * false), or if it is focusable and it is not focusable in touch mode
9062     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9063     *
9064     * See also {@link #focusSearch(int)}, which is what you call to say that you
9065     * have focus, and you want your parent to look for the next one.
9066     *
9067     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9068     * <code>null</code> set for the previously focused rectangle.
9069     *
9070     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9071     * @return Whether this view or one of its descendants actually took focus.
9072     */
9073    public final boolean requestFocus(int direction) {
9074        return requestFocus(direction, null);
9075    }
9076
9077    /**
9078     * Call this to try to give focus to a specific view or to one of its descendants
9079     * and give it hints about the direction and a specific rectangle that the focus
9080     * is coming from.  The rectangle can help give larger views a finer grained hint
9081     * about where focus is coming from, and therefore, where to show selection, or
9082     * forward focus change internally.
9083     *
9084     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9085     * false), or if it is focusable and it is not focusable in touch mode
9086     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9087     *
9088     * A View will not take focus if it is not visible.
9089     *
9090     * A View will not take focus if one of its parents has
9091     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9092     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9093     *
9094     * See also {@link #focusSearch(int)}, which is what you call to say that you
9095     * have focus, and you want your parent to look for the next one.
9096     *
9097     * You may wish to override this method if your custom {@link View} has an internal
9098     * {@link View} that it wishes to forward the request to.
9099     *
9100     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9101     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9102     *        to give a finer grained hint about where focus is coming from.  May be null
9103     *        if there is no hint.
9104     * @return Whether this view or one of its descendants actually took focus.
9105     */
9106    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9107        return requestFocusNoSearch(direction, previouslyFocusedRect);
9108    }
9109
9110    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9111        // need to be focusable
9112        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9113                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9114            return false;
9115        }
9116
9117        // need to be focusable in touch mode if in touch mode
9118        if (isInTouchMode() &&
9119            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9120               return false;
9121        }
9122
9123        // need to not have any parents blocking us
9124        if (hasAncestorThatBlocksDescendantFocus()) {
9125            return false;
9126        }
9127
9128        handleFocusGainInternal(direction, previouslyFocusedRect);
9129        return true;
9130    }
9131
9132    /**
9133     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9134     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9135     * touch mode to request focus when they are touched.
9136     *
9137     * @return Whether this view or one of its descendants actually took focus.
9138     *
9139     * @see #isInTouchMode()
9140     *
9141     */
9142    public final boolean requestFocusFromTouch() {
9143        // Leave touch mode if we need to
9144        if (isInTouchMode()) {
9145            ViewRootImpl viewRoot = getViewRootImpl();
9146            if (viewRoot != null) {
9147                viewRoot.ensureTouchMode(false);
9148            }
9149        }
9150        return requestFocus(View.FOCUS_DOWN);
9151    }
9152
9153    /**
9154     * @return Whether any ancestor of this view blocks descendant focus.
9155     */
9156    private boolean hasAncestorThatBlocksDescendantFocus() {
9157        final boolean focusableInTouchMode = isFocusableInTouchMode();
9158        ViewParent ancestor = mParent;
9159        while (ancestor instanceof ViewGroup) {
9160            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9161            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9162                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9163                return true;
9164            } else {
9165                ancestor = vgAncestor.getParent();
9166            }
9167        }
9168        return false;
9169    }
9170
9171    /**
9172     * Gets the mode for determining whether this View is important for accessibility.
9173     * A view is important for accessibility if it fires accessibility events and if it
9174     * is reported to accessibility services that query the screen.
9175     *
9176     * @return The mode for determining whether a view is important for accessibility, one
9177     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9178     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9179     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9180     *
9181     * @attr ref android.R.styleable#View_importantForAccessibility
9182     *
9183     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9184     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9185     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9186     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9187     */
9188    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9189            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9190            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9191            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9192            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9193                    to = "noHideDescendants")
9194        })
9195    public int getImportantForAccessibility() {
9196        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9197                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9198    }
9199
9200    /**
9201     * Sets the live region mode for this view. This indicates to accessibility
9202     * services whether they should automatically notify the user about changes
9203     * to the view's content description or text, or to the content descriptions
9204     * or text of the view's children (where applicable).
9205     * <p>
9206     * For example, in a login screen with a TextView that displays an "incorrect
9207     * password" notification, that view should be marked as a live region with
9208     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9209     * <p>
9210     * To disable change notifications for this view, use
9211     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9212     * mode for most views.
9213     * <p>
9214     * To indicate that the user should be notified of changes, use
9215     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9216     * <p>
9217     * If the view's changes should interrupt ongoing speech and notify the user
9218     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9219     *
9220     * @param mode The live region mode for this view, one of:
9221     *        <ul>
9222     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9223     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9224     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9225     *        </ul>
9226     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9227     */
9228    public void setAccessibilityLiveRegion(int mode) {
9229        if (mode != getAccessibilityLiveRegion()) {
9230            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9231            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9232                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9233            notifyViewAccessibilityStateChangedIfNeeded(
9234                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9235        }
9236    }
9237
9238    /**
9239     * Gets the live region mode for this View.
9240     *
9241     * @return The live region mode for the view.
9242     *
9243     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9244     *
9245     * @see #setAccessibilityLiveRegion(int)
9246     */
9247    public int getAccessibilityLiveRegion() {
9248        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9249                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9250    }
9251
9252    /**
9253     * Sets how to determine whether this view is important for accessibility
9254     * which is if it fires accessibility events and if it is reported to
9255     * accessibility services that query the screen.
9256     *
9257     * @param mode How to determine whether this view is important for accessibility.
9258     *
9259     * @attr ref android.R.styleable#View_importantForAccessibility
9260     *
9261     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9262     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9263     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9264     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9265     */
9266    public void setImportantForAccessibility(int mode) {
9267        final int oldMode = getImportantForAccessibility();
9268        if (mode != oldMode) {
9269            final boolean hideDescendants =
9270                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9271
9272            // If this node or its descendants are no longer important, try to
9273            // clear accessibility focus.
9274            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9275                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9276                if (focusHost != null) {
9277                    focusHost.clearAccessibilityFocus();
9278                }
9279            }
9280
9281            // If we're moving between AUTO and another state, we might not need
9282            // to send a subtree changed notification. We'll store the computed
9283            // importance, since we'll need to check it later to make sure.
9284            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9285                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9286            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9287            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9288            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9289                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9290            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9291                notifySubtreeAccessibilityStateChangedIfNeeded();
9292            } else {
9293                notifyViewAccessibilityStateChangedIfNeeded(
9294                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9295            }
9296        }
9297    }
9298
9299    /**
9300     * Returns the view within this view's hierarchy that is hosting
9301     * accessibility focus.
9302     *
9303     * @param searchDescendants whether to search for focus in descendant views
9304     * @return the view hosting accessibility focus, or {@code null}
9305     */
9306    private View findAccessibilityFocusHost(boolean searchDescendants) {
9307        if (isAccessibilityFocusedViewOrHost()) {
9308            return this;
9309        }
9310
9311        if (searchDescendants) {
9312            final ViewRootImpl viewRoot = getViewRootImpl();
9313            if (viewRoot != null) {
9314                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9315                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9316                    return focusHost;
9317                }
9318            }
9319        }
9320
9321        return null;
9322    }
9323
9324    /**
9325     * Computes whether this view should be exposed for accessibility. In
9326     * general, views that are interactive or provide information are exposed
9327     * while views that serve only as containers are hidden.
9328     * <p>
9329     * If an ancestor of this view has importance
9330     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9331     * returns <code>false</code>.
9332     * <p>
9333     * Otherwise, the value is computed according to the view's
9334     * {@link #getImportantForAccessibility()} value:
9335     * <ol>
9336     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9337     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9338     * </code>
9339     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9340     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9341     * view satisfies any of the following:
9342     * <ul>
9343     * <li>Is actionable, e.g. {@link #isClickable()},
9344     * {@link #isLongClickable()}, or {@link #isFocusable()}
9345     * <li>Has an {@link AccessibilityDelegate}
9346     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9347     * {@link OnKeyListener}, etc.
9348     * <li>Is an accessibility live region, e.g.
9349     * {@link #getAccessibilityLiveRegion()} is not
9350     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9351     * </ul>
9352     * </ol>
9353     *
9354     * @return Whether the view is exposed for accessibility.
9355     * @see #setImportantForAccessibility(int)
9356     * @see #getImportantForAccessibility()
9357     */
9358    public boolean isImportantForAccessibility() {
9359        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9360                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9361        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9362                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9363            return false;
9364        }
9365
9366        // Check parent mode to ensure we're not hidden.
9367        ViewParent parent = mParent;
9368        while (parent instanceof View) {
9369            if (((View) parent).getImportantForAccessibility()
9370                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9371                return false;
9372            }
9373            parent = parent.getParent();
9374        }
9375
9376        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9377                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9378                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9379    }
9380
9381    /**
9382     * Gets the parent for accessibility purposes. Note that the parent for
9383     * accessibility is not necessary the immediate parent. It is the first
9384     * predecessor that is important for accessibility.
9385     *
9386     * @return The parent for accessibility purposes.
9387     */
9388    public ViewParent getParentForAccessibility() {
9389        if (mParent instanceof View) {
9390            View parentView = (View) mParent;
9391            if (parentView.includeForAccessibility()) {
9392                return mParent;
9393            } else {
9394                return mParent.getParentForAccessibility();
9395            }
9396        }
9397        return null;
9398    }
9399
9400    /**
9401     * Adds the children of this View relevant for accessibility to the given list
9402     * as output. Since some Views are not important for accessibility the added
9403     * child views are not necessarily direct children of this view, rather they are
9404     * the first level of descendants important for accessibility.
9405     *
9406     * @param outChildren The output list that will receive children for accessibility.
9407     */
9408    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9409
9410    }
9411
9412    /**
9413     * Whether to regard this view for accessibility. A view is regarded for
9414     * accessibility if it is important for accessibility or the querying
9415     * accessibility service has explicitly requested that view not
9416     * important for accessibility are regarded.
9417     *
9418     * @return Whether to regard the view for accessibility.
9419     *
9420     * @hide
9421     */
9422    public boolean includeForAccessibility() {
9423        if (mAttachInfo != null) {
9424            return (mAttachInfo.mAccessibilityFetchFlags
9425                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9426                    || isImportantForAccessibility();
9427        }
9428        return false;
9429    }
9430
9431    /**
9432     * Returns whether the View is considered actionable from
9433     * accessibility perspective. Such view are important for
9434     * accessibility.
9435     *
9436     * @return True if the view is actionable for accessibility.
9437     *
9438     * @hide
9439     */
9440    public boolean isActionableForAccessibility() {
9441        return (isClickable() || isLongClickable() || isFocusable());
9442    }
9443
9444    /**
9445     * Returns whether the View has registered callbacks which makes it
9446     * important for accessibility.
9447     *
9448     * @return True if the view is actionable for accessibility.
9449     */
9450    private boolean hasListenersForAccessibility() {
9451        ListenerInfo info = getListenerInfo();
9452        return mTouchDelegate != null || info.mOnKeyListener != null
9453                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9454                || info.mOnHoverListener != null || info.mOnDragListener != null;
9455    }
9456
9457    /**
9458     * Notifies that the accessibility state of this view changed. The change
9459     * is local to this view and does not represent structural changes such
9460     * as children and parent. For example, the view became focusable. The
9461     * notification is at at most once every
9462     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9463     * to avoid unnecessary load to the system. Also once a view has a pending
9464     * notification this method is a NOP until the notification has been sent.
9465     *
9466     * @hide
9467     */
9468    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9469        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9470            return;
9471        }
9472        if (mSendViewStateChangedAccessibilityEvent == null) {
9473            mSendViewStateChangedAccessibilityEvent =
9474                    new SendViewStateChangedAccessibilityEvent();
9475        }
9476        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9477    }
9478
9479    /**
9480     * Notifies that the accessibility state of this view changed. The change
9481     * is *not* local to this view and does represent structural changes such
9482     * as children and parent. For example, the view size changed. The
9483     * notification is at at most once every
9484     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9485     * to avoid unnecessary load to the system. Also once a view has a pending
9486     * notification this method is a NOP until the notification has been sent.
9487     *
9488     * @hide
9489     */
9490    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9491        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9492            return;
9493        }
9494        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9495            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9496            if (mParent != null) {
9497                try {
9498                    mParent.notifySubtreeAccessibilityStateChanged(
9499                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9500                } catch (AbstractMethodError e) {
9501                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9502                            " does not fully implement ViewParent", e);
9503                }
9504            }
9505        }
9506    }
9507
9508    /**
9509     * Change the visibility of the View without triggering any other changes. This is
9510     * important for transitions, where visibility changes should not adjust focus or
9511     * trigger a new layout. This is only used when the visibility has already been changed
9512     * and we need a transient value during an animation. When the animation completes,
9513     * the original visibility value is always restored.
9514     *
9515     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9516     * @hide
9517     */
9518    public void setTransitionVisibility(@Visibility int visibility) {
9519        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9520    }
9521
9522    /**
9523     * Reset the flag indicating the accessibility state of the subtree rooted
9524     * at this view changed.
9525     */
9526    void resetSubtreeAccessibilityStateChanged() {
9527        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9528    }
9529
9530    /**
9531     * Report an accessibility action to this view's parents for delegated processing.
9532     *
9533     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9534     * call this method to delegate an accessibility action to a supporting parent. If the parent
9535     * returns true from its
9536     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9537     * method this method will return true to signify that the action was consumed.</p>
9538     *
9539     * <p>This method is useful for implementing nested scrolling child views. If
9540     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9541     * a custom view implementation may invoke this method to allow a parent to consume the
9542     * scroll first. If this method returns true the custom view should skip its own scrolling
9543     * behavior.</p>
9544     *
9545     * @param action Accessibility action to delegate
9546     * @param arguments Optional action arguments
9547     * @return true if the action was consumed by a parent
9548     */
9549    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9550        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9551            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9552                return true;
9553            }
9554        }
9555        return false;
9556    }
9557
9558    /**
9559     * Performs the specified accessibility action on the view. For
9560     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9561     * <p>
9562     * If an {@link AccessibilityDelegate} has been specified via calling
9563     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9564     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9565     * is responsible for handling this call.
9566     * </p>
9567     *
9568     * <p>The default implementation will delegate
9569     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9570     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9571     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9572     *
9573     * @param action The action to perform.
9574     * @param arguments Optional action arguments.
9575     * @return Whether the action was performed.
9576     */
9577    public boolean performAccessibilityAction(int action, Bundle arguments) {
9578      if (mAccessibilityDelegate != null) {
9579          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9580      } else {
9581          return performAccessibilityActionInternal(action, arguments);
9582      }
9583    }
9584
9585   /**
9586    * @see #performAccessibilityAction(int, Bundle)
9587    *
9588    * Note: Called from the default {@link AccessibilityDelegate}.
9589    *
9590    * @hide
9591    */
9592    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9593        if (isNestedScrollingEnabled()
9594                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9595                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9596                || action == R.id.accessibilityActionScrollUp
9597                || action == R.id.accessibilityActionScrollLeft
9598                || action == R.id.accessibilityActionScrollDown
9599                || action == R.id.accessibilityActionScrollRight)) {
9600            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9601                return true;
9602            }
9603        }
9604
9605        switch (action) {
9606            case AccessibilityNodeInfo.ACTION_CLICK: {
9607                if (isClickable()) {
9608                    performClick();
9609                    return true;
9610                }
9611            } break;
9612            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9613                if (isLongClickable()) {
9614                    performLongClick();
9615                    return true;
9616                }
9617            } break;
9618            case AccessibilityNodeInfo.ACTION_FOCUS: {
9619                if (!hasFocus()) {
9620                    // Get out of touch mode since accessibility
9621                    // wants to move focus around.
9622                    getViewRootImpl().ensureTouchMode(false);
9623                    return requestFocus();
9624                }
9625            } break;
9626            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9627                if (hasFocus()) {
9628                    clearFocus();
9629                    return !isFocused();
9630                }
9631            } break;
9632            case AccessibilityNodeInfo.ACTION_SELECT: {
9633                if (!isSelected()) {
9634                    setSelected(true);
9635                    return isSelected();
9636                }
9637            } break;
9638            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9639                if (isSelected()) {
9640                    setSelected(false);
9641                    return !isSelected();
9642                }
9643            } break;
9644            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9645                if (!isAccessibilityFocused()) {
9646                    return requestAccessibilityFocus();
9647                }
9648            } break;
9649            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9650                if (isAccessibilityFocused()) {
9651                    clearAccessibilityFocus();
9652                    return true;
9653                }
9654            } break;
9655            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9656                if (arguments != null) {
9657                    final int granularity = arguments.getInt(
9658                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9659                    final boolean extendSelection = arguments.getBoolean(
9660                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9661                    return traverseAtGranularity(granularity, true, extendSelection);
9662                }
9663            } break;
9664            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9665                if (arguments != null) {
9666                    final int granularity = arguments.getInt(
9667                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9668                    final boolean extendSelection = arguments.getBoolean(
9669                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9670                    return traverseAtGranularity(granularity, false, extendSelection);
9671                }
9672            } break;
9673            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9674                CharSequence text = getIterableTextForAccessibility();
9675                if (text == null) {
9676                    return false;
9677                }
9678                final int start = (arguments != null) ? arguments.getInt(
9679                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9680                final int end = (arguments != null) ? arguments.getInt(
9681                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9682                // Only cursor position can be specified (selection length == 0)
9683                if ((getAccessibilitySelectionStart() != start
9684                        || getAccessibilitySelectionEnd() != end)
9685                        && (start == end)) {
9686                    setAccessibilitySelection(start, end);
9687                    notifyViewAccessibilityStateChangedIfNeeded(
9688                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9689                    return true;
9690                }
9691            } break;
9692            case R.id.accessibilityActionShowOnScreen: {
9693                if (mAttachInfo != null) {
9694                    final Rect r = mAttachInfo.mTmpInvalRect;
9695                    getDrawingRect(r);
9696                    return requestRectangleOnScreen(r, true);
9697                }
9698            } break;
9699            case R.id.accessibilityActionContextClick: {
9700                if (isContextClickable()) {
9701                    performContextClick();
9702                    return true;
9703                }
9704            } break;
9705        }
9706        return false;
9707    }
9708
9709    private boolean traverseAtGranularity(int granularity, boolean forward,
9710            boolean extendSelection) {
9711        CharSequence text = getIterableTextForAccessibility();
9712        if (text == null || text.length() == 0) {
9713            return false;
9714        }
9715        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9716        if (iterator == null) {
9717            return false;
9718        }
9719        int current = getAccessibilitySelectionEnd();
9720        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9721            current = forward ? 0 : text.length();
9722        }
9723        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9724        if (range == null) {
9725            return false;
9726        }
9727        final int segmentStart = range[0];
9728        final int segmentEnd = range[1];
9729        int selectionStart;
9730        int selectionEnd;
9731        if (extendSelection && isAccessibilitySelectionExtendable()) {
9732            selectionStart = getAccessibilitySelectionStart();
9733            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9734                selectionStart = forward ? segmentStart : segmentEnd;
9735            }
9736            selectionEnd = forward ? segmentEnd : segmentStart;
9737        } else {
9738            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9739        }
9740        setAccessibilitySelection(selectionStart, selectionEnd);
9741        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9742                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9743        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9744        return true;
9745    }
9746
9747    /**
9748     * Gets the text reported for accessibility purposes.
9749     *
9750     * @return The accessibility text.
9751     *
9752     * @hide
9753     */
9754    public CharSequence getIterableTextForAccessibility() {
9755        return getContentDescription();
9756    }
9757
9758    /**
9759     * Gets whether accessibility selection can be extended.
9760     *
9761     * @return If selection is extensible.
9762     *
9763     * @hide
9764     */
9765    public boolean isAccessibilitySelectionExtendable() {
9766        return false;
9767    }
9768
9769    /**
9770     * @hide
9771     */
9772    public int getAccessibilitySelectionStart() {
9773        return mAccessibilityCursorPosition;
9774    }
9775
9776    /**
9777     * @hide
9778     */
9779    public int getAccessibilitySelectionEnd() {
9780        return getAccessibilitySelectionStart();
9781    }
9782
9783    /**
9784     * @hide
9785     */
9786    public void setAccessibilitySelection(int start, int end) {
9787        if (start ==  end && end == mAccessibilityCursorPosition) {
9788            return;
9789        }
9790        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9791            mAccessibilityCursorPosition = start;
9792        } else {
9793            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9794        }
9795        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9796    }
9797
9798    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9799            int fromIndex, int toIndex) {
9800        if (mParent == null) {
9801            return;
9802        }
9803        AccessibilityEvent event = AccessibilityEvent.obtain(
9804                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9805        onInitializeAccessibilityEvent(event);
9806        onPopulateAccessibilityEvent(event);
9807        event.setFromIndex(fromIndex);
9808        event.setToIndex(toIndex);
9809        event.setAction(action);
9810        event.setMovementGranularity(granularity);
9811        mParent.requestSendAccessibilityEvent(this, event);
9812    }
9813
9814    /**
9815     * @hide
9816     */
9817    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9818        switch (granularity) {
9819            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9820                CharSequence text = getIterableTextForAccessibility();
9821                if (text != null && text.length() > 0) {
9822                    CharacterTextSegmentIterator iterator =
9823                        CharacterTextSegmentIterator.getInstance(
9824                                mContext.getResources().getConfiguration().locale);
9825                    iterator.initialize(text.toString());
9826                    return iterator;
9827                }
9828            } break;
9829            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9830                CharSequence text = getIterableTextForAccessibility();
9831                if (text != null && text.length() > 0) {
9832                    WordTextSegmentIterator iterator =
9833                        WordTextSegmentIterator.getInstance(
9834                                mContext.getResources().getConfiguration().locale);
9835                    iterator.initialize(text.toString());
9836                    return iterator;
9837                }
9838            } break;
9839            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9840                CharSequence text = getIterableTextForAccessibility();
9841                if (text != null && text.length() > 0) {
9842                    ParagraphTextSegmentIterator iterator =
9843                        ParagraphTextSegmentIterator.getInstance();
9844                    iterator.initialize(text.toString());
9845                    return iterator;
9846                }
9847            } break;
9848        }
9849        return null;
9850    }
9851
9852    /**
9853     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
9854     * and {@link #onFinishTemporaryDetach()}.
9855     *
9856     * <p>This method always returns {@code true} when called directly or indirectly from
9857     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
9858     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
9859     * <ul>
9860     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
9861     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
9862     * </ul>
9863     * </p>
9864     *
9865     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9866     * and {@link #onFinishTemporaryDetach()}.
9867     */
9868    public final boolean isTemporarilyDetached() {
9869        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9870    }
9871
9872    /**
9873     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9874     * a container View.
9875     */
9876    @CallSuper
9877    public void dispatchStartTemporaryDetach() {
9878        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9879        onStartTemporaryDetach();
9880    }
9881
9882    /**
9883     * This is called when a container is going to temporarily detach a child, with
9884     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9885     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9886     * {@link #onDetachedFromWindow()} when the container is done.
9887     */
9888    public void onStartTemporaryDetach() {
9889        removeUnsetPressCallback();
9890        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9891    }
9892
9893    /**
9894     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9895     * a container View.
9896     */
9897    @CallSuper
9898    public void dispatchFinishTemporaryDetach() {
9899        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9900        onFinishTemporaryDetach();
9901        if (hasWindowFocus() && hasFocus()) {
9902            InputMethodManager.getInstance().focusIn(this);
9903        }
9904    }
9905
9906    /**
9907     * Called after {@link #onStartTemporaryDetach} when the container is done
9908     * changing the view.
9909     */
9910    public void onFinishTemporaryDetach() {
9911    }
9912
9913    /**
9914     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9915     * for this view's window.  Returns null if the view is not currently attached
9916     * to the window.  Normally you will not need to use this directly, but
9917     * just use the standard high-level event callbacks like
9918     * {@link #onKeyDown(int, KeyEvent)}.
9919     */
9920    public KeyEvent.DispatcherState getKeyDispatcherState() {
9921        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9922    }
9923
9924    /**
9925     * Dispatch a key event before it is processed by any input method
9926     * associated with the view hierarchy.  This can be used to intercept
9927     * key events in special situations before the IME consumes them; a
9928     * typical example would be handling the BACK key to update the application's
9929     * UI instead of allowing the IME to see it and close itself.
9930     *
9931     * @param event The key event to be dispatched.
9932     * @return True if the event was handled, false otherwise.
9933     */
9934    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9935        return onKeyPreIme(event.getKeyCode(), event);
9936    }
9937
9938    /**
9939     * Dispatch a key event to the next view on the focus path. This path runs
9940     * from the top of the view tree down to the currently focused view. If this
9941     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9942     * the next node down the focus path. This method also fires any key
9943     * listeners.
9944     *
9945     * @param event The key event to be dispatched.
9946     * @return True if the event was handled, false otherwise.
9947     */
9948    public boolean dispatchKeyEvent(KeyEvent event) {
9949        if (mInputEventConsistencyVerifier != null) {
9950            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9951        }
9952
9953        // Give any attached key listener a first crack at the event.
9954        //noinspection SimplifiableIfStatement
9955        ListenerInfo li = mListenerInfo;
9956        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9957                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9958            return true;
9959        }
9960
9961        if (event.dispatch(this, mAttachInfo != null
9962                ? mAttachInfo.mKeyDispatchState : null, this)) {
9963            return true;
9964        }
9965
9966        if (mInputEventConsistencyVerifier != null) {
9967            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9968        }
9969        return false;
9970    }
9971
9972    /**
9973     * Dispatches a key shortcut event.
9974     *
9975     * @param event The key event to be dispatched.
9976     * @return True if the event was handled by the view, false otherwise.
9977     */
9978    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9979        return onKeyShortcut(event.getKeyCode(), event);
9980    }
9981
9982    /**
9983     * Pass the touch screen motion event down to the target view, or this
9984     * view if it is the target.
9985     *
9986     * @param event The motion event to be dispatched.
9987     * @return True if the event was handled by the view, false otherwise.
9988     */
9989    public boolean dispatchTouchEvent(MotionEvent event) {
9990        // If the event should be handled by accessibility focus first.
9991        if (event.isTargetAccessibilityFocus()) {
9992            // We don't have focus or no virtual descendant has it, do not handle the event.
9993            if (!isAccessibilityFocusedViewOrHost()) {
9994                return false;
9995            }
9996            // We have focus and got the event, then use normal event dispatch.
9997            event.setTargetAccessibilityFocus(false);
9998        }
9999
10000        boolean result = false;
10001
10002        if (mInputEventConsistencyVerifier != null) {
10003            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10004        }
10005
10006        final int actionMasked = event.getActionMasked();
10007        if (actionMasked == MotionEvent.ACTION_DOWN) {
10008            // Defensive cleanup for new gesture
10009            stopNestedScroll();
10010        }
10011
10012        if (onFilterTouchEventForSecurity(event)) {
10013            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10014                result = true;
10015            }
10016            //noinspection SimplifiableIfStatement
10017            ListenerInfo li = mListenerInfo;
10018            if (li != null && li.mOnTouchListener != null
10019                    && (mViewFlags & ENABLED_MASK) == ENABLED
10020                    && li.mOnTouchListener.onTouch(this, event)) {
10021                result = true;
10022            }
10023
10024            if (!result && onTouchEvent(event)) {
10025                result = true;
10026            }
10027        }
10028
10029        if (!result && mInputEventConsistencyVerifier != null) {
10030            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10031        }
10032
10033        // Clean up after nested scrolls if this is the end of a gesture;
10034        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10035        // of the gesture.
10036        if (actionMasked == MotionEvent.ACTION_UP ||
10037                actionMasked == MotionEvent.ACTION_CANCEL ||
10038                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10039            stopNestedScroll();
10040        }
10041
10042        return result;
10043    }
10044
10045    boolean isAccessibilityFocusedViewOrHost() {
10046        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10047                .getAccessibilityFocusedHost() == this);
10048    }
10049
10050    /**
10051     * Filter the touch event to apply security policies.
10052     *
10053     * @param event The motion event to be filtered.
10054     * @return True if the event should be dispatched, false if the event should be dropped.
10055     *
10056     * @see #getFilterTouchesWhenObscured
10057     */
10058    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10059        //noinspection RedundantIfStatement
10060        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10061                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10062            // Window is obscured, drop this touch.
10063            return false;
10064        }
10065        return true;
10066    }
10067
10068    /**
10069     * Pass a trackball motion event down to the focused view.
10070     *
10071     * @param event The motion event to be dispatched.
10072     * @return True if the event was handled by the view, false otherwise.
10073     */
10074    public boolean dispatchTrackballEvent(MotionEvent event) {
10075        if (mInputEventConsistencyVerifier != null) {
10076            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10077        }
10078
10079        return onTrackballEvent(event);
10080    }
10081
10082    /**
10083     * Dispatch a generic motion event.
10084     * <p>
10085     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10086     * are delivered to the view under the pointer.  All other generic motion events are
10087     * delivered to the focused view.  Hover events are handled specially and are delivered
10088     * to {@link #onHoverEvent(MotionEvent)}.
10089     * </p>
10090     *
10091     * @param event The motion event to be dispatched.
10092     * @return True if the event was handled by the view, false otherwise.
10093     */
10094    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10095        if (mInputEventConsistencyVerifier != null) {
10096            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10097        }
10098
10099        final int source = event.getSource();
10100        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10101            final int action = event.getAction();
10102            if (action == MotionEvent.ACTION_HOVER_ENTER
10103                    || action == MotionEvent.ACTION_HOVER_MOVE
10104                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10105                if (dispatchHoverEvent(event)) {
10106                    return true;
10107                }
10108            } else if (dispatchGenericPointerEvent(event)) {
10109                return true;
10110            }
10111        } else if (dispatchGenericFocusedEvent(event)) {
10112            return true;
10113        }
10114
10115        if (dispatchGenericMotionEventInternal(event)) {
10116            return true;
10117        }
10118
10119        if (mInputEventConsistencyVerifier != null) {
10120            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10121        }
10122        return false;
10123    }
10124
10125    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10126        //noinspection SimplifiableIfStatement
10127        ListenerInfo li = mListenerInfo;
10128        if (li != null && li.mOnGenericMotionListener != null
10129                && (mViewFlags & ENABLED_MASK) == ENABLED
10130                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10131            return true;
10132        }
10133
10134        if (onGenericMotionEvent(event)) {
10135            return true;
10136        }
10137
10138        final int actionButton = event.getActionButton();
10139        switch (event.getActionMasked()) {
10140            case MotionEvent.ACTION_BUTTON_PRESS:
10141                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10142                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10143                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10144                    if (performContextClick(event.getX(), event.getY())) {
10145                        mInContextButtonPress = true;
10146                        setPressed(true, event.getX(), event.getY());
10147                        removeTapCallback();
10148                        removeLongPressCallback();
10149                        return true;
10150                    }
10151                }
10152                break;
10153
10154            case MotionEvent.ACTION_BUTTON_RELEASE:
10155                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10156                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10157                    mInContextButtonPress = false;
10158                    mIgnoreNextUpEvent = true;
10159                }
10160                break;
10161        }
10162
10163        if (mInputEventConsistencyVerifier != null) {
10164            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10165        }
10166        return false;
10167    }
10168
10169    /**
10170     * Dispatch a hover event.
10171     * <p>
10172     * Do not call this method directly.
10173     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10174     * </p>
10175     *
10176     * @param event The motion event to be dispatched.
10177     * @return True if the event was handled by the view, false otherwise.
10178     */
10179    protected boolean dispatchHoverEvent(MotionEvent event) {
10180        ListenerInfo li = mListenerInfo;
10181        //noinspection SimplifiableIfStatement
10182        if (li != null && li.mOnHoverListener != null
10183                && (mViewFlags & ENABLED_MASK) == ENABLED
10184                && li.mOnHoverListener.onHover(this, event)) {
10185            return true;
10186        }
10187
10188        return onHoverEvent(event);
10189    }
10190
10191    /**
10192     * Returns true if the view has a child to which it has recently sent
10193     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10194     * it does not have a hovered child, then it must be the innermost hovered view.
10195     * @hide
10196     */
10197    protected boolean hasHoveredChild() {
10198        return false;
10199    }
10200
10201    /**
10202     * Dispatch a generic motion event to the view under the first pointer.
10203     * <p>
10204     * Do not call this method directly.
10205     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10206     * </p>
10207     *
10208     * @param event The motion event to be dispatched.
10209     * @return True if the event was handled by the view, false otherwise.
10210     */
10211    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10212        return false;
10213    }
10214
10215    /**
10216     * Dispatch a generic motion event to the currently focused view.
10217     * <p>
10218     * Do not call this method directly.
10219     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10220     * </p>
10221     *
10222     * @param event The motion event to be dispatched.
10223     * @return True if the event was handled by the view, false otherwise.
10224     */
10225    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10226        return false;
10227    }
10228
10229    /**
10230     * Dispatch a pointer event.
10231     * <p>
10232     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10233     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10234     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10235     * and should not be expected to handle other pointing device features.
10236     * </p>
10237     *
10238     * @param event The motion event to be dispatched.
10239     * @return True if the event was handled by the view, false otherwise.
10240     * @hide
10241     */
10242    public final boolean dispatchPointerEvent(MotionEvent event) {
10243        if (event.isTouchEvent()) {
10244            return dispatchTouchEvent(event);
10245        } else {
10246            return dispatchGenericMotionEvent(event);
10247        }
10248    }
10249
10250    /**
10251     * Called when the window containing this view gains or loses window focus.
10252     * ViewGroups should override to route to their children.
10253     *
10254     * @param hasFocus True if the window containing this view now has focus,
10255     *        false otherwise.
10256     */
10257    public void dispatchWindowFocusChanged(boolean hasFocus) {
10258        onWindowFocusChanged(hasFocus);
10259    }
10260
10261    /**
10262     * Called when the window containing this view gains or loses focus.  Note
10263     * that this is separate from view focus: to receive key events, both
10264     * your view and its window must have focus.  If a window is displayed
10265     * on top of yours that takes input focus, then your own window will lose
10266     * focus but the view focus will remain unchanged.
10267     *
10268     * @param hasWindowFocus True if the window containing this view now has
10269     *        focus, false otherwise.
10270     */
10271    public void onWindowFocusChanged(boolean hasWindowFocus) {
10272        InputMethodManager imm = InputMethodManager.peekInstance();
10273        if (!hasWindowFocus) {
10274            if (isPressed()) {
10275                setPressed(false);
10276            }
10277            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10278                imm.focusOut(this);
10279            }
10280            removeLongPressCallback();
10281            removeTapCallback();
10282            onFocusLost();
10283        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10284            imm.focusIn(this);
10285        }
10286        refreshDrawableState();
10287    }
10288
10289    /**
10290     * Returns true if this view is in a window that currently has window focus.
10291     * Note that this is not the same as the view itself having focus.
10292     *
10293     * @return True if this view is in a window that currently has window focus.
10294     */
10295    public boolean hasWindowFocus() {
10296        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10297    }
10298
10299    /**
10300     * Dispatch a view visibility change down the view hierarchy.
10301     * ViewGroups should override to route to their children.
10302     * @param changedView The view whose visibility changed. Could be 'this' or
10303     * an ancestor view.
10304     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10305     * {@link #INVISIBLE} or {@link #GONE}.
10306     */
10307    protected void dispatchVisibilityChanged(@NonNull View changedView,
10308            @Visibility int visibility) {
10309        onVisibilityChanged(changedView, visibility);
10310    }
10311
10312    /**
10313     * Called when the visibility of the view or an ancestor of the view has
10314     * changed.
10315     *
10316     * @param changedView The view whose visibility changed. May be
10317     *                    {@code this} or an ancestor view.
10318     * @param visibility The new visibility, one of {@link #VISIBLE},
10319     *                   {@link #INVISIBLE} or {@link #GONE}.
10320     */
10321    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10322    }
10323
10324    /**
10325     * Dispatch a hint about whether this view is displayed. For instance, when
10326     * a View moves out of the screen, it might receives a display hint indicating
10327     * the view is not displayed. Applications should not <em>rely</em> on this hint
10328     * as there is no guarantee that they will receive one.
10329     *
10330     * @param hint A hint about whether or not this view is displayed:
10331     * {@link #VISIBLE} or {@link #INVISIBLE}.
10332     */
10333    public void dispatchDisplayHint(@Visibility int hint) {
10334        onDisplayHint(hint);
10335    }
10336
10337    /**
10338     * Gives this view a hint about whether is displayed or not. For instance, when
10339     * a View moves out of the screen, it might receives a display hint indicating
10340     * the view is not displayed. Applications should not <em>rely</em> on this hint
10341     * as there is no guarantee that they will receive one.
10342     *
10343     * @param hint A hint about whether or not this view is displayed:
10344     * {@link #VISIBLE} or {@link #INVISIBLE}.
10345     */
10346    protected void onDisplayHint(@Visibility int hint) {
10347    }
10348
10349    /**
10350     * Dispatch a window visibility change down the view hierarchy.
10351     * ViewGroups should override to route to their children.
10352     *
10353     * @param visibility The new visibility of the window.
10354     *
10355     * @see #onWindowVisibilityChanged(int)
10356     */
10357    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10358        onWindowVisibilityChanged(visibility);
10359    }
10360
10361    /**
10362     * Called when the window containing has change its visibility
10363     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10364     * that this tells you whether or not your window is being made visible
10365     * to the window manager; this does <em>not</em> tell you whether or not
10366     * your window is obscured by other windows on the screen, even if it
10367     * is itself visible.
10368     *
10369     * @param visibility The new visibility of the window.
10370     */
10371    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10372        if (visibility == VISIBLE) {
10373            initialAwakenScrollBars();
10374        }
10375    }
10376
10377    /**
10378     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10379     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10380     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10381     *
10382     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10383     *                  ancestors or by window visibility
10384     * @return true if this view is visible to the user, not counting clipping or overlapping
10385     */
10386    boolean dispatchVisibilityAggregated(boolean isVisible) {
10387        final boolean thisVisible = getVisibility() == VISIBLE;
10388        // If we're not visible but something is telling us we are, ignore it.
10389        if (thisVisible || !isVisible) {
10390            onVisibilityAggregated(isVisible);
10391        }
10392        return thisVisible && isVisible;
10393    }
10394
10395    /**
10396     * Called when the user-visibility of this View is potentially affected by a change
10397     * to this view itself, an ancestor view or the window this view is attached to.
10398     *
10399     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10400     *                  and this view's window is also visible
10401     */
10402    @CallSuper
10403    public void onVisibilityAggregated(boolean isVisible) {
10404        if (isVisible && mAttachInfo != null) {
10405            initialAwakenScrollBars();
10406        }
10407
10408        final Drawable dr = mBackground;
10409        if (dr != null && isVisible != dr.isVisible()) {
10410            dr.setVisible(isVisible, false);
10411        }
10412        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10413        if (fg != null && isVisible != fg.isVisible()) {
10414            fg.setVisible(isVisible, false);
10415        }
10416    }
10417
10418    /**
10419     * Returns the current visibility of the window this view is attached to
10420     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10421     *
10422     * @return Returns the current visibility of the view's window.
10423     */
10424    @Visibility
10425    public int getWindowVisibility() {
10426        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10427    }
10428
10429    /**
10430     * Retrieve the overall visible display size in which the window this view is
10431     * attached to has been positioned in.  This takes into account screen
10432     * decorations above the window, for both cases where the window itself
10433     * is being position inside of them or the window is being placed under
10434     * then and covered insets are used for the window to position its content
10435     * inside.  In effect, this tells you the available area where content can
10436     * be placed and remain visible to users.
10437     *
10438     * <p>This function requires an IPC back to the window manager to retrieve
10439     * the requested information, so should not be used in performance critical
10440     * code like drawing.
10441     *
10442     * @param outRect Filled in with the visible display frame.  If the view
10443     * is not attached to a window, this is simply the raw display size.
10444     */
10445    public void getWindowVisibleDisplayFrame(Rect outRect) {
10446        if (mAttachInfo != null) {
10447            try {
10448                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10449            } catch (RemoteException e) {
10450                return;
10451            }
10452            // XXX This is really broken, and probably all needs to be done
10453            // in the window manager, and we need to know more about whether
10454            // we want the area behind or in front of the IME.
10455            final Rect insets = mAttachInfo.mVisibleInsets;
10456            outRect.left += insets.left;
10457            outRect.top += insets.top;
10458            outRect.right -= insets.right;
10459            outRect.bottom -= insets.bottom;
10460            return;
10461        }
10462        // The view is not attached to a display so we don't have a context.
10463        // Make a best guess about the display size.
10464        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10465        d.getRectSize(outRect);
10466    }
10467
10468    /**
10469     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10470     * is currently in without any insets.
10471     *
10472     * @hide
10473     */
10474    public void getWindowDisplayFrame(Rect outRect) {
10475        if (mAttachInfo != null) {
10476            try {
10477                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10478            } catch (RemoteException e) {
10479                return;
10480            }
10481            return;
10482        }
10483        // The view is not attached to a display so we don't have a context.
10484        // Make a best guess about the display size.
10485        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10486        d.getRectSize(outRect);
10487    }
10488
10489    /**
10490     * Dispatch a notification about a resource configuration change down
10491     * the view hierarchy.
10492     * ViewGroups should override to route to their children.
10493     *
10494     * @param newConfig The new resource configuration.
10495     *
10496     * @see #onConfigurationChanged(android.content.res.Configuration)
10497     */
10498    public void dispatchConfigurationChanged(Configuration newConfig) {
10499        onConfigurationChanged(newConfig);
10500    }
10501
10502    /**
10503     * Called when the current configuration of the resources being used
10504     * by the application have changed.  You can use this to decide when
10505     * to reload resources that can changed based on orientation and other
10506     * configuration characteristics.  You only need to use this if you are
10507     * not relying on the normal {@link android.app.Activity} mechanism of
10508     * recreating the activity instance upon a configuration change.
10509     *
10510     * @param newConfig The new resource configuration.
10511     */
10512    protected void onConfigurationChanged(Configuration newConfig) {
10513    }
10514
10515    /**
10516     * Private function to aggregate all per-view attributes in to the view
10517     * root.
10518     */
10519    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10520        performCollectViewAttributes(attachInfo, visibility);
10521    }
10522
10523    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10524        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10525            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10526                attachInfo.mKeepScreenOn = true;
10527            }
10528            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10529            ListenerInfo li = mListenerInfo;
10530            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10531                attachInfo.mHasSystemUiListeners = true;
10532            }
10533        }
10534    }
10535
10536    void needGlobalAttributesUpdate(boolean force) {
10537        final AttachInfo ai = mAttachInfo;
10538        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10539            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10540                    || ai.mHasSystemUiListeners) {
10541                ai.mRecomputeGlobalAttributes = true;
10542            }
10543        }
10544    }
10545
10546    /**
10547     * Returns whether the device is currently in touch mode.  Touch mode is entered
10548     * once the user begins interacting with the device by touch, and affects various
10549     * things like whether focus is always visible to the user.
10550     *
10551     * @return Whether the device is in touch mode.
10552     */
10553    @ViewDebug.ExportedProperty
10554    public boolean isInTouchMode() {
10555        if (mAttachInfo != null) {
10556            return mAttachInfo.mInTouchMode;
10557        } else {
10558            return ViewRootImpl.isInTouchMode();
10559        }
10560    }
10561
10562    /**
10563     * Returns the context the view is running in, through which it can
10564     * access the current theme, resources, etc.
10565     *
10566     * @return The view's Context.
10567     */
10568    @ViewDebug.CapturedViewProperty
10569    public final Context getContext() {
10570        return mContext;
10571    }
10572
10573    /**
10574     * Handle a key event before it is processed by any input method
10575     * associated with the view hierarchy.  This can be used to intercept
10576     * key events in special situations before the IME consumes them; a
10577     * typical example would be handling the BACK key to update the application's
10578     * UI instead of allowing the IME to see it and close itself.
10579     *
10580     * @param keyCode The value in event.getKeyCode().
10581     * @param event Description of the key event.
10582     * @return If you handled the event, return true. If you want to allow the
10583     *         event to be handled by the next receiver, return false.
10584     */
10585    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10586        return false;
10587    }
10588
10589    /**
10590     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10591     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10592     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10593     * is released, if the view is enabled and clickable.
10594     * <p>
10595     * Key presses in software keyboards will generally NOT trigger this
10596     * listener, although some may elect to do so in some situations. Do not
10597     * rely on this to catch software key presses.
10598     *
10599     * @param keyCode a key code that represents the button pressed, from
10600     *                {@link android.view.KeyEvent}
10601     * @param event the KeyEvent object that defines the button action
10602     */
10603    public boolean onKeyDown(int keyCode, KeyEvent event) {
10604        if (KeyEvent.isConfirmKey(keyCode)) {
10605            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10606                return true;
10607            }
10608
10609            // Long clickable items don't necessarily have to be clickable.
10610            if (((mViewFlags & CLICKABLE) == CLICKABLE
10611                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10612                    && (event.getRepeatCount() == 0)) {
10613                // For the purposes of menu anchoring and drawable hotspots,
10614                // key events are considered to be at the center of the view.
10615                final float x = getWidth() / 2f;
10616                final float y = getHeight() / 2f;
10617                setPressed(true, x, y);
10618                checkForLongClick(0, x, y);
10619                return true;
10620            }
10621        }
10622
10623        return false;
10624    }
10625
10626    /**
10627     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10628     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10629     * the event).
10630     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10631     * although some may elect to do so in some situations. Do not rely on this to
10632     * catch software key presses.
10633     */
10634    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10635        return false;
10636    }
10637
10638    /**
10639     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10640     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10641     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10642     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10643     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10644     * although some may elect to do so in some situations. Do not rely on this to
10645     * catch software key presses.
10646     *
10647     * @param keyCode A key code that represents the button pressed, from
10648     *                {@link android.view.KeyEvent}.
10649     * @param event   The KeyEvent object that defines the button action.
10650     */
10651    public boolean onKeyUp(int keyCode, KeyEvent event) {
10652        if (KeyEvent.isConfirmKey(keyCode)) {
10653            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10654                return true;
10655            }
10656            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10657                setPressed(false);
10658
10659                if (!mHasPerformedLongPress) {
10660                    // This is a tap, so remove the longpress check
10661                    removeLongPressCallback();
10662                    return performClick();
10663                }
10664            }
10665        }
10666        return false;
10667    }
10668
10669    /**
10670     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10671     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10672     * the event).
10673     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10674     * although some may elect to do so in some situations. Do not rely on this to
10675     * catch software key presses.
10676     *
10677     * @param keyCode     A key code that represents the button pressed, from
10678     *                    {@link android.view.KeyEvent}.
10679     * @param repeatCount The number of times the action was made.
10680     * @param event       The KeyEvent object that defines the button action.
10681     */
10682    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10683        return false;
10684    }
10685
10686    /**
10687     * Called on the focused view when a key shortcut event is not handled.
10688     * Override this method to implement local key shortcuts for the View.
10689     * Key shortcuts can also be implemented by setting the
10690     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10691     *
10692     * @param keyCode The value in event.getKeyCode().
10693     * @param event Description of the key event.
10694     * @return If you handled the event, return true. If you want to allow the
10695     *         event to be handled by the next receiver, return false.
10696     */
10697    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10698        return false;
10699    }
10700
10701    /**
10702     * Check whether the called view is a text editor, in which case it
10703     * would make sense to automatically display a soft input window for
10704     * it.  Subclasses should override this if they implement
10705     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10706     * a call on that method would return a non-null InputConnection, and
10707     * they are really a first-class editor that the user would normally
10708     * start typing on when the go into a window containing your view.
10709     *
10710     * <p>The default implementation always returns false.  This does
10711     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10712     * will not be called or the user can not otherwise perform edits on your
10713     * view; it is just a hint to the system that this is not the primary
10714     * purpose of this view.
10715     *
10716     * @return Returns true if this view is a text editor, else false.
10717     */
10718    public boolean onCheckIsTextEditor() {
10719        return false;
10720    }
10721
10722    /**
10723     * Create a new InputConnection for an InputMethod to interact
10724     * with the view.  The default implementation returns null, since it doesn't
10725     * support input methods.  You can override this to implement such support.
10726     * This is only needed for views that take focus and text input.
10727     *
10728     * <p>When implementing this, you probably also want to implement
10729     * {@link #onCheckIsTextEditor()} to indicate you will return a
10730     * non-null InputConnection.</p>
10731     *
10732     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10733     * object correctly and in its entirety, so that the connected IME can rely
10734     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10735     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10736     * must be filled in with the correct cursor position for IMEs to work correctly
10737     * with your application.</p>
10738     *
10739     * @param outAttrs Fill in with attribute information about the connection.
10740     */
10741    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10742        return null;
10743    }
10744
10745    /**
10746     * Called by the {@link android.view.inputmethod.InputMethodManager}
10747     * when a view who is not the current
10748     * input connection target is trying to make a call on the manager.  The
10749     * default implementation returns false; you can override this to return
10750     * true for certain views if you are performing InputConnection proxying
10751     * to them.
10752     * @param view The View that is making the InputMethodManager call.
10753     * @return Return true to allow the call, false to reject.
10754     */
10755    public boolean checkInputConnectionProxy(View view) {
10756        return false;
10757    }
10758
10759    /**
10760     * Show the context menu for this view. It is not safe to hold on to the
10761     * menu after returning from this method.
10762     *
10763     * You should normally not overload this method. Overload
10764     * {@link #onCreateContextMenu(ContextMenu)} or define an
10765     * {@link OnCreateContextMenuListener} to add items to the context menu.
10766     *
10767     * @param menu The context menu to populate
10768     */
10769    public void createContextMenu(ContextMenu menu) {
10770        ContextMenuInfo menuInfo = getContextMenuInfo();
10771
10772        // Sets the current menu info so all items added to menu will have
10773        // my extra info set.
10774        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10775
10776        onCreateContextMenu(menu);
10777        ListenerInfo li = mListenerInfo;
10778        if (li != null && li.mOnCreateContextMenuListener != null) {
10779            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10780        }
10781
10782        // Clear the extra information so subsequent items that aren't mine don't
10783        // have my extra info.
10784        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10785
10786        if (mParent != null) {
10787            mParent.createContextMenu(menu);
10788        }
10789    }
10790
10791    /**
10792     * Views should implement this if they have extra information to associate
10793     * with the context menu. The return result is supplied as a parameter to
10794     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10795     * callback.
10796     *
10797     * @return Extra information about the item for which the context menu
10798     *         should be shown. This information will vary across different
10799     *         subclasses of View.
10800     */
10801    protected ContextMenuInfo getContextMenuInfo() {
10802        return null;
10803    }
10804
10805    /**
10806     * Views should implement this if the view itself is going to add items to
10807     * the context menu.
10808     *
10809     * @param menu the context menu to populate
10810     */
10811    protected void onCreateContextMenu(ContextMenu menu) {
10812    }
10813
10814    /**
10815     * Implement this method to handle trackball motion events.  The
10816     * <em>relative</em> movement of the trackball since the last event
10817     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10818     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10819     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10820     * they will often be fractional values, representing the more fine-grained
10821     * movement information available from a trackball).
10822     *
10823     * @param event The motion event.
10824     * @return True if the event was handled, false otherwise.
10825     */
10826    public boolean onTrackballEvent(MotionEvent event) {
10827        return false;
10828    }
10829
10830    /**
10831     * Implement this method to handle generic motion events.
10832     * <p>
10833     * Generic motion events describe joystick movements, mouse hovers, track pad
10834     * touches, scroll wheel movements and other input events.  The
10835     * {@link MotionEvent#getSource() source} of the motion event specifies
10836     * the class of input that was received.  Implementations of this method
10837     * must examine the bits in the source before processing the event.
10838     * The following code example shows how this is done.
10839     * </p><p>
10840     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10841     * are delivered to the view under the pointer.  All other generic motion events are
10842     * delivered to the focused view.
10843     * </p>
10844     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10845     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10846     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10847     *             // process the joystick movement...
10848     *             return true;
10849     *         }
10850     *     }
10851     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10852     *         switch (event.getAction()) {
10853     *             case MotionEvent.ACTION_HOVER_MOVE:
10854     *                 // process the mouse hover movement...
10855     *                 return true;
10856     *             case MotionEvent.ACTION_SCROLL:
10857     *                 // process the scroll wheel movement...
10858     *                 return true;
10859     *         }
10860     *     }
10861     *     return super.onGenericMotionEvent(event);
10862     * }</pre>
10863     *
10864     * @param event The generic motion event being processed.
10865     * @return True if the event was handled, false otherwise.
10866     */
10867    public boolean onGenericMotionEvent(MotionEvent event) {
10868        return false;
10869    }
10870
10871    /**
10872     * Implement this method to handle hover events.
10873     * <p>
10874     * This method is called whenever a pointer is hovering into, over, or out of the
10875     * bounds of a view and the view is not currently being touched.
10876     * Hover events are represented as pointer events with action
10877     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10878     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10879     * </p>
10880     * <ul>
10881     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10882     * when the pointer enters the bounds of the view.</li>
10883     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10884     * when the pointer has already entered the bounds of the view and has moved.</li>
10885     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10886     * when the pointer has exited the bounds of the view or when the pointer is
10887     * about to go down due to a button click, tap, or similar user action that
10888     * causes the view to be touched.</li>
10889     * </ul>
10890     * <p>
10891     * The view should implement this method to return true to indicate that it is
10892     * handling the hover event, such as by changing its drawable state.
10893     * </p><p>
10894     * The default implementation calls {@link #setHovered} to update the hovered state
10895     * of the view when a hover enter or hover exit event is received, if the view
10896     * is enabled and is clickable.  The default implementation also sends hover
10897     * accessibility events.
10898     * </p>
10899     *
10900     * @param event The motion event that describes the hover.
10901     * @return True if the view handled the hover event.
10902     *
10903     * @see #isHovered
10904     * @see #setHovered
10905     * @see #onHoverChanged
10906     */
10907    public boolean onHoverEvent(MotionEvent event) {
10908        // The root view may receive hover (or touch) events that are outside the bounds of
10909        // the window.  This code ensures that we only send accessibility events for
10910        // hovers that are actually within the bounds of the root view.
10911        final int action = event.getActionMasked();
10912        if (!mSendingHoverAccessibilityEvents) {
10913            if ((action == MotionEvent.ACTION_HOVER_ENTER
10914                    || action == MotionEvent.ACTION_HOVER_MOVE)
10915                    && !hasHoveredChild()
10916                    && pointInView(event.getX(), event.getY())) {
10917                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10918                mSendingHoverAccessibilityEvents = true;
10919            }
10920        } else {
10921            if (action == MotionEvent.ACTION_HOVER_EXIT
10922                    || (action == MotionEvent.ACTION_MOVE
10923                            && !pointInView(event.getX(), event.getY()))) {
10924                mSendingHoverAccessibilityEvents = false;
10925                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10926            }
10927        }
10928
10929        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10930                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10931                && isOnScrollbar(event.getX(), event.getY())) {
10932            awakenScrollBars();
10933        }
10934        if (isHoverable()) {
10935            switch (action) {
10936                case MotionEvent.ACTION_HOVER_ENTER:
10937                    setHovered(true);
10938                    break;
10939                case MotionEvent.ACTION_HOVER_EXIT:
10940                    setHovered(false);
10941                    break;
10942            }
10943
10944            // Dispatch the event to onGenericMotionEvent before returning true.
10945            // This is to provide compatibility with existing applications that
10946            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10947            // break because of the new default handling for hoverable views
10948            // in onHoverEvent.
10949            // Note that onGenericMotionEvent will be called by default when
10950            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10951            dispatchGenericMotionEventInternal(event);
10952            // The event was already handled by calling setHovered(), so always
10953            // return true.
10954            return true;
10955        }
10956
10957        return false;
10958    }
10959
10960    /**
10961     * Returns true if the view should handle {@link #onHoverEvent}
10962     * by calling {@link #setHovered} to change its hovered state.
10963     *
10964     * @return True if the view is hoverable.
10965     */
10966    private boolean isHoverable() {
10967        final int viewFlags = mViewFlags;
10968        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10969            return false;
10970        }
10971
10972        return (viewFlags & CLICKABLE) == CLICKABLE
10973                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10974                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10975    }
10976
10977    /**
10978     * Returns true if the view is currently hovered.
10979     *
10980     * @return True if the view is currently hovered.
10981     *
10982     * @see #setHovered
10983     * @see #onHoverChanged
10984     */
10985    @ViewDebug.ExportedProperty
10986    public boolean isHovered() {
10987        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10988    }
10989
10990    /**
10991     * Sets whether the view is currently hovered.
10992     * <p>
10993     * Calling this method also changes the drawable state of the view.  This
10994     * enables the view to react to hover by using different drawable resources
10995     * to change its appearance.
10996     * </p><p>
10997     * The {@link #onHoverChanged} method is called when the hovered state changes.
10998     * </p>
10999     *
11000     * @param hovered True if the view is hovered.
11001     *
11002     * @see #isHovered
11003     * @see #onHoverChanged
11004     */
11005    public void setHovered(boolean hovered) {
11006        if (hovered) {
11007            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11008                mPrivateFlags |= PFLAG_HOVERED;
11009                refreshDrawableState();
11010                onHoverChanged(true);
11011            }
11012        } else {
11013            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11014                mPrivateFlags &= ~PFLAG_HOVERED;
11015                refreshDrawableState();
11016                onHoverChanged(false);
11017            }
11018        }
11019    }
11020
11021    /**
11022     * Implement this method to handle hover state changes.
11023     * <p>
11024     * This method is called whenever the hover state changes as a result of a
11025     * call to {@link #setHovered}.
11026     * </p>
11027     *
11028     * @param hovered The current hover state, as returned by {@link #isHovered}.
11029     *
11030     * @see #isHovered
11031     * @see #setHovered
11032     */
11033    public void onHoverChanged(boolean hovered) {
11034    }
11035
11036    /**
11037     * Handles scroll bar dragging by mouse input.
11038     *
11039     * @hide
11040     * @param event The motion event.
11041     *
11042     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11043     */
11044    protected boolean handleScrollBarDragging(MotionEvent event) {
11045        if (mScrollCache == null) {
11046            return false;
11047        }
11048        final float x = event.getX();
11049        final float y = event.getY();
11050        final int action = event.getAction();
11051        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11052                && action != MotionEvent.ACTION_DOWN)
11053                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11054                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11055            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11056            return false;
11057        }
11058
11059        switch (action) {
11060            case MotionEvent.ACTION_MOVE:
11061                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11062                    return false;
11063                }
11064                if (mScrollCache.mScrollBarDraggingState
11065                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11066                    final Rect bounds = mScrollCache.mScrollBarBounds;
11067                    getVerticalScrollBarBounds(bounds);
11068                    final int range = computeVerticalScrollRange();
11069                    final int offset = computeVerticalScrollOffset();
11070                    final int extent = computeVerticalScrollExtent();
11071
11072                    final int thumbLength = ScrollBarUtils.getThumbLength(
11073                            bounds.height(), bounds.width(), extent, range);
11074                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11075                            bounds.height(), thumbLength, extent, range, offset);
11076
11077                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11078                    final float maxThumbOffset = bounds.height() - thumbLength;
11079                    final float newThumbOffset =
11080                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11081                    final int height = getHeight();
11082                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11083                            && height > 0 && extent > 0) {
11084                        final int newY = Math.round((range - extent)
11085                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11086                        if (newY != getScrollY()) {
11087                            mScrollCache.mScrollBarDraggingPos = y;
11088                            setScrollY(newY);
11089                        }
11090                    }
11091                    return true;
11092                }
11093                if (mScrollCache.mScrollBarDraggingState
11094                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11095                    final Rect bounds = mScrollCache.mScrollBarBounds;
11096                    getHorizontalScrollBarBounds(bounds);
11097                    final int range = computeHorizontalScrollRange();
11098                    final int offset = computeHorizontalScrollOffset();
11099                    final int extent = computeHorizontalScrollExtent();
11100
11101                    final int thumbLength = ScrollBarUtils.getThumbLength(
11102                            bounds.width(), bounds.height(), extent, range);
11103                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11104                            bounds.width(), thumbLength, extent, range, offset);
11105
11106                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11107                    final float maxThumbOffset = bounds.width() - thumbLength;
11108                    final float newThumbOffset =
11109                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11110                    final int width = getWidth();
11111                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11112                            && width > 0 && extent > 0) {
11113                        final int newX = Math.round((range - extent)
11114                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11115                        if (newX != getScrollX()) {
11116                            mScrollCache.mScrollBarDraggingPos = x;
11117                            setScrollX(newX);
11118                        }
11119                    }
11120                    return true;
11121                }
11122            case MotionEvent.ACTION_DOWN:
11123                if (mScrollCache.state == ScrollabilityCache.OFF) {
11124                    return false;
11125                }
11126                if (isOnVerticalScrollbarThumb(x, y)) {
11127                    mScrollCache.mScrollBarDraggingState =
11128                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11129                    mScrollCache.mScrollBarDraggingPos = y;
11130                    return true;
11131                }
11132                if (isOnHorizontalScrollbarThumb(x, y)) {
11133                    mScrollCache.mScrollBarDraggingState =
11134                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11135                    mScrollCache.mScrollBarDraggingPos = x;
11136                    return true;
11137                }
11138        }
11139        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11140        return false;
11141    }
11142
11143    /**
11144     * Implement this method to handle touch screen motion events.
11145     * <p>
11146     * If this method is used to detect click actions, it is recommended that
11147     * the actions be performed by implementing and calling
11148     * {@link #performClick()}. This will ensure consistent system behavior,
11149     * including:
11150     * <ul>
11151     * <li>obeying click sound preferences
11152     * <li>dispatching OnClickListener calls
11153     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11154     * accessibility features are enabled
11155     * </ul>
11156     *
11157     * @param event The motion event.
11158     * @return True if the event was handled, false otherwise.
11159     */
11160    public boolean onTouchEvent(MotionEvent event) {
11161        final float x = event.getX();
11162        final float y = event.getY();
11163        final int viewFlags = mViewFlags;
11164        final int action = event.getAction();
11165
11166        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11167            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11168                setPressed(false);
11169            }
11170            // A disabled view that is clickable still consumes the touch
11171            // events, it just doesn't respond to them.
11172            return (((viewFlags & CLICKABLE) == CLICKABLE
11173                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11174                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11175        }
11176        if (mTouchDelegate != null) {
11177            if (mTouchDelegate.onTouchEvent(event)) {
11178                return true;
11179            }
11180        }
11181
11182        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11183                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11184                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11185            switch (action) {
11186                case MotionEvent.ACTION_UP:
11187                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11188                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11189                        // take focus if we don't have it already and we should in
11190                        // touch mode.
11191                        boolean focusTaken = false;
11192                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11193                            focusTaken = requestFocus();
11194                        }
11195
11196                        if (prepressed) {
11197                            // The button is being released before we actually
11198                            // showed it as pressed.  Make it show the pressed
11199                            // state now (before scheduling the click) to ensure
11200                            // the user sees it.
11201                            setPressed(true, x, y);
11202                       }
11203
11204                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11205                            // This is a tap, so remove the longpress check
11206                            removeLongPressCallback();
11207
11208                            // Only perform take click actions if we were in the pressed state
11209                            if (!focusTaken) {
11210                                // Use a Runnable and post this rather than calling
11211                                // performClick directly. This lets other visual state
11212                                // of the view update before click actions start.
11213                                if (mPerformClick == null) {
11214                                    mPerformClick = new PerformClick();
11215                                }
11216                                if (!post(mPerformClick)) {
11217                                    performClick();
11218                                }
11219                            }
11220                        }
11221
11222                        if (mUnsetPressedState == null) {
11223                            mUnsetPressedState = new UnsetPressedState();
11224                        }
11225
11226                        if (prepressed) {
11227                            postDelayed(mUnsetPressedState,
11228                                    ViewConfiguration.getPressedStateDuration());
11229                        } else if (!post(mUnsetPressedState)) {
11230                            // If the post failed, unpress right now
11231                            mUnsetPressedState.run();
11232                        }
11233
11234                        removeTapCallback();
11235                    }
11236                    mIgnoreNextUpEvent = false;
11237                    break;
11238
11239                case MotionEvent.ACTION_DOWN:
11240                    mHasPerformedLongPress = false;
11241
11242                    if (performButtonActionOnTouchDown(event)) {
11243                        break;
11244                    }
11245
11246                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11247                    boolean isInScrollingContainer = isInScrollingContainer();
11248
11249                    // For views inside a scrolling container, delay the pressed feedback for
11250                    // a short period in case this is a scroll.
11251                    if (isInScrollingContainer) {
11252                        mPrivateFlags |= PFLAG_PREPRESSED;
11253                        if (mPendingCheckForTap == null) {
11254                            mPendingCheckForTap = new CheckForTap();
11255                        }
11256                        mPendingCheckForTap.x = event.getX();
11257                        mPendingCheckForTap.y = event.getY();
11258                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11259                    } else {
11260                        // Not inside a scrolling container, so show the feedback right away
11261                        setPressed(true, x, y);
11262                        checkForLongClick(0, x, y);
11263                    }
11264                    break;
11265
11266                case MotionEvent.ACTION_CANCEL:
11267                    setPressed(false);
11268                    removeTapCallback();
11269                    removeLongPressCallback();
11270                    mInContextButtonPress = false;
11271                    mHasPerformedLongPress = false;
11272                    mIgnoreNextUpEvent = false;
11273                    break;
11274
11275                case MotionEvent.ACTION_MOVE:
11276                    drawableHotspotChanged(x, y);
11277
11278                    // Be lenient about moving outside of buttons
11279                    if (!pointInView(x, y, mTouchSlop)) {
11280                        // Outside button
11281                        removeTapCallback();
11282                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11283                            // Remove any future long press/tap checks
11284                            removeLongPressCallback();
11285
11286                            setPressed(false);
11287                        }
11288                    }
11289                    break;
11290            }
11291
11292            return true;
11293        }
11294
11295        return false;
11296    }
11297
11298    /**
11299     * @hide
11300     */
11301    public boolean isInScrollingContainer() {
11302        ViewParent p = getParent();
11303        while (p != null && p instanceof ViewGroup) {
11304            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11305                return true;
11306            }
11307            p = p.getParent();
11308        }
11309        return false;
11310    }
11311
11312    /**
11313     * Remove the longpress detection timer.
11314     */
11315    private void removeLongPressCallback() {
11316        if (mPendingCheckForLongPress != null) {
11317          removeCallbacks(mPendingCheckForLongPress);
11318        }
11319    }
11320
11321    /**
11322     * Remove the pending click action
11323     */
11324    private void removePerformClickCallback() {
11325        if (mPerformClick != null) {
11326            removeCallbacks(mPerformClick);
11327        }
11328    }
11329
11330    /**
11331     * Remove the prepress detection timer.
11332     */
11333    private void removeUnsetPressCallback() {
11334        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11335            setPressed(false);
11336            removeCallbacks(mUnsetPressedState);
11337        }
11338    }
11339
11340    /**
11341     * Remove the tap detection timer.
11342     */
11343    private void removeTapCallback() {
11344        if (mPendingCheckForTap != null) {
11345            mPrivateFlags &= ~PFLAG_PREPRESSED;
11346            removeCallbacks(mPendingCheckForTap);
11347        }
11348    }
11349
11350    /**
11351     * Cancels a pending long press.  Your subclass can use this if you
11352     * want the context menu to come up if the user presses and holds
11353     * at the same place, but you don't want it to come up if they press
11354     * and then move around enough to cause scrolling.
11355     */
11356    public void cancelLongPress() {
11357        removeLongPressCallback();
11358
11359        /*
11360         * The prepressed state handled by the tap callback is a display
11361         * construct, but the tap callback will post a long press callback
11362         * less its own timeout. Remove it here.
11363         */
11364        removeTapCallback();
11365    }
11366
11367    /**
11368     * Remove the pending callback for sending a
11369     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11370     */
11371    private void removeSendViewScrolledAccessibilityEventCallback() {
11372        if (mSendViewScrolledAccessibilityEvent != null) {
11373            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11374            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11375        }
11376    }
11377
11378    /**
11379     * Sets the TouchDelegate for this View.
11380     */
11381    public void setTouchDelegate(TouchDelegate delegate) {
11382        mTouchDelegate = delegate;
11383    }
11384
11385    /**
11386     * Gets the TouchDelegate for this View.
11387     */
11388    public TouchDelegate getTouchDelegate() {
11389        return mTouchDelegate;
11390    }
11391
11392    /**
11393     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11394     *
11395     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11396     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11397     * available. This method should only be called for touch events.
11398     *
11399     * <p class="note">This api is not intended for most applications. Buffered dispatch
11400     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11401     * streams will not improve your input latency. Side effects include: increased latency,
11402     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11403     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11404     * you.</p>
11405     */
11406    public final void requestUnbufferedDispatch(MotionEvent event) {
11407        final int action = event.getAction();
11408        if (mAttachInfo == null
11409                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11410                || !event.isTouchEvent()) {
11411            return;
11412        }
11413        mAttachInfo.mUnbufferedDispatchRequested = true;
11414    }
11415
11416    /**
11417     * Set flags controlling behavior of this view.
11418     *
11419     * @param flags Constant indicating the value which should be set
11420     * @param mask Constant indicating the bit range that should be changed
11421     */
11422    void setFlags(int flags, int mask) {
11423        final boolean accessibilityEnabled =
11424                AccessibilityManager.getInstance(mContext).isEnabled();
11425        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11426
11427        int old = mViewFlags;
11428        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11429
11430        int changed = mViewFlags ^ old;
11431        if (changed == 0) {
11432            return;
11433        }
11434        int privateFlags = mPrivateFlags;
11435
11436        /* Check if the FOCUSABLE bit has changed */
11437        if (((changed & FOCUSABLE_MASK) != 0) &&
11438                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11439            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11440                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11441                /* Give up focus if we are no longer focusable */
11442                clearFocus();
11443            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11444                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11445                /*
11446                 * Tell the view system that we are now available to take focus
11447                 * if no one else already has it.
11448                 */
11449                if (mParent != null) mParent.focusableViewAvailable(this);
11450            }
11451        }
11452
11453        final int newVisibility = flags & VISIBILITY_MASK;
11454        if (newVisibility == VISIBLE) {
11455            if ((changed & VISIBILITY_MASK) != 0) {
11456                /*
11457                 * If this view is becoming visible, invalidate it in case it changed while
11458                 * it was not visible. Marking it drawn ensures that the invalidation will
11459                 * go through.
11460                 */
11461                mPrivateFlags |= PFLAG_DRAWN;
11462                invalidate(true);
11463
11464                needGlobalAttributesUpdate(true);
11465
11466                // a view becoming visible is worth notifying the parent
11467                // about in case nothing has focus.  even if this specific view
11468                // isn't focusable, it may contain something that is, so let
11469                // the root view try to give this focus if nothing else does.
11470                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11471                    mParent.focusableViewAvailable(this);
11472                }
11473            }
11474        }
11475
11476        /* Check if the GONE bit has changed */
11477        if ((changed & GONE) != 0) {
11478            needGlobalAttributesUpdate(false);
11479            requestLayout();
11480
11481            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11482                if (hasFocus()) clearFocus();
11483                clearAccessibilityFocus();
11484                destroyDrawingCache();
11485                if (mParent instanceof View) {
11486                    // GONE views noop invalidation, so invalidate the parent
11487                    ((View) mParent).invalidate(true);
11488                }
11489                // Mark the view drawn to ensure that it gets invalidated properly the next
11490                // time it is visible and gets invalidated
11491                mPrivateFlags |= PFLAG_DRAWN;
11492            }
11493            if (mAttachInfo != null) {
11494                mAttachInfo.mViewVisibilityChanged = true;
11495            }
11496        }
11497
11498        /* Check if the VISIBLE bit has changed */
11499        if ((changed & INVISIBLE) != 0) {
11500            needGlobalAttributesUpdate(false);
11501            /*
11502             * If this view is becoming invisible, set the DRAWN flag so that
11503             * the next invalidate() will not be skipped.
11504             */
11505            mPrivateFlags |= PFLAG_DRAWN;
11506
11507            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11508                // root view becoming invisible shouldn't clear focus and accessibility focus
11509                if (getRootView() != this) {
11510                    if (hasFocus()) clearFocus();
11511                    clearAccessibilityFocus();
11512                }
11513            }
11514            if (mAttachInfo != null) {
11515                mAttachInfo.mViewVisibilityChanged = true;
11516            }
11517        }
11518
11519        if ((changed & VISIBILITY_MASK) != 0) {
11520            // If the view is invisible, cleanup its display list to free up resources
11521            if (newVisibility != VISIBLE && mAttachInfo != null) {
11522                cleanupDraw();
11523            }
11524
11525            if (mParent instanceof ViewGroup) {
11526                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11527                        (changed & VISIBILITY_MASK), newVisibility);
11528                ((View) mParent).invalidate(true);
11529            } else if (mParent != null) {
11530                mParent.invalidateChild(this, null);
11531            }
11532
11533            if (mAttachInfo != null) {
11534                dispatchVisibilityChanged(this, newVisibility);
11535
11536                // Aggregated visibility changes are dispatched to attached views
11537                // in visible windows where the parent is currently shown/drawn
11538                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11539                // discounting clipping or overlapping. This makes it a good place
11540                // to change animation states.
11541                if (mParent != null && getWindowVisibility() == VISIBLE &&
11542                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11543                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11544                }
11545                notifySubtreeAccessibilityStateChangedIfNeeded();
11546            }
11547        }
11548
11549        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11550            destroyDrawingCache();
11551        }
11552
11553        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11554            destroyDrawingCache();
11555            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11556            invalidateParentCaches();
11557        }
11558
11559        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11560            destroyDrawingCache();
11561            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11562        }
11563
11564        if ((changed & DRAW_MASK) != 0) {
11565            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11566                if (mBackground != null
11567                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11568                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11569                } else {
11570                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11571                }
11572            } else {
11573                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11574            }
11575            requestLayout();
11576            invalidate(true);
11577        }
11578
11579        if ((changed & KEEP_SCREEN_ON) != 0) {
11580            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11581                mParent.recomputeViewAttributes(this);
11582            }
11583        }
11584
11585        if (accessibilityEnabled) {
11586            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11587                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11588                    || (changed & CONTEXT_CLICKABLE) != 0) {
11589                if (oldIncludeForAccessibility != includeForAccessibility()) {
11590                    notifySubtreeAccessibilityStateChangedIfNeeded();
11591                } else {
11592                    notifyViewAccessibilityStateChangedIfNeeded(
11593                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11594                }
11595            } else if ((changed & ENABLED_MASK) != 0) {
11596                notifyViewAccessibilityStateChangedIfNeeded(
11597                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11598            }
11599        }
11600    }
11601
11602    /**
11603     * Change the view's z order in the tree, so it's on top of other sibling
11604     * views. This ordering change may affect layout, if the parent container
11605     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11606     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11607     * method should be followed by calls to {@link #requestLayout()} and
11608     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11609     * with the new child ordering.
11610     *
11611     * @see ViewGroup#bringChildToFront(View)
11612     */
11613    public void bringToFront() {
11614        if (mParent != null) {
11615            mParent.bringChildToFront(this);
11616        }
11617    }
11618
11619    /**
11620     * This is called in response to an internal scroll in this view (i.e., the
11621     * view scrolled its own contents). This is typically as a result of
11622     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11623     * called.
11624     *
11625     * @param l Current horizontal scroll origin.
11626     * @param t Current vertical scroll origin.
11627     * @param oldl Previous horizontal scroll origin.
11628     * @param oldt Previous vertical scroll origin.
11629     */
11630    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11631        notifySubtreeAccessibilityStateChangedIfNeeded();
11632
11633        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11634            postSendViewScrolledAccessibilityEventCallback();
11635        }
11636
11637        mBackgroundSizeChanged = true;
11638        if (mForegroundInfo != null) {
11639            mForegroundInfo.mBoundsChanged = true;
11640        }
11641
11642        final AttachInfo ai = mAttachInfo;
11643        if (ai != null) {
11644            ai.mViewScrollChanged = true;
11645        }
11646
11647        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11648            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11649        }
11650    }
11651
11652    /**
11653     * Interface definition for a callback to be invoked when the scroll
11654     * X or Y positions of a view change.
11655     * <p>
11656     * <b>Note:</b> Some views handle scrolling independently from View and may
11657     * have their own separate listeners for scroll-type events. For example,
11658     * {@link android.widget.ListView ListView} allows clients to register an
11659     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11660     * to listen for changes in list scroll position.
11661     *
11662     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11663     */
11664    public interface OnScrollChangeListener {
11665        /**
11666         * Called when the scroll position of a view changes.
11667         *
11668         * @param v The view whose scroll position has changed.
11669         * @param scrollX Current horizontal scroll origin.
11670         * @param scrollY Current vertical scroll origin.
11671         * @param oldScrollX Previous horizontal scroll origin.
11672         * @param oldScrollY Previous vertical scroll origin.
11673         */
11674        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11675    }
11676
11677    /**
11678     * Interface definition for a callback to be invoked when the layout bounds of a view
11679     * changes due to layout processing.
11680     */
11681    public interface OnLayoutChangeListener {
11682        /**
11683         * Called when the layout bounds of a view changes due to layout processing.
11684         *
11685         * @param v The view whose bounds have changed.
11686         * @param left The new value of the view's left property.
11687         * @param top The new value of the view's top property.
11688         * @param right The new value of the view's right property.
11689         * @param bottom The new value of the view's bottom property.
11690         * @param oldLeft The previous value of the view's left property.
11691         * @param oldTop The previous value of the view's top property.
11692         * @param oldRight The previous value of the view's right property.
11693         * @param oldBottom The previous value of the view's bottom property.
11694         */
11695        void onLayoutChange(View v, int left, int top, int right, int bottom,
11696            int oldLeft, int oldTop, int oldRight, int oldBottom);
11697    }
11698
11699    /**
11700     * This is called during layout when the size of this view has changed. If
11701     * you were just added to the view hierarchy, you're called with the old
11702     * values of 0.
11703     *
11704     * @param w Current width of this view.
11705     * @param h Current height of this view.
11706     * @param oldw Old width of this view.
11707     * @param oldh Old height of this view.
11708     */
11709    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11710    }
11711
11712    /**
11713     * Called by draw to draw the child views. This may be overridden
11714     * by derived classes to gain control just before its children are drawn
11715     * (but after its own view has been drawn).
11716     * @param canvas the canvas on which to draw the view
11717     */
11718    protected void dispatchDraw(Canvas canvas) {
11719
11720    }
11721
11722    /**
11723     * Gets the parent of this view. Note that the parent is a
11724     * ViewParent and not necessarily a View.
11725     *
11726     * @return Parent of this view.
11727     */
11728    public final ViewParent getParent() {
11729        return mParent;
11730    }
11731
11732    /**
11733     * Set the horizontal scrolled position of your view. This will cause a call to
11734     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11735     * invalidated.
11736     * @param value the x position to scroll to
11737     */
11738    public void setScrollX(int value) {
11739        scrollTo(value, mScrollY);
11740    }
11741
11742    /**
11743     * Set the vertical scrolled position of your view. This will cause a call to
11744     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11745     * invalidated.
11746     * @param value the y position to scroll to
11747     */
11748    public void setScrollY(int value) {
11749        scrollTo(mScrollX, value);
11750    }
11751
11752    /**
11753     * Return the scrolled left position of this view. This is the left edge of
11754     * the displayed part of your view. You do not need to draw any pixels
11755     * farther left, since those are outside of the frame of your view on
11756     * screen.
11757     *
11758     * @return The left edge of the displayed part of your view, in pixels.
11759     */
11760    public final int getScrollX() {
11761        return mScrollX;
11762    }
11763
11764    /**
11765     * Return the scrolled top position of this view. This is the top edge of
11766     * the displayed part of your view. You do not need to draw any pixels above
11767     * it, since those are outside of the frame of your view on screen.
11768     *
11769     * @return The top edge of the displayed part of your view, in pixels.
11770     */
11771    public final int getScrollY() {
11772        return mScrollY;
11773    }
11774
11775    /**
11776     * Return the width of the your view.
11777     *
11778     * @return The width of your view, in pixels.
11779     */
11780    @ViewDebug.ExportedProperty(category = "layout")
11781    public final int getWidth() {
11782        return mRight - mLeft;
11783    }
11784
11785    /**
11786     * Return the height of your view.
11787     *
11788     * @return The height of your view, in pixels.
11789     */
11790    @ViewDebug.ExportedProperty(category = "layout")
11791    public final int getHeight() {
11792        return mBottom - mTop;
11793    }
11794
11795    /**
11796     * Return the visible drawing bounds of your view. Fills in the output
11797     * rectangle with the values from getScrollX(), getScrollY(),
11798     * getWidth(), and getHeight(). These bounds do not account for any
11799     * transformation properties currently set on the view, such as
11800     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11801     *
11802     * @param outRect The (scrolled) drawing bounds of the view.
11803     */
11804    public void getDrawingRect(Rect outRect) {
11805        outRect.left = mScrollX;
11806        outRect.top = mScrollY;
11807        outRect.right = mScrollX + (mRight - mLeft);
11808        outRect.bottom = mScrollY + (mBottom - mTop);
11809    }
11810
11811    /**
11812     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11813     * raw width component (that is the result is masked by
11814     * {@link #MEASURED_SIZE_MASK}).
11815     *
11816     * @return The raw measured width of this view.
11817     */
11818    public final int getMeasuredWidth() {
11819        return mMeasuredWidth & MEASURED_SIZE_MASK;
11820    }
11821
11822    /**
11823     * Return the full width measurement information for this view as computed
11824     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11825     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11826     * This should be used during measurement and layout calculations only. Use
11827     * {@link #getWidth()} to see how wide a view is after layout.
11828     *
11829     * @return The measured width of this view as a bit mask.
11830     */
11831    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11832            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11833                    name = "MEASURED_STATE_TOO_SMALL"),
11834    })
11835    public final int getMeasuredWidthAndState() {
11836        return mMeasuredWidth;
11837    }
11838
11839    /**
11840     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11841     * raw height component (that is the result is masked by
11842     * {@link #MEASURED_SIZE_MASK}).
11843     *
11844     * @return The raw measured height of this view.
11845     */
11846    public final int getMeasuredHeight() {
11847        return mMeasuredHeight & MEASURED_SIZE_MASK;
11848    }
11849
11850    /**
11851     * Return the full height measurement information for this view as computed
11852     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11853     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11854     * This should be used during measurement and layout calculations only. Use
11855     * {@link #getHeight()} to see how wide a view is after layout.
11856     *
11857     * @return The measured height of this view as a bit mask.
11858     */
11859    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11860            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11861                    name = "MEASURED_STATE_TOO_SMALL"),
11862    })
11863    public final int getMeasuredHeightAndState() {
11864        return mMeasuredHeight;
11865    }
11866
11867    /**
11868     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11869     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11870     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11871     * and the height component is at the shifted bits
11872     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11873     */
11874    public final int getMeasuredState() {
11875        return (mMeasuredWidth&MEASURED_STATE_MASK)
11876                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11877                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11878    }
11879
11880    /**
11881     * The transform matrix of this view, which is calculated based on the current
11882     * rotation, scale, and pivot properties.
11883     *
11884     * @see #getRotation()
11885     * @see #getScaleX()
11886     * @see #getScaleY()
11887     * @see #getPivotX()
11888     * @see #getPivotY()
11889     * @return The current transform matrix for the view
11890     */
11891    public Matrix getMatrix() {
11892        ensureTransformationInfo();
11893        final Matrix matrix = mTransformationInfo.mMatrix;
11894        mRenderNode.getMatrix(matrix);
11895        return matrix;
11896    }
11897
11898    /**
11899     * Returns true if the transform matrix is the identity matrix.
11900     * Recomputes the matrix if necessary.
11901     *
11902     * @return True if the transform matrix is the identity matrix, false otherwise.
11903     */
11904    final boolean hasIdentityMatrix() {
11905        return mRenderNode.hasIdentityMatrix();
11906    }
11907
11908    void ensureTransformationInfo() {
11909        if (mTransformationInfo == null) {
11910            mTransformationInfo = new TransformationInfo();
11911        }
11912    }
11913
11914    /**
11915     * Utility method to retrieve the inverse of the current mMatrix property.
11916     * We cache the matrix to avoid recalculating it when transform properties
11917     * have not changed.
11918     *
11919     * @return The inverse of the current matrix of this view.
11920     * @hide
11921     */
11922    public final Matrix getInverseMatrix() {
11923        ensureTransformationInfo();
11924        if (mTransformationInfo.mInverseMatrix == null) {
11925            mTransformationInfo.mInverseMatrix = new Matrix();
11926        }
11927        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11928        mRenderNode.getInverseMatrix(matrix);
11929        return matrix;
11930    }
11931
11932    /**
11933     * Gets the distance along the Z axis from the camera to this view.
11934     *
11935     * @see #setCameraDistance(float)
11936     *
11937     * @return The distance along the Z axis.
11938     */
11939    public float getCameraDistance() {
11940        final float dpi = mResources.getDisplayMetrics().densityDpi;
11941        return -(mRenderNode.getCameraDistance() * dpi);
11942    }
11943
11944    /**
11945     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11946     * views are drawn) from the camera to this view. The camera's distance
11947     * affects 3D transformations, for instance rotations around the X and Y
11948     * axis. If the rotationX or rotationY properties are changed and this view is
11949     * large (more than half the size of the screen), it is recommended to always
11950     * use a camera distance that's greater than the height (X axis rotation) or
11951     * the width (Y axis rotation) of this view.</p>
11952     *
11953     * <p>The distance of the camera from the view plane can have an affect on the
11954     * perspective distortion of the view when it is rotated around the x or y axis.
11955     * For example, a large distance will result in a large viewing angle, and there
11956     * will not be much perspective distortion of the view as it rotates. A short
11957     * distance may cause much more perspective distortion upon rotation, and can
11958     * also result in some drawing artifacts if the rotated view ends up partially
11959     * behind the camera (which is why the recommendation is to use a distance at
11960     * least as far as the size of the view, if the view is to be rotated.)</p>
11961     *
11962     * <p>The distance is expressed in "depth pixels." The default distance depends
11963     * on the screen density. For instance, on a medium density display, the
11964     * default distance is 1280. On a high density display, the default distance
11965     * is 1920.</p>
11966     *
11967     * <p>If you want to specify a distance that leads to visually consistent
11968     * results across various densities, use the following formula:</p>
11969     * <pre>
11970     * float scale = context.getResources().getDisplayMetrics().density;
11971     * view.setCameraDistance(distance * scale);
11972     * </pre>
11973     *
11974     * <p>The density scale factor of a high density display is 1.5,
11975     * and 1920 = 1280 * 1.5.</p>
11976     *
11977     * @param distance The distance in "depth pixels", if negative the opposite
11978     *        value is used
11979     *
11980     * @see #setRotationX(float)
11981     * @see #setRotationY(float)
11982     */
11983    public void setCameraDistance(float distance) {
11984        final float dpi = mResources.getDisplayMetrics().densityDpi;
11985
11986        invalidateViewProperty(true, false);
11987        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11988        invalidateViewProperty(false, false);
11989
11990        invalidateParentIfNeededAndWasQuickRejected();
11991    }
11992
11993    /**
11994     * The degrees that the view is rotated around the pivot point.
11995     *
11996     * @see #setRotation(float)
11997     * @see #getPivotX()
11998     * @see #getPivotY()
11999     *
12000     * @return The degrees of rotation.
12001     */
12002    @ViewDebug.ExportedProperty(category = "drawing")
12003    public float getRotation() {
12004        return mRenderNode.getRotation();
12005    }
12006
12007    /**
12008     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12009     * result in clockwise rotation.
12010     *
12011     * @param rotation The degrees of rotation.
12012     *
12013     * @see #getRotation()
12014     * @see #getPivotX()
12015     * @see #getPivotY()
12016     * @see #setRotationX(float)
12017     * @see #setRotationY(float)
12018     *
12019     * @attr ref android.R.styleable#View_rotation
12020     */
12021    public void setRotation(float rotation) {
12022        if (rotation != getRotation()) {
12023            // Double-invalidation is necessary to capture view's old and new areas
12024            invalidateViewProperty(true, false);
12025            mRenderNode.setRotation(rotation);
12026            invalidateViewProperty(false, true);
12027
12028            invalidateParentIfNeededAndWasQuickRejected();
12029            notifySubtreeAccessibilityStateChangedIfNeeded();
12030        }
12031    }
12032
12033    /**
12034     * The degrees that the view is rotated around the vertical axis through the pivot point.
12035     *
12036     * @see #getPivotX()
12037     * @see #getPivotY()
12038     * @see #setRotationY(float)
12039     *
12040     * @return The degrees of Y rotation.
12041     */
12042    @ViewDebug.ExportedProperty(category = "drawing")
12043    public float getRotationY() {
12044        return mRenderNode.getRotationY();
12045    }
12046
12047    /**
12048     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12049     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12050     * down the y axis.
12051     *
12052     * When rotating large views, it is recommended to adjust the camera distance
12053     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12054     *
12055     * @param rotationY The degrees of Y rotation.
12056     *
12057     * @see #getRotationY()
12058     * @see #getPivotX()
12059     * @see #getPivotY()
12060     * @see #setRotation(float)
12061     * @see #setRotationX(float)
12062     * @see #setCameraDistance(float)
12063     *
12064     * @attr ref android.R.styleable#View_rotationY
12065     */
12066    public void setRotationY(float rotationY) {
12067        if (rotationY != getRotationY()) {
12068            invalidateViewProperty(true, false);
12069            mRenderNode.setRotationY(rotationY);
12070            invalidateViewProperty(false, true);
12071
12072            invalidateParentIfNeededAndWasQuickRejected();
12073            notifySubtreeAccessibilityStateChangedIfNeeded();
12074        }
12075    }
12076
12077    /**
12078     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12079     *
12080     * @see #getPivotX()
12081     * @see #getPivotY()
12082     * @see #setRotationX(float)
12083     *
12084     * @return The degrees of X rotation.
12085     */
12086    @ViewDebug.ExportedProperty(category = "drawing")
12087    public float getRotationX() {
12088        return mRenderNode.getRotationX();
12089    }
12090
12091    /**
12092     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12093     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12094     * x axis.
12095     *
12096     * When rotating large views, it is recommended to adjust the camera distance
12097     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12098     *
12099     * @param rotationX The degrees of X rotation.
12100     *
12101     * @see #getRotationX()
12102     * @see #getPivotX()
12103     * @see #getPivotY()
12104     * @see #setRotation(float)
12105     * @see #setRotationY(float)
12106     * @see #setCameraDistance(float)
12107     *
12108     * @attr ref android.R.styleable#View_rotationX
12109     */
12110    public void setRotationX(float rotationX) {
12111        if (rotationX != getRotationX()) {
12112            invalidateViewProperty(true, false);
12113            mRenderNode.setRotationX(rotationX);
12114            invalidateViewProperty(false, true);
12115
12116            invalidateParentIfNeededAndWasQuickRejected();
12117            notifySubtreeAccessibilityStateChangedIfNeeded();
12118        }
12119    }
12120
12121    /**
12122     * The amount that the view is scaled in x around the pivot point, as a proportion of
12123     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12124     *
12125     * <p>By default, this is 1.0f.
12126     *
12127     * @see #getPivotX()
12128     * @see #getPivotY()
12129     * @return The scaling factor.
12130     */
12131    @ViewDebug.ExportedProperty(category = "drawing")
12132    public float getScaleX() {
12133        return mRenderNode.getScaleX();
12134    }
12135
12136    /**
12137     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12138     * the view's unscaled width. A value of 1 means that no scaling is applied.
12139     *
12140     * @param scaleX The scaling factor.
12141     * @see #getPivotX()
12142     * @see #getPivotY()
12143     *
12144     * @attr ref android.R.styleable#View_scaleX
12145     */
12146    public void setScaleX(float scaleX) {
12147        if (scaleX != getScaleX()) {
12148            invalidateViewProperty(true, false);
12149            mRenderNode.setScaleX(scaleX);
12150            invalidateViewProperty(false, true);
12151
12152            invalidateParentIfNeededAndWasQuickRejected();
12153            notifySubtreeAccessibilityStateChangedIfNeeded();
12154        }
12155    }
12156
12157    /**
12158     * The amount that the view is scaled in y around the pivot point, as a proportion of
12159     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12160     *
12161     * <p>By default, this is 1.0f.
12162     *
12163     * @see #getPivotX()
12164     * @see #getPivotY()
12165     * @return The scaling factor.
12166     */
12167    @ViewDebug.ExportedProperty(category = "drawing")
12168    public float getScaleY() {
12169        return mRenderNode.getScaleY();
12170    }
12171
12172    /**
12173     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12174     * the view's unscaled width. A value of 1 means that no scaling is applied.
12175     *
12176     * @param scaleY The scaling factor.
12177     * @see #getPivotX()
12178     * @see #getPivotY()
12179     *
12180     * @attr ref android.R.styleable#View_scaleY
12181     */
12182    public void setScaleY(float scaleY) {
12183        if (scaleY != getScaleY()) {
12184            invalidateViewProperty(true, false);
12185            mRenderNode.setScaleY(scaleY);
12186            invalidateViewProperty(false, true);
12187
12188            invalidateParentIfNeededAndWasQuickRejected();
12189            notifySubtreeAccessibilityStateChangedIfNeeded();
12190        }
12191    }
12192
12193    /**
12194     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12195     * and {@link #setScaleX(float) scaled}.
12196     *
12197     * @see #getRotation()
12198     * @see #getScaleX()
12199     * @see #getScaleY()
12200     * @see #getPivotY()
12201     * @return The x location of the pivot point.
12202     *
12203     * @attr ref android.R.styleable#View_transformPivotX
12204     */
12205    @ViewDebug.ExportedProperty(category = "drawing")
12206    public float getPivotX() {
12207        return mRenderNode.getPivotX();
12208    }
12209
12210    /**
12211     * Sets the x location of the point around which the view is
12212     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12213     * By default, the pivot point is centered on the object.
12214     * Setting this property disables this behavior and causes the view to use only the
12215     * explicitly set pivotX and pivotY values.
12216     *
12217     * @param pivotX The x location of the pivot point.
12218     * @see #getRotation()
12219     * @see #getScaleX()
12220     * @see #getScaleY()
12221     * @see #getPivotY()
12222     *
12223     * @attr ref android.R.styleable#View_transformPivotX
12224     */
12225    public void setPivotX(float pivotX) {
12226        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12227            invalidateViewProperty(true, false);
12228            mRenderNode.setPivotX(pivotX);
12229            invalidateViewProperty(false, true);
12230
12231            invalidateParentIfNeededAndWasQuickRejected();
12232        }
12233    }
12234
12235    /**
12236     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12237     * and {@link #setScaleY(float) scaled}.
12238     *
12239     * @see #getRotation()
12240     * @see #getScaleX()
12241     * @see #getScaleY()
12242     * @see #getPivotY()
12243     * @return The y location of the pivot point.
12244     *
12245     * @attr ref android.R.styleable#View_transformPivotY
12246     */
12247    @ViewDebug.ExportedProperty(category = "drawing")
12248    public float getPivotY() {
12249        return mRenderNode.getPivotY();
12250    }
12251
12252    /**
12253     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12254     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12255     * Setting this property disables this behavior and causes the view to use only the
12256     * explicitly set pivotX and pivotY values.
12257     *
12258     * @param pivotY The y location of the pivot point.
12259     * @see #getRotation()
12260     * @see #getScaleX()
12261     * @see #getScaleY()
12262     * @see #getPivotY()
12263     *
12264     * @attr ref android.R.styleable#View_transformPivotY
12265     */
12266    public void setPivotY(float pivotY) {
12267        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12268            invalidateViewProperty(true, false);
12269            mRenderNode.setPivotY(pivotY);
12270            invalidateViewProperty(false, true);
12271
12272            invalidateParentIfNeededAndWasQuickRejected();
12273        }
12274    }
12275
12276    /**
12277     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12278     * completely transparent and 1 means the view is completely opaque.
12279     *
12280     * <p>By default this is 1.0f.
12281     * @return The opacity of the view.
12282     */
12283    @ViewDebug.ExportedProperty(category = "drawing")
12284    public float getAlpha() {
12285        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12286    }
12287
12288    /**
12289     * Sets the behavior for overlapping rendering for this view (see {@link
12290     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12291     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12292     * providing the value which is then used internally. That is, when {@link
12293     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12294     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12295     * instead.
12296     *
12297     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12298     * instead of that returned by {@link #hasOverlappingRendering()}.
12299     *
12300     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12301     */
12302    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12303        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12304        if (hasOverlappingRendering) {
12305            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12306        } else {
12307            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12308        }
12309    }
12310
12311    /**
12312     * Returns the value for overlapping rendering that is used internally. This is either
12313     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12314     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12315     *
12316     * @return The value for overlapping rendering being used internally.
12317     */
12318    public final boolean getHasOverlappingRendering() {
12319        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12320                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12321                hasOverlappingRendering();
12322    }
12323
12324    /**
12325     * Returns whether this View has content which overlaps.
12326     *
12327     * <p>This function, intended to be overridden by specific View types, is an optimization when
12328     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12329     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12330     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12331     * directly. An example of overlapping rendering is a TextView with a background image, such as
12332     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12333     * ImageView with only the foreground image. The default implementation returns true; subclasses
12334     * should override if they have cases which can be optimized.</p>
12335     *
12336     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12337     * necessitates that a View return true if it uses the methods internally without passing the
12338     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12339     *
12340     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12341     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12342     *
12343     * @return true if the content in this view might overlap, false otherwise.
12344     */
12345    @ViewDebug.ExportedProperty(category = "drawing")
12346    public boolean hasOverlappingRendering() {
12347        return true;
12348    }
12349
12350    /**
12351     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12352     * completely transparent and 1 means the view is completely opaque.
12353     *
12354     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12355     * can have significant performance implications, especially for large views. It is best to use
12356     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12357     *
12358     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12359     * strongly recommended for performance reasons to either override
12360     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12361     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12362     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12363     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12364     * of rendering cost, even for simple or small views. Starting with
12365     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12366     * applied to the view at the rendering level.</p>
12367     *
12368     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12369     * responsible for applying the opacity itself.</p>
12370     *
12371     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12372     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12373     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12374     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12375     *
12376     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12377     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12378     * {@link #hasOverlappingRendering}.</p>
12379     *
12380     * @param alpha The opacity of the view.
12381     *
12382     * @see #hasOverlappingRendering()
12383     * @see #setLayerType(int, android.graphics.Paint)
12384     *
12385     * @attr ref android.R.styleable#View_alpha
12386     */
12387    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12388        ensureTransformationInfo();
12389        if (mTransformationInfo.mAlpha != alpha) {
12390            // Report visibility changes, which can affect children, to accessibility
12391            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
12392                notifySubtreeAccessibilityStateChangedIfNeeded();
12393            }
12394            mTransformationInfo.mAlpha = alpha;
12395            if (onSetAlpha((int) (alpha * 255))) {
12396                mPrivateFlags |= PFLAG_ALPHA_SET;
12397                // subclass is handling alpha - don't optimize rendering cache invalidation
12398                invalidateParentCaches();
12399                invalidate(true);
12400            } else {
12401                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12402                invalidateViewProperty(true, false);
12403                mRenderNode.setAlpha(getFinalAlpha());
12404            }
12405        }
12406    }
12407
12408    /**
12409     * Faster version of setAlpha() which performs the same steps except there are
12410     * no calls to invalidate(). The caller of this function should perform proper invalidation
12411     * on the parent and this object. The return value indicates whether the subclass handles
12412     * alpha (the return value for onSetAlpha()).
12413     *
12414     * @param alpha The new value for the alpha property
12415     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12416     *         the new value for the alpha property is different from the old value
12417     */
12418    boolean setAlphaNoInvalidation(float alpha) {
12419        ensureTransformationInfo();
12420        if (mTransformationInfo.mAlpha != alpha) {
12421            mTransformationInfo.mAlpha = alpha;
12422            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12423            if (subclassHandlesAlpha) {
12424                mPrivateFlags |= PFLAG_ALPHA_SET;
12425                return true;
12426            } else {
12427                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12428                mRenderNode.setAlpha(getFinalAlpha());
12429            }
12430        }
12431        return false;
12432    }
12433
12434    /**
12435     * This property is hidden and intended only for use by the Fade transition, which
12436     * animates it to produce a visual translucency that does not side-effect (or get
12437     * affected by) the real alpha property. This value is composited with the other
12438     * alpha value (and the AlphaAnimation value, when that is present) to produce
12439     * a final visual translucency result, which is what is passed into the DisplayList.
12440     *
12441     * @hide
12442     */
12443    public void setTransitionAlpha(float alpha) {
12444        ensureTransformationInfo();
12445        if (mTransformationInfo.mTransitionAlpha != alpha) {
12446            mTransformationInfo.mTransitionAlpha = alpha;
12447            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12448            invalidateViewProperty(true, false);
12449            mRenderNode.setAlpha(getFinalAlpha());
12450        }
12451    }
12452
12453    /**
12454     * Calculates the visual alpha of this view, which is a combination of the actual
12455     * alpha value and the transitionAlpha value (if set).
12456     */
12457    private float getFinalAlpha() {
12458        if (mTransformationInfo != null) {
12459            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12460        }
12461        return 1;
12462    }
12463
12464    /**
12465     * This property is hidden and intended only for use by the Fade transition, which
12466     * animates it to produce a visual translucency that does not side-effect (or get
12467     * affected by) the real alpha property. This value is composited with the other
12468     * alpha value (and the AlphaAnimation value, when that is present) to produce
12469     * a final visual translucency result, which is what is passed into the DisplayList.
12470     *
12471     * @hide
12472     */
12473    @ViewDebug.ExportedProperty(category = "drawing")
12474    public float getTransitionAlpha() {
12475        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12476    }
12477
12478    /**
12479     * Top position of this view relative to its parent.
12480     *
12481     * @return The top of this view, in pixels.
12482     */
12483    @ViewDebug.CapturedViewProperty
12484    public final int getTop() {
12485        return mTop;
12486    }
12487
12488    /**
12489     * Sets the top position of this view relative to its parent. This method is meant to be called
12490     * by the layout system and should not generally be called otherwise, because the property
12491     * may be changed at any time by the layout.
12492     *
12493     * @param top The top of this view, in pixels.
12494     */
12495    public final void setTop(int top) {
12496        if (top != mTop) {
12497            final boolean matrixIsIdentity = hasIdentityMatrix();
12498            if (matrixIsIdentity) {
12499                if (mAttachInfo != null) {
12500                    int minTop;
12501                    int yLoc;
12502                    if (top < mTop) {
12503                        minTop = top;
12504                        yLoc = top - mTop;
12505                    } else {
12506                        minTop = mTop;
12507                        yLoc = 0;
12508                    }
12509                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12510                }
12511            } else {
12512                // Double-invalidation is necessary to capture view's old and new areas
12513                invalidate(true);
12514            }
12515
12516            int width = mRight - mLeft;
12517            int oldHeight = mBottom - mTop;
12518
12519            mTop = top;
12520            mRenderNode.setTop(mTop);
12521
12522            sizeChange(width, mBottom - mTop, width, oldHeight);
12523
12524            if (!matrixIsIdentity) {
12525                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12526                invalidate(true);
12527            }
12528            mBackgroundSizeChanged = true;
12529            if (mForegroundInfo != null) {
12530                mForegroundInfo.mBoundsChanged = true;
12531            }
12532            invalidateParentIfNeeded();
12533            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12534                // View was rejected last time it was drawn by its parent; this may have changed
12535                invalidateParentIfNeeded();
12536            }
12537        }
12538    }
12539
12540    /**
12541     * Bottom position of this view relative to its parent.
12542     *
12543     * @return The bottom of this view, in pixels.
12544     */
12545    @ViewDebug.CapturedViewProperty
12546    public final int getBottom() {
12547        return mBottom;
12548    }
12549
12550    /**
12551     * True if this view has changed since the last time being drawn.
12552     *
12553     * @return The dirty state of this view.
12554     */
12555    public boolean isDirty() {
12556        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12557    }
12558
12559    /**
12560     * Sets the bottom position of this view relative to its parent. This method is meant to be
12561     * called by the layout system and should not generally be called otherwise, because the
12562     * property may be changed at any time by the layout.
12563     *
12564     * @param bottom The bottom of this view, in pixels.
12565     */
12566    public final void setBottom(int bottom) {
12567        if (bottom != mBottom) {
12568            final boolean matrixIsIdentity = hasIdentityMatrix();
12569            if (matrixIsIdentity) {
12570                if (mAttachInfo != null) {
12571                    int maxBottom;
12572                    if (bottom < mBottom) {
12573                        maxBottom = mBottom;
12574                    } else {
12575                        maxBottom = bottom;
12576                    }
12577                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12578                }
12579            } else {
12580                // Double-invalidation is necessary to capture view's old and new areas
12581                invalidate(true);
12582            }
12583
12584            int width = mRight - mLeft;
12585            int oldHeight = mBottom - mTop;
12586
12587            mBottom = bottom;
12588            mRenderNode.setBottom(mBottom);
12589
12590            sizeChange(width, mBottom - mTop, width, oldHeight);
12591
12592            if (!matrixIsIdentity) {
12593                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12594                invalidate(true);
12595            }
12596            mBackgroundSizeChanged = true;
12597            if (mForegroundInfo != null) {
12598                mForegroundInfo.mBoundsChanged = true;
12599            }
12600            invalidateParentIfNeeded();
12601            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12602                // View was rejected last time it was drawn by its parent; this may have changed
12603                invalidateParentIfNeeded();
12604            }
12605        }
12606    }
12607
12608    /**
12609     * Left position of this view relative to its parent.
12610     *
12611     * @return The left edge of this view, in pixels.
12612     */
12613    @ViewDebug.CapturedViewProperty
12614    public final int getLeft() {
12615        return mLeft;
12616    }
12617
12618    /**
12619     * Sets the left position of this view relative to its parent. This method is meant to be called
12620     * by the layout system and should not generally be called otherwise, because the property
12621     * may be changed at any time by the layout.
12622     *
12623     * @param left The left of this view, in pixels.
12624     */
12625    public final void setLeft(int left) {
12626        if (left != mLeft) {
12627            final boolean matrixIsIdentity = hasIdentityMatrix();
12628            if (matrixIsIdentity) {
12629                if (mAttachInfo != null) {
12630                    int minLeft;
12631                    int xLoc;
12632                    if (left < mLeft) {
12633                        minLeft = left;
12634                        xLoc = left - mLeft;
12635                    } else {
12636                        minLeft = mLeft;
12637                        xLoc = 0;
12638                    }
12639                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12640                }
12641            } else {
12642                // Double-invalidation is necessary to capture view's old and new areas
12643                invalidate(true);
12644            }
12645
12646            int oldWidth = mRight - mLeft;
12647            int height = mBottom - mTop;
12648
12649            mLeft = left;
12650            mRenderNode.setLeft(left);
12651
12652            sizeChange(mRight - mLeft, height, oldWidth, height);
12653
12654            if (!matrixIsIdentity) {
12655                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12656                invalidate(true);
12657            }
12658            mBackgroundSizeChanged = true;
12659            if (mForegroundInfo != null) {
12660                mForegroundInfo.mBoundsChanged = true;
12661            }
12662            invalidateParentIfNeeded();
12663            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12664                // View was rejected last time it was drawn by its parent; this may have changed
12665                invalidateParentIfNeeded();
12666            }
12667        }
12668    }
12669
12670    /**
12671     * Right position of this view relative to its parent.
12672     *
12673     * @return The right edge of this view, in pixels.
12674     */
12675    @ViewDebug.CapturedViewProperty
12676    public final int getRight() {
12677        return mRight;
12678    }
12679
12680    /**
12681     * Sets the right position of this view relative to its parent. This method is meant to be called
12682     * by the layout system and should not generally be called otherwise, because the property
12683     * may be changed at any time by the layout.
12684     *
12685     * @param right The right of this view, in pixels.
12686     */
12687    public final void setRight(int right) {
12688        if (right != mRight) {
12689            final boolean matrixIsIdentity = hasIdentityMatrix();
12690            if (matrixIsIdentity) {
12691                if (mAttachInfo != null) {
12692                    int maxRight;
12693                    if (right < mRight) {
12694                        maxRight = mRight;
12695                    } else {
12696                        maxRight = right;
12697                    }
12698                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12699                }
12700            } else {
12701                // Double-invalidation is necessary to capture view's old and new areas
12702                invalidate(true);
12703            }
12704
12705            int oldWidth = mRight - mLeft;
12706            int height = mBottom - mTop;
12707
12708            mRight = right;
12709            mRenderNode.setRight(mRight);
12710
12711            sizeChange(mRight - mLeft, height, oldWidth, height);
12712
12713            if (!matrixIsIdentity) {
12714                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12715                invalidate(true);
12716            }
12717            mBackgroundSizeChanged = true;
12718            if (mForegroundInfo != null) {
12719                mForegroundInfo.mBoundsChanged = true;
12720            }
12721            invalidateParentIfNeeded();
12722            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12723                // View was rejected last time it was drawn by its parent; this may have changed
12724                invalidateParentIfNeeded();
12725            }
12726        }
12727    }
12728
12729    /**
12730     * The visual x position of this view, in pixels. This is equivalent to the
12731     * {@link #setTranslationX(float) translationX} property plus the current
12732     * {@link #getLeft() left} property.
12733     *
12734     * @return The visual x position of this view, in pixels.
12735     */
12736    @ViewDebug.ExportedProperty(category = "drawing")
12737    public float getX() {
12738        return mLeft + getTranslationX();
12739    }
12740
12741    /**
12742     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12743     * {@link #setTranslationX(float) translationX} property to be the difference between
12744     * the x value passed in and the current {@link #getLeft() left} property.
12745     *
12746     * @param x The visual x position of this view, in pixels.
12747     */
12748    public void setX(float x) {
12749        setTranslationX(x - mLeft);
12750    }
12751
12752    /**
12753     * The visual y position of this view, in pixels. This is equivalent to the
12754     * {@link #setTranslationY(float) translationY} property plus the current
12755     * {@link #getTop() top} property.
12756     *
12757     * @return The visual y position of this view, in pixels.
12758     */
12759    @ViewDebug.ExportedProperty(category = "drawing")
12760    public float getY() {
12761        return mTop + getTranslationY();
12762    }
12763
12764    /**
12765     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12766     * {@link #setTranslationY(float) translationY} property to be the difference between
12767     * the y value passed in and the current {@link #getTop() top} property.
12768     *
12769     * @param y The visual y position of this view, in pixels.
12770     */
12771    public void setY(float y) {
12772        setTranslationY(y - mTop);
12773    }
12774
12775    /**
12776     * The visual z position of this view, in pixels. This is equivalent to the
12777     * {@link #setTranslationZ(float) translationZ} property plus the current
12778     * {@link #getElevation() elevation} property.
12779     *
12780     * @return The visual z position of this view, in pixels.
12781     */
12782    @ViewDebug.ExportedProperty(category = "drawing")
12783    public float getZ() {
12784        return getElevation() + getTranslationZ();
12785    }
12786
12787    /**
12788     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12789     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12790     * the x value passed in and the current {@link #getElevation() elevation} property.
12791     *
12792     * @param z The visual z position of this view, in pixels.
12793     */
12794    public void setZ(float z) {
12795        setTranslationZ(z - getElevation());
12796    }
12797
12798    /**
12799     * The base elevation of this view relative to its parent, in pixels.
12800     *
12801     * @return The base depth position of the view, in pixels.
12802     */
12803    @ViewDebug.ExportedProperty(category = "drawing")
12804    public float getElevation() {
12805        return mRenderNode.getElevation();
12806    }
12807
12808    /**
12809     * Sets the base elevation of this view, in pixels.
12810     *
12811     * @attr ref android.R.styleable#View_elevation
12812     */
12813    public void setElevation(float elevation) {
12814        if (elevation != getElevation()) {
12815            invalidateViewProperty(true, false);
12816            mRenderNode.setElevation(elevation);
12817            invalidateViewProperty(false, true);
12818
12819            invalidateParentIfNeededAndWasQuickRejected();
12820        }
12821    }
12822
12823    /**
12824     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12825     * This position is post-layout, in addition to wherever the object's
12826     * layout placed it.
12827     *
12828     * @return The horizontal position of this view relative to its left position, in pixels.
12829     */
12830    @ViewDebug.ExportedProperty(category = "drawing")
12831    public float getTranslationX() {
12832        return mRenderNode.getTranslationX();
12833    }
12834
12835    /**
12836     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12837     * This effectively positions the object post-layout, in addition to wherever the object's
12838     * layout placed it.
12839     *
12840     * @param translationX The horizontal position of this view relative to its left position,
12841     * in pixels.
12842     *
12843     * @attr ref android.R.styleable#View_translationX
12844     */
12845    public void setTranslationX(float translationX) {
12846        if (translationX != getTranslationX()) {
12847            invalidateViewProperty(true, false);
12848            mRenderNode.setTranslationX(translationX);
12849            invalidateViewProperty(false, true);
12850
12851            invalidateParentIfNeededAndWasQuickRejected();
12852            notifySubtreeAccessibilityStateChangedIfNeeded();
12853        }
12854    }
12855
12856    /**
12857     * The vertical location of this view relative to its {@link #getTop() top} position.
12858     * This position is post-layout, in addition to wherever the object's
12859     * layout placed it.
12860     *
12861     * @return The vertical position of this view relative to its top position,
12862     * in pixels.
12863     */
12864    @ViewDebug.ExportedProperty(category = "drawing")
12865    public float getTranslationY() {
12866        return mRenderNode.getTranslationY();
12867    }
12868
12869    /**
12870     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12871     * This effectively positions the object post-layout, in addition to wherever the object's
12872     * layout placed it.
12873     *
12874     * @param translationY The vertical position of this view relative to its top position,
12875     * in pixels.
12876     *
12877     * @attr ref android.R.styleable#View_translationY
12878     */
12879    public void setTranslationY(float translationY) {
12880        if (translationY != getTranslationY()) {
12881            invalidateViewProperty(true, false);
12882            mRenderNode.setTranslationY(translationY);
12883            invalidateViewProperty(false, true);
12884
12885            invalidateParentIfNeededAndWasQuickRejected();
12886            notifySubtreeAccessibilityStateChangedIfNeeded();
12887        }
12888    }
12889
12890    /**
12891     * The depth location of this view relative to its {@link #getElevation() elevation}.
12892     *
12893     * @return The depth of this view relative to its elevation.
12894     */
12895    @ViewDebug.ExportedProperty(category = "drawing")
12896    public float getTranslationZ() {
12897        return mRenderNode.getTranslationZ();
12898    }
12899
12900    /**
12901     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12902     *
12903     * @attr ref android.R.styleable#View_translationZ
12904     */
12905    public void setTranslationZ(float translationZ) {
12906        if (translationZ != getTranslationZ()) {
12907            invalidateViewProperty(true, false);
12908            mRenderNode.setTranslationZ(translationZ);
12909            invalidateViewProperty(false, true);
12910
12911            invalidateParentIfNeededAndWasQuickRejected();
12912        }
12913    }
12914
12915    /** @hide */
12916    public void setAnimationMatrix(Matrix matrix) {
12917        invalidateViewProperty(true, false);
12918        mRenderNode.setAnimationMatrix(matrix);
12919        invalidateViewProperty(false, true);
12920
12921        invalidateParentIfNeededAndWasQuickRejected();
12922    }
12923
12924    /**
12925     * Returns the current StateListAnimator if exists.
12926     *
12927     * @return StateListAnimator or null if it does not exists
12928     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12929     */
12930    public StateListAnimator getStateListAnimator() {
12931        return mStateListAnimator;
12932    }
12933
12934    /**
12935     * Attaches the provided StateListAnimator to this View.
12936     * <p>
12937     * Any previously attached StateListAnimator will be detached.
12938     *
12939     * @param stateListAnimator The StateListAnimator to update the view
12940     * @see {@link android.animation.StateListAnimator}
12941     */
12942    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12943        if (mStateListAnimator == stateListAnimator) {
12944            return;
12945        }
12946        if (mStateListAnimator != null) {
12947            mStateListAnimator.setTarget(null);
12948        }
12949        mStateListAnimator = stateListAnimator;
12950        if (stateListAnimator != null) {
12951            stateListAnimator.setTarget(this);
12952            if (isAttachedToWindow()) {
12953                stateListAnimator.setState(getDrawableState());
12954            }
12955        }
12956    }
12957
12958    /**
12959     * Returns whether the Outline should be used to clip the contents of the View.
12960     * <p>
12961     * Note that this flag will only be respected if the View's Outline returns true from
12962     * {@link Outline#canClip()}.
12963     *
12964     * @see #setOutlineProvider(ViewOutlineProvider)
12965     * @see #setClipToOutline(boolean)
12966     */
12967    public final boolean getClipToOutline() {
12968        return mRenderNode.getClipToOutline();
12969    }
12970
12971    /**
12972     * Sets whether the View's Outline should be used to clip the contents of the View.
12973     * <p>
12974     * Only a single non-rectangular clip can be applied on a View at any time.
12975     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12976     * circular reveal} animation take priority over Outline clipping, and
12977     * child Outline clipping takes priority over Outline clipping done by a
12978     * parent.
12979     * <p>
12980     * Note that this flag will only be respected if the View's Outline returns true from
12981     * {@link Outline#canClip()}.
12982     *
12983     * @see #setOutlineProvider(ViewOutlineProvider)
12984     * @see #getClipToOutline()
12985     */
12986    public void setClipToOutline(boolean clipToOutline) {
12987        damageInParent();
12988        if (getClipToOutline() != clipToOutline) {
12989            mRenderNode.setClipToOutline(clipToOutline);
12990        }
12991    }
12992
12993    // correspond to the enum values of View_outlineProvider
12994    private static final int PROVIDER_BACKGROUND = 0;
12995    private static final int PROVIDER_NONE = 1;
12996    private static final int PROVIDER_BOUNDS = 2;
12997    private static final int PROVIDER_PADDED_BOUNDS = 3;
12998    private void setOutlineProviderFromAttribute(int providerInt) {
12999        switch (providerInt) {
13000            case PROVIDER_BACKGROUND:
13001                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13002                break;
13003            case PROVIDER_NONE:
13004                setOutlineProvider(null);
13005                break;
13006            case PROVIDER_BOUNDS:
13007                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13008                break;
13009            case PROVIDER_PADDED_BOUNDS:
13010                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13011                break;
13012        }
13013    }
13014
13015    /**
13016     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13017     * the shape of the shadow it casts, and enables outline clipping.
13018     * <p>
13019     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13020     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13021     * outline provider with this method allows this behavior to be overridden.
13022     * <p>
13023     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13024     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13025     * <p>
13026     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13027     *
13028     * @see #setClipToOutline(boolean)
13029     * @see #getClipToOutline()
13030     * @see #getOutlineProvider()
13031     */
13032    public void setOutlineProvider(ViewOutlineProvider provider) {
13033        mOutlineProvider = provider;
13034        invalidateOutline();
13035    }
13036
13037    /**
13038     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13039     * that defines the shape of the shadow it casts, and enables outline clipping.
13040     *
13041     * @see #setOutlineProvider(ViewOutlineProvider)
13042     */
13043    public ViewOutlineProvider getOutlineProvider() {
13044        return mOutlineProvider;
13045    }
13046
13047    /**
13048     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13049     *
13050     * @see #setOutlineProvider(ViewOutlineProvider)
13051     */
13052    public void invalidateOutline() {
13053        rebuildOutline();
13054
13055        notifySubtreeAccessibilityStateChangedIfNeeded();
13056        invalidateViewProperty(false, false);
13057    }
13058
13059    /**
13060     * Internal version of {@link #invalidateOutline()} which invalidates the
13061     * outline without invalidating the view itself. This is intended to be called from
13062     * within methods in the View class itself which are the result of the view being
13063     * invalidated already. For example, when we are drawing the background of a View,
13064     * we invalidate the outline in case it changed in the meantime, but we do not
13065     * need to invalidate the view because we're already drawing the background as part
13066     * of drawing the view in response to an earlier invalidation of the view.
13067     */
13068    private void rebuildOutline() {
13069        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13070        if (mAttachInfo == null) return;
13071
13072        if (mOutlineProvider == null) {
13073            // no provider, remove outline
13074            mRenderNode.setOutline(null);
13075        } else {
13076            final Outline outline = mAttachInfo.mTmpOutline;
13077            outline.setEmpty();
13078            outline.setAlpha(1.0f);
13079
13080            mOutlineProvider.getOutline(this, outline);
13081            mRenderNode.setOutline(outline);
13082        }
13083    }
13084
13085    /**
13086     * HierarchyViewer only
13087     *
13088     * @hide
13089     */
13090    @ViewDebug.ExportedProperty(category = "drawing")
13091    public boolean hasShadow() {
13092        return mRenderNode.hasShadow();
13093    }
13094
13095
13096    /** @hide */
13097    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13098        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13099        invalidateViewProperty(false, false);
13100    }
13101
13102    /**
13103     * Hit rectangle in parent's coordinates
13104     *
13105     * @param outRect The hit rectangle of the view.
13106     */
13107    public void getHitRect(Rect outRect) {
13108        if (hasIdentityMatrix() || mAttachInfo == null) {
13109            outRect.set(mLeft, mTop, mRight, mBottom);
13110        } else {
13111            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13112            tmpRect.set(0, 0, getWidth(), getHeight());
13113            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13114            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13115                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13116        }
13117    }
13118
13119    /**
13120     * Determines whether the given point, in local coordinates is inside the view.
13121     */
13122    /*package*/ final boolean pointInView(float localX, float localY) {
13123        return pointInView(localX, localY, 0);
13124    }
13125
13126    /**
13127     * Utility method to determine whether the given point, in local coordinates,
13128     * is inside the view, where the area of the view is expanded by the slop factor.
13129     * This method is called while processing touch-move events to determine if the event
13130     * is still within the view.
13131     *
13132     * @hide
13133     */
13134    public boolean pointInView(float localX, float localY, float slop) {
13135        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13136                localY < ((mBottom - mTop) + slop);
13137    }
13138
13139    /**
13140     * When a view has focus and the user navigates away from it, the next view is searched for
13141     * starting from the rectangle filled in by this method.
13142     *
13143     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13144     * of the view.  However, if your view maintains some idea of internal selection,
13145     * such as a cursor, or a selected row or column, you should override this method and
13146     * fill in a more specific rectangle.
13147     *
13148     * @param r The rectangle to fill in, in this view's coordinates.
13149     */
13150    public void getFocusedRect(Rect r) {
13151        getDrawingRect(r);
13152    }
13153
13154    /**
13155     * If some part of this view is not clipped by any of its parents, then
13156     * return that area in r in global (root) coordinates. To convert r to local
13157     * coordinates (without taking possible View rotations into account), offset
13158     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13159     * If the view is completely clipped or translated out, return false.
13160     *
13161     * @param r If true is returned, r holds the global coordinates of the
13162     *        visible portion of this view.
13163     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13164     *        between this view and its root. globalOffet may be null.
13165     * @return true if r is non-empty (i.e. part of the view is visible at the
13166     *         root level.
13167     */
13168    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13169        int width = mRight - mLeft;
13170        int height = mBottom - mTop;
13171        if (width > 0 && height > 0) {
13172            r.set(0, 0, width, height);
13173            if (globalOffset != null) {
13174                globalOffset.set(-mScrollX, -mScrollY);
13175            }
13176            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13177        }
13178        return false;
13179    }
13180
13181    public final boolean getGlobalVisibleRect(Rect r) {
13182        return getGlobalVisibleRect(r, null);
13183    }
13184
13185    public final boolean getLocalVisibleRect(Rect r) {
13186        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13187        if (getGlobalVisibleRect(r, offset)) {
13188            r.offset(-offset.x, -offset.y); // make r local
13189            return true;
13190        }
13191        return false;
13192    }
13193
13194    /**
13195     * Offset this view's vertical location by the specified number of pixels.
13196     *
13197     * @param offset the number of pixels to offset the view by
13198     */
13199    public void offsetTopAndBottom(int offset) {
13200        if (offset != 0) {
13201            final boolean matrixIsIdentity = hasIdentityMatrix();
13202            if (matrixIsIdentity) {
13203                if (isHardwareAccelerated()) {
13204                    invalidateViewProperty(false, false);
13205                } else {
13206                    final ViewParent p = mParent;
13207                    if (p != null && mAttachInfo != null) {
13208                        final Rect r = mAttachInfo.mTmpInvalRect;
13209                        int minTop;
13210                        int maxBottom;
13211                        int yLoc;
13212                        if (offset < 0) {
13213                            minTop = mTop + offset;
13214                            maxBottom = mBottom;
13215                            yLoc = offset;
13216                        } else {
13217                            minTop = mTop;
13218                            maxBottom = mBottom + offset;
13219                            yLoc = 0;
13220                        }
13221                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13222                        p.invalidateChild(this, r);
13223                    }
13224                }
13225            } else {
13226                invalidateViewProperty(false, false);
13227            }
13228
13229            mTop += offset;
13230            mBottom += offset;
13231            mRenderNode.offsetTopAndBottom(offset);
13232            if (isHardwareAccelerated()) {
13233                invalidateViewProperty(false, false);
13234                invalidateParentIfNeededAndWasQuickRejected();
13235            } else {
13236                if (!matrixIsIdentity) {
13237                    invalidateViewProperty(false, true);
13238                }
13239                invalidateParentIfNeeded();
13240            }
13241            notifySubtreeAccessibilityStateChangedIfNeeded();
13242        }
13243    }
13244
13245    /**
13246     * Offset this view's horizontal location by the specified amount of pixels.
13247     *
13248     * @param offset the number of pixels to offset the view by
13249     */
13250    public void offsetLeftAndRight(int offset) {
13251        if (offset != 0) {
13252            final boolean matrixIsIdentity = hasIdentityMatrix();
13253            if (matrixIsIdentity) {
13254                if (isHardwareAccelerated()) {
13255                    invalidateViewProperty(false, false);
13256                } else {
13257                    final ViewParent p = mParent;
13258                    if (p != null && mAttachInfo != null) {
13259                        final Rect r = mAttachInfo.mTmpInvalRect;
13260                        int minLeft;
13261                        int maxRight;
13262                        if (offset < 0) {
13263                            minLeft = mLeft + offset;
13264                            maxRight = mRight;
13265                        } else {
13266                            minLeft = mLeft;
13267                            maxRight = mRight + offset;
13268                        }
13269                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13270                        p.invalidateChild(this, r);
13271                    }
13272                }
13273            } else {
13274                invalidateViewProperty(false, false);
13275            }
13276
13277            mLeft += offset;
13278            mRight += offset;
13279            mRenderNode.offsetLeftAndRight(offset);
13280            if (isHardwareAccelerated()) {
13281                invalidateViewProperty(false, false);
13282                invalidateParentIfNeededAndWasQuickRejected();
13283            } else {
13284                if (!matrixIsIdentity) {
13285                    invalidateViewProperty(false, true);
13286                }
13287                invalidateParentIfNeeded();
13288            }
13289            notifySubtreeAccessibilityStateChangedIfNeeded();
13290        }
13291    }
13292
13293    /**
13294     * Get the LayoutParams associated with this view. All views should have
13295     * layout parameters. These supply parameters to the <i>parent</i> of this
13296     * view specifying how it should be arranged. There are many subclasses of
13297     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13298     * of ViewGroup that are responsible for arranging their children.
13299     *
13300     * This method may return null if this View is not attached to a parent
13301     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13302     * was not invoked successfully. When a View is attached to a parent
13303     * ViewGroup, this method must not return null.
13304     *
13305     * @return The LayoutParams associated with this view, or null if no
13306     *         parameters have been set yet
13307     */
13308    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13309    public ViewGroup.LayoutParams getLayoutParams() {
13310        return mLayoutParams;
13311    }
13312
13313    /**
13314     * Set the layout parameters associated with this view. These supply
13315     * parameters to the <i>parent</i> of this view specifying how it should be
13316     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13317     * correspond to the different subclasses of ViewGroup that are responsible
13318     * for arranging their children.
13319     *
13320     * @param params The layout parameters for this view, cannot be null
13321     */
13322    public void setLayoutParams(ViewGroup.LayoutParams params) {
13323        if (params == null) {
13324            throw new NullPointerException("Layout parameters cannot be null");
13325        }
13326        mLayoutParams = params;
13327        resolveLayoutParams();
13328        if (mParent instanceof ViewGroup) {
13329            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13330        }
13331        requestLayout();
13332    }
13333
13334    /**
13335     * Resolve the layout parameters depending on the resolved layout direction
13336     *
13337     * @hide
13338     */
13339    public void resolveLayoutParams() {
13340        if (mLayoutParams != null) {
13341            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13342        }
13343    }
13344
13345    /**
13346     * Set the scrolled position of your view. This will cause a call to
13347     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13348     * invalidated.
13349     * @param x the x position to scroll to
13350     * @param y the y position to scroll to
13351     */
13352    public void scrollTo(int x, int y) {
13353        if (mScrollX != x || mScrollY != y) {
13354            int oldX = mScrollX;
13355            int oldY = mScrollY;
13356            mScrollX = x;
13357            mScrollY = y;
13358            invalidateParentCaches();
13359            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13360            if (!awakenScrollBars()) {
13361                postInvalidateOnAnimation();
13362            }
13363        }
13364    }
13365
13366    /**
13367     * Move the scrolled position of your view. This will cause a call to
13368     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13369     * invalidated.
13370     * @param x the amount of pixels to scroll by horizontally
13371     * @param y the amount of pixels to scroll by vertically
13372     */
13373    public void scrollBy(int x, int y) {
13374        scrollTo(mScrollX + x, mScrollY + y);
13375    }
13376
13377    /**
13378     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13379     * animation to fade the scrollbars out after a default delay. If a subclass
13380     * provides animated scrolling, the start delay should equal the duration
13381     * of the scrolling animation.</p>
13382     *
13383     * <p>The animation starts only if at least one of the scrollbars is
13384     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13385     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13386     * this method returns true, and false otherwise. If the animation is
13387     * started, this method calls {@link #invalidate()}; in that case the
13388     * caller should not call {@link #invalidate()}.</p>
13389     *
13390     * <p>This method should be invoked every time a subclass directly updates
13391     * the scroll parameters.</p>
13392     *
13393     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13394     * and {@link #scrollTo(int, int)}.</p>
13395     *
13396     * @return true if the animation is played, false otherwise
13397     *
13398     * @see #awakenScrollBars(int)
13399     * @see #scrollBy(int, int)
13400     * @see #scrollTo(int, int)
13401     * @see #isHorizontalScrollBarEnabled()
13402     * @see #isVerticalScrollBarEnabled()
13403     * @see #setHorizontalScrollBarEnabled(boolean)
13404     * @see #setVerticalScrollBarEnabled(boolean)
13405     */
13406    protected boolean awakenScrollBars() {
13407        return mScrollCache != null &&
13408                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13409    }
13410
13411    /**
13412     * Trigger the scrollbars to draw.
13413     * This method differs from awakenScrollBars() only in its default duration.
13414     * initialAwakenScrollBars() will show the scroll bars for longer than
13415     * usual to give the user more of a chance to notice them.
13416     *
13417     * @return true if the animation is played, false otherwise.
13418     */
13419    private boolean initialAwakenScrollBars() {
13420        return mScrollCache != null &&
13421                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13422    }
13423
13424    /**
13425     * <p>
13426     * Trigger the scrollbars to draw. When invoked this method starts an
13427     * animation to fade the scrollbars out after a fixed delay. If a subclass
13428     * provides animated scrolling, the start delay should equal the duration of
13429     * the scrolling animation.
13430     * </p>
13431     *
13432     * <p>
13433     * The animation starts only if at least one of the scrollbars is enabled,
13434     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13435     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13436     * this method returns true, and false otherwise. If the animation is
13437     * started, this method calls {@link #invalidate()}; in that case the caller
13438     * should not call {@link #invalidate()}.
13439     * </p>
13440     *
13441     * <p>
13442     * This method should be invoked every time a subclass directly updates the
13443     * scroll parameters.
13444     * </p>
13445     *
13446     * @param startDelay the delay, in milliseconds, after which the animation
13447     *        should start; when the delay is 0, the animation starts
13448     *        immediately
13449     * @return true if the animation is played, false otherwise
13450     *
13451     * @see #scrollBy(int, int)
13452     * @see #scrollTo(int, int)
13453     * @see #isHorizontalScrollBarEnabled()
13454     * @see #isVerticalScrollBarEnabled()
13455     * @see #setHorizontalScrollBarEnabled(boolean)
13456     * @see #setVerticalScrollBarEnabled(boolean)
13457     */
13458    protected boolean awakenScrollBars(int startDelay) {
13459        return awakenScrollBars(startDelay, true);
13460    }
13461
13462    /**
13463     * <p>
13464     * Trigger the scrollbars to draw. When invoked this method starts an
13465     * animation to fade the scrollbars out after a fixed delay. If a subclass
13466     * provides animated scrolling, the start delay should equal the duration of
13467     * the scrolling animation.
13468     * </p>
13469     *
13470     * <p>
13471     * The animation starts only if at least one of the scrollbars is enabled,
13472     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13473     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13474     * this method returns true, and false otherwise. If the animation is
13475     * started, this method calls {@link #invalidate()} if the invalidate parameter
13476     * is set to true; in that case the caller
13477     * should not call {@link #invalidate()}.
13478     * </p>
13479     *
13480     * <p>
13481     * This method should be invoked every time a subclass directly updates the
13482     * scroll parameters.
13483     * </p>
13484     *
13485     * @param startDelay the delay, in milliseconds, after which the animation
13486     *        should start; when the delay is 0, the animation starts
13487     *        immediately
13488     *
13489     * @param invalidate Whether this method should call invalidate
13490     *
13491     * @return true if the animation is played, false otherwise
13492     *
13493     * @see #scrollBy(int, int)
13494     * @see #scrollTo(int, int)
13495     * @see #isHorizontalScrollBarEnabled()
13496     * @see #isVerticalScrollBarEnabled()
13497     * @see #setHorizontalScrollBarEnabled(boolean)
13498     * @see #setVerticalScrollBarEnabled(boolean)
13499     */
13500    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13501        final ScrollabilityCache scrollCache = mScrollCache;
13502
13503        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13504            return false;
13505        }
13506
13507        if (scrollCache.scrollBar == null) {
13508            scrollCache.scrollBar = new ScrollBarDrawable();
13509            scrollCache.scrollBar.setState(getDrawableState());
13510            scrollCache.scrollBar.setCallback(this);
13511        }
13512
13513        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13514
13515            if (invalidate) {
13516                // Invalidate to show the scrollbars
13517                postInvalidateOnAnimation();
13518            }
13519
13520            if (scrollCache.state == ScrollabilityCache.OFF) {
13521                // FIXME: this is copied from WindowManagerService.
13522                // We should get this value from the system when it
13523                // is possible to do so.
13524                final int KEY_REPEAT_FIRST_DELAY = 750;
13525                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13526            }
13527
13528            // Tell mScrollCache when we should start fading. This may
13529            // extend the fade start time if one was already scheduled
13530            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13531            scrollCache.fadeStartTime = fadeStartTime;
13532            scrollCache.state = ScrollabilityCache.ON;
13533
13534            // Schedule our fader to run, unscheduling any old ones first
13535            if (mAttachInfo != null) {
13536                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13537                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13538            }
13539
13540            return true;
13541        }
13542
13543        return false;
13544    }
13545
13546    /**
13547     * Do not invalidate views which are not visible and which are not running an animation. They
13548     * will not get drawn and they should not set dirty flags as if they will be drawn
13549     */
13550    private boolean skipInvalidate() {
13551        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13552                (!(mParent instanceof ViewGroup) ||
13553                        !((ViewGroup) mParent).isViewTransitioning(this));
13554    }
13555
13556    /**
13557     * Mark the area defined by dirty as needing to be drawn. If the view is
13558     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13559     * point in the future.
13560     * <p>
13561     * This must be called from a UI thread. To call from a non-UI thread, call
13562     * {@link #postInvalidate()}.
13563     * <p>
13564     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13565     * {@code dirty}.
13566     *
13567     * @param dirty the rectangle representing the bounds of the dirty region
13568     */
13569    public void invalidate(Rect dirty) {
13570        final int scrollX = mScrollX;
13571        final int scrollY = mScrollY;
13572        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13573                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13574    }
13575
13576    /**
13577     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13578     * coordinates of the dirty rect are relative to the view. If the view is
13579     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13580     * point in the future.
13581     * <p>
13582     * This must be called from a UI thread. To call from a non-UI thread, call
13583     * {@link #postInvalidate()}.
13584     *
13585     * @param l the left position of the dirty region
13586     * @param t the top position of the dirty region
13587     * @param r the right position of the dirty region
13588     * @param b the bottom position of the dirty region
13589     */
13590    public void invalidate(int l, int t, int r, int b) {
13591        final int scrollX = mScrollX;
13592        final int scrollY = mScrollY;
13593        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13594    }
13595
13596    /**
13597     * Invalidate the whole view. If the view is visible,
13598     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13599     * the future.
13600     * <p>
13601     * This must be called from a UI thread. To call from a non-UI thread, call
13602     * {@link #postInvalidate()}.
13603     */
13604    public void invalidate() {
13605        invalidate(true);
13606    }
13607
13608    /**
13609     * This is where the invalidate() work actually happens. A full invalidate()
13610     * causes the drawing cache to be invalidated, but this function can be
13611     * called with invalidateCache set to false to skip that invalidation step
13612     * for cases that do not need it (for example, a component that remains at
13613     * the same dimensions with the same content).
13614     *
13615     * @param invalidateCache Whether the drawing cache for this view should be
13616     *            invalidated as well. This is usually true for a full
13617     *            invalidate, but may be set to false if the View's contents or
13618     *            dimensions have not changed.
13619     */
13620    void invalidate(boolean invalidateCache) {
13621        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13622    }
13623
13624    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13625            boolean fullInvalidate) {
13626        if (mGhostView != null) {
13627            mGhostView.invalidate(true);
13628            return;
13629        }
13630
13631        if (skipInvalidate()) {
13632            return;
13633        }
13634
13635        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13636                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13637                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13638                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13639            if (fullInvalidate) {
13640                mLastIsOpaque = isOpaque();
13641                mPrivateFlags &= ~PFLAG_DRAWN;
13642            }
13643
13644            mPrivateFlags |= PFLAG_DIRTY;
13645
13646            if (invalidateCache) {
13647                mPrivateFlags |= PFLAG_INVALIDATED;
13648                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13649            }
13650
13651            // Propagate the damage rectangle to the parent view.
13652            final AttachInfo ai = mAttachInfo;
13653            final ViewParent p = mParent;
13654            if (p != null && ai != null && l < r && t < b) {
13655                final Rect damage = ai.mTmpInvalRect;
13656                damage.set(l, t, r, b);
13657                p.invalidateChild(this, damage);
13658            }
13659
13660            // Damage the entire projection receiver, if necessary.
13661            if (mBackground != null && mBackground.isProjected()) {
13662                final View receiver = getProjectionReceiver();
13663                if (receiver != null) {
13664                    receiver.damageInParent();
13665                }
13666            }
13667
13668            // Damage the entire IsolatedZVolume receiving this view's shadow.
13669            if (isHardwareAccelerated() && getZ() != 0) {
13670                damageShadowReceiver();
13671            }
13672        }
13673    }
13674
13675    /**
13676     * @return this view's projection receiver, or {@code null} if none exists
13677     */
13678    private View getProjectionReceiver() {
13679        ViewParent p = getParent();
13680        while (p != null && p instanceof View) {
13681            final View v = (View) p;
13682            if (v.isProjectionReceiver()) {
13683                return v;
13684            }
13685            p = p.getParent();
13686        }
13687
13688        return null;
13689    }
13690
13691    /**
13692     * @return whether the view is a projection receiver
13693     */
13694    private boolean isProjectionReceiver() {
13695        return mBackground != null;
13696    }
13697
13698    /**
13699     * Damage area of the screen that can be covered by this View's shadow.
13700     *
13701     * This method will guarantee that any changes to shadows cast by a View
13702     * are damaged on the screen for future redraw.
13703     */
13704    private void damageShadowReceiver() {
13705        final AttachInfo ai = mAttachInfo;
13706        if (ai != null) {
13707            ViewParent p = getParent();
13708            if (p != null && p instanceof ViewGroup) {
13709                final ViewGroup vg = (ViewGroup) p;
13710                vg.damageInParent();
13711            }
13712        }
13713    }
13714
13715    /**
13716     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13717     * set any flags or handle all of the cases handled by the default invalidation methods.
13718     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13719     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13720     * walk up the hierarchy, transforming the dirty rect as necessary.
13721     *
13722     * The method also handles normal invalidation logic if display list properties are not
13723     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13724     * backup approach, to handle these cases used in the various property-setting methods.
13725     *
13726     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13727     * are not being used in this view
13728     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13729     * list properties are not being used in this view
13730     */
13731    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13732        if (!isHardwareAccelerated()
13733                || !mRenderNode.isValid()
13734                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13735            if (invalidateParent) {
13736                invalidateParentCaches();
13737            }
13738            if (forceRedraw) {
13739                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13740            }
13741            invalidate(false);
13742        } else {
13743            damageInParent();
13744        }
13745        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13746            damageShadowReceiver();
13747        }
13748    }
13749
13750    /**
13751     * Tells the parent view to damage this view's bounds.
13752     *
13753     * @hide
13754     */
13755    protected void damageInParent() {
13756        final AttachInfo ai = mAttachInfo;
13757        final ViewParent p = mParent;
13758        if (p != null && ai != null) {
13759            final Rect r = ai.mTmpInvalRect;
13760            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13761            if (mParent instanceof ViewGroup) {
13762                ((ViewGroup) mParent).damageChild(this, r);
13763            } else {
13764                mParent.invalidateChild(this, r);
13765            }
13766        }
13767    }
13768
13769    /**
13770     * Utility method to transform a given Rect by the current matrix of this view.
13771     */
13772    void transformRect(final Rect rect) {
13773        if (!getMatrix().isIdentity()) {
13774            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13775            boundingRect.set(rect);
13776            getMatrix().mapRect(boundingRect);
13777            rect.set((int) Math.floor(boundingRect.left),
13778                    (int) Math.floor(boundingRect.top),
13779                    (int) Math.ceil(boundingRect.right),
13780                    (int) Math.ceil(boundingRect.bottom));
13781        }
13782    }
13783
13784    /**
13785     * Used to indicate that the parent of this view should clear its caches. This functionality
13786     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13787     * which is necessary when various parent-managed properties of the view change, such as
13788     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13789     * clears the parent caches and does not causes an invalidate event.
13790     *
13791     * @hide
13792     */
13793    protected void invalidateParentCaches() {
13794        if (mParent instanceof View) {
13795            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13796        }
13797    }
13798
13799    /**
13800     * Used to indicate that the parent of this view should be invalidated. This functionality
13801     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13802     * which is necessary when various parent-managed properties of the view change, such as
13803     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13804     * an invalidation event to the parent.
13805     *
13806     * @hide
13807     */
13808    protected void invalidateParentIfNeeded() {
13809        if (isHardwareAccelerated() && mParent instanceof View) {
13810            ((View) mParent).invalidate(true);
13811        }
13812    }
13813
13814    /**
13815     * @hide
13816     */
13817    protected void invalidateParentIfNeededAndWasQuickRejected() {
13818        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13819            // View was rejected last time it was drawn by its parent; this may have changed
13820            invalidateParentIfNeeded();
13821        }
13822    }
13823
13824    /**
13825     * Indicates whether this View is opaque. An opaque View guarantees that it will
13826     * draw all the pixels overlapping its bounds using a fully opaque color.
13827     *
13828     * Subclasses of View should override this method whenever possible to indicate
13829     * whether an instance is opaque. Opaque Views are treated in a special way by
13830     * the View hierarchy, possibly allowing it to perform optimizations during
13831     * invalidate/draw passes.
13832     *
13833     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13834     */
13835    @ViewDebug.ExportedProperty(category = "drawing")
13836    public boolean isOpaque() {
13837        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13838                getFinalAlpha() >= 1.0f;
13839    }
13840
13841    /**
13842     * @hide
13843     */
13844    protected void computeOpaqueFlags() {
13845        // Opaque if:
13846        //   - Has a background
13847        //   - Background is opaque
13848        //   - Doesn't have scrollbars or scrollbars overlay
13849
13850        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13851            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13852        } else {
13853            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13854        }
13855
13856        final int flags = mViewFlags;
13857        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13858                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13859                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13860            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13861        } else {
13862            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13863        }
13864    }
13865
13866    /**
13867     * @hide
13868     */
13869    protected boolean hasOpaqueScrollbars() {
13870        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13871    }
13872
13873    /**
13874     * @return A handler associated with the thread running the View. This
13875     * handler can be used to pump events in the UI events queue.
13876     */
13877    public Handler getHandler() {
13878        final AttachInfo attachInfo = mAttachInfo;
13879        if (attachInfo != null) {
13880            return attachInfo.mHandler;
13881        }
13882        return null;
13883    }
13884
13885    /**
13886     * Returns the queue of runnable for this view.
13887     *
13888     * @return the queue of runnables for this view
13889     */
13890    private HandlerActionQueue getRunQueue() {
13891        if (mRunQueue == null) {
13892            mRunQueue = new HandlerActionQueue();
13893        }
13894        return mRunQueue;
13895    }
13896
13897    /**
13898     * Gets the view root associated with the View.
13899     * @return The view root, or null if none.
13900     * @hide
13901     */
13902    public ViewRootImpl getViewRootImpl() {
13903        if (mAttachInfo != null) {
13904            return mAttachInfo.mViewRootImpl;
13905        }
13906        return null;
13907    }
13908
13909    /**
13910     * @hide
13911     */
13912    public ThreadedRenderer getThreadedRenderer() {
13913        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
13914    }
13915
13916    /**
13917     * <p>Causes the Runnable to be added to the message queue.
13918     * The runnable will be run on the user interface thread.</p>
13919     *
13920     * @param action The Runnable that will be executed.
13921     *
13922     * @return Returns true if the Runnable was successfully placed in to the
13923     *         message queue.  Returns false on failure, usually because the
13924     *         looper processing the message queue is exiting.
13925     *
13926     * @see #postDelayed
13927     * @see #removeCallbacks
13928     */
13929    public boolean post(Runnable action) {
13930        final AttachInfo attachInfo = mAttachInfo;
13931        if (attachInfo != null) {
13932            return attachInfo.mHandler.post(action);
13933        }
13934
13935        // Postpone the runnable until we know on which thread it needs to run.
13936        // Assume that the runnable will be successfully placed after attach.
13937        getRunQueue().post(action);
13938        return true;
13939    }
13940
13941    /**
13942     * <p>Causes the Runnable to be added to the message queue, to be run
13943     * after the specified amount of time elapses.
13944     * The runnable will be run on the user interface thread.</p>
13945     *
13946     * @param action The Runnable that will be executed.
13947     * @param delayMillis The delay (in milliseconds) until the Runnable
13948     *        will be executed.
13949     *
13950     * @return true if the Runnable was successfully placed in to the
13951     *         message queue.  Returns false on failure, usually because the
13952     *         looper processing the message queue is exiting.  Note that a
13953     *         result of true does not mean the Runnable will be processed --
13954     *         if the looper is quit before the delivery time of the message
13955     *         occurs then the message will be dropped.
13956     *
13957     * @see #post
13958     * @see #removeCallbacks
13959     */
13960    public boolean postDelayed(Runnable action, long delayMillis) {
13961        final AttachInfo attachInfo = mAttachInfo;
13962        if (attachInfo != null) {
13963            return attachInfo.mHandler.postDelayed(action, delayMillis);
13964        }
13965
13966        // Postpone the runnable until we know on which thread it needs to run.
13967        // Assume that the runnable will be successfully placed after attach.
13968        getRunQueue().postDelayed(action, delayMillis);
13969        return true;
13970    }
13971
13972    /**
13973     * <p>Causes the Runnable to execute on the next animation time step.
13974     * The runnable will be run on the user interface thread.</p>
13975     *
13976     * @param action The Runnable that will be executed.
13977     *
13978     * @see #postOnAnimationDelayed
13979     * @see #removeCallbacks
13980     */
13981    public void postOnAnimation(Runnable action) {
13982        final AttachInfo attachInfo = mAttachInfo;
13983        if (attachInfo != null) {
13984            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13985                    Choreographer.CALLBACK_ANIMATION, action, null);
13986        } else {
13987            // Postpone the runnable until we know
13988            // on which thread it needs to run.
13989            getRunQueue().post(action);
13990        }
13991    }
13992
13993    /**
13994     * <p>Causes the Runnable to execute on the next animation time step,
13995     * after the specified amount of time elapses.
13996     * The runnable will be run on the user interface thread.</p>
13997     *
13998     * @param action The Runnable that will be executed.
13999     * @param delayMillis The delay (in milliseconds) until the Runnable
14000     *        will be executed.
14001     *
14002     * @see #postOnAnimation
14003     * @see #removeCallbacks
14004     */
14005    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14006        final AttachInfo attachInfo = mAttachInfo;
14007        if (attachInfo != null) {
14008            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14009                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14010        } else {
14011            // Postpone the runnable until we know
14012            // on which thread it needs to run.
14013            getRunQueue().postDelayed(action, delayMillis);
14014        }
14015    }
14016
14017    /**
14018     * <p>Removes the specified Runnable from the message queue.</p>
14019     *
14020     * @param action The Runnable to remove from the message handling queue
14021     *
14022     * @return true if this view could ask the Handler to remove the Runnable,
14023     *         false otherwise. When the returned value is true, the Runnable
14024     *         may or may not have been actually removed from the message queue
14025     *         (for instance, if the Runnable was not in the queue already.)
14026     *
14027     * @see #post
14028     * @see #postDelayed
14029     * @see #postOnAnimation
14030     * @see #postOnAnimationDelayed
14031     */
14032    public boolean removeCallbacks(Runnable action) {
14033        if (action != null) {
14034            final AttachInfo attachInfo = mAttachInfo;
14035            if (attachInfo != null) {
14036                attachInfo.mHandler.removeCallbacks(action);
14037                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14038                        Choreographer.CALLBACK_ANIMATION, action, null);
14039            }
14040            getRunQueue().removeCallbacks(action);
14041        }
14042        return true;
14043    }
14044
14045    /**
14046     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14047     * Use this to invalidate the View from a non-UI thread.</p>
14048     *
14049     * <p>This method can be invoked from outside of the UI thread
14050     * only when this View is attached to a window.</p>
14051     *
14052     * @see #invalidate()
14053     * @see #postInvalidateDelayed(long)
14054     */
14055    public void postInvalidate() {
14056        postInvalidateDelayed(0);
14057    }
14058
14059    /**
14060     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14061     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14062     *
14063     * <p>This method can be invoked from outside of the UI thread
14064     * only when this View is attached to a window.</p>
14065     *
14066     * @param left The left coordinate of the rectangle to invalidate.
14067     * @param top The top coordinate of the rectangle to invalidate.
14068     * @param right The right coordinate of the rectangle to invalidate.
14069     * @param bottom The bottom coordinate of the rectangle to invalidate.
14070     *
14071     * @see #invalidate(int, int, int, int)
14072     * @see #invalidate(Rect)
14073     * @see #postInvalidateDelayed(long, int, int, int, int)
14074     */
14075    public void postInvalidate(int left, int top, int right, int bottom) {
14076        postInvalidateDelayed(0, left, top, right, bottom);
14077    }
14078
14079    /**
14080     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14081     * loop. Waits for the specified amount of time.</p>
14082     *
14083     * <p>This method can be invoked from outside of the UI thread
14084     * only when this View is attached to a window.</p>
14085     *
14086     * @param delayMilliseconds the duration in milliseconds to delay the
14087     *         invalidation by
14088     *
14089     * @see #invalidate()
14090     * @see #postInvalidate()
14091     */
14092    public void postInvalidateDelayed(long delayMilliseconds) {
14093        // We try only with the AttachInfo because there's no point in invalidating
14094        // if we are not attached to our window
14095        final AttachInfo attachInfo = mAttachInfo;
14096        if (attachInfo != null) {
14097            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14098        }
14099    }
14100
14101    /**
14102     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14103     * through the event loop. Waits for the specified amount of time.</p>
14104     *
14105     * <p>This method can be invoked from outside of the UI thread
14106     * only when this View is attached to a window.</p>
14107     *
14108     * @param delayMilliseconds the duration in milliseconds to delay the
14109     *         invalidation by
14110     * @param left The left coordinate of the rectangle to invalidate.
14111     * @param top The top coordinate of the rectangle to invalidate.
14112     * @param right The right coordinate of the rectangle to invalidate.
14113     * @param bottom The bottom coordinate of the rectangle to invalidate.
14114     *
14115     * @see #invalidate(int, int, int, int)
14116     * @see #invalidate(Rect)
14117     * @see #postInvalidate(int, int, int, int)
14118     */
14119    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14120            int right, int bottom) {
14121
14122        // We try only with the AttachInfo because there's no point in invalidating
14123        // if we are not attached to our window
14124        final AttachInfo attachInfo = mAttachInfo;
14125        if (attachInfo != null) {
14126            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14127            info.target = this;
14128            info.left = left;
14129            info.top = top;
14130            info.right = right;
14131            info.bottom = bottom;
14132
14133            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14134        }
14135    }
14136
14137    /**
14138     * <p>Cause an invalidate to happen on the next animation time step, typically the
14139     * next display frame.</p>
14140     *
14141     * <p>This method can be invoked from outside of the UI thread
14142     * only when this View is attached to a window.</p>
14143     *
14144     * @see #invalidate()
14145     */
14146    public void postInvalidateOnAnimation() {
14147        // We try only with the AttachInfo because there's no point in invalidating
14148        // if we are not attached to our window
14149        final AttachInfo attachInfo = mAttachInfo;
14150        if (attachInfo != null) {
14151            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14152        }
14153    }
14154
14155    /**
14156     * <p>Cause an invalidate of the specified area to happen on the next animation
14157     * time step, typically the next display frame.</p>
14158     *
14159     * <p>This method can be invoked from outside of the UI thread
14160     * only when this View is attached to a window.</p>
14161     *
14162     * @param left The left coordinate of the rectangle to invalidate.
14163     * @param top The top coordinate of the rectangle to invalidate.
14164     * @param right The right coordinate of the rectangle to invalidate.
14165     * @param bottom The bottom coordinate of the rectangle to invalidate.
14166     *
14167     * @see #invalidate(int, int, int, int)
14168     * @see #invalidate(Rect)
14169     */
14170    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14171        // We try only with the AttachInfo because there's no point in invalidating
14172        // if we are not attached to our window
14173        final AttachInfo attachInfo = mAttachInfo;
14174        if (attachInfo != null) {
14175            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14176            info.target = this;
14177            info.left = left;
14178            info.top = top;
14179            info.right = right;
14180            info.bottom = bottom;
14181
14182            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14183        }
14184    }
14185
14186    /**
14187     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14188     * This event is sent at most once every
14189     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14190     */
14191    private void postSendViewScrolledAccessibilityEventCallback() {
14192        if (mSendViewScrolledAccessibilityEvent == null) {
14193            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14194        }
14195        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14196            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14197            postDelayed(mSendViewScrolledAccessibilityEvent,
14198                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14199        }
14200    }
14201
14202    /**
14203     * Called by a parent to request that a child update its values for mScrollX
14204     * and mScrollY if necessary. This will typically be done if the child is
14205     * animating a scroll using a {@link android.widget.Scroller Scroller}
14206     * object.
14207     */
14208    public void computeScroll() {
14209    }
14210
14211    /**
14212     * <p>Indicate whether the horizontal edges are faded when the view is
14213     * scrolled horizontally.</p>
14214     *
14215     * @return true if the horizontal edges should are faded on scroll, false
14216     *         otherwise
14217     *
14218     * @see #setHorizontalFadingEdgeEnabled(boolean)
14219     *
14220     * @attr ref android.R.styleable#View_requiresFadingEdge
14221     */
14222    public boolean isHorizontalFadingEdgeEnabled() {
14223        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14224    }
14225
14226    /**
14227     * <p>Define whether the horizontal edges should be faded when this view
14228     * is scrolled horizontally.</p>
14229     *
14230     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14231     *                                    be faded when the view is scrolled
14232     *                                    horizontally
14233     *
14234     * @see #isHorizontalFadingEdgeEnabled()
14235     *
14236     * @attr ref android.R.styleable#View_requiresFadingEdge
14237     */
14238    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14239        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14240            if (horizontalFadingEdgeEnabled) {
14241                initScrollCache();
14242            }
14243
14244            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14245        }
14246    }
14247
14248    /**
14249     * <p>Indicate whether the vertical edges are faded when the view is
14250     * scrolled horizontally.</p>
14251     *
14252     * @return true if the vertical edges should are faded on scroll, false
14253     *         otherwise
14254     *
14255     * @see #setVerticalFadingEdgeEnabled(boolean)
14256     *
14257     * @attr ref android.R.styleable#View_requiresFadingEdge
14258     */
14259    public boolean isVerticalFadingEdgeEnabled() {
14260        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14261    }
14262
14263    /**
14264     * <p>Define whether the vertical edges should be faded when this view
14265     * is scrolled vertically.</p>
14266     *
14267     * @param verticalFadingEdgeEnabled true if the vertical edges should
14268     *                                  be faded when the view is scrolled
14269     *                                  vertically
14270     *
14271     * @see #isVerticalFadingEdgeEnabled()
14272     *
14273     * @attr ref android.R.styleable#View_requiresFadingEdge
14274     */
14275    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14276        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14277            if (verticalFadingEdgeEnabled) {
14278                initScrollCache();
14279            }
14280
14281            mViewFlags ^= FADING_EDGE_VERTICAL;
14282        }
14283    }
14284
14285    /**
14286     * Returns the strength, or intensity, of the top faded edge. The strength is
14287     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14288     * returns 0.0 or 1.0 but no value in between.
14289     *
14290     * Subclasses should override this method to provide a smoother fade transition
14291     * when scrolling occurs.
14292     *
14293     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14294     */
14295    protected float getTopFadingEdgeStrength() {
14296        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14297    }
14298
14299    /**
14300     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14301     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14302     * returns 0.0 or 1.0 but no value in between.
14303     *
14304     * Subclasses should override this method to provide a smoother fade transition
14305     * when scrolling occurs.
14306     *
14307     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14308     */
14309    protected float getBottomFadingEdgeStrength() {
14310        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14311                computeVerticalScrollRange() ? 1.0f : 0.0f;
14312    }
14313
14314    /**
14315     * Returns the strength, or intensity, of the left faded edge. The strength is
14316     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14317     * returns 0.0 or 1.0 but no value in between.
14318     *
14319     * Subclasses should override this method to provide a smoother fade transition
14320     * when scrolling occurs.
14321     *
14322     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14323     */
14324    protected float getLeftFadingEdgeStrength() {
14325        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14326    }
14327
14328    /**
14329     * Returns the strength, or intensity, of the right faded edge. The strength is
14330     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14331     * returns 0.0 or 1.0 but no value in between.
14332     *
14333     * Subclasses should override this method to provide a smoother fade transition
14334     * when scrolling occurs.
14335     *
14336     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14337     */
14338    protected float getRightFadingEdgeStrength() {
14339        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14340                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14341    }
14342
14343    /**
14344     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14345     * scrollbar is not drawn by default.</p>
14346     *
14347     * @return true if the horizontal scrollbar should be painted, false
14348     *         otherwise
14349     *
14350     * @see #setHorizontalScrollBarEnabled(boolean)
14351     */
14352    public boolean isHorizontalScrollBarEnabled() {
14353        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14354    }
14355
14356    /**
14357     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14358     * scrollbar is not drawn by default.</p>
14359     *
14360     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14361     *                                   be painted
14362     *
14363     * @see #isHorizontalScrollBarEnabled()
14364     */
14365    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14366        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14367            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14368            computeOpaqueFlags();
14369            resolvePadding();
14370        }
14371    }
14372
14373    /**
14374     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14375     * scrollbar is not drawn by default.</p>
14376     *
14377     * @return true if the vertical scrollbar should be painted, false
14378     *         otherwise
14379     *
14380     * @see #setVerticalScrollBarEnabled(boolean)
14381     */
14382    public boolean isVerticalScrollBarEnabled() {
14383        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14384    }
14385
14386    /**
14387     * <p>Define whether the vertical scrollbar should be drawn or not. The
14388     * scrollbar is not drawn by default.</p>
14389     *
14390     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14391     *                                 be painted
14392     *
14393     * @see #isVerticalScrollBarEnabled()
14394     */
14395    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14396        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14397            mViewFlags ^= SCROLLBARS_VERTICAL;
14398            computeOpaqueFlags();
14399            resolvePadding();
14400        }
14401    }
14402
14403    /**
14404     * @hide
14405     */
14406    protected void recomputePadding() {
14407        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14408    }
14409
14410    /**
14411     * Define whether scrollbars will fade when the view is not scrolling.
14412     *
14413     * @param fadeScrollbars whether to enable fading
14414     *
14415     * @attr ref android.R.styleable#View_fadeScrollbars
14416     */
14417    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14418        initScrollCache();
14419        final ScrollabilityCache scrollabilityCache = mScrollCache;
14420        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14421        if (fadeScrollbars) {
14422            scrollabilityCache.state = ScrollabilityCache.OFF;
14423        } else {
14424            scrollabilityCache.state = ScrollabilityCache.ON;
14425        }
14426    }
14427
14428    /**
14429     *
14430     * Returns true if scrollbars will fade when this view is not scrolling
14431     *
14432     * @return true if scrollbar fading is enabled
14433     *
14434     * @attr ref android.R.styleable#View_fadeScrollbars
14435     */
14436    public boolean isScrollbarFadingEnabled() {
14437        return mScrollCache != null && mScrollCache.fadeScrollBars;
14438    }
14439
14440    /**
14441     *
14442     * Returns the delay before scrollbars fade.
14443     *
14444     * @return the delay before scrollbars fade
14445     *
14446     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14447     */
14448    public int getScrollBarDefaultDelayBeforeFade() {
14449        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14450                mScrollCache.scrollBarDefaultDelayBeforeFade;
14451    }
14452
14453    /**
14454     * Define the delay before scrollbars fade.
14455     *
14456     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14457     *
14458     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14459     */
14460    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14461        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14462    }
14463
14464    /**
14465     *
14466     * Returns the scrollbar fade duration.
14467     *
14468     * @return the scrollbar fade duration, in milliseconds
14469     *
14470     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14471     */
14472    public int getScrollBarFadeDuration() {
14473        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14474                mScrollCache.scrollBarFadeDuration;
14475    }
14476
14477    /**
14478     * Define the scrollbar fade duration.
14479     *
14480     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
14481     *
14482     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14483     */
14484    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14485        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14486    }
14487
14488    /**
14489     *
14490     * Returns the scrollbar size.
14491     *
14492     * @return the scrollbar size
14493     *
14494     * @attr ref android.R.styleable#View_scrollbarSize
14495     */
14496    public int getScrollBarSize() {
14497        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14498                mScrollCache.scrollBarSize;
14499    }
14500
14501    /**
14502     * Define the scrollbar size.
14503     *
14504     * @param scrollBarSize - the scrollbar size
14505     *
14506     * @attr ref android.R.styleable#View_scrollbarSize
14507     */
14508    public void setScrollBarSize(int scrollBarSize) {
14509        getScrollCache().scrollBarSize = scrollBarSize;
14510    }
14511
14512    /**
14513     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14514     * inset. When inset, they add to the padding of the view. And the scrollbars
14515     * can be drawn inside the padding area or on the edge of the view. For example,
14516     * if a view has a background drawable and you want to draw the scrollbars
14517     * inside the padding specified by the drawable, you can use
14518     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14519     * appear at the edge of the view, ignoring the padding, then you can use
14520     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14521     * @param style the style of the scrollbars. Should be one of
14522     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14523     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14524     * @see #SCROLLBARS_INSIDE_OVERLAY
14525     * @see #SCROLLBARS_INSIDE_INSET
14526     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14527     * @see #SCROLLBARS_OUTSIDE_INSET
14528     *
14529     * @attr ref android.R.styleable#View_scrollbarStyle
14530     */
14531    public void setScrollBarStyle(@ScrollBarStyle int style) {
14532        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14533            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14534            computeOpaqueFlags();
14535            resolvePadding();
14536        }
14537    }
14538
14539    /**
14540     * <p>Returns the current scrollbar style.</p>
14541     * @return the current scrollbar style
14542     * @see #SCROLLBARS_INSIDE_OVERLAY
14543     * @see #SCROLLBARS_INSIDE_INSET
14544     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14545     * @see #SCROLLBARS_OUTSIDE_INSET
14546     *
14547     * @attr ref android.R.styleable#View_scrollbarStyle
14548     */
14549    @ViewDebug.ExportedProperty(mapping = {
14550            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14551            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14552            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14553            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14554    })
14555    @ScrollBarStyle
14556    public int getScrollBarStyle() {
14557        return mViewFlags & SCROLLBARS_STYLE_MASK;
14558    }
14559
14560    /**
14561     * <p>Compute the horizontal range that the horizontal scrollbar
14562     * represents.</p>
14563     *
14564     * <p>The range is expressed in arbitrary units that must be the same as the
14565     * units used by {@link #computeHorizontalScrollExtent()} and
14566     * {@link #computeHorizontalScrollOffset()}.</p>
14567     *
14568     * <p>The default range is the drawing width of this view.</p>
14569     *
14570     * @return the total horizontal range represented by the horizontal
14571     *         scrollbar
14572     *
14573     * @see #computeHorizontalScrollExtent()
14574     * @see #computeHorizontalScrollOffset()
14575     * @see android.widget.ScrollBarDrawable
14576     */
14577    protected int computeHorizontalScrollRange() {
14578        return getWidth();
14579    }
14580
14581    /**
14582     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14583     * within the horizontal range. This value is used to compute the position
14584     * of the thumb within the scrollbar's track.</p>
14585     *
14586     * <p>The range is expressed in arbitrary units that must be the same as the
14587     * units used by {@link #computeHorizontalScrollRange()} and
14588     * {@link #computeHorizontalScrollExtent()}.</p>
14589     *
14590     * <p>The default offset is the scroll offset of this view.</p>
14591     *
14592     * @return the horizontal offset of the scrollbar's thumb
14593     *
14594     * @see #computeHorizontalScrollRange()
14595     * @see #computeHorizontalScrollExtent()
14596     * @see android.widget.ScrollBarDrawable
14597     */
14598    protected int computeHorizontalScrollOffset() {
14599        return mScrollX;
14600    }
14601
14602    /**
14603     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14604     * within the horizontal range. This value is used to compute the length
14605     * of the thumb within the scrollbar's track.</p>
14606     *
14607     * <p>The range is expressed in arbitrary units that must be the same as the
14608     * units used by {@link #computeHorizontalScrollRange()} and
14609     * {@link #computeHorizontalScrollOffset()}.</p>
14610     *
14611     * <p>The default extent is the drawing width of this view.</p>
14612     *
14613     * @return the horizontal extent of the scrollbar's thumb
14614     *
14615     * @see #computeHorizontalScrollRange()
14616     * @see #computeHorizontalScrollOffset()
14617     * @see android.widget.ScrollBarDrawable
14618     */
14619    protected int computeHorizontalScrollExtent() {
14620        return getWidth();
14621    }
14622
14623    /**
14624     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14625     *
14626     * <p>The range is expressed in arbitrary units that must be the same as the
14627     * units used by {@link #computeVerticalScrollExtent()} and
14628     * {@link #computeVerticalScrollOffset()}.</p>
14629     *
14630     * @return the total vertical range represented by the vertical scrollbar
14631     *
14632     * <p>The default range is the drawing height of this view.</p>
14633     *
14634     * @see #computeVerticalScrollExtent()
14635     * @see #computeVerticalScrollOffset()
14636     * @see android.widget.ScrollBarDrawable
14637     */
14638    protected int computeVerticalScrollRange() {
14639        return getHeight();
14640    }
14641
14642    /**
14643     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14644     * within the horizontal range. This value is used to compute the position
14645     * of the thumb within the scrollbar's track.</p>
14646     *
14647     * <p>The range is expressed in arbitrary units that must be the same as the
14648     * units used by {@link #computeVerticalScrollRange()} and
14649     * {@link #computeVerticalScrollExtent()}.</p>
14650     *
14651     * <p>The default offset is the scroll offset of this view.</p>
14652     *
14653     * @return the vertical offset of the scrollbar's thumb
14654     *
14655     * @see #computeVerticalScrollRange()
14656     * @see #computeVerticalScrollExtent()
14657     * @see android.widget.ScrollBarDrawable
14658     */
14659    protected int computeVerticalScrollOffset() {
14660        return mScrollY;
14661    }
14662
14663    /**
14664     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14665     * within the vertical range. This value is used to compute the length
14666     * of the thumb within the scrollbar's track.</p>
14667     *
14668     * <p>The range is expressed in arbitrary units that must be the same as the
14669     * units used by {@link #computeVerticalScrollRange()} and
14670     * {@link #computeVerticalScrollOffset()}.</p>
14671     *
14672     * <p>The default extent is the drawing height of this view.</p>
14673     *
14674     * @return the vertical extent of the scrollbar's thumb
14675     *
14676     * @see #computeVerticalScrollRange()
14677     * @see #computeVerticalScrollOffset()
14678     * @see android.widget.ScrollBarDrawable
14679     */
14680    protected int computeVerticalScrollExtent() {
14681        return getHeight();
14682    }
14683
14684    /**
14685     * Check if this view can be scrolled horizontally in a certain direction.
14686     *
14687     * @param direction Negative to check scrolling left, positive to check scrolling right.
14688     * @return true if this view can be scrolled in the specified direction, false otherwise.
14689     */
14690    public boolean canScrollHorizontally(int direction) {
14691        final int offset = computeHorizontalScrollOffset();
14692        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14693        if (range == 0) return false;
14694        if (direction < 0) {
14695            return offset > 0;
14696        } else {
14697            return offset < range - 1;
14698        }
14699    }
14700
14701    /**
14702     * Check if this view can be scrolled vertically in a certain direction.
14703     *
14704     * @param direction Negative to check scrolling up, positive to check scrolling down.
14705     * @return true if this view can be scrolled in the specified direction, false otherwise.
14706     */
14707    public boolean canScrollVertically(int direction) {
14708        final int offset = computeVerticalScrollOffset();
14709        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14710        if (range == 0) return false;
14711        if (direction < 0) {
14712            return offset > 0;
14713        } else {
14714            return offset < range - 1;
14715        }
14716    }
14717
14718    void getScrollIndicatorBounds(@NonNull Rect out) {
14719        out.left = mScrollX;
14720        out.right = mScrollX + mRight - mLeft;
14721        out.top = mScrollY;
14722        out.bottom = mScrollY + mBottom - mTop;
14723    }
14724
14725    private void onDrawScrollIndicators(Canvas c) {
14726        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14727            // No scroll indicators enabled.
14728            return;
14729        }
14730
14731        final Drawable dr = mScrollIndicatorDrawable;
14732        if (dr == null) {
14733            // Scroll indicators aren't supported here.
14734            return;
14735        }
14736
14737        final int h = dr.getIntrinsicHeight();
14738        final int w = dr.getIntrinsicWidth();
14739        final Rect rect = mAttachInfo.mTmpInvalRect;
14740        getScrollIndicatorBounds(rect);
14741
14742        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14743            final boolean canScrollUp = canScrollVertically(-1);
14744            if (canScrollUp) {
14745                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14746                dr.draw(c);
14747            }
14748        }
14749
14750        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14751            final boolean canScrollDown = canScrollVertically(1);
14752            if (canScrollDown) {
14753                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14754                dr.draw(c);
14755            }
14756        }
14757
14758        final int leftRtl;
14759        final int rightRtl;
14760        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14761            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14762            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14763        } else {
14764            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14765            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14766        }
14767
14768        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14769        if ((mPrivateFlags3 & leftMask) != 0) {
14770            final boolean canScrollLeft = canScrollHorizontally(-1);
14771            if (canScrollLeft) {
14772                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14773                dr.draw(c);
14774            }
14775        }
14776
14777        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14778        if ((mPrivateFlags3 & rightMask) != 0) {
14779            final boolean canScrollRight = canScrollHorizontally(1);
14780            if (canScrollRight) {
14781                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14782                dr.draw(c);
14783            }
14784        }
14785    }
14786
14787    private void getHorizontalScrollBarBounds(Rect bounds) {
14788        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14789        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14790                && !isVerticalScrollBarHidden();
14791        final int size = getHorizontalScrollbarHeight();
14792        final int verticalScrollBarGap = drawVerticalScrollBar ?
14793                getVerticalScrollbarWidth() : 0;
14794        final int width = mRight - mLeft;
14795        final int height = mBottom - mTop;
14796        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14797        bounds.left = mScrollX + (mPaddingLeft & inside);
14798        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14799        bounds.bottom = bounds.top + size;
14800    }
14801
14802    private void getVerticalScrollBarBounds(Rect bounds) {
14803        if (mRoundScrollbarRenderer == null) {
14804            getStraightVerticalScrollBarBounds(bounds);
14805        } else {
14806            getRoundVerticalScrollBarBounds(bounds);
14807        }
14808    }
14809
14810    private void getRoundVerticalScrollBarBounds(Rect bounds) {
14811        final int width = mRight - mLeft;
14812        final int height = mBottom - mTop;
14813        // Do not take padding into account as we always want the scrollbars
14814        // to hug the screen for round wearable devices.
14815        bounds.left = mScrollX;
14816        bounds.top = mScrollY;
14817        bounds.right = bounds.left + width;
14818        bounds.bottom = mScrollY + height;
14819    }
14820
14821    private void getStraightVerticalScrollBarBounds(Rect bounds) {
14822        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14823        final int size = getVerticalScrollbarWidth();
14824        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14825        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14826            verticalScrollbarPosition = isLayoutRtl() ?
14827                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14828        }
14829        final int width = mRight - mLeft;
14830        final int height = mBottom - mTop;
14831        switch (verticalScrollbarPosition) {
14832            default:
14833            case SCROLLBAR_POSITION_RIGHT:
14834                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14835                break;
14836            case SCROLLBAR_POSITION_LEFT:
14837                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14838                break;
14839        }
14840        bounds.top = mScrollY + (mPaddingTop & inside);
14841        bounds.right = bounds.left + size;
14842        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14843    }
14844
14845    /**
14846     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14847     * scrollbars are painted only if they have been awakened first.</p>
14848     *
14849     * @param canvas the canvas on which to draw the scrollbars
14850     *
14851     * @see #awakenScrollBars(int)
14852     */
14853    protected final void onDrawScrollBars(Canvas canvas) {
14854        // scrollbars are drawn only when the animation is running
14855        final ScrollabilityCache cache = mScrollCache;
14856
14857        if (cache != null) {
14858
14859            int state = cache.state;
14860
14861            if (state == ScrollabilityCache.OFF) {
14862                return;
14863            }
14864
14865            boolean invalidate = false;
14866
14867            if (state == ScrollabilityCache.FADING) {
14868                // We're fading -- get our fade interpolation
14869                if (cache.interpolatorValues == null) {
14870                    cache.interpolatorValues = new float[1];
14871                }
14872
14873                float[] values = cache.interpolatorValues;
14874
14875                // Stops the animation if we're done
14876                if (cache.scrollBarInterpolator.timeToValues(values) ==
14877                        Interpolator.Result.FREEZE_END) {
14878                    cache.state = ScrollabilityCache.OFF;
14879                } else {
14880                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14881                }
14882
14883                // This will make the scroll bars inval themselves after
14884                // drawing. We only want this when we're fading so that
14885                // we prevent excessive redraws
14886                invalidate = true;
14887            } else {
14888                // We're just on -- but we may have been fading before so
14889                // reset alpha
14890                cache.scrollBar.mutate().setAlpha(255);
14891            }
14892
14893            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14894            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14895                    && !isVerticalScrollBarHidden();
14896
14897            // Fork out the scroll bar drawing for round wearable devices.
14898            if (mRoundScrollbarRenderer != null) {
14899                if (drawVerticalScrollBar) {
14900                    final Rect bounds = cache.mScrollBarBounds;
14901                    getVerticalScrollBarBounds(bounds);
14902                    mRoundScrollbarRenderer.drawRoundScrollbars(
14903                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
14904                    if (invalidate) {
14905                        invalidate();
14906                    }
14907                }
14908                // Do not draw horizontal scroll bars for round wearable devices.
14909            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14910                final ScrollBarDrawable scrollBar = cache.scrollBar;
14911
14912                if (drawHorizontalScrollBar) {
14913                    scrollBar.setParameters(computeHorizontalScrollRange(),
14914                            computeHorizontalScrollOffset(),
14915                            computeHorizontalScrollExtent(), false);
14916                    final Rect bounds = cache.mScrollBarBounds;
14917                    getHorizontalScrollBarBounds(bounds);
14918                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14919                            bounds.right, bounds.bottom);
14920                    if (invalidate) {
14921                        invalidate(bounds);
14922                    }
14923                }
14924
14925                if (drawVerticalScrollBar) {
14926                    scrollBar.setParameters(computeVerticalScrollRange(),
14927                            computeVerticalScrollOffset(),
14928                            computeVerticalScrollExtent(), true);
14929                    final Rect bounds = cache.mScrollBarBounds;
14930                    getVerticalScrollBarBounds(bounds);
14931                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14932                            bounds.right, bounds.bottom);
14933                    if (invalidate) {
14934                        invalidate(bounds);
14935                    }
14936                }
14937            }
14938        }
14939    }
14940
14941    /**
14942     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14943     * FastScroller is visible.
14944     * @return whether to temporarily hide the vertical scrollbar
14945     * @hide
14946     */
14947    protected boolean isVerticalScrollBarHidden() {
14948        return false;
14949    }
14950
14951    /**
14952     * <p>Draw the horizontal scrollbar if
14953     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14954     *
14955     * @param canvas the canvas on which to draw the scrollbar
14956     * @param scrollBar the scrollbar's drawable
14957     *
14958     * @see #isHorizontalScrollBarEnabled()
14959     * @see #computeHorizontalScrollRange()
14960     * @see #computeHorizontalScrollExtent()
14961     * @see #computeHorizontalScrollOffset()
14962     * @see android.widget.ScrollBarDrawable
14963     * @hide
14964     */
14965    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14966            int l, int t, int r, int b) {
14967        scrollBar.setBounds(l, t, r, b);
14968        scrollBar.draw(canvas);
14969    }
14970
14971    /**
14972     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14973     * returns true.</p>
14974     *
14975     * @param canvas the canvas on which to draw the scrollbar
14976     * @param scrollBar the scrollbar's drawable
14977     *
14978     * @see #isVerticalScrollBarEnabled()
14979     * @see #computeVerticalScrollRange()
14980     * @see #computeVerticalScrollExtent()
14981     * @see #computeVerticalScrollOffset()
14982     * @see android.widget.ScrollBarDrawable
14983     * @hide
14984     */
14985    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14986            int l, int t, int r, int b) {
14987        scrollBar.setBounds(l, t, r, b);
14988        scrollBar.draw(canvas);
14989    }
14990
14991    /**
14992     * Implement this to do your drawing.
14993     *
14994     * @param canvas the canvas on which the background will be drawn
14995     */
14996    protected void onDraw(Canvas canvas) {
14997    }
14998
14999    /*
15000     * Caller is responsible for calling requestLayout if necessary.
15001     * (This allows addViewInLayout to not request a new layout.)
15002     */
15003    void assignParent(ViewParent parent) {
15004        if (mParent == null) {
15005            mParent = parent;
15006        } else if (parent == null) {
15007            mParent = null;
15008        } else {
15009            throw new RuntimeException("view " + this + " being added, but"
15010                    + " it already has a parent");
15011        }
15012    }
15013
15014    /**
15015     * This is called when the view is attached to a window.  At this point it
15016     * has a Surface and will start drawing.  Note that this function is
15017     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15018     * however it may be called any time before the first onDraw -- including
15019     * before or after {@link #onMeasure(int, int)}.
15020     *
15021     * @see #onDetachedFromWindow()
15022     */
15023    @CallSuper
15024    protected void onAttachedToWindow() {
15025        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15026            mParent.requestTransparentRegion(this);
15027        }
15028
15029        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15030
15031        jumpDrawablesToCurrentState();
15032
15033        resetSubtreeAccessibilityStateChanged();
15034
15035        // rebuild, since Outline not maintained while View is detached
15036        rebuildOutline();
15037
15038        if (isFocused()) {
15039            InputMethodManager imm = InputMethodManager.peekInstance();
15040            if (imm != null) {
15041                imm.focusIn(this);
15042            }
15043        }
15044    }
15045
15046    /**
15047     * Resolve all RTL related properties.
15048     *
15049     * @return true if resolution of RTL properties has been done
15050     *
15051     * @hide
15052     */
15053    public boolean resolveRtlPropertiesIfNeeded() {
15054        if (!needRtlPropertiesResolution()) return false;
15055
15056        // Order is important here: LayoutDirection MUST be resolved first
15057        if (!isLayoutDirectionResolved()) {
15058            resolveLayoutDirection();
15059            resolveLayoutParams();
15060        }
15061        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15062        if (!isTextDirectionResolved()) {
15063            resolveTextDirection();
15064        }
15065        if (!isTextAlignmentResolved()) {
15066            resolveTextAlignment();
15067        }
15068        // Should resolve Drawables before Padding because we need the layout direction of the
15069        // Drawable to correctly resolve Padding.
15070        if (!areDrawablesResolved()) {
15071            resolveDrawables();
15072        }
15073        if (!isPaddingResolved()) {
15074            resolvePadding();
15075        }
15076        onRtlPropertiesChanged(getLayoutDirection());
15077        return true;
15078    }
15079
15080    /**
15081     * Reset resolution of all RTL related properties.
15082     *
15083     * @hide
15084     */
15085    public void resetRtlProperties() {
15086        resetResolvedLayoutDirection();
15087        resetResolvedTextDirection();
15088        resetResolvedTextAlignment();
15089        resetResolvedPadding();
15090        resetResolvedDrawables();
15091    }
15092
15093    /**
15094     * @see #onScreenStateChanged(int)
15095     */
15096    void dispatchScreenStateChanged(int screenState) {
15097        onScreenStateChanged(screenState);
15098    }
15099
15100    /**
15101     * This method is called whenever the state of the screen this view is
15102     * attached to changes. A state change will usually occurs when the screen
15103     * turns on or off (whether it happens automatically or the user does it
15104     * manually.)
15105     *
15106     * @param screenState The new state of the screen. Can be either
15107     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15108     */
15109    public void onScreenStateChanged(int screenState) {
15110    }
15111
15112    /**
15113     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15114     */
15115    private boolean hasRtlSupport() {
15116        return mContext.getApplicationInfo().hasRtlSupport();
15117    }
15118
15119    /**
15120     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15121     * RTL not supported)
15122     */
15123    private boolean isRtlCompatibilityMode() {
15124        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15125        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15126    }
15127
15128    /**
15129     * @return true if RTL properties need resolution.
15130     *
15131     */
15132    private boolean needRtlPropertiesResolution() {
15133        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15134    }
15135
15136    /**
15137     * Called when any RTL property (layout direction or text direction or text alignment) has
15138     * been changed.
15139     *
15140     * Subclasses need to override this method to take care of cached information that depends on the
15141     * resolved layout direction, or to inform child views that inherit their layout direction.
15142     *
15143     * The default implementation does nothing.
15144     *
15145     * @param layoutDirection the direction of the layout
15146     *
15147     * @see #LAYOUT_DIRECTION_LTR
15148     * @see #LAYOUT_DIRECTION_RTL
15149     */
15150    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15151    }
15152
15153    /**
15154     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15155     * that the parent directionality can and will be resolved before its children.
15156     *
15157     * @return true if resolution has been done, false otherwise.
15158     *
15159     * @hide
15160     */
15161    public boolean resolveLayoutDirection() {
15162        // Clear any previous layout direction resolution
15163        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15164
15165        if (hasRtlSupport()) {
15166            // Set resolved depending on layout direction
15167            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15168                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15169                case LAYOUT_DIRECTION_INHERIT:
15170                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15171                    // later to get the correct resolved value
15172                    if (!canResolveLayoutDirection()) return false;
15173
15174                    // Parent has not yet resolved, LTR is still the default
15175                    try {
15176                        if (!mParent.isLayoutDirectionResolved()) return false;
15177
15178                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15179                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15180                        }
15181                    } catch (AbstractMethodError e) {
15182                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15183                                " does not fully implement ViewParent", e);
15184                    }
15185                    break;
15186                case LAYOUT_DIRECTION_RTL:
15187                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15188                    break;
15189                case LAYOUT_DIRECTION_LOCALE:
15190                    if((LAYOUT_DIRECTION_RTL ==
15191                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15192                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15193                    }
15194                    break;
15195                default:
15196                    // Nothing to do, LTR by default
15197            }
15198        }
15199
15200        // Set to resolved
15201        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15202        return true;
15203    }
15204
15205    /**
15206     * Check if layout direction resolution can be done.
15207     *
15208     * @return true if layout direction resolution can be done otherwise return false.
15209     */
15210    public boolean canResolveLayoutDirection() {
15211        switch (getRawLayoutDirection()) {
15212            case LAYOUT_DIRECTION_INHERIT:
15213                if (mParent != null) {
15214                    try {
15215                        return mParent.canResolveLayoutDirection();
15216                    } catch (AbstractMethodError e) {
15217                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15218                                " does not fully implement ViewParent", e);
15219                    }
15220                }
15221                return false;
15222
15223            default:
15224                return true;
15225        }
15226    }
15227
15228    /**
15229     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15230     * {@link #onMeasure(int, int)}.
15231     *
15232     * @hide
15233     */
15234    public void resetResolvedLayoutDirection() {
15235        // Reset the current resolved bits
15236        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15237    }
15238
15239    /**
15240     * @return true if the layout direction is inherited.
15241     *
15242     * @hide
15243     */
15244    public boolean isLayoutDirectionInherited() {
15245        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15246    }
15247
15248    /**
15249     * @return true if layout direction has been resolved.
15250     */
15251    public boolean isLayoutDirectionResolved() {
15252        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15253    }
15254
15255    /**
15256     * Return if padding has been resolved
15257     *
15258     * @hide
15259     */
15260    boolean isPaddingResolved() {
15261        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15262    }
15263
15264    /**
15265     * Resolves padding depending on layout direction, if applicable, and
15266     * recomputes internal padding values to adjust for scroll bars.
15267     *
15268     * @hide
15269     */
15270    public void resolvePadding() {
15271        final int resolvedLayoutDirection = getLayoutDirection();
15272
15273        if (!isRtlCompatibilityMode()) {
15274            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15275            // If start / end padding are defined, they will be resolved (hence overriding) to
15276            // left / right or right / left depending on the resolved layout direction.
15277            // If start / end padding are not defined, use the left / right ones.
15278            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15279                Rect padding = sThreadLocal.get();
15280                if (padding == null) {
15281                    padding = new Rect();
15282                    sThreadLocal.set(padding);
15283                }
15284                mBackground.getPadding(padding);
15285                if (!mLeftPaddingDefined) {
15286                    mUserPaddingLeftInitial = padding.left;
15287                }
15288                if (!mRightPaddingDefined) {
15289                    mUserPaddingRightInitial = padding.right;
15290                }
15291            }
15292            switch (resolvedLayoutDirection) {
15293                case LAYOUT_DIRECTION_RTL:
15294                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15295                        mUserPaddingRight = mUserPaddingStart;
15296                    } else {
15297                        mUserPaddingRight = mUserPaddingRightInitial;
15298                    }
15299                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15300                        mUserPaddingLeft = mUserPaddingEnd;
15301                    } else {
15302                        mUserPaddingLeft = mUserPaddingLeftInitial;
15303                    }
15304                    break;
15305                case LAYOUT_DIRECTION_LTR:
15306                default:
15307                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15308                        mUserPaddingLeft = mUserPaddingStart;
15309                    } else {
15310                        mUserPaddingLeft = mUserPaddingLeftInitial;
15311                    }
15312                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15313                        mUserPaddingRight = mUserPaddingEnd;
15314                    } else {
15315                        mUserPaddingRight = mUserPaddingRightInitial;
15316                    }
15317            }
15318
15319            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15320        }
15321
15322        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15323        onRtlPropertiesChanged(resolvedLayoutDirection);
15324
15325        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15326    }
15327
15328    /**
15329     * Reset the resolved layout direction.
15330     *
15331     * @hide
15332     */
15333    public void resetResolvedPadding() {
15334        resetResolvedPaddingInternal();
15335    }
15336
15337    /**
15338     * Used when we only want to reset *this* view's padding and not trigger overrides
15339     * in ViewGroup that reset children too.
15340     */
15341    void resetResolvedPaddingInternal() {
15342        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15343    }
15344
15345    /**
15346     * This is called when the view is detached from a window.  At this point it
15347     * no longer has a surface for drawing.
15348     *
15349     * @see #onAttachedToWindow()
15350     */
15351    @CallSuper
15352    protected void onDetachedFromWindow() {
15353    }
15354
15355    /**
15356     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15357     * after onDetachedFromWindow().
15358     *
15359     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15360     * The super method should be called at the end of the overridden method to ensure
15361     * subclasses are destroyed first
15362     *
15363     * @hide
15364     */
15365    @CallSuper
15366    protected void onDetachedFromWindowInternal() {
15367        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15368        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15369        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15370
15371        removeUnsetPressCallback();
15372        removeLongPressCallback();
15373        removePerformClickCallback();
15374        removeSendViewScrolledAccessibilityEventCallback();
15375        stopNestedScroll();
15376
15377        // Anything that started animating right before detach should already
15378        // be in its final state when re-attached.
15379        jumpDrawablesToCurrentState();
15380
15381        destroyDrawingCache();
15382
15383        cleanupDraw();
15384        mCurrentAnimation = null;
15385    }
15386
15387    private void cleanupDraw() {
15388        resetDisplayList();
15389        if (mAttachInfo != null) {
15390            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15391        }
15392    }
15393
15394    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15395    }
15396
15397    /**
15398     * @return The number of times this view has been attached to a window
15399     */
15400    protected int getWindowAttachCount() {
15401        return mWindowAttachCount;
15402    }
15403
15404    /**
15405     * Retrieve a unique token identifying the window this view is attached to.
15406     * @return Return the window's token for use in
15407     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15408     */
15409    public IBinder getWindowToken() {
15410        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15411    }
15412
15413    /**
15414     * Retrieve the {@link WindowId} for the window this view is
15415     * currently attached to.
15416     */
15417    public WindowId getWindowId() {
15418        if (mAttachInfo == null) {
15419            return null;
15420        }
15421        if (mAttachInfo.mWindowId == null) {
15422            try {
15423                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15424                        mAttachInfo.mWindowToken);
15425                mAttachInfo.mWindowId = new WindowId(
15426                        mAttachInfo.mIWindowId);
15427            } catch (RemoteException e) {
15428            }
15429        }
15430        return mAttachInfo.mWindowId;
15431    }
15432
15433    /**
15434     * Retrieve a unique token identifying the top-level "real" window of
15435     * the window that this view is attached to.  That is, this is like
15436     * {@link #getWindowToken}, except if the window this view in is a panel
15437     * window (attached to another containing window), then the token of
15438     * the containing window is returned instead.
15439     *
15440     * @return Returns the associated window token, either
15441     * {@link #getWindowToken()} or the containing window's token.
15442     */
15443    public IBinder getApplicationWindowToken() {
15444        AttachInfo ai = mAttachInfo;
15445        if (ai != null) {
15446            IBinder appWindowToken = ai.mPanelParentWindowToken;
15447            if (appWindowToken == null) {
15448                appWindowToken = ai.mWindowToken;
15449            }
15450            return appWindowToken;
15451        }
15452        return null;
15453    }
15454
15455    /**
15456     * Gets the logical display to which the view's window has been attached.
15457     *
15458     * @return The logical display, or null if the view is not currently attached to a window.
15459     */
15460    public Display getDisplay() {
15461        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15462    }
15463
15464    /**
15465     * Retrieve private session object this view hierarchy is using to
15466     * communicate with the window manager.
15467     * @return the session object to communicate with the window manager
15468     */
15469    /*package*/ IWindowSession getWindowSession() {
15470        return mAttachInfo != null ? mAttachInfo.mSession : null;
15471    }
15472
15473    /**
15474     * Return the visibility value of the least visible component passed.
15475     */
15476    int combineVisibility(int vis1, int vis2) {
15477        // This works because VISIBLE < INVISIBLE < GONE.
15478        return Math.max(vis1, vis2);
15479    }
15480
15481    /**
15482     * @param info the {@link android.view.View.AttachInfo} to associated with
15483     *        this view
15484     */
15485    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15486        mAttachInfo = info;
15487        if (mOverlay != null) {
15488            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15489        }
15490        mWindowAttachCount++;
15491        // We will need to evaluate the drawable state at least once.
15492        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15493        if (mFloatingTreeObserver != null) {
15494            info.mTreeObserver.merge(mFloatingTreeObserver);
15495            mFloatingTreeObserver = null;
15496        }
15497
15498        registerPendingFrameMetricsObservers();
15499
15500        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15501            mAttachInfo.mScrollContainers.add(this);
15502            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15503        }
15504        // Transfer all pending runnables.
15505        if (mRunQueue != null) {
15506            mRunQueue.executeActions(info.mHandler);
15507            mRunQueue = null;
15508        }
15509        performCollectViewAttributes(mAttachInfo, visibility);
15510        onAttachedToWindow();
15511
15512        ListenerInfo li = mListenerInfo;
15513        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15514                li != null ? li.mOnAttachStateChangeListeners : null;
15515        if (listeners != null && listeners.size() > 0) {
15516            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15517            // perform the dispatching. The iterator is a safe guard against listeners that
15518            // could mutate the list by calling the various add/remove methods. This prevents
15519            // the array from being modified while we iterate it.
15520            for (OnAttachStateChangeListener listener : listeners) {
15521                listener.onViewAttachedToWindow(this);
15522            }
15523        }
15524
15525        int vis = info.mWindowVisibility;
15526        if (vis != GONE) {
15527            onWindowVisibilityChanged(vis);
15528            if (isShown()) {
15529                // Calling onVisibilityAggregated directly here since the subtree will also
15530                // receive dispatchAttachedToWindow and this same call
15531                onVisibilityAggregated(vis == VISIBLE);
15532            }
15533        }
15534
15535        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15536        // As all views in the subtree will already receive dispatchAttachedToWindow
15537        // traversing the subtree again here is not desired.
15538        onVisibilityChanged(this, visibility);
15539
15540        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15541            // If nobody has evaluated the drawable state yet, then do it now.
15542            refreshDrawableState();
15543        }
15544        needGlobalAttributesUpdate(false);
15545    }
15546
15547    void dispatchDetachedFromWindow() {
15548        AttachInfo info = mAttachInfo;
15549        if (info != null) {
15550            int vis = info.mWindowVisibility;
15551            if (vis != GONE) {
15552                onWindowVisibilityChanged(GONE);
15553                if (isShown()) {
15554                    // Invoking onVisibilityAggregated directly here since the subtree
15555                    // will also receive detached from window
15556                    onVisibilityAggregated(false);
15557                }
15558            }
15559        }
15560
15561        onDetachedFromWindow();
15562        onDetachedFromWindowInternal();
15563
15564        InputMethodManager imm = InputMethodManager.peekInstance();
15565        if (imm != null) {
15566            imm.onViewDetachedFromWindow(this);
15567        }
15568
15569        ListenerInfo li = mListenerInfo;
15570        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15571                li != null ? li.mOnAttachStateChangeListeners : null;
15572        if (listeners != null && listeners.size() > 0) {
15573            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15574            // perform the dispatching. The iterator is a safe guard against listeners that
15575            // could mutate the list by calling the various add/remove methods. This prevents
15576            // the array from being modified while we iterate it.
15577            for (OnAttachStateChangeListener listener : listeners) {
15578                listener.onViewDetachedFromWindow(this);
15579            }
15580        }
15581
15582        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15583            mAttachInfo.mScrollContainers.remove(this);
15584            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15585        }
15586
15587        mAttachInfo = null;
15588        if (mOverlay != null) {
15589            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15590        }
15591    }
15592
15593    /**
15594     * Cancel any deferred high-level input events that were previously posted to the event queue.
15595     *
15596     * <p>Many views post high-level events such as click handlers to the event queue
15597     * to run deferred in order to preserve a desired user experience - clearing visible
15598     * pressed states before executing, etc. This method will abort any events of this nature
15599     * that are currently in flight.</p>
15600     *
15601     * <p>Custom views that generate their own high-level deferred input events should override
15602     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15603     *
15604     * <p>This will also cancel pending input events for any child views.</p>
15605     *
15606     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15607     * This will not impact newer events posted after this call that may occur as a result of
15608     * lower-level input events still waiting in the queue. If you are trying to prevent
15609     * double-submitted  events for the duration of some sort of asynchronous transaction
15610     * you should also take other steps to protect against unexpected double inputs e.g. calling
15611     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15612     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15613     */
15614    public final void cancelPendingInputEvents() {
15615        dispatchCancelPendingInputEvents();
15616    }
15617
15618    /**
15619     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15620     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15621     */
15622    void dispatchCancelPendingInputEvents() {
15623        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15624        onCancelPendingInputEvents();
15625        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15626            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15627                    " did not call through to super.onCancelPendingInputEvents()");
15628        }
15629    }
15630
15631    /**
15632     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15633     * a parent view.
15634     *
15635     * <p>This method is responsible for removing any pending high-level input events that were
15636     * posted to the event queue to run later. Custom view classes that post their own deferred
15637     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15638     * {@link android.os.Handler} should override this method, call
15639     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15640     * </p>
15641     */
15642    public void onCancelPendingInputEvents() {
15643        removePerformClickCallback();
15644        cancelLongPress();
15645        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15646    }
15647
15648    /**
15649     * Store this view hierarchy's frozen state into the given container.
15650     *
15651     * @param container The SparseArray in which to save the view's state.
15652     *
15653     * @see #restoreHierarchyState(android.util.SparseArray)
15654     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15655     * @see #onSaveInstanceState()
15656     */
15657    public void saveHierarchyState(SparseArray<Parcelable> container) {
15658        dispatchSaveInstanceState(container);
15659    }
15660
15661    /**
15662     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15663     * this view and its children. May be overridden to modify how freezing happens to a
15664     * view's children; for example, some views may want to not store state for their children.
15665     *
15666     * @param container The SparseArray in which to save the view's state.
15667     *
15668     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15669     * @see #saveHierarchyState(android.util.SparseArray)
15670     * @see #onSaveInstanceState()
15671     */
15672    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15673        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15674            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15675            Parcelable state = onSaveInstanceState();
15676            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15677                throw new IllegalStateException(
15678                        "Derived class did not call super.onSaveInstanceState()");
15679            }
15680            if (state != null) {
15681                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15682                // + ": " + state);
15683                container.put(mID, state);
15684            }
15685        }
15686    }
15687
15688    /**
15689     * Hook allowing a view to generate a representation of its internal state
15690     * that can later be used to create a new instance with that same state.
15691     * This state should only contain information that is not persistent or can
15692     * not be reconstructed later. For example, you will never store your
15693     * current position on screen because that will be computed again when a
15694     * new instance of the view is placed in its view hierarchy.
15695     * <p>
15696     * Some examples of things you may store here: the current cursor position
15697     * in a text view (but usually not the text itself since that is stored in a
15698     * content provider or other persistent storage), the currently selected
15699     * item in a list view.
15700     *
15701     * @return Returns a Parcelable object containing the view's current dynamic
15702     *         state, or null if there is nothing interesting to save. The
15703     *         default implementation returns null.
15704     * @see #onRestoreInstanceState(android.os.Parcelable)
15705     * @see #saveHierarchyState(android.util.SparseArray)
15706     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15707     * @see #setSaveEnabled(boolean)
15708     */
15709    @CallSuper
15710    protected Parcelable onSaveInstanceState() {
15711        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15712        if (mStartActivityRequestWho != null) {
15713            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15714            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15715            return state;
15716        }
15717        return BaseSavedState.EMPTY_STATE;
15718    }
15719
15720    /**
15721     * Restore this view hierarchy's frozen state from the given container.
15722     *
15723     * @param container The SparseArray which holds previously frozen states.
15724     *
15725     * @see #saveHierarchyState(android.util.SparseArray)
15726     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15727     * @see #onRestoreInstanceState(android.os.Parcelable)
15728     */
15729    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15730        dispatchRestoreInstanceState(container);
15731    }
15732
15733    /**
15734     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15735     * state for this view and its children. May be overridden to modify how restoring
15736     * happens to a view's children; for example, some views may want to not store state
15737     * for their children.
15738     *
15739     * @param container The SparseArray which holds previously saved state.
15740     *
15741     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15742     * @see #restoreHierarchyState(android.util.SparseArray)
15743     * @see #onRestoreInstanceState(android.os.Parcelable)
15744     */
15745    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15746        if (mID != NO_ID) {
15747            Parcelable state = container.get(mID);
15748            if (state != null) {
15749                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15750                // + ": " + state);
15751                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15752                onRestoreInstanceState(state);
15753                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15754                    throw new IllegalStateException(
15755                            "Derived class did not call super.onRestoreInstanceState()");
15756                }
15757            }
15758        }
15759    }
15760
15761    /**
15762     * Hook allowing a view to re-apply a representation of its internal state that had previously
15763     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15764     * null state.
15765     *
15766     * @param state The frozen state that had previously been returned by
15767     *        {@link #onSaveInstanceState}.
15768     *
15769     * @see #onSaveInstanceState()
15770     * @see #restoreHierarchyState(android.util.SparseArray)
15771     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15772     */
15773    @CallSuper
15774    protected void onRestoreInstanceState(Parcelable state) {
15775        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15776        if (state != null && !(state instanceof AbsSavedState)) {
15777            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15778                    + "received " + state.getClass().toString() + " instead. This usually happens "
15779                    + "when two views of different type have the same id in the same hierarchy. "
15780                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15781                    + "other views do not use the same id.");
15782        }
15783        if (state != null && state instanceof BaseSavedState) {
15784            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15785        }
15786    }
15787
15788    /**
15789     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15790     *
15791     * @return the drawing start time in milliseconds
15792     */
15793    public long getDrawingTime() {
15794        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15795    }
15796
15797    /**
15798     * <p>Enables or disables the duplication of the parent's state into this view. When
15799     * duplication is enabled, this view gets its drawable state from its parent rather
15800     * than from its own internal properties.</p>
15801     *
15802     * <p>Note: in the current implementation, setting this property to true after the
15803     * view was added to a ViewGroup might have no effect at all. This property should
15804     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15805     *
15806     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15807     * property is enabled, an exception will be thrown.</p>
15808     *
15809     * <p>Note: if the child view uses and updates additional states which are unknown to the
15810     * parent, these states should not be affected by this method.</p>
15811     *
15812     * @param enabled True to enable duplication of the parent's drawable state, false
15813     *                to disable it.
15814     *
15815     * @see #getDrawableState()
15816     * @see #isDuplicateParentStateEnabled()
15817     */
15818    public void setDuplicateParentStateEnabled(boolean enabled) {
15819        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15820    }
15821
15822    /**
15823     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15824     *
15825     * @return True if this view's drawable state is duplicated from the parent,
15826     *         false otherwise
15827     *
15828     * @see #getDrawableState()
15829     * @see #setDuplicateParentStateEnabled(boolean)
15830     */
15831    public boolean isDuplicateParentStateEnabled() {
15832        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15833    }
15834
15835    /**
15836     * <p>Specifies the type of layer backing this view. The layer can be
15837     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15838     * {@link #LAYER_TYPE_HARDWARE}.</p>
15839     *
15840     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15841     * instance that controls how the layer is composed on screen. The following
15842     * properties of the paint are taken into account when composing the layer:</p>
15843     * <ul>
15844     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15845     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15846     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15847     * </ul>
15848     *
15849     * <p>If this view has an alpha value set to < 1.0 by calling
15850     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15851     * by this view's alpha value.</p>
15852     *
15853     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15854     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15855     * for more information on when and how to use layers.</p>
15856     *
15857     * @param layerType The type of layer to use with this view, must be one of
15858     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15859     *        {@link #LAYER_TYPE_HARDWARE}
15860     * @param paint The paint used to compose the layer. This argument is optional
15861     *        and can be null. It is ignored when the layer type is
15862     *        {@link #LAYER_TYPE_NONE}
15863     *
15864     * @see #getLayerType()
15865     * @see #LAYER_TYPE_NONE
15866     * @see #LAYER_TYPE_SOFTWARE
15867     * @see #LAYER_TYPE_HARDWARE
15868     * @see #setAlpha(float)
15869     *
15870     * @attr ref android.R.styleable#View_layerType
15871     */
15872    public void setLayerType(int layerType, @Nullable Paint paint) {
15873        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15874            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15875                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15876        }
15877
15878        boolean typeChanged = mRenderNode.setLayerType(layerType);
15879
15880        if (!typeChanged) {
15881            setLayerPaint(paint);
15882            return;
15883        }
15884
15885        if (layerType != LAYER_TYPE_SOFTWARE) {
15886            // Destroy any previous software drawing cache if present
15887            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15888            // drawing cache created in View#draw when drawing to a SW canvas.
15889            destroyDrawingCache();
15890        }
15891
15892        mLayerType = layerType;
15893        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15894        mRenderNode.setLayerPaint(mLayerPaint);
15895
15896        // draw() behaves differently if we are on a layer, so we need to
15897        // invalidate() here
15898        invalidateParentCaches();
15899        invalidate(true);
15900    }
15901
15902    /**
15903     * Updates the {@link Paint} object used with the current layer (used only if the current
15904     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15905     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15906     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15907     * ensure that the view gets redrawn immediately.
15908     *
15909     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15910     * instance that controls how the layer is composed on screen. The following
15911     * properties of the paint are taken into account when composing the layer:</p>
15912     * <ul>
15913     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15914     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15915     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15916     * </ul>
15917     *
15918     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15919     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15920     *
15921     * @param paint The paint used to compose the layer. This argument is optional
15922     *        and can be null. It is ignored when the layer type is
15923     *        {@link #LAYER_TYPE_NONE}
15924     *
15925     * @see #setLayerType(int, android.graphics.Paint)
15926     */
15927    public void setLayerPaint(@Nullable Paint paint) {
15928        int layerType = getLayerType();
15929        if (layerType != LAYER_TYPE_NONE) {
15930            mLayerPaint = paint;
15931            if (layerType == LAYER_TYPE_HARDWARE) {
15932                if (mRenderNode.setLayerPaint(paint)) {
15933                    invalidateViewProperty(false, false);
15934                }
15935            } else {
15936                invalidate();
15937            }
15938        }
15939    }
15940
15941    /**
15942     * Indicates what type of layer is currently associated with this view. By default
15943     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15944     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15945     * for more information on the different types of layers.
15946     *
15947     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15948     *         {@link #LAYER_TYPE_HARDWARE}
15949     *
15950     * @see #setLayerType(int, android.graphics.Paint)
15951     * @see #buildLayer()
15952     * @see #LAYER_TYPE_NONE
15953     * @see #LAYER_TYPE_SOFTWARE
15954     * @see #LAYER_TYPE_HARDWARE
15955     */
15956    public int getLayerType() {
15957        return mLayerType;
15958    }
15959
15960    /**
15961     * Forces this view's layer to be created and this view to be rendered
15962     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15963     * invoking this method will have no effect.
15964     *
15965     * This method can for instance be used to render a view into its layer before
15966     * starting an animation. If this view is complex, rendering into the layer
15967     * before starting the animation will avoid skipping frames.
15968     *
15969     * @throws IllegalStateException If this view is not attached to a window
15970     *
15971     * @see #setLayerType(int, android.graphics.Paint)
15972     */
15973    public void buildLayer() {
15974        if (mLayerType == LAYER_TYPE_NONE) return;
15975
15976        final AttachInfo attachInfo = mAttachInfo;
15977        if (attachInfo == null) {
15978            throw new IllegalStateException("This view must be attached to a window first");
15979        }
15980
15981        if (getWidth() == 0 || getHeight() == 0) {
15982            return;
15983        }
15984
15985        switch (mLayerType) {
15986            case LAYER_TYPE_HARDWARE:
15987                updateDisplayListIfDirty();
15988                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
15989                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
15990                }
15991                break;
15992            case LAYER_TYPE_SOFTWARE:
15993                buildDrawingCache(true);
15994                break;
15995        }
15996    }
15997
15998    /**
15999     * Destroys all hardware rendering resources. This method is invoked
16000     * when the system needs to reclaim resources. Upon execution of this
16001     * method, you should free any OpenGL resources created by the view.
16002     *
16003     * Note: you <strong>must</strong> call
16004     * <code>super.destroyHardwareResources()</code> when overriding
16005     * this method.
16006     *
16007     * @hide
16008     */
16009    @CallSuper
16010    protected void destroyHardwareResources() {
16011        // Although the Layer will be destroyed by RenderNode, we want to release
16012        // the staging display list, which is also a signal to RenderNode that it's
16013        // safe to free its copy of the display list as it knows that we will
16014        // push an updated DisplayList if we try to draw again
16015        resetDisplayList();
16016    }
16017
16018    /**
16019     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16020     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16021     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16022     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16023     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16024     * null.</p>
16025     *
16026     * <p>Enabling the drawing cache is similar to
16027     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16028     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16029     * drawing cache has no effect on rendering because the system uses a different mechanism
16030     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16031     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16032     * for information on how to enable software and hardware layers.</p>
16033     *
16034     * <p>This API can be used to manually generate
16035     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16036     * {@link #getDrawingCache()}.</p>
16037     *
16038     * @param enabled true to enable the drawing cache, false otherwise
16039     *
16040     * @see #isDrawingCacheEnabled()
16041     * @see #getDrawingCache()
16042     * @see #buildDrawingCache()
16043     * @see #setLayerType(int, android.graphics.Paint)
16044     */
16045    public void setDrawingCacheEnabled(boolean enabled) {
16046        mCachingFailed = false;
16047        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16048    }
16049
16050    /**
16051     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16052     *
16053     * @return true if the drawing cache is enabled
16054     *
16055     * @see #setDrawingCacheEnabled(boolean)
16056     * @see #getDrawingCache()
16057     */
16058    @ViewDebug.ExportedProperty(category = "drawing")
16059    public boolean isDrawingCacheEnabled() {
16060        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16061    }
16062
16063    /**
16064     * Debugging utility which recursively outputs the dirty state of a view and its
16065     * descendants.
16066     *
16067     * @hide
16068     */
16069    @SuppressWarnings({"UnusedDeclaration"})
16070    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16071        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16072                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16073                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16074                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16075        if (clear) {
16076            mPrivateFlags &= clearMask;
16077        }
16078        if (this instanceof ViewGroup) {
16079            ViewGroup parent = (ViewGroup) this;
16080            final int count = parent.getChildCount();
16081            for (int i = 0; i < count; i++) {
16082                final View child = parent.getChildAt(i);
16083                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16084            }
16085        }
16086    }
16087
16088    /**
16089     * This method is used by ViewGroup to cause its children to restore or recreate their
16090     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16091     * to recreate its own display list, which would happen if it went through the normal
16092     * draw/dispatchDraw mechanisms.
16093     *
16094     * @hide
16095     */
16096    protected void dispatchGetDisplayList() {}
16097
16098    /**
16099     * A view that is not attached or hardware accelerated cannot create a display list.
16100     * This method checks these conditions and returns the appropriate result.
16101     *
16102     * @return true if view has the ability to create a display list, false otherwise.
16103     *
16104     * @hide
16105     */
16106    public boolean canHaveDisplayList() {
16107        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16108    }
16109
16110    /**
16111     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16112     * @hide
16113     */
16114    @NonNull
16115    public RenderNode updateDisplayListIfDirty() {
16116        final RenderNode renderNode = mRenderNode;
16117        if (!canHaveDisplayList()) {
16118            // can't populate RenderNode, don't try
16119            return renderNode;
16120        }
16121
16122        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16123                || !renderNode.isValid()
16124                || (mRecreateDisplayList)) {
16125            // Don't need to recreate the display list, just need to tell our
16126            // children to restore/recreate theirs
16127            if (renderNode.isValid()
16128                    && !mRecreateDisplayList) {
16129                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16130                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16131                dispatchGetDisplayList();
16132
16133                return renderNode; // no work needed
16134            }
16135
16136            // If we got here, we're recreating it. Mark it as such to ensure that
16137            // we copy in child display lists into ours in drawChild()
16138            mRecreateDisplayList = true;
16139
16140            int width = mRight - mLeft;
16141            int height = mBottom - mTop;
16142            int layerType = getLayerType();
16143
16144            final DisplayListCanvas canvas = renderNode.start(width, height);
16145            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16146
16147            try {
16148                if (layerType == LAYER_TYPE_SOFTWARE) {
16149                    buildDrawingCache(true);
16150                    Bitmap cache = getDrawingCache(true);
16151                    if (cache != null) {
16152                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16153                    }
16154                } else {
16155                    computeScroll();
16156
16157                    canvas.translate(-mScrollX, -mScrollY);
16158                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16159                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16160
16161                    // Fast path for layouts with no backgrounds
16162                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16163                        dispatchDraw(canvas);
16164                        if (mOverlay != null && !mOverlay.isEmpty()) {
16165                            mOverlay.getOverlayView().draw(canvas);
16166                        }
16167                    } else {
16168                        draw(canvas);
16169                    }
16170                }
16171            } finally {
16172                renderNode.end(canvas);
16173                setDisplayListProperties(renderNode);
16174            }
16175        } else {
16176            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16177            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16178        }
16179        return renderNode;
16180    }
16181
16182    private void resetDisplayList() {
16183        if (mRenderNode.isValid()) {
16184            mRenderNode.discardDisplayList();
16185        }
16186
16187        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16188            mBackgroundRenderNode.discardDisplayList();
16189        }
16190    }
16191
16192    /**
16193     * Called when the passed RenderNode is removed from the draw tree
16194     * @hide
16195     */
16196    public void onRenderNodeDetached(RenderNode renderNode) {
16197    }
16198
16199    /**
16200     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16201     *
16202     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16203     *
16204     * @see #getDrawingCache(boolean)
16205     */
16206    public Bitmap getDrawingCache() {
16207        return getDrawingCache(false);
16208    }
16209
16210    /**
16211     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16212     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16213     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16214     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16215     * request the drawing cache by calling this method and draw it on screen if the
16216     * returned bitmap is not null.</p>
16217     *
16218     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16219     * this method will create a bitmap of the same size as this view. Because this bitmap
16220     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16221     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16222     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16223     * size than the view. This implies that your application must be able to handle this
16224     * size.</p>
16225     *
16226     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16227     *        the current density of the screen when the application is in compatibility
16228     *        mode.
16229     *
16230     * @return A bitmap representing this view or null if cache is disabled.
16231     *
16232     * @see #setDrawingCacheEnabled(boolean)
16233     * @see #isDrawingCacheEnabled()
16234     * @see #buildDrawingCache(boolean)
16235     * @see #destroyDrawingCache()
16236     */
16237    public Bitmap getDrawingCache(boolean autoScale) {
16238        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16239            return null;
16240        }
16241        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16242            buildDrawingCache(autoScale);
16243        }
16244        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16245    }
16246
16247    /**
16248     * <p>Frees the resources used by the drawing cache. If you call
16249     * {@link #buildDrawingCache()} manually without calling
16250     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16251     * should cleanup the cache with this method afterwards.</p>
16252     *
16253     * @see #setDrawingCacheEnabled(boolean)
16254     * @see #buildDrawingCache()
16255     * @see #getDrawingCache()
16256     */
16257    public void destroyDrawingCache() {
16258        if (mDrawingCache != null) {
16259            mDrawingCache.recycle();
16260            mDrawingCache = null;
16261        }
16262        if (mUnscaledDrawingCache != null) {
16263            mUnscaledDrawingCache.recycle();
16264            mUnscaledDrawingCache = null;
16265        }
16266    }
16267
16268    /**
16269     * Setting a solid background color for the drawing cache's bitmaps will improve
16270     * performance and memory usage. Note, though that this should only be used if this
16271     * view will always be drawn on top of a solid color.
16272     *
16273     * @param color The background color to use for the drawing cache's bitmap
16274     *
16275     * @see #setDrawingCacheEnabled(boolean)
16276     * @see #buildDrawingCache()
16277     * @see #getDrawingCache()
16278     */
16279    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16280        if (color != mDrawingCacheBackgroundColor) {
16281            mDrawingCacheBackgroundColor = color;
16282            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16283        }
16284    }
16285
16286    /**
16287     * @see #setDrawingCacheBackgroundColor(int)
16288     *
16289     * @return The background color to used for the drawing cache's bitmap
16290     */
16291    @ColorInt
16292    public int getDrawingCacheBackgroundColor() {
16293        return mDrawingCacheBackgroundColor;
16294    }
16295
16296    /**
16297     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16298     *
16299     * @see #buildDrawingCache(boolean)
16300     */
16301    public void buildDrawingCache() {
16302        buildDrawingCache(false);
16303    }
16304
16305    /**
16306     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16307     *
16308     * <p>If you call {@link #buildDrawingCache()} manually without calling
16309     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16310     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16311     *
16312     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16313     * this method will create a bitmap of the same size as this view. Because this bitmap
16314     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16315     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16316     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16317     * size than the view. This implies that your application must be able to handle this
16318     * size.</p>
16319     *
16320     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16321     * you do not need the drawing cache bitmap, calling this method will increase memory
16322     * usage and cause the view to be rendered in software once, thus negatively impacting
16323     * performance.</p>
16324     *
16325     * @see #getDrawingCache()
16326     * @see #destroyDrawingCache()
16327     */
16328    public void buildDrawingCache(boolean autoScale) {
16329        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16330                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16331            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16332                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16333                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16334            }
16335            try {
16336                buildDrawingCacheImpl(autoScale);
16337            } finally {
16338                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16339            }
16340        }
16341    }
16342
16343    /**
16344     * private, internal implementation of buildDrawingCache, used to enable tracing
16345     */
16346    private void buildDrawingCacheImpl(boolean autoScale) {
16347        mCachingFailed = false;
16348
16349        int width = mRight - mLeft;
16350        int height = mBottom - mTop;
16351
16352        final AttachInfo attachInfo = mAttachInfo;
16353        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16354
16355        if (autoScale && scalingRequired) {
16356            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16357            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16358        }
16359
16360        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16361        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16362        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16363
16364        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16365        final long drawingCacheSize =
16366                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16367        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16368            if (width > 0 && height > 0) {
16369                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16370                        + " too large to fit into a software layer (or drawing cache), needs "
16371                        + projectedBitmapSize + " bytes, only "
16372                        + drawingCacheSize + " available");
16373            }
16374            destroyDrawingCache();
16375            mCachingFailed = true;
16376            return;
16377        }
16378
16379        boolean clear = true;
16380        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16381
16382        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16383            Bitmap.Config quality;
16384            if (!opaque) {
16385                // Never pick ARGB_4444 because it looks awful
16386                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16387                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16388                    case DRAWING_CACHE_QUALITY_AUTO:
16389                    case DRAWING_CACHE_QUALITY_LOW:
16390                    case DRAWING_CACHE_QUALITY_HIGH:
16391                    default:
16392                        quality = Bitmap.Config.ARGB_8888;
16393                        break;
16394                }
16395            } else {
16396                // Optimization for translucent windows
16397                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16398                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16399            }
16400
16401            // Try to cleanup memory
16402            if (bitmap != null) bitmap.recycle();
16403
16404            try {
16405                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16406                        width, height, quality);
16407                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16408                if (autoScale) {
16409                    mDrawingCache = bitmap;
16410                } else {
16411                    mUnscaledDrawingCache = bitmap;
16412                }
16413                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16414            } catch (OutOfMemoryError e) {
16415                // If there is not enough memory to create the bitmap cache, just
16416                // ignore the issue as bitmap caches are not required to draw the
16417                // view hierarchy
16418                if (autoScale) {
16419                    mDrawingCache = null;
16420                } else {
16421                    mUnscaledDrawingCache = null;
16422                }
16423                mCachingFailed = true;
16424                return;
16425            }
16426
16427            clear = drawingCacheBackgroundColor != 0;
16428        }
16429
16430        Canvas canvas;
16431        if (attachInfo != null) {
16432            canvas = attachInfo.mCanvas;
16433            if (canvas == null) {
16434                canvas = new Canvas();
16435            }
16436            canvas.setBitmap(bitmap);
16437            // Temporarily clobber the cached Canvas in case one of our children
16438            // is also using a drawing cache. Without this, the children would
16439            // steal the canvas by attaching their own bitmap to it and bad, bad
16440            // thing would happen (invisible views, corrupted drawings, etc.)
16441            attachInfo.mCanvas = null;
16442        } else {
16443            // This case should hopefully never or seldom happen
16444            canvas = new Canvas(bitmap);
16445        }
16446
16447        if (clear) {
16448            bitmap.eraseColor(drawingCacheBackgroundColor);
16449        }
16450
16451        computeScroll();
16452        final int restoreCount = canvas.save();
16453
16454        if (autoScale && scalingRequired) {
16455            final float scale = attachInfo.mApplicationScale;
16456            canvas.scale(scale, scale);
16457        }
16458
16459        canvas.translate(-mScrollX, -mScrollY);
16460
16461        mPrivateFlags |= PFLAG_DRAWN;
16462        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16463                mLayerType != LAYER_TYPE_NONE) {
16464            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16465        }
16466
16467        // Fast path for layouts with no backgrounds
16468        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16469            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16470            dispatchDraw(canvas);
16471            if (mOverlay != null && !mOverlay.isEmpty()) {
16472                mOverlay.getOverlayView().draw(canvas);
16473            }
16474        } else {
16475            draw(canvas);
16476        }
16477
16478        canvas.restoreToCount(restoreCount);
16479        canvas.setBitmap(null);
16480
16481        if (attachInfo != null) {
16482            // Restore the cached Canvas for our siblings
16483            attachInfo.mCanvas = canvas;
16484        }
16485    }
16486
16487    /**
16488     * Create a snapshot of the view into a bitmap.  We should probably make
16489     * some form of this public, but should think about the API.
16490     *
16491     * @hide
16492     */
16493    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16494        int width = mRight - mLeft;
16495        int height = mBottom - mTop;
16496
16497        final AttachInfo attachInfo = mAttachInfo;
16498        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16499        width = (int) ((width * scale) + 0.5f);
16500        height = (int) ((height * scale) + 0.5f);
16501
16502        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16503                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16504        if (bitmap == null) {
16505            throw new OutOfMemoryError();
16506        }
16507
16508        Resources resources = getResources();
16509        if (resources != null) {
16510            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16511        }
16512
16513        Canvas canvas;
16514        if (attachInfo != null) {
16515            canvas = attachInfo.mCanvas;
16516            if (canvas == null) {
16517                canvas = new Canvas();
16518            }
16519            canvas.setBitmap(bitmap);
16520            // Temporarily clobber the cached Canvas in case one of our children
16521            // is also using a drawing cache. Without this, the children would
16522            // steal the canvas by attaching their own bitmap to it and bad, bad
16523            // things would happen (invisible views, corrupted drawings, etc.)
16524            attachInfo.mCanvas = null;
16525        } else {
16526            // This case should hopefully never or seldom happen
16527            canvas = new Canvas(bitmap);
16528        }
16529
16530        if ((backgroundColor & 0xff000000) != 0) {
16531            bitmap.eraseColor(backgroundColor);
16532        }
16533
16534        computeScroll();
16535        final int restoreCount = canvas.save();
16536        canvas.scale(scale, scale);
16537        canvas.translate(-mScrollX, -mScrollY);
16538
16539        // Temporarily remove the dirty mask
16540        int flags = mPrivateFlags;
16541        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16542
16543        // Fast path for layouts with no backgrounds
16544        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16545            dispatchDraw(canvas);
16546            if (mOverlay != null && !mOverlay.isEmpty()) {
16547                mOverlay.getOverlayView().draw(canvas);
16548            }
16549        } else {
16550            draw(canvas);
16551        }
16552
16553        mPrivateFlags = flags;
16554
16555        canvas.restoreToCount(restoreCount);
16556        canvas.setBitmap(null);
16557
16558        if (attachInfo != null) {
16559            // Restore the cached Canvas for our siblings
16560            attachInfo.mCanvas = canvas;
16561        }
16562
16563        return bitmap;
16564    }
16565
16566    /**
16567     * Indicates whether this View is currently in edit mode. A View is usually
16568     * in edit mode when displayed within a developer tool. For instance, if
16569     * this View is being drawn by a visual user interface builder, this method
16570     * should return true.
16571     *
16572     * Subclasses should check the return value of this method to provide
16573     * different behaviors if their normal behavior might interfere with the
16574     * host environment. For instance: the class spawns a thread in its
16575     * constructor, the drawing code relies on device-specific features, etc.
16576     *
16577     * This method is usually checked in the drawing code of custom widgets.
16578     *
16579     * @return True if this View is in edit mode, false otherwise.
16580     */
16581    public boolean isInEditMode() {
16582        return false;
16583    }
16584
16585    /**
16586     * If the View draws content inside its padding and enables fading edges,
16587     * it needs to support padding offsets. Padding offsets are added to the
16588     * fading edges to extend the length of the fade so that it covers pixels
16589     * drawn inside the padding.
16590     *
16591     * Subclasses of this class should override this method if they need
16592     * to draw content inside the padding.
16593     *
16594     * @return True if padding offset must be applied, false otherwise.
16595     *
16596     * @see #getLeftPaddingOffset()
16597     * @see #getRightPaddingOffset()
16598     * @see #getTopPaddingOffset()
16599     * @see #getBottomPaddingOffset()
16600     *
16601     * @since CURRENT
16602     */
16603    protected boolean isPaddingOffsetRequired() {
16604        return false;
16605    }
16606
16607    /**
16608     * Amount by which to extend the left fading region. Called only when
16609     * {@link #isPaddingOffsetRequired()} returns true.
16610     *
16611     * @return The left padding offset in pixels.
16612     *
16613     * @see #isPaddingOffsetRequired()
16614     *
16615     * @since CURRENT
16616     */
16617    protected int getLeftPaddingOffset() {
16618        return 0;
16619    }
16620
16621    /**
16622     * Amount by which to extend the right fading region. Called only when
16623     * {@link #isPaddingOffsetRequired()} returns true.
16624     *
16625     * @return The right padding offset in pixels.
16626     *
16627     * @see #isPaddingOffsetRequired()
16628     *
16629     * @since CURRENT
16630     */
16631    protected int getRightPaddingOffset() {
16632        return 0;
16633    }
16634
16635    /**
16636     * Amount by which to extend the top fading region. Called only when
16637     * {@link #isPaddingOffsetRequired()} returns true.
16638     *
16639     * @return The top padding offset in pixels.
16640     *
16641     * @see #isPaddingOffsetRequired()
16642     *
16643     * @since CURRENT
16644     */
16645    protected int getTopPaddingOffset() {
16646        return 0;
16647    }
16648
16649    /**
16650     * Amount by which to extend the bottom fading region. Called only when
16651     * {@link #isPaddingOffsetRequired()} returns true.
16652     *
16653     * @return The bottom padding offset in pixels.
16654     *
16655     * @see #isPaddingOffsetRequired()
16656     *
16657     * @since CURRENT
16658     */
16659    protected int getBottomPaddingOffset() {
16660        return 0;
16661    }
16662
16663    /**
16664     * @hide
16665     * @param offsetRequired
16666     */
16667    protected int getFadeTop(boolean offsetRequired) {
16668        int top = mPaddingTop;
16669        if (offsetRequired) top += getTopPaddingOffset();
16670        return top;
16671    }
16672
16673    /**
16674     * @hide
16675     * @param offsetRequired
16676     */
16677    protected int getFadeHeight(boolean offsetRequired) {
16678        int padding = mPaddingTop;
16679        if (offsetRequired) padding += getTopPaddingOffset();
16680        return mBottom - mTop - mPaddingBottom - padding;
16681    }
16682
16683    /**
16684     * <p>Indicates whether this view is attached to a hardware accelerated
16685     * window or not.</p>
16686     *
16687     * <p>Even if this method returns true, it does not mean that every call
16688     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16689     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16690     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16691     * window is hardware accelerated,
16692     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16693     * return false, and this method will return true.</p>
16694     *
16695     * @return True if the view is attached to a window and the window is
16696     *         hardware accelerated; false in any other case.
16697     */
16698    @ViewDebug.ExportedProperty(category = "drawing")
16699    public boolean isHardwareAccelerated() {
16700        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16701    }
16702
16703    /**
16704     * Sets a rectangular area on this view to which the view will be clipped
16705     * when it is drawn. Setting the value to null will remove the clip bounds
16706     * and the view will draw normally, using its full bounds.
16707     *
16708     * @param clipBounds The rectangular area, in the local coordinates of
16709     * this view, to which future drawing operations will be clipped.
16710     */
16711    public void setClipBounds(Rect clipBounds) {
16712        if (clipBounds == mClipBounds
16713                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16714            return;
16715        }
16716        if (clipBounds != null) {
16717            if (mClipBounds == null) {
16718                mClipBounds = new Rect(clipBounds);
16719            } else {
16720                mClipBounds.set(clipBounds);
16721            }
16722        } else {
16723            mClipBounds = null;
16724        }
16725        mRenderNode.setClipBounds(mClipBounds);
16726        invalidateViewProperty(false, false);
16727    }
16728
16729    /**
16730     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16731     *
16732     * @return A copy of the current clip bounds if clip bounds are set,
16733     * otherwise null.
16734     */
16735    public Rect getClipBounds() {
16736        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16737    }
16738
16739
16740    /**
16741     * Populates an output rectangle with the clip bounds of the view,
16742     * returning {@code true} if successful or {@code false} if the view's
16743     * clip bounds are {@code null}.
16744     *
16745     * @param outRect rectangle in which to place the clip bounds of the view
16746     * @return {@code true} if successful or {@code false} if the view's
16747     *         clip bounds are {@code null}
16748     */
16749    public boolean getClipBounds(Rect outRect) {
16750        if (mClipBounds != null) {
16751            outRect.set(mClipBounds);
16752            return true;
16753        }
16754        return false;
16755    }
16756
16757    /**
16758     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16759     * case of an active Animation being run on the view.
16760     */
16761    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16762            Animation a, boolean scalingRequired) {
16763        Transformation invalidationTransform;
16764        final int flags = parent.mGroupFlags;
16765        final boolean initialized = a.isInitialized();
16766        if (!initialized) {
16767            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16768            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16769            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16770            onAnimationStart();
16771        }
16772
16773        final Transformation t = parent.getChildTransformation();
16774        boolean more = a.getTransformation(drawingTime, t, 1f);
16775        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16776            if (parent.mInvalidationTransformation == null) {
16777                parent.mInvalidationTransformation = new Transformation();
16778            }
16779            invalidationTransform = parent.mInvalidationTransformation;
16780            a.getTransformation(drawingTime, invalidationTransform, 1f);
16781        } else {
16782            invalidationTransform = t;
16783        }
16784
16785        if (more) {
16786            if (!a.willChangeBounds()) {
16787                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16788                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16789                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16790                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16791                    // The child need to draw an animation, potentially offscreen, so
16792                    // make sure we do not cancel invalidate requests
16793                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16794                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16795                }
16796            } else {
16797                if (parent.mInvalidateRegion == null) {
16798                    parent.mInvalidateRegion = new RectF();
16799                }
16800                final RectF region = parent.mInvalidateRegion;
16801                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16802                        invalidationTransform);
16803
16804                // The child need to draw an animation, potentially offscreen, so
16805                // make sure we do not cancel invalidate requests
16806                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16807
16808                final int left = mLeft + (int) region.left;
16809                final int top = mTop + (int) region.top;
16810                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16811                        top + (int) (region.height() + .5f));
16812            }
16813        }
16814        return more;
16815    }
16816
16817    /**
16818     * This method is called by getDisplayList() when a display list is recorded for a View.
16819     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16820     */
16821    void setDisplayListProperties(RenderNode renderNode) {
16822        if (renderNode != null) {
16823            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16824            renderNode.setClipToBounds(mParent instanceof ViewGroup
16825                    && ((ViewGroup) mParent).getClipChildren());
16826
16827            float alpha = 1;
16828            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16829                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16830                ViewGroup parentVG = (ViewGroup) mParent;
16831                final Transformation t = parentVG.getChildTransformation();
16832                if (parentVG.getChildStaticTransformation(this, t)) {
16833                    final int transformType = t.getTransformationType();
16834                    if (transformType != Transformation.TYPE_IDENTITY) {
16835                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16836                            alpha = t.getAlpha();
16837                        }
16838                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16839                            renderNode.setStaticMatrix(t.getMatrix());
16840                        }
16841                    }
16842                }
16843            }
16844            if (mTransformationInfo != null) {
16845                alpha *= getFinalAlpha();
16846                if (alpha < 1) {
16847                    final int multipliedAlpha = (int) (255 * alpha);
16848                    if (onSetAlpha(multipliedAlpha)) {
16849                        alpha = 1;
16850                    }
16851                }
16852                renderNode.setAlpha(alpha);
16853            } else if (alpha < 1) {
16854                renderNode.setAlpha(alpha);
16855            }
16856        }
16857    }
16858
16859    /**
16860     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16861     *
16862     * This is where the View specializes rendering behavior based on layer type,
16863     * and hardware acceleration.
16864     */
16865    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16866        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16867        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16868         *
16869         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16870         * HW accelerated, it can't handle drawing RenderNodes.
16871         */
16872        boolean drawingWithRenderNode = mAttachInfo != null
16873                && mAttachInfo.mHardwareAccelerated
16874                && hardwareAcceleratedCanvas;
16875
16876        boolean more = false;
16877        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16878        final int parentFlags = parent.mGroupFlags;
16879
16880        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16881            parent.getChildTransformation().clear();
16882            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16883        }
16884
16885        Transformation transformToApply = null;
16886        boolean concatMatrix = false;
16887        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16888        final Animation a = getAnimation();
16889        if (a != null) {
16890            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16891            concatMatrix = a.willChangeTransformationMatrix();
16892            if (concatMatrix) {
16893                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16894            }
16895            transformToApply = parent.getChildTransformation();
16896        } else {
16897            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16898                // No longer animating: clear out old animation matrix
16899                mRenderNode.setAnimationMatrix(null);
16900                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16901            }
16902            if (!drawingWithRenderNode
16903                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16904                final Transformation t = parent.getChildTransformation();
16905                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16906                if (hasTransform) {
16907                    final int transformType = t.getTransformationType();
16908                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16909                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16910                }
16911            }
16912        }
16913
16914        concatMatrix |= !childHasIdentityMatrix;
16915
16916        // Sets the flag as early as possible to allow draw() implementations
16917        // to call invalidate() successfully when doing animations
16918        mPrivateFlags |= PFLAG_DRAWN;
16919
16920        if (!concatMatrix &&
16921                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16922                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16923                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16924                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16925            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16926            return more;
16927        }
16928        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16929
16930        if (hardwareAcceleratedCanvas) {
16931            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16932            // retain the flag's value temporarily in the mRecreateDisplayList flag
16933            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16934            mPrivateFlags &= ~PFLAG_INVALIDATED;
16935        }
16936
16937        RenderNode renderNode = null;
16938        Bitmap cache = null;
16939        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16940        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16941             if (layerType != LAYER_TYPE_NONE) {
16942                 // If not drawing with RenderNode, treat HW layers as SW
16943                 layerType = LAYER_TYPE_SOFTWARE;
16944                 buildDrawingCache(true);
16945            }
16946            cache = getDrawingCache(true);
16947        }
16948
16949        if (drawingWithRenderNode) {
16950            // Delay getting the display list until animation-driven alpha values are
16951            // set up and possibly passed on to the view
16952            renderNode = updateDisplayListIfDirty();
16953            if (!renderNode.isValid()) {
16954                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16955                // to getDisplayList(), the display list will be marked invalid and we should not
16956                // try to use it again.
16957                renderNode = null;
16958                drawingWithRenderNode = false;
16959            }
16960        }
16961
16962        int sx = 0;
16963        int sy = 0;
16964        if (!drawingWithRenderNode) {
16965            computeScroll();
16966            sx = mScrollX;
16967            sy = mScrollY;
16968        }
16969
16970        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16971        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16972
16973        int restoreTo = -1;
16974        if (!drawingWithRenderNode || transformToApply != null) {
16975            restoreTo = canvas.save();
16976        }
16977        if (offsetForScroll) {
16978            canvas.translate(mLeft - sx, mTop - sy);
16979        } else {
16980            if (!drawingWithRenderNode) {
16981                canvas.translate(mLeft, mTop);
16982            }
16983            if (scalingRequired) {
16984                if (drawingWithRenderNode) {
16985                    // TODO: Might not need this if we put everything inside the DL
16986                    restoreTo = canvas.save();
16987                }
16988                // mAttachInfo cannot be null, otherwise scalingRequired == false
16989                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16990                canvas.scale(scale, scale);
16991            }
16992        }
16993
16994        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16995        if (transformToApply != null
16996                || alpha < 1
16997                || !hasIdentityMatrix()
16998                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16999            if (transformToApply != null || !childHasIdentityMatrix) {
17000                int transX = 0;
17001                int transY = 0;
17002
17003                if (offsetForScroll) {
17004                    transX = -sx;
17005                    transY = -sy;
17006                }
17007
17008                if (transformToApply != null) {
17009                    if (concatMatrix) {
17010                        if (drawingWithRenderNode) {
17011                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17012                        } else {
17013                            // Undo the scroll translation, apply the transformation matrix,
17014                            // then redo the scroll translate to get the correct result.
17015                            canvas.translate(-transX, -transY);
17016                            canvas.concat(transformToApply.getMatrix());
17017                            canvas.translate(transX, transY);
17018                        }
17019                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17020                    }
17021
17022                    float transformAlpha = transformToApply.getAlpha();
17023                    if (transformAlpha < 1) {
17024                        alpha *= transformAlpha;
17025                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17026                    }
17027                }
17028
17029                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17030                    canvas.translate(-transX, -transY);
17031                    canvas.concat(getMatrix());
17032                    canvas.translate(transX, transY);
17033                }
17034            }
17035
17036            // Deal with alpha if it is or used to be <1
17037            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17038                if (alpha < 1) {
17039                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17040                } else {
17041                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17042                }
17043                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17044                if (!drawingWithDrawingCache) {
17045                    final int multipliedAlpha = (int) (255 * alpha);
17046                    if (!onSetAlpha(multipliedAlpha)) {
17047                        if (drawingWithRenderNode) {
17048                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17049                        } else if (layerType == LAYER_TYPE_NONE) {
17050                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17051                                    multipliedAlpha);
17052                        }
17053                    } else {
17054                        // Alpha is handled by the child directly, clobber the layer's alpha
17055                        mPrivateFlags |= PFLAG_ALPHA_SET;
17056                    }
17057                }
17058            }
17059        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17060            onSetAlpha(255);
17061            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17062        }
17063
17064        if (!drawingWithRenderNode) {
17065            // apply clips directly, since RenderNode won't do it for this draw
17066            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17067                if (offsetForScroll) {
17068                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17069                } else {
17070                    if (!scalingRequired || cache == null) {
17071                        canvas.clipRect(0, 0, getWidth(), getHeight());
17072                    } else {
17073                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17074                    }
17075                }
17076            }
17077
17078            if (mClipBounds != null) {
17079                // clip bounds ignore scroll
17080                canvas.clipRect(mClipBounds);
17081            }
17082        }
17083
17084        if (!drawingWithDrawingCache) {
17085            if (drawingWithRenderNode) {
17086                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17087                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17088            } else {
17089                // Fast path for layouts with no backgrounds
17090                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17091                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17092                    dispatchDraw(canvas);
17093                } else {
17094                    draw(canvas);
17095                }
17096            }
17097        } else if (cache != null) {
17098            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17099            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17100                // no layer paint, use temporary paint to draw bitmap
17101                Paint cachePaint = parent.mCachePaint;
17102                if (cachePaint == null) {
17103                    cachePaint = new Paint();
17104                    cachePaint.setDither(false);
17105                    parent.mCachePaint = cachePaint;
17106                }
17107                cachePaint.setAlpha((int) (alpha * 255));
17108                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17109            } else {
17110                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17111                int layerPaintAlpha = mLayerPaint.getAlpha();
17112                if (alpha < 1) {
17113                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17114                }
17115                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17116                if (alpha < 1) {
17117                    mLayerPaint.setAlpha(layerPaintAlpha);
17118                }
17119            }
17120        }
17121
17122        if (restoreTo >= 0) {
17123            canvas.restoreToCount(restoreTo);
17124        }
17125
17126        if (a != null && !more) {
17127            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17128                onSetAlpha(255);
17129            }
17130            parent.finishAnimatingView(this, a);
17131        }
17132
17133        if (more && hardwareAcceleratedCanvas) {
17134            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17135                // alpha animations should cause the child to recreate its display list
17136                invalidate(true);
17137            }
17138        }
17139
17140        mRecreateDisplayList = false;
17141
17142        return more;
17143    }
17144
17145    /**
17146     * Manually render this view (and all of its children) to the given Canvas.
17147     * The view must have already done a full layout before this function is
17148     * called.  When implementing a view, implement
17149     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17150     * If you do need to override this method, call the superclass version.
17151     *
17152     * @param canvas The Canvas to which the View is rendered.
17153     */
17154    @CallSuper
17155    public void draw(Canvas canvas) {
17156        final int privateFlags = mPrivateFlags;
17157        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17158                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17159        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17160
17161        /*
17162         * Draw traversal performs several drawing steps which must be executed
17163         * in the appropriate order:
17164         *
17165         *      1. Draw the background
17166         *      2. If necessary, save the canvas' layers to prepare for fading
17167         *      3. Draw view's content
17168         *      4. Draw children
17169         *      5. If necessary, draw the fading edges and restore layers
17170         *      6. Draw decorations (scrollbars for instance)
17171         */
17172
17173        // Step 1, draw the background, if needed
17174        int saveCount;
17175
17176        if (!dirtyOpaque) {
17177            drawBackground(canvas);
17178        }
17179
17180        // skip step 2 & 5 if possible (common case)
17181        final int viewFlags = mViewFlags;
17182        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17183        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17184        if (!verticalEdges && !horizontalEdges) {
17185            // Step 3, draw the content
17186            if (!dirtyOpaque) onDraw(canvas);
17187
17188            // Step 4, draw the children
17189            dispatchDraw(canvas);
17190
17191            // Overlay is part of the content and draws beneath Foreground
17192            if (mOverlay != null && !mOverlay.isEmpty()) {
17193                mOverlay.getOverlayView().dispatchDraw(canvas);
17194            }
17195
17196            // Step 6, draw decorations (foreground, scrollbars)
17197            onDrawForeground(canvas);
17198
17199            // we're done...
17200            return;
17201        }
17202
17203        /*
17204         * Here we do the full fledged routine...
17205         * (this is an uncommon case where speed matters less,
17206         * this is why we repeat some of the tests that have been
17207         * done above)
17208         */
17209
17210        boolean drawTop = false;
17211        boolean drawBottom = false;
17212        boolean drawLeft = false;
17213        boolean drawRight = false;
17214
17215        float topFadeStrength = 0.0f;
17216        float bottomFadeStrength = 0.0f;
17217        float leftFadeStrength = 0.0f;
17218        float rightFadeStrength = 0.0f;
17219
17220        // Step 2, save the canvas' layers
17221        int paddingLeft = mPaddingLeft;
17222
17223        final boolean offsetRequired = isPaddingOffsetRequired();
17224        if (offsetRequired) {
17225            paddingLeft += getLeftPaddingOffset();
17226        }
17227
17228        int left = mScrollX + paddingLeft;
17229        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17230        int top = mScrollY + getFadeTop(offsetRequired);
17231        int bottom = top + getFadeHeight(offsetRequired);
17232
17233        if (offsetRequired) {
17234            right += getRightPaddingOffset();
17235            bottom += getBottomPaddingOffset();
17236        }
17237
17238        final ScrollabilityCache scrollabilityCache = mScrollCache;
17239        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17240        int length = (int) fadeHeight;
17241
17242        // clip the fade length if top and bottom fades overlap
17243        // overlapping fades produce odd-looking artifacts
17244        if (verticalEdges && (top + length > bottom - length)) {
17245            length = (bottom - top) / 2;
17246        }
17247
17248        // also clip horizontal fades if necessary
17249        if (horizontalEdges && (left + length > right - length)) {
17250            length = (right - left) / 2;
17251        }
17252
17253        if (verticalEdges) {
17254            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17255            drawTop = topFadeStrength * fadeHeight > 1.0f;
17256            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17257            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17258        }
17259
17260        if (horizontalEdges) {
17261            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17262            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17263            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17264            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17265        }
17266
17267        saveCount = canvas.getSaveCount();
17268
17269        int solidColor = getSolidColor();
17270        if (solidColor == 0) {
17271            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17272
17273            if (drawTop) {
17274                canvas.saveLayer(left, top, right, top + length, null, flags);
17275            }
17276
17277            if (drawBottom) {
17278                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17279            }
17280
17281            if (drawLeft) {
17282                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17283            }
17284
17285            if (drawRight) {
17286                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17287            }
17288        } else {
17289            scrollabilityCache.setFadeColor(solidColor);
17290        }
17291
17292        // Step 3, draw the content
17293        if (!dirtyOpaque) onDraw(canvas);
17294
17295        // Step 4, draw the children
17296        dispatchDraw(canvas);
17297
17298        // Step 5, draw the fade effect and restore layers
17299        final Paint p = scrollabilityCache.paint;
17300        final Matrix matrix = scrollabilityCache.matrix;
17301        final Shader fade = scrollabilityCache.shader;
17302
17303        if (drawTop) {
17304            matrix.setScale(1, fadeHeight * topFadeStrength);
17305            matrix.postTranslate(left, top);
17306            fade.setLocalMatrix(matrix);
17307            p.setShader(fade);
17308            canvas.drawRect(left, top, right, top + length, p);
17309        }
17310
17311        if (drawBottom) {
17312            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17313            matrix.postRotate(180);
17314            matrix.postTranslate(left, bottom);
17315            fade.setLocalMatrix(matrix);
17316            p.setShader(fade);
17317            canvas.drawRect(left, bottom - length, right, bottom, p);
17318        }
17319
17320        if (drawLeft) {
17321            matrix.setScale(1, fadeHeight * leftFadeStrength);
17322            matrix.postRotate(-90);
17323            matrix.postTranslate(left, top);
17324            fade.setLocalMatrix(matrix);
17325            p.setShader(fade);
17326            canvas.drawRect(left, top, left + length, bottom, p);
17327        }
17328
17329        if (drawRight) {
17330            matrix.setScale(1, fadeHeight * rightFadeStrength);
17331            matrix.postRotate(90);
17332            matrix.postTranslate(right, top);
17333            fade.setLocalMatrix(matrix);
17334            p.setShader(fade);
17335            canvas.drawRect(right - length, top, right, bottom, p);
17336        }
17337
17338        canvas.restoreToCount(saveCount);
17339
17340        // Overlay is part of the content and draws beneath Foreground
17341        if (mOverlay != null && !mOverlay.isEmpty()) {
17342            mOverlay.getOverlayView().dispatchDraw(canvas);
17343        }
17344
17345        // Step 6, draw decorations (foreground, scrollbars)
17346        onDrawForeground(canvas);
17347    }
17348
17349    /**
17350     * Draws the background onto the specified canvas.
17351     *
17352     * @param canvas Canvas on which to draw the background
17353     */
17354    private void drawBackground(Canvas canvas) {
17355        final Drawable background = mBackground;
17356        if (background == null) {
17357            return;
17358        }
17359
17360        setBackgroundBounds();
17361
17362        // Attempt to use a display list if requested.
17363        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17364                && mAttachInfo.mThreadedRenderer != null) {
17365            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17366
17367            final RenderNode renderNode = mBackgroundRenderNode;
17368            if (renderNode != null && renderNode.isValid()) {
17369                setBackgroundRenderNodeProperties(renderNode);
17370                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17371                return;
17372            }
17373        }
17374
17375        final int scrollX = mScrollX;
17376        final int scrollY = mScrollY;
17377        if ((scrollX | scrollY) == 0) {
17378            background.draw(canvas);
17379        } else {
17380            canvas.translate(scrollX, scrollY);
17381            background.draw(canvas);
17382            canvas.translate(-scrollX, -scrollY);
17383        }
17384    }
17385
17386    /**
17387     * Sets the correct background bounds and rebuilds the outline, if needed.
17388     * <p/>
17389     * This is called by LayoutLib.
17390     */
17391    void setBackgroundBounds() {
17392        if (mBackgroundSizeChanged && mBackground != null) {
17393            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17394            mBackgroundSizeChanged = false;
17395            rebuildOutline();
17396        }
17397    }
17398
17399    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17400        renderNode.setTranslationX(mScrollX);
17401        renderNode.setTranslationY(mScrollY);
17402    }
17403
17404    /**
17405     * Creates a new display list or updates the existing display list for the
17406     * specified Drawable.
17407     *
17408     * @param drawable Drawable for which to create a display list
17409     * @param renderNode Existing RenderNode, or {@code null}
17410     * @return A valid display list for the specified drawable
17411     */
17412    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17413        if (renderNode == null) {
17414            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17415        }
17416
17417        final Rect bounds = drawable.getBounds();
17418        final int width = bounds.width();
17419        final int height = bounds.height();
17420        final DisplayListCanvas canvas = renderNode.start(width, height);
17421
17422        // Reverse left/top translation done by drawable canvas, which will
17423        // instead be applied by rendernode's LTRB bounds below. This way, the
17424        // drawable's bounds match with its rendernode bounds and its content
17425        // will lie within those bounds in the rendernode tree.
17426        canvas.translate(-bounds.left, -bounds.top);
17427
17428        try {
17429            drawable.draw(canvas);
17430        } finally {
17431            renderNode.end(canvas);
17432        }
17433
17434        // Set up drawable properties that are view-independent.
17435        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17436        renderNode.setProjectBackwards(drawable.isProjected());
17437        renderNode.setProjectionReceiver(true);
17438        renderNode.setClipToBounds(false);
17439        return renderNode;
17440    }
17441
17442    /**
17443     * Returns the overlay for this view, creating it if it does not yet exist.
17444     * Adding drawables to the overlay will cause them to be displayed whenever
17445     * the view itself is redrawn. Objects in the overlay should be actively
17446     * managed: remove them when they should not be displayed anymore. The
17447     * overlay will always have the same size as its host view.
17448     *
17449     * <p>Note: Overlays do not currently work correctly with {@link
17450     * SurfaceView} or {@link TextureView}; contents in overlays for these
17451     * types of views may not display correctly.</p>
17452     *
17453     * @return The ViewOverlay object for this view.
17454     * @see ViewOverlay
17455     */
17456    public ViewOverlay getOverlay() {
17457        if (mOverlay == null) {
17458            mOverlay = new ViewOverlay(mContext, this);
17459        }
17460        return mOverlay;
17461    }
17462
17463    /**
17464     * Override this if your view is known to always be drawn on top of a solid color background,
17465     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17466     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17467     * should be set to 0xFF.
17468     *
17469     * @see #setVerticalFadingEdgeEnabled(boolean)
17470     * @see #setHorizontalFadingEdgeEnabled(boolean)
17471     *
17472     * @return The known solid color background for this view, or 0 if the color may vary
17473     */
17474    @ViewDebug.ExportedProperty(category = "drawing")
17475    @ColorInt
17476    public int getSolidColor() {
17477        return 0;
17478    }
17479
17480    /**
17481     * Build a human readable string representation of the specified view flags.
17482     *
17483     * @param flags the view flags to convert to a string
17484     * @return a String representing the supplied flags
17485     */
17486    private static String printFlags(int flags) {
17487        String output = "";
17488        int numFlags = 0;
17489        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17490            output += "TAKES_FOCUS";
17491            numFlags++;
17492        }
17493
17494        switch (flags & VISIBILITY_MASK) {
17495        case INVISIBLE:
17496            if (numFlags > 0) {
17497                output += " ";
17498            }
17499            output += "INVISIBLE";
17500            // USELESS HERE numFlags++;
17501            break;
17502        case GONE:
17503            if (numFlags > 0) {
17504                output += " ";
17505            }
17506            output += "GONE";
17507            // USELESS HERE numFlags++;
17508            break;
17509        default:
17510            break;
17511        }
17512        return output;
17513    }
17514
17515    /**
17516     * Build a human readable string representation of the specified private
17517     * view flags.
17518     *
17519     * @param privateFlags the private view flags to convert to a string
17520     * @return a String representing the supplied flags
17521     */
17522    private static String printPrivateFlags(int privateFlags) {
17523        String output = "";
17524        int numFlags = 0;
17525
17526        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17527            output += "WANTS_FOCUS";
17528            numFlags++;
17529        }
17530
17531        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17532            if (numFlags > 0) {
17533                output += " ";
17534            }
17535            output += "FOCUSED";
17536            numFlags++;
17537        }
17538
17539        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17540            if (numFlags > 0) {
17541                output += " ";
17542            }
17543            output += "SELECTED";
17544            numFlags++;
17545        }
17546
17547        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17548            if (numFlags > 0) {
17549                output += " ";
17550            }
17551            output += "IS_ROOT_NAMESPACE";
17552            numFlags++;
17553        }
17554
17555        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17556            if (numFlags > 0) {
17557                output += " ";
17558            }
17559            output += "HAS_BOUNDS";
17560            numFlags++;
17561        }
17562
17563        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17564            if (numFlags > 0) {
17565                output += " ";
17566            }
17567            output += "DRAWN";
17568            // USELESS HERE numFlags++;
17569        }
17570        return output;
17571    }
17572
17573    /**
17574     * <p>Indicates whether or not this view's layout will be requested during
17575     * the next hierarchy layout pass.</p>
17576     *
17577     * @return true if the layout will be forced during next layout pass
17578     */
17579    public boolean isLayoutRequested() {
17580        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17581    }
17582
17583    /**
17584     * Return true if o is a ViewGroup that is laying out using optical bounds.
17585     * @hide
17586     */
17587    public static boolean isLayoutModeOptical(Object o) {
17588        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17589    }
17590
17591    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17592        Insets parentInsets = mParent instanceof View ?
17593                ((View) mParent).getOpticalInsets() : Insets.NONE;
17594        Insets childInsets = getOpticalInsets();
17595        return setFrame(
17596                left   + parentInsets.left - childInsets.left,
17597                top    + parentInsets.top  - childInsets.top,
17598                right  + parentInsets.left + childInsets.right,
17599                bottom + parentInsets.top  + childInsets.bottom);
17600    }
17601
17602    /**
17603     * Assign a size and position to a view and all of its
17604     * descendants
17605     *
17606     * <p>This is the second phase of the layout mechanism.
17607     * (The first is measuring). In this phase, each parent calls
17608     * layout on all of its children to position them.
17609     * This is typically done using the child measurements
17610     * that were stored in the measure pass().</p>
17611     *
17612     * <p>Derived classes should not override this method.
17613     * Derived classes with children should override
17614     * onLayout. In that method, they should
17615     * call layout on each of their children.</p>
17616     *
17617     * @param l Left position, relative to parent
17618     * @param t Top position, relative to parent
17619     * @param r Right position, relative to parent
17620     * @param b Bottom position, relative to parent
17621     */
17622    @SuppressWarnings({"unchecked"})
17623    public void layout(int l, int t, int r, int b) {
17624        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17625            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17626            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17627        }
17628
17629        int oldL = mLeft;
17630        int oldT = mTop;
17631        int oldB = mBottom;
17632        int oldR = mRight;
17633
17634        boolean changed = isLayoutModeOptical(mParent) ?
17635                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17636
17637        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17638            onLayout(changed, l, t, r, b);
17639
17640            if (shouldDrawRoundScrollbar()) {
17641                if(mRoundScrollbarRenderer == null) {
17642                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
17643                }
17644            } else {
17645                mRoundScrollbarRenderer = null;
17646            }
17647
17648            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17649
17650            ListenerInfo li = mListenerInfo;
17651            if (li != null && li.mOnLayoutChangeListeners != null) {
17652                ArrayList<OnLayoutChangeListener> listenersCopy =
17653                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17654                int numListeners = listenersCopy.size();
17655                for (int i = 0; i < numListeners; ++i) {
17656                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17657                }
17658            }
17659        }
17660
17661        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17662        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17663    }
17664
17665    /**
17666     * Called from layout when this view should
17667     * assign a size and position to each of its children.
17668     *
17669     * Derived classes with children should override
17670     * this method and call layout on each of
17671     * their children.
17672     * @param changed This is a new size or position for this view
17673     * @param left Left position, relative to parent
17674     * @param top Top position, relative to parent
17675     * @param right Right position, relative to parent
17676     * @param bottom Bottom position, relative to parent
17677     */
17678    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17679    }
17680
17681    /**
17682     * Assign a size and position to this view.
17683     *
17684     * This is called from layout.
17685     *
17686     * @param left Left position, relative to parent
17687     * @param top Top position, relative to parent
17688     * @param right Right position, relative to parent
17689     * @param bottom Bottom position, relative to parent
17690     * @return true if the new size and position are different than the
17691     *         previous ones
17692     * {@hide}
17693     */
17694    protected boolean setFrame(int left, int top, int right, int bottom) {
17695        boolean changed = false;
17696
17697        if (DBG) {
17698            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17699                    + right + "," + bottom + ")");
17700        }
17701
17702        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17703            changed = true;
17704
17705            // Remember our drawn bit
17706            int drawn = mPrivateFlags & PFLAG_DRAWN;
17707
17708            int oldWidth = mRight - mLeft;
17709            int oldHeight = mBottom - mTop;
17710            int newWidth = right - left;
17711            int newHeight = bottom - top;
17712            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17713
17714            // Invalidate our old position
17715            invalidate(sizeChanged);
17716
17717            mLeft = left;
17718            mTop = top;
17719            mRight = right;
17720            mBottom = bottom;
17721            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17722
17723            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17724
17725
17726            if (sizeChanged) {
17727                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17728            }
17729
17730            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17731                // If we are visible, force the DRAWN bit to on so that
17732                // this invalidate will go through (at least to our parent).
17733                // This is because someone may have invalidated this view
17734                // before this call to setFrame came in, thereby clearing
17735                // the DRAWN bit.
17736                mPrivateFlags |= PFLAG_DRAWN;
17737                invalidate(sizeChanged);
17738                // parent display list may need to be recreated based on a change in the bounds
17739                // of any child
17740                invalidateParentCaches();
17741            }
17742
17743            // Reset drawn bit to original value (invalidate turns it off)
17744            mPrivateFlags |= drawn;
17745
17746            mBackgroundSizeChanged = true;
17747            if (mForegroundInfo != null) {
17748                mForegroundInfo.mBoundsChanged = true;
17749            }
17750
17751            notifySubtreeAccessibilityStateChangedIfNeeded();
17752        }
17753        return changed;
17754    }
17755
17756    /**
17757     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17758     * @hide
17759     */
17760    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17761        setFrame(left, top, right, bottom);
17762    }
17763
17764    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17765        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17766        if (mOverlay != null) {
17767            mOverlay.getOverlayView().setRight(newWidth);
17768            mOverlay.getOverlayView().setBottom(newHeight);
17769        }
17770        rebuildOutline();
17771    }
17772
17773    /**
17774     * Finalize inflating a view from XML.  This is called as the last phase
17775     * of inflation, after all child views have been added.
17776     *
17777     * <p>Even if the subclass overrides onFinishInflate, they should always be
17778     * sure to call the super method, so that we get called.
17779     */
17780    @CallSuper
17781    protected void onFinishInflate() {
17782    }
17783
17784    /**
17785     * Returns the resources associated with this view.
17786     *
17787     * @return Resources object.
17788     */
17789    public Resources getResources() {
17790        return mResources;
17791    }
17792
17793    /**
17794     * Invalidates the specified Drawable.
17795     *
17796     * @param drawable the drawable to invalidate
17797     */
17798    @Override
17799    public void invalidateDrawable(@NonNull Drawable drawable) {
17800        if (verifyDrawable(drawable)) {
17801            final Rect dirty = drawable.getDirtyBounds();
17802            final int scrollX = mScrollX;
17803            final int scrollY = mScrollY;
17804
17805            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17806                    dirty.right + scrollX, dirty.bottom + scrollY);
17807            rebuildOutline();
17808        }
17809    }
17810
17811    /**
17812     * Schedules an action on a drawable to occur at a specified time.
17813     *
17814     * @param who the recipient of the action
17815     * @param what the action to run on the drawable
17816     * @param when the time at which the action must occur. Uses the
17817     *        {@link SystemClock#uptimeMillis} timebase.
17818     */
17819    @Override
17820    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17821        if (verifyDrawable(who) && what != null) {
17822            final long delay = when - SystemClock.uptimeMillis();
17823            if (mAttachInfo != null) {
17824                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17825                        Choreographer.CALLBACK_ANIMATION, what, who,
17826                        Choreographer.subtractFrameDelay(delay));
17827            } else {
17828                // Postpone the runnable until we know
17829                // on which thread it needs to run.
17830                getRunQueue().postDelayed(what, delay);
17831            }
17832        }
17833    }
17834
17835    /**
17836     * Cancels a scheduled action on a drawable.
17837     *
17838     * @param who the recipient of the action
17839     * @param what the action to cancel
17840     */
17841    @Override
17842    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17843        if (verifyDrawable(who) && what != null) {
17844            if (mAttachInfo != null) {
17845                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17846                        Choreographer.CALLBACK_ANIMATION, what, who);
17847            }
17848            getRunQueue().removeCallbacks(what);
17849        }
17850    }
17851
17852    /**
17853     * Unschedule any events associated with the given Drawable.  This can be
17854     * used when selecting a new Drawable into a view, so that the previous
17855     * one is completely unscheduled.
17856     *
17857     * @param who The Drawable to unschedule.
17858     *
17859     * @see #drawableStateChanged
17860     */
17861    public void unscheduleDrawable(Drawable who) {
17862        if (mAttachInfo != null && who != null) {
17863            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17864                    Choreographer.CALLBACK_ANIMATION, null, who);
17865        }
17866    }
17867
17868    /**
17869     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17870     * that the View directionality can and will be resolved before its Drawables.
17871     *
17872     * Will call {@link View#onResolveDrawables} when resolution is done.
17873     *
17874     * @hide
17875     */
17876    protected void resolveDrawables() {
17877        // Drawables resolution may need to happen before resolving the layout direction (which is
17878        // done only during the measure() call).
17879        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17880        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17881        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17882        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17883        // direction to be resolved as its resolved value will be the same as its raw value.
17884        if (!isLayoutDirectionResolved() &&
17885                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17886            return;
17887        }
17888
17889        final int layoutDirection = isLayoutDirectionResolved() ?
17890                getLayoutDirection() : getRawLayoutDirection();
17891
17892        if (mBackground != null) {
17893            mBackground.setLayoutDirection(layoutDirection);
17894        }
17895        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17896            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17897        }
17898        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17899        onResolveDrawables(layoutDirection);
17900    }
17901
17902    boolean areDrawablesResolved() {
17903        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17904    }
17905
17906    /**
17907     * Called when layout direction has been resolved.
17908     *
17909     * The default implementation does nothing.
17910     *
17911     * @param layoutDirection The resolved layout direction.
17912     *
17913     * @see #LAYOUT_DIRECTION_LTR
17914     * @see #LAYOUT_DIRECTION_RTL
17915     *
17916     * @hide
17917     */
17918    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17919    }
17920
17921    /**
17922     * @hide
17923     */
17924    protected void resetResolvedDrawables() {
17925        resetResolvedDrawablesInternal();
17926    }
17927
17928    void resetResolvedDrawablesInternal() {
17929        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17930    }
17931
17932    /**
17933     * If your view subclass is displaying its own Drawable objects, it should
17934     * override this function and return true for any Drawable it is
17935     * displaying.  This allows animations for those drawables to be
17936     * scheduled.
17937     *
17938     * <p>Be sure to call through to the super class when overriding this
17939     * function.
17940     *
17941     * @param who The Drawable to verify.  Return true if it is one you are
17942     *            displaying, else return the result of calling through to the
17943     *            super class.
17944     *
17945     * @return boolean If true than the Drawable is being displayed in the
17946     *         view; else false and it is not allowed to animate.
17947     *
17948     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17949     * @see #drawableStateChanged()
17950     */
17951    @CallSuper
17952    protected boolean verifyDrawable(@NonNull Drawable who) {
17953        // Avoid verifying the scroll bar drawable so that we don't end up in
17954        // an invalidation loop. This effectively prevents the scroll bar
17955        // drawable from triggering invalidations and scheduling runnables.
17956        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17957    }
17958
17959    /**
17960     * This function is called whenever the state of the view changes in such
17961     * a way that it impacts the state of drawables being shown.
17962     * <p>
17963     * If the View has a StateListAnimator, it will also be called to run necessary state
17964     * change animations.
17965     * <p>
17966     * Be sure to call through to the superclass when overriding this function.
17967     *
17968     * @see Drawable#setState(int[])
17969     */
17970    @CallSuper
17971    protected void drawableStateChanged() {
17972        final int[] state = getDrawableState();
17973        boolean changed = false;
17974
17975        final Drawable bg = mBackground;
17976        if (bg != null && bg.isStateful()) {
17977            changed |= bg.setState(state);
17978        }
17979
17980        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17981        if (fg != null && fg.isStateful()) {
17982            changed |= fg.setState(state);
17983        }
17984
17985        if (mScrollCache != null) {
17986            final Drawable scrollBar = mScrollCache.scrollBar;
17987            if (scrollBar != null && scrollBar.isStateful()) {
17988                changed |= scrollBar.setState(state)
17989                        && mScrollCache.state != ScrollabilityCache.OFF;
17990            }
17991        }
17992
17993        if (mStateListAnimator != null) {
17994            mStateListAnimator.setState(state);
17995        }
17996
17997        if (changed) {
17998            invalidate();
17999        }
18000    }
18001
18002    /**
18003     * This function is called whenever the view hotspot changes and needs to
18004     * be propagated to drawables or child views managed by the view.
18005     * <p>
18006     * Dispatching to child views is handled by
18007     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18008     * <p>
18009     * Be sure to call through to the superclass when overriding this function.
18010     *
18011     * @param x hotspot x coordinate
18012     * @param y hotspot y coordinate
18013     */
18014    @CallSuper
18015    public void drawableHotspotChanged(float x, float y) {
18016        if (mBackground != null) {
18017            mBackground.setHotspot(x, y);
18018        }
18019        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18020            mForegroundInfo.mDrawable.setHotspot(x, y);
18021        }
18022
18023        dispatchDrawableHotspotChanged(x, y);
18024    }
18025
18026    /**
18027     * Dispatches drawableHotspotChanged to all of this View's children.
18028     *
18029     * @param x hotspot x coordinate
18030     * @param y hotspot y coordinate
18031     * @see #drawableHotspotChanged(float, float)
18032     */
18033    public void dispatchDrawableHotspotChanged(float x, float y) {
18034    }
18035
18036    /**
18037     * Call this to force a view to update its drawable state. This will cause
18038     * drawableStateChanged to be called on this view. Views that are interested
18039     * in the new state should call getDrawableState.
18040     *
18041     * @see #drawableStateChanged
18042     * @see #getDrawableState
18043     */
18044    public void refreshDrawableState() {
18045        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18046        drawableStateChanged();
18047
18048        ViewParent parent = mParent;
18049        if (parent != null) {
18050            parent.childDrawableStateChanged(this);
18051        }
18052    }
18053
18054    /**
18055     * Return an array of resource IDs of the drawable states representing the
18056     * current state of the view.
18057     *
18058     * @return The current drawable state
18059     *
18060     * @see Drawable#setState(int[])
18061     * @see #drawableStateChanged()
18062     * @see #onCreateDrawableState(int)
18063     */
18064    public final int[] getDrawableState() {
18065        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18066            return mDrawableState;
18067        } else {
18068            mDrawableState = onCreateDrawableState(0);
18069            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18070            return mDrawableState;
18071        }
18072    }
18073
18074    /**
18075     * Generate the new {@link android.graphics.drawable.Drawable} state for
18076     * this view. This is called by the view
18077     * system when the cached Drawable state is determined to be invalid.  To
18078     * retrieve the current state, you should use {@link #getDrawableState}.
18079     *
18080     * @param extraSpace if non-zero, this is the number of extra entries you
18081     * would like in the returned array in which you can place your own
18082     * states.
18083     *
18084     * @return Returns an array holding the current {@link Drawable} state of
18085     * the view.
18086     *
18087     * @see #mergeDrawableStates(int[], int[])
18088     */
18089    protected int[] onCreateDrawableState(int extraSpace) {
18090        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18091                mParent instanceof View) {
18092            return ((View) mParent).onCreateDrawableState(extraSpace);
18093        }
18094
18095        int[] drawableState;
18096
18097        int privateFlags = mPrivateFlags;
18098
18099        int viewStateIndex = 0;
18100        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18101        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18102        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18103        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18104        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18105        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18106        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18107                ThreadedRenderer.isAvailable()) {
18108            // This is set if HW acceleration is requested, even if the current
18109            // process doesn't allow it.  This is just to allow app preview
18110            // windows to better match their app.
18111            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18112        }
18113        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18114
18115        final int privateFlags2 = mPrivateFlags2;
18116        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18117            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18118        }
18119        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18120            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18121        }
18122
18123        drawableState = StateSet.get(viewStateIndex);
18124
18125        //noinspection ConstantIfStatement
18126        if (false) {
18127            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18128            Log.i("View", toString()
18129                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18130                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18131                    + " fo=" + hasFocus()
18132                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18133                    + " wf=" + hasWindowFocus()
18134                    + ": " + Arrays.toString(drawableState));
18135        }
18136
18137        if (extraSpace == 0) {
18138            return drawableState;
18139        }
18140
18141        final int[] fullState;
18142        if (drawableState != null) {
18143            fullState = new int[drawableState.length + extraSpace];
18144            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18145        } else {
18146            fullState = new int[extraSpace];
18147        }
18148
18149        return fullState;
18150    }
18151
18152    /**
18153     * Merge your own state values in <var>additionalState</var> into the base
18154     * state values <var>baseState</var> that were returned by
18155     * {@link #onCreateDrawableState(int)}.
18156     *
18157     * @param baseState The base state values returned by
18158     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18159     * own additional state values.
18160     *
18161     * @param additionalState The additional state values you would like
18162     * added to <var>baseState</var>; this array is not modified.
18163     *
18164     * @return As a convenience, the <var>baseState</var> array you originally
18165     * passed into the function is returned.
18166     *
18167     * @see #onCreateDrawableState(int)
18168     */
18169    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18170        final int N = baseState.length;
18171        int i = N - 1;
18172        while (i >= 0 && baseState[i] == 0) {
18173            i--;
18174        }
18175        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18176        return baseState;
18177    }
18178
18179    /**
18180     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18181     * on all Drawable objects associated with this view.
18182     * <p>
18183     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18184     * attached to this view.
18185     */
18186    @CallSuper
18187    public void jumpDrawablesToCurrentState() {
18188        if (mBackground != null) {
18189            mBackground.jumpToCurrentState();
18190        }
18191        if (mStateListAnimator != null) {
18192            mStateListAnimator.jumpToCurrentState();
18193        }
18194        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18195            mForegroundInfo.mDrawable.jumpToCurrentState();
18196        }
18197    }
18198
18199    /**
18200     * Sets the background color for this view.
18201     * @param color the color of the background
18202     */
18203    @RemotableViewMethod
18204    public void setBackgroundColor(@ColorInt int color) {
18205        if (mBackground instanceof ColorDrawable) {
18206            ((ColorDrawable) mBackground.mutate()).setColor(color);
18207            computeOpaqueFlags();
18208            mBackgroundResource = 0;
18209        } else {
18210            setBackground(new ColorDrawable(color));
18211        }
18212    }
18213
18214    /**
18215     * Set the background to a given resource. The resource should refer to
18216     * a Drawable object or 0 to remove the background.
18217     * @param resid The identifier of the resource.
18218     *
18219     * @attr ref android.R.styleable#View_background
18220     */
18221    @RemotableViewMethod
18222    public void setBackgroundResource(@DrawableRes int resid) {
18223        if (resid != 0 && resid == mBackgroundResource) {
18224            return;
18225        }
18226
18227        Drawable d = null;
18228        if (resid != 0) {
18229            d = mContext.getDrawable(resid);
18230        }
18231        setBackground(d);
18232
18233        mBackgroundResource = resid;
18234    }
18235
18236    /**
18237     * Set the background to a given Drawable, or remove the background. If the
18238     * background has padding, this View's padding is set to the background's
18239     * padding. However, when a background is removed, this View's padding isn't
18240     * touched. If setting the padding is desired, please use
18241     * {@link #setPadding(int, int, int, int)}.
18242     *
18243     * @param background The Drawable to use as the background, or null to remove the
18244     *        background
18245     */
18246    public void setBackground(Drawable background) {
18247        //noinspection deprecation
18248        setBackgroundDrawable(background);
18249    }
18250
18251    /**
18252     * @deprecated use {@link #setBackground(Drawable)} instead
18253     */
18254    @Deprecated
18255    public void setBackgroundDrawable(Drawable background) {
18256        computeOpaqueFlags();
18257
18258        if (background == mBackground) {
18259            return;
18260        }
18261
18262        boolean requestLayout = false;
18263
18264        mBackgroundResource = 0;
18265
18266        /*
18267         * Regardless of whether we're setting a new background or not, we want
18268         * to clear the previous drawable. setVisible first while we still have the callback set.
18269         */
18270        if (mBackground != null) {
18271            if (isAttachedToWindow()) {
18272                mBackground.setVisible(false, false);
18273            }
18274            mBackground.setCallback(null);
18275            unscheduleDrawable(mBackground);
18276        }
18277
18278        if (background != null) {
18279            Rect padding = sThreadLocal.get();
18280            if (padding == null) {
18281                padding = new Rect();
18282                sThreadLocal.set(padding);
18283            }
18284            resetResolvedDrawablesInternal();
18285            background.setLayoutDirection(getLayoutDirection());
18286            if (background.getPadding(padding)) {
18287                resetResolvedPaddingInternal();
18288                switch (background.getLayoutDirection()) {
18289                    case LAYOUT_DIRECTION_RTL:
18290                        mUserPaddingLeftInitial = padding.right;
18291                        mUserPaddingRightInitial = padding.left;
18292                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18293                        break;
18294                    case LAYOUT_DIRECTION_LTR:
18295                    default:
18296                        mUserPaddingLeftInitial = padding.left;
18297                        mUserPaddingRightInitial = padding.right;
18298                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18299                }
18300                mLeftPaddingDefined = false;
18301                mRightPaddingDefined = false;
18302            }
18303
18304            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18305            // if it has a different minimum size, we should layout again
18306            if (mBackground == null
18307                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18308                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18309                requestLayout = true;
18310            }
18311
18312            // Set mBackground before we set this as the callback and start making other
18313            // background drawable state change calls. In particular, the setVisible call below
18314            // can result in drawables attempting to start animations or otherwise invalidate,
18315            // which requires the view set as the callback (us) to recognize the drawable as
18316            // belonging to it as per verifyDrawable.
18317            mBackground = background;
18318            if (background.isStateful()) {
18319                background.setState(getDrawableState());
18320            }
18321            if (isAttachedToWindow()) {
18322                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18323            }
18324
18325            applyBackgroundTint();
18326
18327            // Set callback last, since the view may still be initializing.
18328            background.setCallback(this);
18329
18330            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18331                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18332                requestLayout = true;
18333            }
18334        } else {
18335            /* Remove the background */
18336            mBackground = null;
18337            if ((mViewFlags & WILL_NOT_DRAW) != 0
18338                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18339                mPrivateFlags |= PFLAG_SKIP_DRAW;
18340            }
18341
18342            /*
18343             * When the background is set, we try to apply its padding to this
18344             * View. When the background is removed, we don't touch this View's
18345             * padding. This is noted in the Javadocs. Hence, we don't need to
18346             * requestLayout(), the invalidate() below is sufficient.
18347             */
18348
18349            // The old background's minimum size could have affected this
18350            // View's layout, so let's requestLayout
18351            requestLayout = true;
18352        }
18353
18354        computeOpaqueFlags();
18355
18356        if (requestLayout) {
18357            requestLayout();
18358        }
18359
18360        mBackgroundSizeChanged = true;
18361        invalidate(true);
18362        invalidateOutline();
18363    }
18364
18365    /**
18366     * Gets the background drawable
18367     *
18368     * @return The drawable used as the background for this view, if any.
18369     *
18370     * @see #setBackground(Drawable)
18371     *
18372     * @attr ref android.R.styleable#View_background
18373     */
18374    public Drawable getBackground() {
18375        return mBackground;
18376    }
18377
18378    /**
18379     * Applies a tint to the background drawable. Does not modify the current tint
18380     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18381     * <p>
18382     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18383     * mutate the drawable and apply the specified tint and tint mode using
18384     * {@link Drawable#setTintList(ColorStateList)}.
18385     *
18386     * @param tint the tint to apply, may be {@code null} to clear tint
18387     *
18388     * @attr ref android.R.styleable#View_backgroundTint
18389     * @see #getBackgroundTintList()
18390     * @see Drawable#setTintList(ColorStateList)
18391     */
18392    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18393        if (mBackgroundTint == null) {
18394            mBackgroundTint = new TintInfo();
18395        }
18396        mBackgroundTint.mTintList = tint;
18397        mBackgroundTint.mHasTintList = true;
18398
18399        applyBackgroundTint();
18400    }
18401
18402    /**
18403     * Return the tint applied to the background drawable, if specified.
18404     *
18405     * @return the tint applied to the background drawable
18406     * @attr ref android.R.styleable#View_backgroundTint
18407     * @see #setBackgroundTintList(ColorStateList)
18408     */
18409    @Nullable
18410    public ColorStateList getBackgroundTintList() {
18411        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18412    }
18413
18414    /**
18415     * Specifies the blending mode used to apply the tint specified by
18416     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18417     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18418     *
18419     * @param tintMode the blending mode used to apply the tint, may be
18420     *                 {@code null} to clear tint
18421     * @attr ref android.R.styleable#View_backgroundTintMode
18422     * @see #getBackgroundTintMode()
18423     * @see Drawable#setTintMode(PorterDuff.Mode)
18424     */
18425    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18426        if (mBackgroundTint == null) {
18427            mBackgroundTint = new TintInfo();
18428        }
18429        mBackgroundTint.mTintMode = tintMode;
18430        mBackgroundTint.mHasTintMode = true;
18431
18432        applyBackgroundTint();
18433    }
18434
18435    /**
18436     * Return the blending mode used to apply the tint to the background
18437     * drawable, if specified.
18438     *
18439     * @return the blending mode used to apply the tint to the background
18440     *         drawable
18441     * @attr ref android.R.styleable#View_backgroundTintMode
18442     * @see #setBackgroundTintMode(PorterDuff.Mode)
18443     */
18444    @Nullable
18445    public PorterDuff.Mode getBackgroundTintMode() {
18446        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18447    }
18448
18449    private void applyBackgroundTint() {
18450        if (mBackground != null && mBackgroundTint != null) {
18451            final TintInfo tintInfo = mBackgroundTint;
18452            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18453                mBackground = mBackground.mutate();
18454
18455                if (tintInfo.mHasTintList) {
18456                    mBackground.setTintList(tintInfo.mTintList);
18457                }
18458
18459                if (tintInfo.mHasTintMode) {
18460                    mBackground.setTintMode(tintInfo.mTintMode);
18461                }
18462
18463                // The drawable (or one of its children) may not have been
18464                // stateful before applying the tint, so let's try again.
18465                if (mBackground.isStateful()) {
18466                    mBackground.setState(getDrawableState());
18467                }
18468            }
18469        }
18470    }
18471
18472    /**
18473     * Returns the drawable used as the foreground of this View. The
18474     * foreground drawable, if non-null, is always drawn on top of the view's content.
18475     *
18476     * @return a Drawable or null if no foreground was set
18477     *
18478     * @see #onDrawForeground(Canvas)
18479     */
18480    public Drawable getForeground() {
18481        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18482    }
18483
18484    /**
18485     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18486     *
18487     * @param foreground the Drawable to be drawn on top of the children
18488     *
18489     * @attr ref android.R.styleable#View_foreground
18490     */
18491    public void setForeground(Drawable foreground) {
18492        if (mForegroundInfo == null) {
18493            if (foreground == null) {
18494                // Nothing to do.
18495                return;
18496            }
18497            mForegroundInfo = new ForegroundInfo();
18498        }
18499
18500        if (foreground == mForegroundInfo.mDrawable) {
18501            // Nothing to do
18502            return;
18503        }
18504
18505        if (mForegroundInfo.mDrawable != null) {
18506            if (isAttachedToWindow()) {
18507                mForegroundInfo.mDrawable.setVisible(false, false);
18508            }
18509            mForegroundInfo.mDrawable.setCallback(null);
18510            unscheduleDrawable(mForegroundInfo.mDrawable);
18511        }
18512
18513        mForegroundInfo.mDrawable = foreground;
18514        mForegroundInfo.mBoundsChanged = true;
18515        if (foreground != null) {
18516            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18517                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18518            }
18519            foreground.setLayoutDirection(getLayoutDirection());
18520            if (foreground.isStateful()) {
18521                foreground.setState(getDrawableState());
18522            }
18523            applyForegroundTint();
18524            if (isAttachedToWindow()) {
18525                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18526            }
18527            // Set callback last, since the view may still be initializing.
18528            foreground.setCallback(this);
18529        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18530            mPrivateFlags |= PFLAG_SKIP_DRAW;
18531        }
18532        requestLayout();
18533        invalidate();
18534    }
18535
18536    /**
18537     * Magic bit used to support features of framework-internal window decor implementation details.
18538     * This used to live exclusively in FrameLayout.
18539     *
18540     * @return true if the foreground should draw inside the padding region or false
18541     *         if it should draw inset by the view's padding
18542     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18543     */
18544    public boolean isForegroundInsidePadding() {
18545        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18546    }
18547
18548    /**
18549     * Describes how the foreground is positioned.
18550     *
18551     * @return foreground gravity.
18552     *
18553     * @see #setForegroundGravity(int)
18554     *
18555     * @attr ref android.R.styleable#View_foregroundGravity
18556     */
18557    public int getForegroundGravity() {
18558        return mForegroundInfo != null ? mForegroundInfo.mGravity
18559                : Gravity.START | Gravity.TOP;
18560    }
18561
18562    /**
18563     * Describes how the foreground is positioned. Defaults to START and TOP.
18564     *
18565     * @param gravity see {@link android.view.Gravity}
18566     *
18567     * @see #getForegroundGravity()
18568     *
18569     * @attr ref android.R.styleable#View_foregroundGravity
18570     */
18571    public void setForegroundGravity(int gravity) {
18572        if (mForegroundInfo == null) {
18573            mForegroundInfo = new ForegroundInfo();
18574        }
18575
18576        if (mForegroundInfo.mGravity != gravity) {
18577            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18578                gravity |= Gravity.START;
18579            }
18580
18581            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18582                gravity |= Gravity.TOP;
18583            }
18584
18585            mForegroundInfo.mGravity = gravity;
18586            requestLayout();
18587        }
18588    }
18589
18590    /**
18591     * Applies a tint to the foreground drawable. Does not modify the current tint
18592     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18593     * <p>
18594     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18595     * mutate the drawable and apply the specified tint and tint mode using
18596     * {@link Drawable#setTintList(ColorStateList)}.
18597     *
18598     * @param tint the tint to apply, may be {@code null} to clear tint
18599     *
18600     * @attr ref android.R.styleable#View_foregroundTint
18601     * @see #getForegroundTintList()
18602     * @see Drawable#setTintList(ColorStateList)
18603     */
18604    public void setForegroundTintList(@Nullable ColorStateList tint) {
18605        if (mForegroundInfo == null) {
18606            mForegroundInfo = new ForegroundInfo();
18607        }
18608        if (mForegroundInfo.mTintInfo == null) {
18609            mForegroundInfo.mTintInfo = new TintInfo();
18610        }
18611        mForegroundInfo.mTintInfo.mTintList = tint;
18612        mForegroundInfo.mTintInfo.mHasTintList = true;
18613
18614        applyForegroundTint();
18615    }
18616
18617    /**
18618     * Return the tint applied to the foreground drawable, if specified.
18619     *
18620     * @return the tint applied to the foreground drawable
18621     * @attr ref android.R.styleable#View_foregroundTint
18622     * @see #setForegroundTintList(ColorStateList)
18623     */
18624    @Nullable
18625    public ColorStateList getForegroundTintList() {
18626        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18627                ? mForegroundInfo.mTintInfo.mTintList : null;
18628    }
18629
18630    /**
18631     * Specifies the blending mode used to apply the tint specified by
18632     * {@link #setForegroundTintList(ColorStateList)}} to the background
18633     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18634     *
18635     * @param tintMode the blending mode used to apply the tint, may be
18636     *                 {@code null} to clear tint
18637     * @attr ref android.R.styleable#View_foregroundTintMode
18638     * @see #getForegroundTintMode()
18639     * @see Drawable#setTintMode(PorterDuff.Mode)
18640     */
18641    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18642        if (mForegroundInfo == null) {
18643            mForegroundInfo = new ForegroundInfo();
18644        }
18645        if (mForegroundInfo.mTintInfo == null) {
18646            mForegroundInfo.mTintInfo = new TintInfo();
18647        }
18648        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18649        mForegroundInfo.mTintInfo.mHasTintMode = true;
18650
18651        applyForegroundTint();
18652    }
18653
18654    /**
18655     * Return the blending mode used to apply the tint to the foreground
18656     * drawable, if specified.
18657     *
18658     * @return the blending mode used to apply the tint to the foreground
18659     *         drawable
18660     * @attr ref android.R.styleable#View_foregroundTintMode
18661     * @see #setForegroundTintMode(PorterDuff.Mode)
18662     */
18663    @Nullable
18664    public PorterDuff.Mode getForegroundTintMode() {
18665        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18666                ? mForegroundInfo.mTintInfo.mTintMode : null;
18667    }
18668
18669    private void applyForegroundTint() {
18670        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18671                && mForegroundInfo.mTintInfo != null) {
18672            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18673            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18674                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18675
18676                if (tintInfo.mHasTintList) {
18677                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18678                }
18679
18680                if (tintInfo.mHasTintMode) {
18681                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18682                }
18683
18684                // The drawable (or one of its children) may not have been
18685                // stateful before applying the tint, so let's try again.
18686                if (mForegroundInfo.mDrawable.isStateful()) {
18687                    mForegroundInfo.mDrawable.setState(getDrawableState());
18688                }
18689            }
18690        }
18691    }
18692
18693    /**
18694     * Draw any foreground content for this view.
18695     *
18696     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18697     * drawable or other view-specific decorations. The foreground is drawn on top of the
18698     * primary view content.</p>
18699     *
18700     * @param canvas canvas to draw into
18701     */
18702    public void onDrawForeground(Canvas canvas) {
18703        onDrawScrollIndicators(canvas);
18704        onDrawScrollBars(canvas);
18705
18706        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18707        if (foreground != null) {
18708            if (mForegroundInfo.mBoundsChanged) {
18709                mForegroundInfo.mBoundsChanged = false;
18710                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18711                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18712
18713                if (mForegroundInfo.mInsidePadding) {
18714                    selfBounds.set(0, 0, getWidth(), getHeight());
18715                } else {
18716                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18717                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18718                }
18719
18720                final int ld = getLayoutDirection();
18721                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18722                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18723                foreground.setBounds(overlayBounds);
18724            }
18725
18726            foreground.draw(canvas);
18727        }
18728    }
18729
18730    /**
18731     * Sets the padding. The view may add on the space required to display
18732     * the scrollbars, depending on the style and visibility of the scrollbars.
18733     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18734     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18735     * from the values set in this call.
18736     *
18737     * @attr ref android.R.styleable#View_padding
18738     * @attr ref android.R.styleable#View_paddingBottom
18739     * @attr ref android.R.styleable#View_paddingLeft
18740     * @attr ref android.R.styleable#View_paddingRight
18741     * @attr ref android.R.styleable#View_paddingTop
18742     * @param left the left padding in pixels
18743     * @param top the top padding in pixels
18744     * @param right the right padding in pixels
18745     * @param bottom the bottom padding in pixels
18746     */
18747    public void setPadding(int left, int top, int right, int bottom) {
18748        resetResolvedPaddingInternal();
18749
18750        mUserPaddingStart = UNDEFINED_PADDING;
18751        mUserPaddingEnd = UNDEFINED_PADDING;
18752
18753        mUserPaddingLeftInitial = left;
18754        mUserPaddingRightInitial = right;
18755
18756        mLeftPaddingDefined = true;
18757        mRightPaddingDefined = true;
18758
18759        internalSetPadding(left, top, right, bottom);
18760    }
18761
18762    /**
18763     * @hide
18764     */
18765    protected void internalSetPadding(int left, int top, int right, int bottom) {
18766        mUserPaddingLeft = left;
18767        mUserPaddingRight = right;
18768        mUserPaddingBottom = bottom;
18769
18770        final int viewFlags = mViewFlags;
18771        boolean changed = false;
18772
18773        // Common case is there are no scroll bars.
18774        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18775            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18776                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18777                        ? 0 : getVerticalScrollbarWidth();
18778                switch (mVerticalScrollbarPosition) {
18779                    case SCROLLBAR_POSITION_DEFAULT:
18780                        if (isLayoutRtl()) {
18781                            left += offset;
18782                        } else {
18783                            right += offset;
18784                        }
18785                        break;
18786                    case SCROLLBAR_POSITION_RIGHT:
18787                        right += offset;
18788                        break;
18789                    case SCROLLBAR_POSITION_LEFT:
18790                        left += offset;
18791                        break;
18792                }
18793            }
18794            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18795                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18796                        ? 0 : getHorizontalScrollbarHeight();
18797            }
18798        }
18799
18800        if (mPaddingLeft != left) {
18801            changed = true;
18802            mPaddingLeft = left;
18803        }
18804        if (mPaddingTop != top) {
18805            changed = true;
18806            mPaddingTop = top;
18807        }
18808        if (mPaddingRight != right) {
18809            changed = true;
18810            mPaddingRight = right;
18811        }
18812        if (mPaddingBottom != bottom) {
18813            changed = true;
18814            mPaddingBottom = bottom;
18815        }
18816
18817        if (changed) {
18818            requestLayout();
18819            invalidateOutline();
18820        }
18821    }
18822
18823    /**
18824     * Sets the relative padding. The view may add on the space required to display
18825     * the scrollbars, depending on the style and visibility of the scrollbars.
18826     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18827     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18828     * from the values set in this call.
18829     *
18830     * @attr ref android.R.styleable#View_padding
18831     * @attr ref android.R.styleable#View_paddingBottom
18832     * @attr ref android.R.styleable#View_paddingStart
18833     * @attr ref android.R.styleable#View_paddingEnd
18834     * @attr ref android.R.styleable#View_paddingTop
18835     * @param start the start padding in pixels
18836     * @param top the top padding in pixels
18837     * @param end the end padding in pixels
18838     * @param bottom the bottom padding in pixels
18839     */
18840    public void setPaddingRelative(int start, int top, int end, int bottom) {
18841        resetResolvedPaddingInternal();
18842
18843        mUserPaddingStart = start;
18844        mUserPaddingEnd = end;
18845        mLeftPaddingDefined = true;
18846        mRightPaddingDefined = true;
18847
18848        switch(getLayoutDirection()) {
18849            case LAYOUT_DIRECTION_RTL:
18850                mUserPaddingLeftInitial = end;
18851                mUserPaddingRightInitial = start;
18852                internalSetPadding(end, top, start, bottom);
18853                break;
18854            case LAYOUT_DIRECTION_LTR:
18855            default:
18856                mUserPaddingLeftInitial = start;
18857                mUserPaddingRightInitial = end;
18858                internalSetPadding(start, top, end, bottom);
18859        }
18860    }
18861
18862    /**
18863     * Returns the top padding of this view.
18864     *
18865     * @return the top padding in pixels
18866     */
18867    public int getPaddingTop() {
18868        return mPaddingTop;
18869    }
18870
18871    /**
18872     * Returns the bottom padding of this view. If there are inset and enabled
18873     * scrollbars, this value may include the space required to display the
18874     * scrollbars as well.
18875     *
18876     * @return the bottom padding in pixels
18877     */
18878    public int getPaddingBottom() {
18879        return mPaddingBottom;
18880    }
18881
18882    /**
18883     * Returns the left padding of this view. If there are inset and enabled
18884     * scrollbars, this value may include the space required to display the
18885     * scrollbars as well.
18886     *
18887     * @return the left padding in pixels
18888     */
18889    public int getPaddingLeft() {
18890        if (!isPaddingResolved()) {
18891            resolvePadding();
18892        }
18893        return mPaddingLeft;
18894    }
18895
18896    /**
18897     * Returns the start padding of this view depending on its resolved layout direction.
18898     * If there are inset and enabled scrollbars, this value may include the space
18899     * required to display the scrollbars as well.
18900     *
18901     * @return the start padding in pixels
18902     */
18903    public int getPaddingStart() {
18904        if (!isPaddingResolved()) {
18905            resolvePadding();
18906        }
18907        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18908                mPaddingRight : mPaddingLeft;
18909    }
18910
18911    /**
18912     * Returns the right padding of this view. If there are inset and enabled
18913     * scrollbars, this value may include the space required to display the
18914     * scrollbars as well.
18915     *
18916     * @return the right padding in pixels
18917     */
18918    public int getPaddingRight() {
18919        if (!isPaddingResolved()) {
18920            resolvePadding();
18921        }
18922        return mPaddingRight;
18923    }
18924
18925    /**
18926     * Returns the end padding of this view depending on its resolved layout direction.
18927     * If there are inset and enabled scrollbars, this value may include the space
18928     * required to display the scrollbars as well.
18929     *
18930     * @return the end padding in pixels
18931     */
18932    public int getPaddingEnd() {
18933        if (!isPaddingResolved()) {
18934            resolvePadding();
18935        }
18936        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18937                mPaddingLeft : mPaddingRight;
18938    }
18939
18940    /**
18941     * Return if the padding has been set through relative values
18942     * {@link #setPaddingRelative(int, int, int, int)} or through
18943     * @attr ref android.R.styleable#View_paddingStart or
18944     * @attr ref android.R.styleable#View_paddingEnd
18945     *
18946     * @return true if the padding is relative or false if it is not.
18947     */
18948    public boolean isPaddingRelative() {
18949        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18950    }
18951
18952    Insets computeOpticalInsets() {
18953        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18954    }
18955
18956    /**
18957     * @hide
18958     */
18959    public void resetPaddingToInitialValues() {
18960        if (isRtlCompatibilityMode()) {
18961            mPaddingLeft = mUserPaddingLeftInitial;
18962            mPaddingRight = mUserPaddingRightInitial;
18963            return;
18964        }
18965        if (isLayoutRtl()) {
18966            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18967            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18968        } else {
18969            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18970            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18971        }
18972    }
18973
18974    /**
18975     * @hide
18976     */
18977    public Insets getOpticalInsets() {
18978        if (mLayoutInsets == null) {
18979            mLayoutInsets = computeOpticalInsets();
18980        }
18981        return mLayoutInsets;
18982    }
18983
18984    /**
18985     * Set this view's optical insets.
18986     *
18987     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18988     * property. Views that compute their own optical insets should call it as part of measurement.
18989     * This method does not request layout. If you are setting optical insets outside of
18990     * measure/layout itself you will want to call requestLayout() yourself.
18991     * </p>
18992     * @hide
18993     */
18994    public void setOpticalInsets(Insets insets) {
18995        mLayoutInsets = insets;
18996    }
18997
18998    /**
18999     * Changes the selection state of this view. A view can be selected or not.
19000     * Note that selection is not the same as focus. Views are typically
19001     * selected in the context of an AdapterView like ListView or GridView;
19002     * the selected view is the view that is highlighted.
19003     *
19004     * @param selected true if the view must be selected, false otherwise
19005     */
19006    public void setSelected(boolean selected) {
19007        //noinspection DoubleNegation
19008        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19009            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19010            if (!selected) resetPressedState();
19011            invalidate(true);
19012            refreshDrawableState();
19013            dispatchSetSelected(selected);
19014            if (selected) {
19015                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19016            } else {
19017                notifyViewAccessibilityStateChangedIfNeeded(
19018                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19019            }
19020        }
19021    }
19022
19023    /**
19024     * Dispatch setSelected to all of this View's children.
19025     *
19026     * @see #setSelected(boolean)
19027     *
19028     * @param selected The new selected state
19029     */
19030    protected void dispatchSetSelected(boolean selected) {
19031    }
19032
19033    /**
19034     * Indicates the selection state of this view.
19035     *
19036     * @return true if the view is selected, false otherwise
19037     */
19038    @ViewDebug.ExportedProperty
19039    public boolean isSelected() {
19040        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19041    }
19042
19043    /**
19044     * Changes the activated state of this view. A view can be activated or not.
19045     * Note that activation is not the same as selection.  Selection is
19046     * a transient property, representing the view (hierarchy) the user is
19047     * currently interacting with.  Activation is a longer-term state that the
19048     * user can move views in and out of.  For example, in a list view with
19049     * single or multiple selection enabled, the views in the current selection
19050     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19051     * here.)  The activated state is propagated down to children of the view it
19052     * is set on.
19053     *
19054     * @param activated true if the view must be activated, false otherwise
19055     */
19056    public void setActivated(boolean activated) {
19057        //noinspection DoubleNegation
19058        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19059            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19060            invalidate(true);
19061            refreshDrawableState();
19062            dispatchSetActivated(activated);
19063        }
19064    }
19065
19066    /**
19067     * Dispatch setActivated to all of this View's children.
19068     *
19069     * @see #setActivated(boolean)
19070     *
19071     * @param activated The new activated state
19072     */
19073    protected void dispatchSetActivated(boolean activated) {
19074    }
19075
19076    /**
19077     * Indicates the activation state of this view.
19078     *
19079     * @return true if the view is activated, false otherwise
19080     */
19081    @ViewDebug.ExportedProperty
19082    public boolean isActivated() {
19083        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19084    }
19085
19086    /**
19087     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19088     * observer can be used to get notifications when global events, like
19089     * layout, happen.
19090     *
19091     * The returned ViewTreeObserver observer is not guaranteed to remain
19092     * valid for the lifetime of this View. If the caller of this method keeps
19093     * a long-lived reference to ViewTreeObserver, it should always check for
19094     * the return value of {@link ViewTreeObserver#isAlive()}.
19095     *
19096     * @return The ViewTreeObserver for this view's hierarchy.
19097     */
19098    public ViewTreeObserver getViewTreeObserver() {
19099        if (mAttachInfo != null) {
19100            return mAttachInfo.mTreeObserver;
19101        }
19102        if (mFloatingTreeObserver == null) {
19103            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19104        }
19105        return mFloatingTreeObserver;
19106    }
19107
19108    /**
19109     * <p>Finds the topmost view in the current view hierarchy.</p>
19110     *
19111     * @return the topmost view containing this view
19112     */
19113    public View getRootView() {
19114        if (mAttachInfo != null) {
19115            final View v = mAttachInfo.mRootView;
19116            if (v != null) {
19117                return v;
19118            }
19119        }
19120
19121        View parent = this;
19122
19123        while (parent.mParent != null && parent.mParent instanceof View) {
19124            parent = (View) parent.mParent;
19125        }
19126
19127        return parent;
19128    }
19129
19130    /**
19131     * Transforms a motion event from view-local coordinates to on-screen
19132     * coordinates.
19133     *
19134     * @param ev the view-local motion event
19135     * @return false if the transformation could not be applied
19136     * @hide
19137     */
19138    public boolean toGlobalMotionEvent(MotionEvent ev) {
19139        final AttachInfo info = mAttachInfo;
19140        if (info == null) {
19141            return false;
19142        }
19143
19144        final Matrix m = info.mTmpMatrix;
19145        m.set(Matrix.IDENTITY_MATRIX);
19146        transformMatrixToGlobal(m);
19147        ev.transform(m);
19148        return true;
19149    }
19150
19151    /**
19152     * Transforms a motion event from on-screen coordinates to view-local
19153     * coordinates.
19154     *
19155     * @param ev the on-screen motion event
19156     * @return false if the transformation could not be applied
19157     * @hide
19158     */
19159    public boolean toLocalMotionEvent(MotionEvent ev) {
19160        final AttachInfo info = mAttachInfo;
19161        if (info == null) {
19162            return false;
19163        }
19164
19165        final Matrix m = info.mTmpMatrix;
19166        m.set(Matrix.IDENTITY_MATRIX);
19167        transformMatrixToLocal(m);
19168        ev.transform(m);
19169        return true;
19170    }
19171
19172    /**
19173     * Modifies the input matrix such that it maps view-local coordinates to
19174     * on-screen coordinates.
19175     *
19176     * @param m input matrix to modify
19177     * @hide
19178     */
19179    public void transformMatrixToGlobal(Matrix m) {
19180        final ViewParent parent = mParent;
19181        if (parent instanceof View) {
19182            final View vp = (View) parent;
19183            vp.transformMatrixToGlobal(m);
19184            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19185        } else if (parent instanceof ViewRootImpl) {
19186            final ViewRootImpl vr = (ViewRootImpl) parent;
19187            vr.transformMatrixToGlobal(m);
19188            m.preTranslate(0, -vr.mCurScrollY);
19189        }
19190
19191        m.preTranslate(mLeft, mTop);
19192
19193        if (!hasIdentityMatrix()) {
19194            m.preConcat(getMatrix());
19195        }
19196    }
19197
19198    /**
19199     * Modifies the input matrix such that it maps on-screen coordinates to
19200     * view-local coordinates.
19201     *
19202     * @param m input matrix to modify
19203     * @hide
19204     */
19205    public void transformMatrixToLocal(Matrix m) {
19206        final ViewParent parent = mParent;
19207        if (parent instanceof View) {
19208            final View vp = (View) parent;
19209            vp.transformMatrixToLocal(m);
19210            m.postTranslate(vp.mScrollX, vp.mScrollY);
19211        } else if (parent instanceof ViewRootImpl) {
19212            final ViewRootImpl vr = (ViewRootImpl) parent;
19213            vr.transformMatrixToLocal(m);
19214            m.postTranslate(0, vr.mCurScrollY);
19215        }
19216
19217        m.postTranslate(-mLeft, -mTop);
19218
19219        if (!hasIdentityMatrix()) {
19220            m.postConcat(getInverseMatrix());
19221        }
19222    }
19223
19224    /**
19225     * @hide
19226     */
19227    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19228            @ViewDebug.IntToString(from = 0, to = "x"),
19229            @ViewDebug.IntToString(from = 1, to = "y")
19230    })
19231    public int[] getLocationOnScreen() {
19232        int[] location = new int[2];
19233        getLocationOnScreen(location);
19234        return location;
19235    }
19236
19237    /**
19238     * <p>Computes the coordinates of this view on the screen. The argument
19239     * must be an array of two integers. After the method returns, the array
19240     * contains the x and y location in that order.</p>
19241     *
19242     * @param outLocation an array of two integers in which to hold the coordinates
19243     */
19244    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19245        getLocationInWindow(outLocation);
19246
19247        final AttachInfo info = mAttachInfo;
19248        if (info != null) {
19249            outLocation[0] += info.mWindowLeft;
19250            outLocation[1] += info.mWindowTop;
19251        }
19252    }
19253
19254    /**
19255     * <p>Computes the coordinates of this view in its window. The argument
19256     * must be an array of two integers. After the method returns, the array
19257     * contains the x and y location in that order.</p>
19258     *
19259     * @param outLocation an array of two integers in which to hold the coordinates
19260     */
19261    public void getLocationInWindow(@Size(2) int[] outLocation) {
19262        if (outLocation == null || outLocation.length < 2) {
19263            throw new IllegalArgumentException("outLocation must be an array of two integers");
19264        }
19265
19266        outLocation[0] = 0;
19267        outLocation[1] = 0;
19268
19269        transformFromViewToWindowSpace(outLocation);
19270    }
19271
19272    /** @hide */
19273    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19274        if (inOutLocation == null || inOutLocation.length < 2) {
19275            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19276        }
19277
19278        if (mAttachInfo == null) {
19279            // When the view is not attached to a window, this method does not make sense
19280            inOutLocation[0] = inOutLocation[1] = 0;
19281            return;
19282        }
19283
19284        float position[] = mAttachInfo.mTmpTransformLocation;
19285        position[0] = inOutLocation[0];
19286        position[1] = inOutLocation[1];
19287
19288        if (!hasIdentityMatrix()) {
19289            getMatrix().mapPoints(position);
19290        }
19291
19292        position[0] += mLeft;
19293        position[1] += mTop;
19294
19295        ViewParent viewParent = mParent;
19296        while (viewParent instanceof View) {
19297            final View view = (View) viewParent;
19298
19299            position[0] -= view.mScrollX;
19300            position[1] -= view.mScrollY;
19301
19302            if (!view.hasIdentityMatrix()) {
19303                view.getMatrix().mapPoints(position);
19304            }
19305
19306            position[0] += view.mLeft;
19307            position[1] += view.mTop;
19308
19309            viewParent = view.mParent;
19310         }
19311
19312        if (viewParent instanceof ViewRootImpl) {
19313            // *cough*
19314            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19315            position[1] -= vr.mCurScrollY;
19316        }
19317
19318        inOutLocation[0] = Math.round(position[0]);
19319        inOutLocation[1] = Math.round(position[1]);
19320    }
19321
19322    /**
19323     * {@hide}
19324     * @param id the id of the view to be found
19325     * @return the view of the specified id, null if cannot be found
19326     */
19327    protected View findViewTraversal(@IdRes int id) {
19328        if (id == mID) {
19329            return this;
19330        }
19331        return null;
19332    }
19333
19334    /**
19335     * {@hide}
19336     * @param tag the tag of the view to be found
19337     * @return the view of specified tag, null if cannot be found
19338     */
19339    protected View findViewWithTagTraversal(Object tag) {
19340        if (tag != null && tag.equals(mTag)) {
19341            return this;
19342        }
19343        return null;
19344    }
19345
19346    /**
19347     * {@hide}
19348     * @param predicate The predicate to evaluate.
19349     * @param childToSkip If not null, ignores this child during the recursive traversal.
19350     * @return The first view that matches the predicate or null.
19351     */
19352    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19353        if (predicate.apply(this)) {
19354            return this;
19355        }
19356        return null;
19357    }
19358
19359    /**
19360     * Look for a child view with the given id.  If this view has the given
19361     * id, return this view.
19362     *
19363     * @param id The id to search for.
19364     * @return The view that has the given id in the hierarchy or null
19365     */
19366    @Nullable
19367    public final View findViewById(@IdRes int id) {
19368        if (id < 0) {
19369            return null;
19370        }
19371        return findViewTraversal(id);
19372    }
19373
19374    /**
19375     * Finds a view by its unuque and stable accessibility id.
19376     *
19377     * @param accessibilityId The searched accessibility id.
19378     * @return The found view.
19379     */
19380    final View findViewByAccessibilityId(int accessibilityId) {
19381        if (accessibilityId < 0) {
19382            return null;
19383        }
19384        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19385        if (view != null) {
19386            return view.includeForAccessibility() ? view : null;
19387        }
19388        return null;
19389    }
19390
19391    /**
19392     * Performs the traversal to find a view by its unuque and stable accessibility id.
19393     *
19394     * <strong>Note:</strong>This method does not stop at the root namespace
19395     * boundary since the user can touch the screen at an arbitrary location
19396     * potentially crossing the root namespace bounday which will send an
19397     * accessibility event to accessibility services and they should be able
19398     * to obtain the event source. Also accessibility ids are guaranteed to be
19399     * unique in the window.
19400     *
19401     * @param accessibilityId The accessibility id.
19402     * @return The found view.
19403     *
19404     * @hide
19405     */
19406    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19407        if (getAccessibilityViewId() == accessibilityId) {
19408            return this;
19409        }
19410        return null;
19411    }
19412
19413    /**
19414     * Look for a child view with the given tag.  If this view has the given
19415     * tag, return this view.
19416     *
19417     * @param tag The tag to search for, using "tag.equals(getTag())".
19418     * @return The View that has the given tag in the hierarchy or null
19419     */
19420    public final View findViewWithTag(Object tag) {
19421        if (tag == null) {
19422            return null;
19423        }
19424        return findViewWithTagTraversal(tag);
19425    }
19426
19427    /**
19428     * {@hide}
19429     * Look for a child view that matches the specified predicate.
19430     * If this view matches the predicate, return this view.
19431     *
19432     * @param predicate The predicate to evaluate.
19433     * @return The first view that matches the predicate or null.
19434     */
19435    public final View findViewByPredicate(Predicate<View> predicate) {
19436        return findViewByPredicateTraversal(predicate, null);
19437    }
19438
19439    /**
19440     * {@hide}
19441     * Look for a child view that matches the specified predicate,
19442     * starting with the specified view and its descendents and then
19443     * recusively searching the ancestors and siblings of that view
19444     * until this view is reached.
19445     *
19446     * This method is useful in cases where the predicate does not match
19447     * a single unique view (perhaps multiple views use the same id)
19448     * and we are trying to find the view that is "closest" in scope to the
19449     * starting view.
19450     *
19451     * @param start The view to start from.
19452     * @param predicate The predicate to evaluate.
19453     * @return The first view that matches the predicate or null.
19454     */
19455    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19456        View childToSkip = null;
19457        for (;;) {
19458            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19459            if (view != null || start == this) {
19460                return view;
19461            }
19462
19463            ViewParent parent = start.getParent();
19464            if (parent == null || !(parent instanceof View)) {
19465                return null;
19466            }
19467
19468            childToSkip = start;
19469            start = (View) parent;
19470        }
19471    }
19472
19473    /**
19474     * Sets the identifier for this view. The identifier does not have to be
19475     * unique in this view's hierarchy. The identifier should be a positive
19476     * number.
19477     *
19478     * @see #NO_ID
19479     * @see #getId()
19480     * @see #findViewById(int)
19481     *
19482     * @param id a number used to identify the view
19483     *
19484     * @attr ref android.R.styleable#View_id
19485     */
19486    public void setId(@IdRes int id) {
19487        mID = id;
19488        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19489            mID = generateViewId();
19490        }
19491    }
19492
19493    /**
19494     * {@hide}
19495     *
19496     * @param isRoot true if the view belongs to the root namespace, false
19497     *        otherwise
19498     */
19499    public void setIsRootNamespace(boolean isRoot) {
19500        if (isRoot) {
19501            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19502        } else {
19503            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19504        }
19505    }
19506
19507    /**
19508     * {@hide}
19509     *
19510     * @return true if the view belongs to the root namespace, false otherwise
19511     */
19512    public boolean isRootNamespace() {
19513        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19514    }
19515
19516    /**
19517     * Returns this view's identifier.
19518     *
19519     * @return a positive integer used to identify the view or {@link #NO_ID}
19520     *         if the view has no ID
19521     *
19522     * @see #setId(int)
19523     * @see #findViewById(int)
19524     * @attr ref android.R.styleable#View_id
19525     */
19526    @IdRes
19527    @ViewDebug.CapturedViewProperty
19528    public int getId() {
19529        return mID;
19530    }
19531
19532    /**
19533     * Returns this view's tag.
19534     *
19535     * @return the Object stored in this view as a tag, or {@code null} if not
19536     *         set
19537     *
19538     * @see #setTag(Object)
19539     * @see #getTag(int)
19540     */
19541    @ViewDebug.ExportedProperty
19542    public Object getTag() {
19543        return mTag;
19544    }
19545
19546    /**
19547     * Sets the tag associated with this view. A tag can be used to mark
19548     * a view in its hierarchy and does not have to be unique within the
19549     * hierarchy. Tags can also be used to store data within a view without
19550     * resorting to another data structure.
19551     *
19552     * @param tag an Object to tag the view with
19553     *
19554     * @see #getTag()
19555     * @see #setTag(int, Object)
19556     */
19557    public void setTag(final Object tag) {
19558        mTag = tag;
19559    }
19560
19561    /**
19562     * Returns the tag associated with this view and the specified key.
19563     *
19564     * @param key The key identifying the tag
19565     *
19566     * @return the Object stored in this view as a tag, or {@code null} if not
19567     *         set
19568     *
19569     * @see #setTag(int, Object)
19570     * @see #getTag()
19571     */
19572    public Object getTag(int key) {
19573        if (mKeyedTags != null) return mKeyedTags.get(key);
19574        return null;
19575    }
19576
19577    /**
19578     * Sets a tag associated with this view and a key. A tag can be used
19579     * to mark a view in its hierarchy and does not have to be unique within
19580     * the hierarchy. Tags can also be used to store data within a view
19581     * without resorting to another data structure.
19582     *
19583     * The specified key should be an id declared in the resources of the
19584     * application to ensure it is unique (see the <a
19585     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19586     * Keys identified as belonging to
19587     * the Android framework or not associated with any package will cause
19588     * an {@link IllegalArgumentException} to be thrown.
19589     *
19590     * @param key The key identifying the tag
19591     * @param tag An Object to tag the view with
19592     *
19593     * @throws IllegalArgumentException If they specified key is not valid
19594     *
19595     * @see #setTag(Object)
19596     * @see #getTag(int)
19597     */
19598    public void setTag(int key, final Object tag) {
19599        // If the package id is 0x00 or 0x01, it's either an undefined package
19600        // or a framework id
19601        if ((key >>> 24) < 2) {
19602            throw new IllegalArgumentException("The key must be an application-specific "
19603                    + "resource id.");
19604        }
19605
19606        setKeyedTag(key, tag);
19607    }
19608
19609    /**
19610     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19611     * framework id.
19612     *
19613     * @hide
19614     */
19615    public void setTagInternal(int key, Object tag) {
19616        if ((key >>> 24) != 0x1) {
19617            throw new IllegalArgumentException("The key must be a framework-specific "
19618                    + "resource id.");
19619        }
19620
19621        setKeyedTag(key, tag);
19622    }
19623
19624    private void setKeyedTag(int key, Object tag) {
19625        if (mKeyedTags == null) {
19626            mKeyedTags = new SparseArray<Object>(2);
19627        }
19628
19629        mKeyedTags.put(key, tag);
19630    }
19631
19632    /**
19633     * Prints information about this view in the log output, with the tag
19634     * {@link #VIEW_LOG_TAG}.
19635     *
19636     * @hide
19637     */
19638    public void debug() {
19639        debug(0);
19640    }
19641
19642    /**
19643     * Prints information about this view in the log output, with the tag
19644     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19645     * indentation defined by the <code>depth</code>.
19646     *
19647     * @param depth the indentation level
19648     *
19649     * @hide
19650     */
19651    protected void debug(int depth) {
19652        String output = debugIndent(depth - 1);
19653
19654        output += "+ " + this;
19655        int id = getId();
19656        if (id != -1) {
19657            output += " (id=" + id + ")";
19658        }
19659        Object tag = getTag();
19660        if (tag != null) {
19661            output += " (tag=" + tag + ")";
19662        }
19663        Log.d(VIEW_LOG_TAG, output);
19664
19665        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19666            output = debugIndent(depth) + " FOCUSED";
19667            Log.d(VIEW_LOG_TAG, output);
19668        }
19669
19670        output = debugIndent(depth);
19671        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19672                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19673                + "} ";
19674        Log.d(VIEW_LOG_TAG, output);
19675
19676        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19677                || mPaddingBottom != 0) {
19678            output = debugIndent(depth);
19679            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19680                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19681            Log.d(VIEW_LOG_TAG, output);
19682        }
19683
19684        output = debugIndent(depth);
19685        output += "mMeasureWidth=" + mMeasuredWidth +
19686                " mMeasureHeight=" + mMeasuredHeight;
19687        Log.d(VIEW_LOG_TAG, output);
19688
19689        output = debugIndent(depth);
19690        if (mLayoutParams == null) {
19691            output += "BAD! no layout params";
19692        } else {
19693            output = mLayoutParams.debug(output);
19694        }
19695        Log.d(VIEW_LOG_TAG, output);
19696
19697        output = debugIndent(depth);
19698        output += "flags={";
19699        output += View.printFlags(mViewFlags);
19700        output += "}";
19701        Log.d(VIEW_LOG_TAG, output);
19702
19703        output = debugIndent(depth);
19704        output += "privateFlags={";
19705        output += View.printPrivateFlags(mPrivateFlags);
19706        output += "}";
19707        Log.d(VIEW_LOG_TAG, output);
19708    }
19709
19710    /**
19711     * Creates a string of whitespaces used for indentation.
19712     *
19713     * @param depth the indentation level
19714     * @return a String containing (depth * 2 + 3) * 2 white spaces
19715     *
19716     * @hide
19717     */
19718    protected static String debugIndent(int depth) {
19719        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19720        for (int i = 0; i < (depth * 2) + 3; i++) {
19721            spaces.append(' ').append(' ');
19722        }
19723        return spaces.toString();
19724    }
19725
19726    /**
19727     * <p>Return the offset of the widget's text baseline from the widget's top
19728     * boundary. If this widget does not support baseline alignment, this
19729     * method returns -1. </p>
19730     *
19731     * @return the offset of the baseline within the widget's bounds or -1
19732     *         if baseline alignment is not supported
19733     */
19734    @ViewDebug.ExportedProperty(category = "layout")
19735    public int getBaseline() {
19736        return -1;
19737    }
19738
19739    /**
19740     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19741     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19742     * a layout pass.
19743     *
19744     * @return whether the view hierarchy is currently undergoing a layout pass
19745     */
19746    public boolean isInLayout() {
19747        ViewRootImpl viewRoot = getViewRootImpl();
19748        return (viewRoot != null && viewRoot.isInLayout());
19749    }
19750
19751    /**
19752     * Call this when something has changed which has invalidated the
19753     * layout of this view. This will schedule a layout pass of the view
19754     * tree. This should not be called while the view hierarchy is currently in a layout
19755     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19756     * end of the current layout pass (and then layout will run again) or after the current
19757     * frame is drawn and the next layout occurs.
19758     *
19759     * <p>Subclasses which override this method should call the superclass method to
19760     * handle possible request-during-layout errors correctly.</p>
19761     */
19762    @CallSuper
19763    public void requestLayout() {
19764        if (mMeasureCache != null) mMeasureCache.clear();
19765
19766        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19767            // Only trigger request-during-layout logic if this is the view requesting it,
19768            // not the views in its parent hierarchy
19769            ViewRootImpl viewRoot = getViewRootImpl();
19770            if (viewRoot != null && viewRoot.isInLayout()) {
19771                if (!viewRoot.requestLayoutDuringLayout(this)) {
19772                    return;
19773                }
19774            }
19775            mAttachInfo.mViewRequestingLayout = this;
19776        }
19777
19778        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19779        mPrivateFlags |= PFLAG_INVALIDATED;
19780
19781        if (mParent != null && !mParent.isLayoutRequested()) {
19782            mParent.requestLayout();
19783        }
19784        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19785            mAttachInfo.mViewRequestingLayout = null;
19786        }
19787    }
19788
19789    /**
19790     * Forces this view to be laid out during the next layout pass.
19791     * This method does not call requestLayout() or forceLayout()
19792     * on the parent.
19793     */
19794    public void forceLayout() {
19795        if (mMeasureCache != null) mMeasureCache.clear();
19796
19797        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19798        mPrivateFlags |= PFLAG_INVALIDATED;
19799    }
19800
19801    /**
19802     * <p>
19803     * This is called to find out how big a view should be. The parent
19804     * supplies constraint information in the width and height parameters.
19805     * </p>
19806     *
19807     * <p>
19808     * The actual measurement work of a view is performed in
19809     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19810     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19811     * </p>
19812     *
19813     *
19814     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19815     *        parent
19816     * @param heightMeasureSpec Vertical space requirements as imposed by the
19817     *        parent
19818     *
19819     * @see #onMeasure(int, int)
19820     */
19821    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19822        boolean optical = isLayoutModeOptical(this);
19823        if (optical != isLayoutModeOptical(mParent)) {
19824            Insets insets = getOpticalInsets();
19825            int oWidth  = insets.left + insets.right;
19826            int oHeight = insets.top  + insets.bottom;
19827            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19828            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19829        }
19830
19831        // Suppress sign extension for the low bytes
19832        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19833        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19834
19835        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19836
19837        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19838        // already measured as the correct size. In API 23 and below, this
19839        // extra pass is required to make LinearLayout re-distribute weight.
19840        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19841                || heightMeasureSpec != mOldHeightMeasureSpec;
19842        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19843                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19844        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19845                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19846        final boolean needsLayout = specChanged
19847                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19848
19849        if (forceLayout || needsLayout) {
19850            // first clears the measured dimension flag
19851            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19852
19853            resolveRtlPropertiesIfNeeded();
19854
19855            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19856            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19857                // measure ourselves, this should set the measured dimension flag back
19858                onMeasure(widthMeasureSpec, heightMeasureSpec);
19859                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19860            } else {
19861                long value = mMeasureCache.valueAt(cacheIndex);
19862                // Casting a long to int drops the high 32 bits, no mask needed
19863                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19864                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19865            }
19866
19867            // flag not set, setMeasuredDimension() was not invoked, we raise
19868            // an exception to warn the developer
19869            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19870                throw new IllegalStateException("View with id " + getId() + ": "
19871                        + getClass().getName() + "#onMeasure() did not set the"
19872                        + " measured dimension by calling"
19873                        + " setMeasuredDimension()");
19874            }
19875
19876            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19877        }
19878
19879        mOldWidthMeasureSpec = widthMeasureSpec;
19880        mOldHeightMeasureSpec = heightMeasureSpec;
19881
19882        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19883                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19884    }
19885
19886    /**
19887     * <p>
19888     * Measure the view and its content to determine the measured width and the
19889     * measured height. This method is invoked by {@link #measure(int, int)} and
19890     * should be overridden by subclasses to provide accurate and efficient
19891     * measurement of their contents.
19892     * </p>
19893     *
19894     * <p>
19895     * <strong>CONTRACT:</strong> When overriding this method, you
19896     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19897     * measured width and height of this view. Failure to do so will trigger an
19898     * <code>IllegalStateException</code>, thrown by
19899     * {@link #measure(int, int)}. Calling the superclass'
19900     * {@link #onMeasure(int, int)} is a valid use.
19901     * </p>
19902     *
19903     * <p>
19904     * The base class implementation of measure defaults to the background size,
19905     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19906     * override {@link #onMeasure(int, int)} to provide better measurements of
19907     * their content.
19908     * </p>
19909     *
19910     * <p>
19911     * If this method is overridden, it is the subclass's responsibility to make
19912     * sure the measured height and width are at least the view's minimum height
19913     * and width ({@link #getSuggestedMinimumHeight()} and
19914     * {@link #getSuggestedMinimumWidth()}).
19915     * </p>
19916     *
19917     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19918     *                         The requirements are encoded with
19919     *                         {@link android.view.View.MeasureSpec}.
19920     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19921     *                         The requirements are encoded with
19922     *                         {@link android.view.View.MeasureSpec}.
19923     *
19924     * @see #getMeasuredWidth()
19925     * @see #getMeasuredHeight()
19926     * @see #setMeasuredDimension(int, int)
19927     * @see #getSuggestedMinimumHeight()
19928     * @see #getSuggestedMinimumWidth()
19929     * @see android.view.View.MeasureSpec#getMode(int)
19930     * @see android.view.View.MeasureSpec#getSize(int)
19931     */
19932    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19933        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19934                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19935    }
19936
19937    /**
19938     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19939     * measured width and measured height. Failing to do so will trigger an
19940     * exception at measurement time.</p>
19941     *
19942     * @param measuredWidth The measured width of this view.  May be a complex
19943     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19944     * {@link #MEASURED_STATE_TOO_SMALL}.
19945     * @param measuredHeight The measured height of this view.  May be a complex
19946     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19947     * {@link #MEASURED_STATE_TOO_SMALL}.
19948     */
19949    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19950        boolean optical = isLayoutModeOptical(this);
19951        if (optical != isLayoutModeOptical(mParent)) {
19952            Insets insets = getOpticalInsets();
19953            int opticalWidth  = insets.left + insets.right;
19954            int opticalHeight = insets.top  + insets.bottom;
19955
19956            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19957            measuredHeight += optical ? opticalHeight : -opticalHeight;
19958        }
19959        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19960    }
19961
19962    /**
19963     * Sets the measured dimension without extra processing for things like optical bounds.
19964     * Useful for reapplying consistent values that have already been cooked with adjustments
19965     * for optical bounds, etc. such as those from the measurement cache.
19966     *
19967     * @param measuredWidth The measured width of this view.  May be a complex
19968     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19969     * {@link #MEASURED_STATE_TOO_SMALL}.
19970     * @param measuredHeight The measured height of this view.  May be a complex
19971     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19972     * {@link #MEASURED_STATE_TOO_SMALL}.
19973     */
19974    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19975        mMeasuredWidth = measuredWidth;
19976        mMeasuredHeight = measuredHeight;
19977
19978        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19979    }
19980
19981    /**
19982     * Merge two states as returned by {@link #getMeasuredState()}.
19983     * @param curState The current state as returned from a view or the result
19984     * of combining multiple views.
19985     * @param newState The new view state to combine.
19986     * @return Returns a new integer reflecting the combination of the two
19987     * states.
19988     */
19989    public static int combineMeasuredStates(int curState, int newState) {
19990        return curState | newState;
19991    }
19992
19993    /**
19994     * Version of {@link #resolveSizeAndState(int, int, int)}
19995     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19996     */
19997    public static int resolveSize(int size, int measureSpec) {
19998        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19999    }
20000
20001    /**
20002     * Utility to reconcile a desired size and state, with constraints imposed
20003     * by a MeasureSpec. Will take the desired size, unless a different size
20004     * is imposed by the constraints. The returned value is a compound integer,
20005     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20006     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20007     * resulting size is smaller than the size the view wants to be.
20008     *
20009     * @param size How big the view wants to be.
20010     * @param measureSpec Constraints imposed by the parent.
20011     * @param childMeasuredState Size information bit mask for the view's
20012     *                           children.
20013     * @return Size information bit mask as defined by
20014     *         {@link #MEASURED_SIZE_MASK} and
20015     *         {@link #MEASURED_STATE_TOO_SMALL}.
20016     */
20017    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20018        final int specMode = MeasureSpec.getMode(measureSpec);
20019        final int specSize = MeasureSpec.getSize(measureSpec);
20020        final int result;
20021        switch (specMode) {
20022            case MeasureSpec.AT_MOST:
20023                if (specSize < size) {
20024                    result = specSize | MEASURED_STATE_TOO_SMALL;
20025                } else {
20026                    result = size;
20027                }
20028                break;
20029            case MeasureSpec.EXACTLY:
20030                result = specSize;
20031                break;
20032            case MeasureSpec.UNSPECIFIED:
20033            default:
20034                result = size;
20035        }
20036        return result | (childMeasuredState & MEASURED_STATE_MASK);
20037    }
20038
20039    /**
20040     * Utility to return a default size. Uses the supplied size if the
20041     * MeasureSpec imposed no constraints. Will get larger if allowed
20042     * by the MeasureSpec.
20043     *
20044     * @param size Default size for this view
20045     * @param measureSpec Constraints imposed by the parent
20046     * @return The size this view should be.
20047     */
20048    public static int getDefaultSize(int size, int measureSpec) {
20049        int result = size;
20050        int specMode = MeasureSpec.getMode(measureSpec);
20051        int specSize = MeasureSpec.getSize(measureSpec);
20052
20053        switch (specMode) {
20054        case MeasureSpec.UNSPECIFIED:
20055            result = size;
20056            break;
20057        case MeasureSpec.AT_MOST:
20058        case MeasureSpec.EXACTLY:
20059            result = specSize;
20060            break;
20061        }
20062        return result;
20063    }
20064
20065    /**
20066     * Returns the suggested minimum height that the view should use. This
20067     * returns the maximum of the view's minimum height
20068     * and the background's minimum height
20069     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20070     * <p>
20071     * When being used in {@link #onMeasure(int, int)}, the caller should still
20072     * ensure the returned height is within the requirements of the parent.
20073     *
20074     * @return The suggested minimum height of the view.
20075     */
20076    protected int getSuggestedMinimumHeight() {
20077        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20078
20079    }
20080
20081    /**
20082     * Returns the suggested minimum width that the view should use. This
20083     * returns the maximum of the view's minimum width
20084     * and the background's minimum width
20085     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20086     * <p>
20087     * When being used in {@link #onMeasure(int, int)}, the caller should still
20088     * ensure the returned width is within the requirements of the parent.
20089     *
20090     * @return The suggested minimum width of the view.
20091     */
20092    protected int getSuggestedMinimumWidth() {
20093        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20094    }
20095
20096    /**
20097     * Returns the minimum height of the view.
20098     *
20099     * @return the minimum height the view will try to be, in pixels
20100     *
20101     * @see #setMinimumHeight(int)
20102     *
20103     * @attr ref android.R.styleable#View_minHeight
20104     */
20105    public int getMinimumHeight() {
20106        return mMinHeight;
20107    }
20108
20109    /**
20110     * Sets the minimum height of the view. It is not guaranteed the view will
20111     * be able to achieve this minimum height (for example, if its parent layout
20112     * constrains it with less available height).
20113     *
20114     * @param minHeight The minimum height the view will try to be, in pixels
20115     *
20116     * @see #getMinimumHeight()
20117     *
20118     * @attr ref android.R.styleable#View_minHeight
20119     */
20120    @RemotableViewMethod
20121    public void setMinimumHeight(int minHeight) {
20122        mMinHeight = minHeight;
20123        requestLayout();
20124    }
20125
20126    /**
20127     * Returns the minimum width of the view.
20128     *
20129     * @return the minimum width the view will try to be, in pixels
20130     *
20131     * @see #setMinimumWidth(int)
20132     *
20133     * @attr ref android.R.styleable#View_minWidth
20134     */
20135    public int getMinimumWidth() {
20136        return mMinWidth;
20137    }
20138
20139    /**
20140     * Sets the minimum width of the view. It is not guaranteed the view will
20141     * be able to achieve this minimum width (for example, if its parent layout
20142     * constrains it with less available width).
20143     *
20144     * @param minWidth The minimum width the view will try to be, in pixels
20145     *
20146     * @see #getMinimumWidth()
20147     *
20148     * @attr ref android.R.styleable#View_minWidth
20149     */
20150    public void setMinimumWidth(int minWidth) {
20151        mMinWidth = minWidth;
20152        requestLayout();
20153
20154    }
20155
20156    /**
20157     * Get the animation currently associated with this view.
20158     *
20159     * @return The animation that is currently playing or
20160     *         scheduled to play for this view.
20161     */
20162    public Animation getAnimation() {
20163        return mCurrentAnimation;
20164    }
20165
20166    /**
20167     * Start the specified animation now.
20168     *
20169     * @param animation the animation to start now
20170     */
20171    public void startAnimation(Animation animation) {
20172        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20173        setAnimation(animation);
20174        invalidateParentCaches();
20175        invalidate(true);
20176    }
20177
20178    /**
20179     * Cancels any animations for this view.
20180     */
20181    public void clearAnimation() {
20182        if (mCurrentAnimation != null) {
20183            mCurrentAnimation.detach();
20184        }
20185        mCurrentAnimation = null;
20186        invalidateParentIfNeeded();
20187    }
20188
20189    /**
20190     * Sets the next animation to play for this view.
20191     * If you want the animation to play immediately, use
20192     * {@link #startAnimation(android.view.animation.Animation)} instead.
20193     * This method provides allows fine-grained
20194     * control over the start time and invalidation, but you
20195     * must make sure that 1) the animation has a start time set, and
20196     * 2) the view's parent (which controls animations on its children)
20197     * will be invalidated when the animation is supposed to
20198     * start.
20199     *
20200     * @param animation The next animation, or null.
20201     */
20202    public void setAnimation(Animation animation) {
20203        mCurrentAnimation = animation;
20204
20205        if (animation != null) {
20206            // If the screen is off assume the animation start time is now instead of
20207            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20208            // would cause the animation to start when the screen turns back on
20209            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20210                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20211                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20212            }
20213            animation.reset();
20214        }
20215    }
20216
20217    /**
20218     * Invoked by a parent ViewGroup to notify the start of the animation
20219     * currently associated with this view. If you override this method,
20220     * always call super.onAnimationStart();
20221     *
20222     * @see #setAnimation(android.view.animation.Animation)
20223     * @see #getAnimation()
20224     */
20225    @CallSuper
20226    protected void onAnimationStart() {
20227        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20228    }
20229
20230    /**
20231     * Invoked by a parent ViewGroup to notify the end of the animation
20232     * currently associated with this view. If you override this method,
20233     * always call super.onAnimationEnd();
20234     *
20235     * @see #setAnimation(android.view.animation.Animation)
20236     * @see #getAnimation()
20237     */
20238    @CallSuper
20239    protected void onAnimationEnd() {
20240        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20241    }
20242
20243    /**
20244     * Invoked if there is a Transform that involves alpha. Subclass that can
20245     * draw themselves with the specified alpha should return true, and then
20246     * respect that alpha when their onDraw() is called. If this returns false
20247     * then the view may be redirected to draw into an offscreen buffer to
20248     * fulfill the request, which will look fine, but may be slower than if the
20249     * subclass handles it internally. The default implementation returns false.
20250     *
20251     * @param alpha The alpha (0..255) to apply to the view's drawing
20252     * @return true if the view can draw with the specified alpha.
20253     */
20254    protected boolean onSetAlpha(int alpha) {
20255        return false;
20256    }
20257
20258    /**
20259     * This is used by the RootView to perform an optimization when
20260     * the view hierarchy contains one or several SurfaceView.
20261     * SurfaceView is always considered transparent, but its children are not,
20262     * therefore all View objects remove themselves from the global transparent
20263     * region (passed as a parameter to this function).
20264     *
20265     * @param region The transparent region for this ViewAncestor (window).
20266     *
20267     * @return Returns true if the effective visibility of the view at this
20268     * point is opaque, regardless of the transparent region; returns false
20269     * if it is possible for underlying windows to be seen behind the view.
20270     *
20271     * {@hide}
20272     */
20273    public boolean gatherTransparentRegion(Region region) {
20274        final AttachInfo attachInfo = mAttachInfo;
20275        if (region != null && attachInfo != null) {
20276            final int pflags = mPrivateFlags;
20277            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20278                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20279                // remove it from the transparent region.
20280                final int[] location = attachInfo.mTransparentLocation;
20281                getLocationInWindow(location);
20282                // When a view has Z value, then it will be better to leave some area below the view
20283                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20284                // the bottom part needs more offset than the left, top and right parts due to the
20285                // spot light effects.
20286                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20287                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20288                        location[0] + mRight - mLeft + shadowOffset,
20289                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20290            } else {
20291                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20292                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20293                    // the background drawable's non-transparent parts from this transparent region.
20294                    applyDrawableToTransparentRegion(mBackground, region);
20295                }
20296                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20297                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20298                    // Similarly, we remove the foreground drawable's non-transparent parts.
20299                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20300                }
20301            }
20302        }
20303        return true;
20304    }
20305
20306    /**
20307     * Play a sound effect for this view.
20308     *
20309     * <p>The framework will play sound effects for some built in actions, such as
20310     * clicking, but you may wish to play these effects in your widget,
20311     * for instance, for internal navigation.
20312     *
20313     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20314     * {@link #isSoundEffectsEnabled()} is true.
20315     *
20316     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20317     */
20318    public void playSoundEffect(int soundConstant) {
20319        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20320            return;
20321        }
20322        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20323    }
20324
20325    /**
20326     * BZZZTT!!1!
20327     *
20328     * <p>Provide haptic feedback to the user for this view.
20329     *
20330     * <p>The framework will provide haptic feedback for some built in actions,
20331     * such as long presses, but you may wish to provide feedback for your
20332     * own widget.
20333     *
20334     * <p>The feedback will only be performed if
20335     * {@link #isHapticFeedbackEnabled()} is true.
20336     *
20337     * @param feedbackConstant One of the constants defined in
20338     * {@link HapticFeedbackConstants}
20339     */
20340    public boolean performHapticFeedback(int feedbackConstant) {
20341        return performHapticFeedback(feedbackConstant, 0);
20342    }
20343
20344    /**
20345     * BZZZTT!!1!
20346     *
20347     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20348     *
20349     * @param feedbackConstant One of the constants defined in
20350     * {@link HapticFeedbackConstants}
20351     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20352     */
20353    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20354        if (mAttachInfo == null) {
20355            return false;
20356        }
20357        //noinspection SimplifiableIfStatement
20358        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20359                && !isHapticFeedbackEnabled()) {
20360            return false;
20361        }
20362        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20363                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20364    }
20365
20366    /**
20367     * Request that the visibility of the status bar or other screen/window
20368     * decorations be changed.
20369     *
20370     * <p>This method is used to put the over device UI into temporary modes
20371     * where the user's attention is focused more on the application content,
20372     * by dimming or hiding surrounding system affordances.  This is typically
20373     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20374     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20375     * to be placed behind the action bar (and with these flags other system
20376     * affordances) so that smooth transitions between hiding and showing them
20377     * can be done.
20378     *
20379     * <p>Two representative examples of the use of system UI visibility is
20380     * implementing a content browsing application (like a magazine reader)
20381     * and a video playing application.
20382     *
20383     * <p>The first code shows a typical implementation of a View in a content
20384     * browsing application.  In this implementation, the application goes
20385     * into a content-oriented mode by hiding the status bar and action bar,
20386     * and putting the navigation elements into lights out mode.  The user can
20387     * then interact with content while in this mode.  Such an application should
20388     * provide an easy way for the user to toggle out of the mode (such as to
20389     * check information in the status bar or access notifications).  In the
20390     * implementation here, this is done simply by tapping on the content.
20391     *
20392     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20393     *      content}
20394     *
20395     * <p>This second code sample shows a typical implementation of a View
20396     * in a video playing application.  In this situation, while the video is
20397     * playing the application would like to go into a complete full-screen mode,
20398     * to use as much of the display as possible for the video.  When in this state
20399     * the user can not interact with the application; the system intercepts
20400     * touching on the screen to pop the UI out of full screen mode.  See
20401     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20402     *
20403     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20404     *      content}
20405     *
20406     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20407     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20408     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20409     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20410     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20411     */
20412    public void setSystemUiVisibility(int visibility) {
20413        if (visibility != mSystemUiVisibility) {
20414            mSystemUiVisibility = visibility;
20415            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20416                mParent.recomputeViewAttributes(this);
20417            }
20418        }
20419    }
20420
20421    /**
20422     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20423     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20424     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20425     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20426     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20427     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20428     */
20429    public int getSystemUiVisibility() {
20430        return mSystemUiVisibility;
20431    }
20432
20433    /**
20434     * Returns the current system UI visibility that is currently set for
20435     * the entire window.  This is the combination of the
20436     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20437     * views in the window.
20438     */
20439    public int getWindowSystemUiVisibility() {
20440        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20441    }
20442
20443    /**
20444     * Override to find out when the window's requested system UI visibility
20445     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20446     * This is different from the callbacks received through
20447     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20448     * in that this is only telling you about the local request of the window,
20449     * not the actual values applied by the system.
20450     */
20451    public void onWindowSystemUiVisibilityChanged(int visible) {
20452    }
20453
20454    /**
20455     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20456     * the view hierarchy.
20457     */
20458    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20459        onWindowSystemUiVisibilityChanged(visible);
20460    }
20461
20462    /**
20463     * Set a listener to receive callbacks when the visibility of the system bar changes.
20464     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20465     */
20466    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20467        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20468        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20469            mParent.recomputeViewAttributes(this);
20470        }
20471    }
20472
20473    /**
20474     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20475     * the view hierarchy.
20476     */
20477    public void dispatchSystemUiVisibilityChanged(int visibility) {
20478        ListenerInfo li = mListenerInfo;
20479        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20480            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20481                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20482        }
20483    }
20484
20485    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20486        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20487        if (val != mSystemUiVisibility) {
20488            setSystemUiVisibility(val);
20489            return true;
20490        }
20491        return false;
20492    }
20493
20494    /** @hide */
20495    public void setDisabledSystemUiVisibility(int flags) {
20496        if (mAttachInfo != null) {
20497            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20498                mAttachInfo.mDisabledSystemUiVisibility = flags;
20499                if (mParent != null) {
20500                    mParent.recomputeViewAttributes(this);
20501                }
20502            }
20503        }
20504    }
20505
20506    /**
20507     * Creates an image that the system displays during the drag and drop
20508     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20509     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20510     * appearance as the given View. The default also positions the center of the drag shadow
20511     * directly under the touch point. If no View is provided (the constructor with no parameters
20512     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20513     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20514     * default is an invisible drag shadow.
20515     * <p>
20516     * You are not required to use the View you provide to the constructor as the basis of the
20517     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20518     * anything you want as the drag shadow.
20519     * </p>
20520     * <p>
20521     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20522     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20523     *  size and position of the drag shadow. It uses this data to construct a
20524     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20525     *  so that your application can draw the shadow image in the Canvas.
20526     * </p>
20527     *
20528     * <div class="special reference">
20529     * <h3>Developer Guides</h3>
20530     * <p>For a guide to implementing drag and drop features, read the
20531     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20532     * </div>
20533     */
20534    public static class DragShadowBuilder {
20535        private final WeakReference<View> mView;
20536
20537        /**
20538         * Constructs a shadow image builder based on a View. By default, the resulting drag
20539         * shadow will have the same appearance and dimensions as the View, with the touch point
20540         * over the center of the View.
20541         * @param view A View. Any View in scope can be used.
20542         */
20543        public DragShadowBuilder(View view) {
20544            mView = new WeakReference<View>(view);
20545        }
20546
20547        /**
20548         * Construct a shadow builder object with no associated View.  This
20549         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20550         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20551         * to supply the drag shadow's dimensions and appearance without
20552         * reference to any View object. If they are not overridden, then the result is an
20553         * invisible drag shadow.
20554         */
20555        public DragShadowBuilder() {
20556            mView = new WeakReference<View>(null);
20557        }
20558
20559        /**
20560         * Returns the View object that had been passed to the
20561         * {@link #View.DragShadowBuilder(View)}
20562         * constructor.  If that View parameter was {@code null} or if the
20563         * {@link #View.DragShadowBuilder()}
20564         * constructor was used to instantiate the builder object, this method will return
20565         * null.
20566         *
20567         * @return The View object associate with this builder object.
20568         */
20569        @SuppressWarnings({"JavadocReference"})
20570        final public View getView() {
20571            return mView.get();
20572        }
20573
20574        /**
20575         * Provides the metrics for the shadow image. These include the dimensions of
20576         * the shadow image, and the point within that shadow that should
20577         * be centered under the touch location while dragging.
20578         * <p>
20579         * The default implementation sets the dimensions of the shadow to be the
20580         * same as the dimensions of the View itself and centers the shadow under
20581         * the touch point.
20582         * </p>
20583         *
20584         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20585         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20586         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20587         * image.
20588         *
20589         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20590         * shadow image that should be underneath the touch point during the drag and drop
20591         * operation. Your application must set {@link android.graphics.Point#x} to the
20592         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20593         */
20594        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20595            final View view = mView.get();
20596            if (view != null) {
20597                outShadowSize.set(view.getWidth(), view.getHeight());
20598                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20599            } else {
20600                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20601            }
20602        }
20603
20604        /**
20605         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20606         * based on the dimensions it received from the
20607         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20608         *
20609         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20610         */
20611        public void onDrawShadow(Canvas canvas) {
20612            final View view = mView.get();
20613            if (view != null) {
20614                view.draw(canvas);
20615            } else {
20616                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20617            }
20618        }
20619    }
20620
20621    /**
20622     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20623     * startDragAndDrop()} for newer platform versions.
20624     */
20625    @Deprecated
20626    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20627                                   Object myLocalState, int flags) {
20628        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20629    }
20630
20631    /**
20632     * Starts a drag and drop operation. When your application calls this method, it passes a
20633     * {@link android.view.View.DragShadowBuilder} object to the system. The
20634     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20635     * to get metrics for the drag shadow, and then calls the object's
20636     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20637     * <p>
20638     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20639     *  drag events to all the View objects in your application that are currently visible. It does
20640     *  this either by calling the View object's drag listener (an implementation of
20641     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20642     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20643     *  Both are passed a {@link android.view.DragEvent} object that has a
20644     *  {@link android.view.DragEvent#getAction()} value of
20645     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20646     * </p>
20647     * <p>
20648     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20649     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20650     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20651     * to the View the user selected for dragging.
20652     * </p>
20653     * @param data A {@link android.content.ClipData} object pointing to the data to be
20654     * transferred by the drag and drop operation.
20655     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20656     * drag shadow.
20657     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20658     * drop operation. When dispatching drag events to views in the same activity this object
20659     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
20660     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
20661     * will return null).
20662     * <p>
20663     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20664     * to the target Views. For example, it can contain flags that differentiate between a
20665     * a copy operation and a move operation.
20666     * </p>
20667     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
20668     * flags, or any combination of the following:
20669     *     <ul>
20670     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
20671     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
20672     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20673     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
20674     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
20675     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
20676     *     </ul>
20677     * @return {@code true} if the method completes successfully, or
20678     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20679     * do a drag, and so no drag operation is in progress.
20680     */
20681    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20682            Object myLocalState, int flags) {
20683        if (ViewDebug.DEBUG_DRAG) {
20684            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20685        }
20686        if (mAttachInfo == null) {
20687            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
20688            return false;
20689        }
20690
20691        data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
20692
20693        boolean okay = false;
20694
20695        Point shadowSize = new Point();
20696        Point shadowTouchPoint = new Point();
20697        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20698
20699        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20700                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20701            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20702        }
20703
20704        if (ViewDebug.DEBUG_DRAG) {
20705            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20706                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20707        }
20708        if (mAttachInfo.mDragSurface != null) {
20709            mAttachInfo.mDragSurface.release();
20710        }
20711        mAttachInfo.mDragSurface = new Surface();
20712        try {
20713            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20714                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20715            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20716                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20717            if (mAttachInfo.mDragToken != null) {
20718                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20719                try {
20720                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20721                    shadowBuilder.onDrawShadow(canvas);
20722                } finally {
20723                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20724                }
20725
20726                final ViewRootImpl root = getViewRootImpl();
20727
20728                // Cache the local state object for delivery with DragEvents
20729                root.setLocalDragState(myLocalState);
20730
20731                // repurpose 'shadowSize' for the last touch point
20732                root.getLastTouchPoint(shadowSize);
20733
20734                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20735                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20736                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20737                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20738            }
20739        } catch (Exception e) {
20740            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20741            mAttachInfo.mDragSurface.destroy();
20742            mAttachInfo.mDragSurface = null;
20743        }
20744
20745        return okay;
20746    }
20747
20748    /**
20749     * Cancels an ongoing drag and drop operation.
20750     * <p>
20751     * A {@link android.view.DragEvent} object with
20752     * {@link android.view.DragEvent#getAction()} value of
20753     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20754     * {@link android.view.DragEvent#getResult()} value of {@code false}
20755     * will be sent to every
20756     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20757     * even if they are not currently visible.
20758     * </p>
20759     * <p>
20760     * This method can be called on any View in the same window as the View on which
20761     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20762     * was called.
20763     * </p>
20764     */
20765    public final void cancelDragAndDrop() {
20766        if (ViewDebug.DEBUG_DRAG) {
20767            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20768        }
20769        if (mAttachInfo == null) {
20770            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
20771            return;
20772        }
20773        if (mAttachInfo.mDragToken != null) {
20774            try {
20775                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20776            } catch (Exception e) {
20777                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20778            }
20779            mAttachInfo.mDragToken = null;
20780        } else {
20781            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20782        }
20783    }
20784
20785    /**
20786     * Updates the drag shadow for the ongoing drag and drop operation.
20787     *
20788     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20789     * new drag shadow.
20790     */
20791    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20792        if (ViewDebug.DEBUG_DRAG) {
20793            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20794        }
20795        if (mAttachInfo == null) {
20796            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
20797            return;
20798        }
20799        if (mAttachInfo.mDragToken != null) {
20800            try {
20801                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20802                try {
20803                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20804                    shadowBuilder.onDrawShadow(canvas);
20805                } finally {
20806                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20807                }
20808            } catch (Exception e) {
20809                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20810            }
20811        } else {
20812            Log.e(VIEW_LOG_TAG, "No active drag");
20813        }
20814    }
20815
20816    /**
20817     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20818     * between {startX, startY} and the new cursor positon.
20819     * @param startX horizontal coordinate where the move started.
20820     * @param startY vertical coordinate where the move started.
20821     * @return whether moving was started successfully.
20822     * @hide
20823     */
20824    public final boolean startMovingTask(float startX, float startY) {
20825        if (ViewDebug.DEBUG_POSITIONING) {
20826            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20827        }
20828        try {
20829            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20830        } catch (RemoteException e) {
20831            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20832        }
20833        return false;
20834    }
20835
20836    /**
20837     * Handles drag events sent by the system following a call to
20838     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20839     * startDragAndDrop()}.
20840     *<p>
20841     * When the system calls this method, it passes a
20842     * {@link android.view.DragEvent} object. A call to
20843     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20844     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20845     * operation.
20846     * @param event The {@link android.view.DragEvent} sent by the system.
20847     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20848     * in DragEvent, indicating the type of drag event represented by this object.
20849     * @return {@code true} if the method was successful, otherwise {@code false}.
20850     * <p>
20851     *  The method should return {@code true} in response to an action type of
20852     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20853     *  operation.
20854     * </p>
20855     * <p>
20856     *  The method should also return {@code true} in response to an action type of
20857     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20858     *  {@code false} if it didn't.
20859     * </p>
20860     */
20861    public boolean onDragEvent(DragEvent event) {
20862        return false;
20863    }
20864
20865    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
20866    boolean dispatchDragEnterExitInPreN(DragEvent event) {
20867        return callDragEventHandler(event);
20868    }
20869
20870    /**
20871     * Detects if this View is enabled and has a drag event listener.
20872     * If both are true, then it calls the drag event listener with the
20873     * {@link android.view.DragEvent} it received. If the drag event listener returns
20874     * {@code true}, then dispatchDragEvent() returns {@code true}.
20875     * <p>
20876     * For all other cases, the method calls the
20877     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20878     * method and returns its result.
20879     * </p>
20880     * <p>
20881     * This ensures that a drag event is always consumed, even if the View does not have a drag
20882     * event listener. However, if the View has a listener and the listener returns true, then
20883     * onDragEvent() is not called.
20884     * </p>
20885     */
20886    public boolean dispatchDragEvent(DragEvent event) {
20887        event.mEventHandlerWasCalled = true;
20888        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
20889            event.mAction == DragEvent.ACTION_DROP) {
20890            // About to deliver an event with coordinates to this view. Notify that now this view
20891            // has drag focus. This will send exit/enter events as needed.
20892            getViewRootImpl().setDragFocus(this, event);
20893        }
20894        return callDragEventHandler(event);
20895    }
20896
20897    final boolean callDragEventHandler(DragEvent event) {
20898        final boolean result;
20899
20900        ListenerInfo li = mListenerInfo;
20901        //noinspection SimplifiableIfStatement
20902        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20903                && li.mOnDragListener.onDrag(this, event)) {
20904            result = true;
20905        } else {
20906            result = onDragEvent(event);
20907        }
20908
20909        switch (event.mAction) {
20910            case DragEvent.ACTION_DRAG_ENTERED: {
20911                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
20912                refreshDrawableState();
20913            } break;
20914            case DragEvent.ACTION_DRAG_EXITED: {
20915                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
20916                refreshDrawableState();
20917            } break;
20918            case DragEvent.ACTION_DRAG_ENDED: {
20919                mPrivateFlags2 &= ~View.DRAG_MASK;
20920                refreshDrawableState();
20921            } break;
20922        }
20923
20924        return result;
20925    }
20926
20927    boolean canAcceptDrag() {
20928        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20929    }
20930
20931    /**
20932     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20933     * it is ever exposed at all.
20934     * @hide
20935     */
20936    public void onCloseSystemDialogs(String reason) {
20937    }
20938
20939    /**
20940     * Given a Drawable whose bounds have been set to draw into this view,
20941     * update a Region being computed for
20942     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20943     * that any non-transparent parts of the Drawable are removed from the
20944     * given transparent region.
20945     *
20946     * @param dr The Drawable whose transparency is to be applied to the region.
20947     * @param region A Region holding the current transparency information,
20948     * where any parts of the region that are set are considered to be
20949     * transparent.  On return, this region will be modified to have the
20950     * transparency information reduced by the corresponding parts of the
20951     * Drawable that are not transparent.
20952     * {@hide}
20953     */
20954    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20955        if (DBG) {
20956            Log.i("View", "Getting transparent region for: " + this);
20957        }
20958        final Region r = dr.getTransparentRegion();
20959        final Rect db = dr.getBounds();
20960        final AttachInfo attachInfo = mAttachInfo;
20961        if (r != null && attachInfo != null) {
20962            final int w = getRight()-getLeft();
20963            final int h = getBottom()-getTop();
20964            if (db.left > 0) {
20965                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20966                r.op(0, 0, db.left, h, Region.Op.UNION);
20967            }
20968            if (db.right < w) {
20969                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20970                r.op(db.right, 0, w, h, Region.Op.UNION);
20971            }
20972            if (db.top > 0) {
20973                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20974                r.op(0, 0, w, db.top, Region.Op.UNION);
20975            }
20976            if (db.bottom < h) {
20977                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20978                r.op(0, db.bottom, w, h, Region.Op.UNION);
20979            }
20980            final int[] location = attachInfo.mTransparentLocation;
20981            getLocationInWindow(location);
20982            r.translate(location[0], location[1]);
20983            region.op(r, Region.Op.INTERSECT);
20984        } else {
20985            region.op(db, Region.Op.DIFFERENCE);
20986        }
20987    }
20988
20989    private void checkForLongClick(int delayOffset, float x, float y) {
20990        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20991            mHasPerformedLongPress = false;
20992
20993            if (mPendingCheckForLongPress == null) {
20994                mPendingCheckForLongPress = new CheckForLongPress();
20995            }
20996            mPendingCheckForLongPress.setAnchor(x, y);
20997            mPendingCheckForLongPress.rememberWindowAttachCount();
20998            postDelayed(mPendingCheckForLongPress,
20999                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21000        }
21001    }
21002
21003    /**
21004     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21005     * LayoutInflater} class, which provides a full range of options for view inflation.
21006     *
21007     * @param context The Context object for your activity or application.
21008     * @param resource The resource ID to inflate
21009     * @param root A view group that will be the parent.  Used to properly inflate the
21010     * layout_* parameters.
21011     * @see LayoutInflater
21012     */
21013    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21014        LayoutInflater factory = LayoutInflater.from(context);
21015        return factory.inflate(resource, root);
21016    }
21017
21018    /**
21019     * Scroll the view with standard behavior for scrolling beyond the normal
21020     * content boundaries. Views that call this method should override
21021     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21022     * results of an over-scroll operation.
21023     *
21024     * Views can use this method to handle any touch or fling-based scrolling.
21025     *
21026     * @param deltaX Change in X in pixels
21027     * @param deltaY Change in Y in pixels
21028     * @param scrollX Current X scroll value in pixels before applying deltaX
21029     * @param scrollY Current Y scroll value in pixels before applying deltaY
21030     * @param scrollRangeX Maximum content scroll range along the X axis
21031     * @param scrollRangeY Maximum content scroll range along the Y axis
21032     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21033     *          along the X axis.
21034     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21035     *          along the Y axis.
21036     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21037     * @return true if scrolling was clamped to an over-scroll boundary along either
21038     *          axis, false otherwise.
21039     */
21040    @SuppressWarnings({"UnusedParameters"})
21041    protected boolean overScrollBy(int deltaX, int deltaY,
21042            int scrollX, int scrollY,
21043            int scrollRangeX, int scrollRangeY,
21044            int maxOverScrollX, int maxOverScrollY,
21045            boolean isTouchEvent) {
21046        final int overScrollMode = mOverScrollMode;
21047        final boolean canScrollHorizontal =
21048                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21049        final boolean canScrollVertical =
21050                computeVerticalScrollRange() > computeVerticalScrollExtent();
21051        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21052                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21053        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21054                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21055
21056        int newScrollX = scrollX + deltaX;
21057        if (!overScrollHorizontal) {
21058            maxOverScrollX = 0;
21059        }
21060
21061        int newScrollY = scrollY + deltaY;
21062        if (!overScrollVertical) {
21063            maxOverScrollY = 0;
21064        }
21065
21066        // Clamp values if at the limits and record
21067        final int left = -maxOverScrollX;
21068        final int right = maxOverScrollX + scrollRangeX;
21069        final int top = -maxOverScrollY;
21070        final int bottom = maxOverScrollY + scrollRangeY;
21071
21072        boolean clampedX = false;
21073        if (newScrollX > right) {
21074            newScrollX = right;
21075            clampedX = true;
21076        } else if (newScrollX < left) {
21077            newScrollX = left;
21078            clampedX = true;
21079        }
21080
21081        boolean clampedY = false;
21082        if (newScrollY > bottom) {
21083            newScrollY = bottom;
21084            clampedY = true;
21085        } else if (newScrollY < top) {
21086            newScrollY = top;
21087            clampedY = true;
21088        }
21089
21090        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21091
21092        return clampedX || clampedY;
21093    }
21094
21095    /**
21096     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21097     * respond to the results of an over-scroll operation.
21098     *
21099     * @param scrollX New X scroll value in pixels
21100     * @param scrollY New Y scroll value in pixels
21101     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21102     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21103     */
21104    protected void onOverScrolled(int scrollX, int scrollY,
21105            boolean clampedX, boolean clampedY) {
21106        // Intentionally empty.
21107    }
21108
21109    /**
21110     * Returns the over-scroll mode for this view. The result will be
21111     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21112     * (allow over-scrolling only if the view content is larger than the container),
21113     * or {@link #OVER_SCROLL_NEVER}.
21114     *
21115     * @return This view's over-scroll mode.
21116     */
21117    public int getOverScrollMode() {
21118        return mOverScrollMode;
21119    }
21120
21121    /**
21122     * Set the over-scroll mode for this view. Valid over-scroll modes are
21123     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21124     * (allow over-scrolling only if the view content is larger than the container),
21125     * or {@link #OVER_SCROLL_NEVER}.
21126     *
21127     * Setting the over-scroll mode of a view will have an effect only if the
21128     * view is capable of scrolling.
21129     *
21130     * @param overScrollMode The new over-scroll mode for this view.
21131     */
21132    public void setOverScrollMode(int overScrollMode) {
21133        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21134                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21135                overScrollMode != OVER_SCROLL_NEVER) {
21136            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21137        }
21138        mOverScrollMode = overScrollMode;
21139    }
21140
21141    /**
21142     * Enable or disable nested scrolling for this view.
21143     *
21144     * <p>If this property is set to true the view will be permitted to initiate nested
21145     * scrolling operations with a compatible parent view in the current hierarchy. If this
21146     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21147     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21148     * the nested scroll.</p>
21149     *
21150     * @param enabled true to enable nested scrolling, false to disable
21151     *
21152     * @see #isNestedScrollingEnabled()
21153     */
21154    public void setNestedScrollingEnabled(boolean enabled) {
21155        if (enabled) {
21156            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21157        } else {
21158            stopNestedScroll();
21159            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21160        }
21161    }
21162
21163    /**
21164     * Returns true if nested scrolling is enabled for this view.
21165     *
21166     * <p>If nested scrolling is enabled and this View class implementation supports it,
21167     * this view will act as a nested scrolling child view when applicable, forwarding data
21168     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21169     * parent.</p>
21170     *
21171     * @return true if nested scrolling is enabled
21172     *
21173     * @see #setNestedScrollingEnabled(boolean)
21174     */
21175    public boolean isNestedScrollingEnabled() {
21176        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21177                PFLAG3_NESTED_SCROLLING_ENABLED;
21178    }
21179
21180    /**
21181     * Begin a nestable scroll operation along the given axes.
21182     *
21183     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21184     *
21185     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21186     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21187     * In the case of touch scrolling the nested scroll will be terminated automatically in
21188     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21189     * In the event of programmatic scrolling the caller must explicitly call
21190     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21191     *
21192     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21193     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21194     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21195     *
21196     * <p>At each incremental step of the scroll the caller should invoke
21197     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21198     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21199     * parent at least partially consumed the scroll and the caller should adjust the amount it
21200     * scrolls by.</p>
21201     *
21202     * <p>After applying the remainder of the scroll delta the caller should invoke
21203     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21204     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21205     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21206     * </p>
21207     *
21208     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21209     *             {@link #SCROLL_AXIS_VERTICAL}.
21210     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21211     *         the current gesture.
21212     *
21213     * @see #stopNestedScroll()
21214     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21215     * @see #dispatchNestedScroll(int, int, int, int, int[])
21216     */
21217    public boolean startNestedScroll(int axes) {
21218        if (hasNestedScrollingParent()) {
21219            // Already in progress
21220            return true;
21221        }
21222        if (isNestedScrollingEnabled()) {
21223            ViewParent p = getParent();
21224            View child = this;
21225            while (p != null) {
21226                try {
21227                    if (p.onStartNestedScroll(child, this, axes)) {
21228                        mNestedScrollingParent = p;
21229                        p.onNestedScrollAccepted(child, this, axes);
21230                        return true;
21231                    }
21232                } catch (AbstractMethodError e) {
21233                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21234                            "method onStartNestedScroll", e);
21235                    // Allow the search upward to continue
21236                }
21237                if (p instanceof View) {
21238                    child = (View) p;
21239                }
21240                p = p.getParent();
21241            }
21242        }
21243        return false;
21244    }
21245
21246    /**
21247     * Stop a nested scroll in progress.
21248     *
21249     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21250     *
21251     * @see #startNestedScroll(int)
21252     */
21253    public void stopNestedScroll() {
21254        if (mNestedScrollingParent != null) {
21255            mNestedScrollingParent.onStopNestedScroll(this);
21256            mNestedScrollingParent = null;
21257        }
21258    }
21259
21260    /**
21261     * Returns true if this view has a nested scrolling parent.
21262     *
21263     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21264     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21265     *
21266     * @return whether this view has a nested scrolling parent
21267     */
21268    public boolean hasNestedScrollingParent() {
21269        return mNestedScrollingParent != null;
21270    }
21271
21272    /**
21273     * Dispatch one step of a nested scroll in progress.
21274     *
21275     * <p>Implementations of views that support nested scrolling should call this to report
21276     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21277     * is not currently in progress or nested scrolling is not
21278     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21279     *
21280     * <p>Compatible View implementations should also call
21281     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21282     * consuming a component of the scroll event themselves.</p>
21283     *
21284     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21285     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21286     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21287     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21288     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21289     *                       in local view coordinates of this view from before this operation
21290     *                       to after it completes. View implementations may use this to adjust
21291     *                       expected input coordinate tracking.
21292     * @return true if the event was dispatched, false if it could not be dispatched.
21293     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21294     */
21295    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21296            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21297        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21298            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21299                int startX = 0;
21300                int startY = 0;
21301                if (offsetInWindow != null) {
21302                    getLocationInWindow(offsetInWindow);
21303                    startX = offsetInWindow[0];
21304                    startY = offsetInWindow[1];
21305                }
21306
21307                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21308                        dxUnconsumed, dyUnconsumed);
21309
21310                if (offsetInWindow != null) {
21311                    getLocationInWindow(offsetInWindow);
21312                    offsetInWindow[0] -= startX;
21313                    offsetInWindow[1] -= startY;
21314                }
21315                return true;
21316            } else if (offsetInWindow != null) {
21317                // No motion, no dispatch. Keep offsetInWindow up to date.
21318                offsetInWindow[0] = 0;
21319                offsetInWindow[1] = 0;
21320            }
21321        }
21322        return false;
21323    }
21324
21325    /**
21326     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21327     *
21328     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21329     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21330     * scrolling operation to consume some or all of the scroll operation before the child view
21331     * consumes it.</p>
21332     *
21333     * @param dx Horizontal scroll distance in pixels
21334     * @param dy Vertical scroll distance in pixels
21335     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21336     *                 and consumed[1] the consumed dy.
21337     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21338     *                       in local view coordinates of this view from before this operation
21339     *                       to after it completes. View implementations may use this to adjust
21340     *                       expected input coordinate tracking.
21341     * @return true if the parent consumed some or all of the scroll delta
21342     * @see #dispatchNestedScroll(int, int, int, int, int[])
21343     */
21344    public boolean dispatchNestedPreScroll(int dx, int dy,
21345            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21346        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21347            if (dx != 0 || dy != 0) {
21348                int startX = 0;
21349                int startY = 0;
21350                if (offsetInWindow != null) {
21351                    getLocationInWindow(offsetInWindow);
21352                    startX = offsetInWindow[0];
21353                    startY = offsetInWindow[1];
21354                }
21355
21356                if (consumed == null) {
21357                    if (mTempNestedScrollConsumed == null) {
21358                        mTempNestedScrollConsumed = new int[2];
21359                    }
21360                    consumed = mTempNestedScrollConsumed;
21361                }
21362                consumed[0] = 0;
21363                consumed[1] = 0;
21364                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21365
21366                if (offsetInWindow != null) {
21367                    getLocationInWindow(offsetInWindow);
21368                    offsetInWindow[0] -= startX;
21369                    offsetInWindow[1] -= startY;
21370                }
21371                return consumed[0] != 0 || consumed[1] != 0;
21372            } else if (offsetInWindow != null) {
21373                offsetInWindow[0] = 0;
21374                offsetInWindow[1] = 0;
21375            }
21376        }
21377        return false;
21378    }
21379
21380    /**
21381     * Dispatch a fling to a nested scrolling parent.
21382     *
21383     * <p>This method should be used to indicate that a nested scrolling child has detected
21384     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21385     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21386     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21387     * along a scrollable axis.</p>
21388     *
21389     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21390     * its own content, it can use this method to delegate the fling to its nested scrolling
21391     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21392     *
21393     * @param velocityX Horizontal fling velocity in pixels per second
21394     * @param velocityY Vertical fling velocity in pixels per second
21395     * @param consumed true if the child consumed the fling, false otherwise
21396     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21397     */
21398    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21399        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21400            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21401        }
21402        return false;
21403    }
21404
21405    /**
21406     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21407     *
21408     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21409     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21410     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21411     * before the child view consumes it. If this method returns <code>true</code>, a nested
21412     * parent view consumed the fling and this view should not scroll as a result.</p>
21413     *
21414     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21415     * the fling at a time. If a parent view consumed the fling this method will return false.
21416     * Custom view implementations should account for this in two ways:</p>
21417     *
21418     * <ul>
21419     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21420     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21421     *     position regardless.</li>
21422     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21423     *     even to settle back to a valid idle position.</li>
21424     * </ul>
21425     *
21426     * <p>Views should also not offer fling velocities to nested parent views along an axis
21427     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21428     * should not offer a horizontal fling velocity to its parents since scrolling along that
21429     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21430     *
21431     * @param velocityX Horizontal fling velocity in pixels per second
21432     * @param velocityY Vertical fling velocity in pixels per second
21433     * @return true if a nested scrolling parent consumed the fling
21434     */
21435    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21436        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21437            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21438        }
21439        return false;
21440    }
21441
21442    /**
21443     * Gets a scale factor that determines the distance the view should scroll
21444     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21445     * @return The vertical scroll scale factor.
21446     * @hide
21447     */
21448    protected float getVerticalScrollFactor() {
21449        if (mVerticalScrollFactor == 0) {
21450            TypedValue outValue = new TypedValue();
21451            if (!mContext.getTheme().resolveAttribute(
21452                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21453                throw new IllegalStateException(
21454                        "Expected theme to define listPreferredItemHeight.");
21455            }
21456            mVerticalScrollFactor = outValue.getDimension(
21457                    mContext.getResources().getDisplayMetrics());
21458        }
21459        return mVerticalScrollFactor;
21460    }
21461
21462    /**
21463     * Gets a scale factor that determines the distance the view should scroll
21464     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21465     * @return The horizontal scroll scale factor.
21466     * @hide
21467     */
21468    protected float getHorizontalScrollFactor() {
21469        // TODO: Should use something else.
21470        return getVerticalScrollFactor();
21471    }
21472
21473    /**
21474     * Return the value specifying the text direction or policy that was set with
21475     * {@link #setTextDirection(int)}.
21476     *
21477     * @return the defined text direction. It can be one of:
21478     *
21479     * {@link #TEXT_DIRECTION_INHERIT},
21480     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21481     * {@link #TEXT_DIRECTION_ANY_RTL},
21482     * {@link #TEXT_DIRECTION_LTR},
21483     * {@link #TEXT_DIRECTION_RTL},
21484     * {@link #TEXT_DIRECTION_LOCALE},
21485     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21486     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21487     *
21488     * @attr ref android.R.styleable#View_textDirection
21489     *
21490     * @hide
21491     */
21492    @ViewDebug.ExportedProperty(category = "text", mapping = {
21493            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21494            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21495            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21496            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21497            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21498            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21499            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21500            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21501    })
21502    public int getRawTextDirection() {
21503        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21504    }
21505
21506    /**
21507     * Set the text direction.
21508     *
21509     * @param textDirection the direction to set. Should be one of:
21510     *
21511     * {@link #TEXT_DIRECTION_INHERIT},
21512     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21513     * {@link #TEXT_DIRECTION_ANY_RTL},
21514     * {@link #TEXT_DIRECTION_LTR},
21515     * {@link #TEXT_DIRECTION_RTL},
21516     * {@link #TEXT_DIRECTION_LOCALE}
21517     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21518     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21519     *
21520     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21521     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21522     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21523     *
21524     * @attr ref android.R.styleable#View_textDirection
21525     */
21526    public void setTextDirection(int textDirection) {
21527        if (getRawTextDirection() != textDirection) {
21528            // Reset the current text direction and the resolved one
21529            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21530            resetResolvedTextDirection();
21531            // Set the new text direction
21532            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21533            // Do resolution
21534            resolveTextDirection();
21535            // Notify change
21536            onRtlPropertiesChanged(getLayoutDirection());
21537            // Refresh
21538            requestLayout();
21539            invalidate(true);
21540        }
21541    }
21542
21543    /**
21544     * Return the resolved text direction.
21545     *
21546     * @return the resolved text direction. Returns one of:
21547     *
21548     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21549     * {@link #TEXT_DIRECTION_ANY_RTL},
21550     * {@link #TEXT_DIRECTION_LTR},
21551     * {@link #TEXT_DIRECTION_RTL},
21552     * {@link #TEXT_DIRECTION_LOCALE},
21553     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21554     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21555     *
21556     * @attr ref android.R.styleable#View_textDirection
21557     */
21558    @ViewDebug.ExportedProperty(category = "text", mapping = {
21559            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21560            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21561            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21562            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21563            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21564            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21565            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21566            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21567    })
21568    public int getTextDirection() {
21569        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21570    }
21571
21572    /**
21573     * Resolve the text direction.
21574     *
21575     * @return true if resolution has been done, false otherwise.
21576     *
21577     * @hide
21578     */
21579    public boolean resolveTextDirection() {
21580        // Reset any previous text direction resolution
21581        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21582
21583        if (hasRtlSupport()) {
21584            // Set resolved text direction flag depending on text direction flag
21585            final int textDirection = getRawTextDirection();
21586            switch(textDirection) {
21587                case TEXT_DIRECTION_INHERIT:
21588                    if (!canResolveTextDirection()) {
21589                        // We cannot do the resolution if there is no parent, so use the default one
21590                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21591                        // Resolution will need to happen again later
21592                        return false;
21593                    }
21594
21595                    // Parent has not yet resolved, so we still return the default
21596                    try {
21597                        if (!mParent.isTextDirectionResolved()) {
21598                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21599                            // Resolution will need to happen again later
21600                            return false;
21601                        }
21602                    } catch (AbstractMethodError e) {
21603                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21604                                " does not fully implement ViewParent", e);
21605                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21606                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21607                        return true;
21608                    }
21609
21610                    // Set current resolved direction to the same value as the parent's one
21611                    int parentResolvedDirection;
21612                    try {
21613                        parentResolvedDirection = mParent.getTextDirection();
21614                    } catch (AbstractMethodError e) {
21615                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21616                                " does not fully implement ViewParent", e);
21617                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21618                    }
21619                    switch (parentResolvedDirection) {
21620                        case TEXT_DIRECTION_FIRST_STRONG:
21621                        case TEXT_DIRECTION_ANY_RTL:
21622                        case TEXT_DIRECTION_LTR:
21623                        case TEXT_DIRECTION_RTL:
21624                        case TEXT_DIRECTION_LOCALE:
21625                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21626                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21627                            mPrivateFlags2 |=
21628                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21629                            break;
21630                        default:
21631                            // Default resolved direction is "first strong" heuristic
21632                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21633                    }
21634                    break;
21635                case TEXT_DIRECTION_FIRST_STRONG:
21636                case TEXT_DIRECTION_ANY_RTL:
21637                case TEXT_DIRECTION_LTR:
21638                case TEXT_DIRECTION_RTL:
21639                case TEXT_DIRECTION_LOCALE:
21640                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21641                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21642                    // Resolved direction is the same as text direction
21643                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21644                    break;
21645                default:
21646                    // Default resolved direction is "first strong" heuristic
21647                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21648            }
21649        } else {
21650            // Default resolved direction is "first strong" heuristic
21651            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21652        }
21653
21654        // Set to resolved
21655        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21656        return true;
21657    }
21658
21659    /**
21660     * Check if text direction resolution can be done.
21661     *
21662     * @return true if text direction resolution can be done otherwise return false.
21663     */
21664    public boolean canResolveTextDirection() {
21665        switch (getRawTextDirection()) {
21666            case TEXT_DIRECTION_INHERIT:
21667                if (mParent != null) {
21668                    try {
21669                        return mParent.canResolveTextDirection();
21670                    } catch (AbstractMethodError e) {
21671                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21672                                " does not fully implement ViewParent", e);
21673                    }
21674                }
21675                return false;
21676
21677            default:
21678                return true;
21679        }
21680    }
21681
21682    /**
21683     * Reset resolved text direction. Text direction will be resolved during a call to
21684     * {@link #onMeasure(int, int)}.
21685     *
21686     * @hide
21687     */
21688    public void resetResolvedTextDirection() {
21689        // Reset any previous text direction resolution
21690        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21691        // Set to default value
21692        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21693    }
21694
21695    /**
21696     * @return true if text direction is inherited.
21697     *
21698     * @hide
21699     */
21700    public boolean isTextDirectionInherited() {
21701        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21702    }
21703
21704    /**
21705     * @return true if text direction is resolved.
21706     */
21707    public boolean isTextDirectionResolved() {
21708        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21709    }
21710
21711    /**
21712     * Return the value specifying the text alignment or policy that was set with
21713     * {@link #setTextAlignment(int)}.
21714     *
21715     * @return the defined text alignment. It can be one of:
21716     *
21717     * {@link #TEXT_ALIGNMENT_INHERIT},
21718     * {@link #TEXT_ALIGNMENT_GRAVITY},
21719     * {@link #TEXT_ALIGNMENT_CENTER},
21720     * {@link #TEXT_ALIGNMENT_TEXT_START},
21721     * {@link #TEXT_ALIGNMENT_TEXT_END},
21722     * {@link #TEXT_ALIGNMENT_VIEW_START},
21723     * {@link #TEXT_ALIGNMENT_VIEW_END}
21724     *
21725     * @attr ref android.R.styleable#View_textAlignment
21726     *
21727     * @hide
21728     */
21729    @ViewDebug.ExportedProperty(category = "text", mapping = {
21730            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21731            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21732            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21733            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21734            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21735            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21736            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21737    })
21738    @TextAlignment
21739    public int getRawTextAlignment() {
21740        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21741    }
21742
21743    /**
21744     * Set the text alignment.
21745     *
21746     * @param textAlignment The text alignment to set. Should be one of
21747     *
21748     * {@link #TEXT_ALIGNMENT_INHERIT},
21749     * {@link #TEXT_ALIGNMENT_GRAVITY},
21750     * {@link #TEXT_ALIGNMENT_CENTER},
21751     * {@link #TEXT_ALIGNMENT_TEXT_START},
21752     * {@link #TEXT_ALIGNMENT_TEXT_END},
21753     * {@link #TEXT_ALIGNMENT_VIEW_START},
21754     * {@link #TEXT_ALIGNMENT_VIEW_END}
21755     *
21756     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21757     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21758     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21759     *
21760     * @attr ref android.R.styleable#View_textAlignment
21761     */
21762    public void setTextAlignment(@TextAlignment int textAlignment) {
21763        if (textAlignment != getRawTextAlignment()) {
21764            // Reset the current and resolved text alignment
21765            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21766            resetResolvedTextAlignment();
21767            // Set the new text alignment
21768            mPrivateFlags2 |=
21769                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21770            // Do resolution
21771            resolveTextAlignment();
21772            // Notify change
21773            onRtlPropertiesChanged(getLayoutDirection());
21774            // Refresh
21775            requestLayout();
21776            invalidate(true);
21777        }
21778    }
21779
21780    /**
21781     * Return the resolved text alignment.
21782     *
21783     * @return the resolved text alignment. Returns one of:
21784     *
21785     * {@link #TEXT_ALIGNMENT_GRAVITY},
21786     * {@link #TEXT_ALIGNMENT_CENTER},
21787     * {@link #TEXT_ALIGNMENT_TEXT_START},
21788     * {@link #TEXT_ALIGNMENT_TEXT_END},
21789     * {@link #TEXT_ALIGNMENT_VIEW_START},
21790     * {@link #TEXT_ALIGNMENT_VIEW_END}
21791     *
21792     * @attr ref android.R.styleable#View_textAlignment
21793     */
21794    @ViewDebug.ExportedProperty(category = "text", mapping = {
21795            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21796            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21797            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21798            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21799            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21800            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21801            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21802    })
21803    @TextAlignment
21804    public int getTextAlignment() {
21805        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21806                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21807    }
21808
21809    /**
21810     * Resolve the text alignment.
21811     *
21812     * @return true if resolution has been done, false otherwise.
21813     *
21814     * @hide
21815     */
21816    public boolean resolveTextAlignment() {
21817        // Reset any previous text alignment resolution
21818        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21819
21820        if (hasRtlSupport()) {
21821            // Set resolved text alignment flag depending on text alignment flag
21822            final int textAlignment = getRawTextAlignment();
21823            switch (textAlignment) {
21824                case TEXT_ALIGNMENT_INHERIT:
21825                    // Check if we can resolve the text alignment
21826                    if (!canResolveTextAlignment()) {
21827                        // We cannot do the resolution if there is no parent so use the default
21828                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21829                        // Resolution will need to happen again later
21830                        return false;
21831                    }
21832
21833                    // Parent has not yet resolved, so we still return the default
21834                    try {
21835                        if (!mParent.isTextAlignmentResolved()) {
21836                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21837                            // Resolution will need to happen again later
21838                            return false;
21839                        }
21840                    } catch (AbstractMethodError e) {
21841                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21842                                " does not fully implement ViewParent", e);
21843                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21844                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21845                        return true;
21846                    }
21847
21848                    int parentResolvedTextAlignment;
21849                    try {
21850                        parentResolvedTextAlignment = mParent.getTextAlignment();
21851                    } catch (AbstractMethodError e) {
21852                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21853                                " does not fully implement ViewParent", e);
21854                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21855                    }
21856                    switch (parentResolvedTextAlignment) {
21857                        case TEXT_ALIGNMENT_GRAVITY:
21858                        case TEXT_ALIGNMENT_TEXT_START:
21859                        case TEXT_ALIGNMENT_TEXT_END:
21860                        case TEXT_ALIGNMENT_CENTER:
21861                        case TEXT_ALIGNMENT_VIEW_START:
21862                        case TEXT_ALIGNMENT_VIEW_END:
21863                            // Resolved text alignment is the same as the parent resolved
21864                            // text alignment
21865                            mPrivateFlags2 |=
21866                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21867                            break;
21868                        default:
21869                            // Use default resolved text alignment
21870                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21871                    }
21872                    break;
21873                case TEXT_ALIGNMENT_GRAVITY:
21874                case TEXT_ALIGNMENT_TEXT_START:
21875                case TEXT_ALIGNMENT_TEXT_END:
21876                case TEXT_ALIGNMENT_CENTER:
21877                case TEXT_ALIGNMENT_VIEW_START:
21878                case TEXT_ALIGNMENT_VIEW_END:
21879                    // Resolved text alignment is the same as text alignment
21880                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21881                    break;
21882                default:
21883                    // Use default resolved text alignment
21884                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21885            }
21886        } else {
21887            // Use default resolved text alignment
21888            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21889        }
21890
21891        // Set the resolved
21892        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21893        return true;
21894    }
21895
21896    /**
21897     * Check if text alignment resolution can be done.
21898     *
21899     * @return true if text alignment resolution can be done otherwise return false.
21900     */
21901    public boolean canResolveTextAlignment() {
21902        switch (getRawTextAlignment()) {
21903            case TEXT_DIRECTION_INHERIT:
21904                if (mParent != null) {
21905                    try {
21906                        return mParent.canResolveTextAlignment();
21907                    } catch (AbstractMethodError e) {
21908                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21909                                " does not fully implement ViewParent", e);
21910                    }
21911                }
21912                return false;
21913
21914            default:
21915                return true;
21916        }
21917    }
21918
21919    /**
21920     * Reset resolved text alignment. Text alignment will be resolved during a call to
21921     * {@link #onMeasure(int, int)}.
21922     *
21923     * @hide
21924     */
21925    public void resetResolvedTextAlignment() {
21926        // Reset any previous text alignment resolution
21927        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21928        // Set to default
21929        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21930    }
21931
21932    /**
21933     * @return true if text alignment is inherited.
21934     *
21935     * @hide
21936     */
21937    public boolean isTextAlignmentInherited() {
21938        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21939    }
21940
21941    /**
21942     * @return true if text alignment is resolved.
21943     */
21944    public boolean isTextAlignmentResolved() {
21945        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21946    }
21947
21948    /**
21949     * Generate a value suitable for use in {@link #setId(int)}.
21950     * This value will not collide with ID values generated at build time by aapt for R.id.
21951     *
21952     * @return a generated ID value
21953     */
21954    public static int generateViewId() {
21955        for (;;) {
21956            final int result = sNextGeneratedId.get();
21957            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21958            int newValue = result + 1;
21959            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21960            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21961                return result;
21962            }
21963        }
21964    }
21965
21966    /**
21967     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21968     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21969     *                           a normal View or a ViewGroup with
21970     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21971     * @hide
21972     */
21973    public void captureTransitioningViews(List<View> transitioningViews) {
21974        if (getVisibility() == View.VISIBLE) {
21975            transitioningViews.add(this);
21976        }
21977    }
21978
21979    /**
21980     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21981     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21982     * @hide
21983     */
21984    public void findNamedViews(Map<String, View> namedElements) {
21985        if (getVisibility() == VISIBLE || mGhostView != null) {
21986            String transitionName = getTransitionName();
21987            if (transitionName != null) {
21988                namedElements.put(transitionName, this);
21989            }
21990        }
21991    }
21992
21993    /**
21994     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21995     * The default implementation does not care the location or event types, but some subclasses
21996     * may use it (such as WebViews).
21997     * @param event The MotionEvent from a mouse
21998     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
21999     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22000     * @see PointerIcon
22001     */
22002    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22003        final float x = event.getX(pointerIndex);
22004        final float y = event.getY(pointerIndex);
22005        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22006            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22007        }
22008        return mPointerIcon;
22009    }
22010
22011    /**
22012     * Set the pointer icon for the current view.
22013     * Passing {@code null} will restore the pointer icon to its default value.
22014     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22015     */
22016    public void setPointerIcon(PointerIcon pointerIcon) {
22017        mPointerIcon = pointerIcon;
22018        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22019            return;
22020        }
22021        try {
22022            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22023        } catch (RemoteException e) {
22024        }
22025    }
22026
22027    /**
22028     * Gets the pointer icon for the current view.
22029     */
22030    public PointerIcon getPointerIcon() {
22031        return mPointerIcon;
22032    }
22033
22034    //
22035    // Properties
22036    //
22037    /**
22038     * A Property wrapper around the <code>alpha</code> functionality handled by the
22039     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22040     */
22041    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22042        @Override
22043        public void setValue(View object, float value) {
22044            object.setAlpha(value);
22045        }
22046
22047        @Override
22048        public Float get(View object) {
22049            return object.getAlpha();
22050        }
22051    };
22052
22053    /**
22054     * A Property wrapper around the <code>translationX</code> functionality handled by the
22055     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22056     */
22057    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22058        @Override
22059        public void setValue(View object, float value) {
22060            object.setTranslationX(value);
22061        }
22062
22063                @Override
22064        public Float get(View object) {
22065            return object.getTranslationX();
22066        }
22067    };
22068
22069    /**
22070     * A Property wrapper around the <code>translationY</code> functionality handled by the
22071     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22072     */
22073    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22074        @Override
22075        public void setValue(View object, float value) {
22076            object.setTranslationY(value);
22077        }
22078
22079        @Override
22080        public Float get(View object) {
22081            return object.getTranslationY();
22082        }
22083    };
22084
22085    /**
22086     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22087     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22088     */
22089    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22090        @Override
22091        public void setValue(View object, float value) {
22092            object.setTranslationZ(value);
22093        }
22094
22095        @Override
22096        public Float get(View object) {
22097            return object.getTranslationZ();
22098        }
22099    };
22100
22101    /**
22102     * A Property wrapper around the <code>x</code> functionality handled by the
22103     * {@link View#setX(float)} and {@link View#getX()} methods.
22104     */
22105    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22106        @Override
22107        public void setValue(View object, float value) {
22108            object.setX(value);
22109        }
22110
22111        @Override
22112        public Float get(View object) {
22113            return object.getX();
22114        }
22115    };
22116
22117    /**
22118     * A Property wrapper around the <code>y</code> functionality handled by the
22119     * {@link View#setY(float)} and {@link View#getY()} methods.
22120     */
22121    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22122        @Override
22123        public void setValue(View object, float value) {
22124            object.setY(value);
22125        }
22126
22127        @Override
22128        public Float get(View object) {
22129            return object.getY();
22130        }
22131    };
22132
22133    /**
22134     * A Property wrapper around the <code>z</code> functionality handled by the
22135     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22136     */
22137    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22138        @Override
22139        public void setValue(View object, float value) {
22140            object.setZ(value);
22141        }
22142
22143        @Override
22144        public Float get(View object) {
22145            return object.getZ();
22146        }
22147    };
22148
22149    /**
22150     * A Property wrapper around the <code>rotation</code> functionality handled by the
22151     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22152     */
22153    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22154        @Override
22155        public void setValue(View object, float value) {
22156            object.setRotation(value);
22157        }
22158
22159        @Override
22160        public Float get(View object) {
22161            return object.getRotation();
22162        }
22163    };
22164
22165    /**
22166     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22167     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22168     */
22169    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22170        @Override
22171        public void setValue(View object, float value) {
22172            object.setRotationX(value);
22173        }
22174
22175        @Override
22176        public Float get(View object) {
22177            return object.getRotationX();
22178        }
22179    };
22180
22181    /**
22182     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22183     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22184     */
22185    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22186        @Override
22187        public void setValue(View object, float value) {
22188            object.setRotationY(value);
22189        }
22190
22191        @Override
22192        public Float get(View object) {
22193            return object.getRotationY();
22194        }
22195    };
22196
22197    /**
22198     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22199     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22200     */
22201    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22202        @Override
22203        public void setValue(View object, float value) {
22204            object.setScaleX(value);
22205        }
22206
22207        @Override
22208        public Float get(View object) {
22209            return object.getScaleX();
22210        }
22211    };
22212
22213    /**
22214     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22215     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22216     */
22217    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22218        @Override
22219        public void setValue(View object, float value) {
22220            object.setScaleY(value);
22221        }
22222
22223        @Override
22224        public Float get(View object) {
22225            return object.getScaleY();
22226        }
22227    };
22228
22229    /**
22230     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22231     * Each MeasureSpec represents a requirement for either the width or the height.
22232     * A MeasureSpec is comprised of a size and a mode. There are three possible
22233     * modes:
22234     * <dl>
22235     * <dt>UNSPECIFIED</dt>
22236     * <dd>
22237     * The parent has not imposed any constraint on the child. It can be whatever size
22238     * it wants.
22239     * </dd>
22240     *
22241     * <dt>EXACTLY</dt>
22242     * <dd>
22243     * The parent has determined an exact size for the child. The child is going to be
22244     * given those bounds regardless of how big it wants to be.
22245     * </dd>
22246     *
22247     * <dt>AT_MOST</dt>
22248     * <dd>
22249     * The child can be as large as it wants up to the specified size.
22250     * </dd>
22251     * </dl>
22252     *
22253     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22254     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22255     */
22256    public static class MeasureSpec {
22257        private static final int MODE_SHIFT = 30;
22258        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22259
22260        /** @hide */
22261        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22262        @Retention(RetentionPolicy.SOURCE)
22263        public @interface MeasureSpecMode {}
22264
22265        /**
22266         * Measure specification mode: The parent has not imposed any constraint
22267         * on the child. It can be whatever size it wants.
22268         */
22269        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22270
22271        /**
22272         * Measure specification mode: The parent has determined an exact size
22273         * for the child. The child is going to be given those bounds regardless
22274         * of how big it wants to be.
22275         */
22276        public static final int EXACTLY     = 1 << MODE_SHIFT;
22277
22278        /**
22279         * Measure specification mode: The child can be as large as it wants up
22280         * to the specified size.
22281         */
22282        public static final int AT_MOST     = 2 << MODE_SHIFT;
22283
22284        /**
22285         * Creates a measure specification based on the supplied size and mode.
22286         *
22287         * The mode must always be one of the following:
22288         * <ul>
22289         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22290         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22291         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22292         * </ul>
22293         *
22294         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22295         * implementation was such that the order of arguments did not matter
22296         * and overflow in either value could impact the resulting MeasureSpec.
22297         * {@link android.widget.RelativeLayout} was affected by this bug.
22298         * Apps targeting API levels greater than 17 will get the fixed, more strict
22299         * behavior.</p>
22300         *
22301         * @param size the size of the measure specification
22302         * @param mode the mode of the measure specification
22303         * @return the measure specification based on size and mode
22304         */
22305        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22306                                          @MeasureSpecMode int mode) {
22307            if (sUseBrokenMakeMeasureSpec) {
22308                return size + mode;
22309            } else {
22310                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22311            }
22312        }
22313
22314        /**
22315         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22316         * will automatically get a size of 0. Older apps expect this.
22317         *
22318         * @hide internal use only for compatibility with system widgets and older apps
22319         */
22320        public static int makeSafeMeasureSpec(int size, int mode) {
22321            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22322                return 0;
22323            }
22324            return makeMeasureSpec(size, mode);
22325        }
22326
22327        /**
22328         * Extracts the mode from the supplied measure specification.
22329         *
22330         * @param measureSpec the measure specification to extract the mode from
22331         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22332         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22333         *         {@link android.view.View.MeasureSpec#EXACTLY}
22334         */
22335        @MeasureSpecMode
22336        public static int getMode(int measureSpec) {
22337            //noinspection ResourceType
22338            return (measureSpec & MODE_MASK);
22339        }
22340
22341        /**
22342         * Extracts the size from the supplied measure specification.
22343         *
22344         * @param measureSpec the measure specification to extract the size from
22345         * @return the size in pixels defined in the supplied measure specification
22346         */
22347        public static int getSize(int measureSpec) {
22348            return (measureSpec & ~MODE_MASK);
22349        }
22350
22351        static int adjust(int measureSpec, int delta) {
22352            final int mode = getMode(measureSpec);
22353            int size = getSize(measureSpec);
22354            if (mode == UNSPECIFIED) {
22355                // No need to adjust size for UNSPECIFIED mode.
22356                return makeMeasureSpec(size, UNSPECIFIED);
22357            }
22358            size += delta;
22359            if (size < 0) {
22360                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22361                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22362                size = 0;
22363            }
22364            return makeMeasureSpec(size, mode);
22365        }
22366
22367        /**
22368         * Returns a String representation of the specified measure
22369         * specification.
22370         *
22371         * @param measureSpec the measure specification to convert to a String
22372         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22373         */
22374        public static String toString(int measureSpec) {
22375            int mode = getMode(measureSpec);
22376            int size = getSize(measureSpec);
22377
22378            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22379
22380            if (mode == UNSPECIFIED)
22381                sb.append("UNSPECIFIED ");
22382            else if (mode == EXACTLY)
22383                sb.append("EXACTLY ");
22384            else if (mode == AT_MOST)
22385                sb.append("AT_MOST ");
22386            else
22387                sb.append(mode).append(" ");
22388
22389            sb.append(size);
22390            return sb.toString();
22391        }
22392    }
22393
22394    private final class CheckForLongPress implements Runnable {
22395        private int mOriginalWindowAttachCount;
22396        private float mX;
22397        private float mY;
22398
22399        @Override
22400        public void run() {
22401            if (isPressed() && (mParent != null)
22402                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22403                if (performLongClick(mX, mY)) {
22404                    mHasPerformedLongPress = true;
22405                }
22406            }
22407        }
22408
22409        public void setAnchor(float x, float y) {
22410            mX = x;
22411            mY = y;
22412        }
22413
22414        public void rememberWindowAttachCount() {
22415            mOriginalWindowAttachCount = mWindowAttachCount;
22416        }
22417    }
22418
22419    private final class CheckForTap implements Runnable {
22420        public float x;
22421        public float y;
22422
22423        @Override
22424        public void run() {
22425            mPrivateFlags &= ~PFLAG_PREPRESSED;
22426            setPressed(true, x, y);
22427            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22428        }
22429    }
22430
22431    private final class PerformClick implements Runnable {
22432        @Override
22433        public void run() {
22434            performClick();
22435        }
22436    }
22437
22438    /**
22439     * This method returns a ViewPropertyAnimator object, which can be used to animate
22440     * specific properties on this View.
22441     *
22442     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22443     */
22444    public ViewPropertyAnimator animate() {
22445        if (mAnimator == null) {
22446            mAnimator = new ViewPropertyAnimator(this);
22447        }
22448        return mAnimator;
22449    }
22450
22451    /**
22452     * Sets the name of the View to be used to identify Views in Transitions.
22453     * Names should be unique in the View hierarchy.
22454     *
22455     * @param transitionName The name of the View to uniquely identify it for Transitions.
22456     */
22457    public final void setTransitionName(String transitionName) {
22458        mTransitionName = transitionName;
22459    }
22460
22461    /**
22462     * Returns the name of the View to be used to identify Views in Transitions.
22463     * Names should be unique in the View hierarchy.
22464     *
22465     * <p>This returns null if the View has not been given a name.</p>
22466     *
22467     * @return The name used of the View to be used to identify Views in Transitions or null
22468     * if no name has been given.
22469     */
22470    @ViewDebug.ExportedProperty
22471    public String getTransitionName() {
22472        return mTransitionName;
22473    }
22474
22475    /**
22476     * @hide
22477     */
22478    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22479        // Do nothing.
22480    }
22481
22482    /**
22483     * Interface definition for a callback to be invoked when a hardware key event is
22484     * dispatched to this view. The callback will be invoked before the key event is
22485     * given to the view. This is only useful for hardware keyboards; a software input
22486     * method has no obligation to trigger this listener.
22487     */
22488    public interface OnKeyListener {
22489        /**
22490         * Called when a hardware key is dispatched to a view. This allows listeners to
22491         * get a chance to respond before the target view.
22492         * <p>Key presses in software keyboards will generally NOT trigger this method,
22493         * although some may elect to do so in some situations. Do not assume a
22494         * software input method has to be key-based; even if it is, it may use key presses
22495         * in a different way than you expect, so there is no way to reliably catch soft
22496         * input key presses.
22497         *
22498         * @param v The view the key has been dispatched to.
22499         * @param keyCode The code for the physical key that was pressed
22500         * @param event The KeyEvent object containing full information about
22501         *        the event.
22502         * @return True if the listener has consumed the event, false otherwise.
22503         */
22504        boolean onKey(View v, int keyCode, KeyEvent event);
22505    }
22506
22507    /**
22508     * Interface definition for a callback to be invoked when a touch event is
22509     * dispatched to this view. The callback will be invoked before the touch
22510     * event is given to the view.
22511     */
22512    public interface OnTouchListener {
22513        /**
22514         * Called when a touch event is dispatched to a view. This allows listeners to
22515         * get a chance to respond before the target view.
22516         *
22517         * @param v The view the touch event has been dispatched to.
22518         * @param event The MotionEvent object containing full information about
22519         *        the event.
22520         * @return True if the listener has consumed the event, false otherwise.
22521         */
22522        boolean onTouch(View v, MotionEvent event);
22523    }
22524
22525    /**
22526     * Interface definition for a callback to be invoked when a hover event is
22527     * dispatched to this view. The callback will be invoked before the hover
22528     * event is given to the view.
22529     */
22530    public interface OnHoverListener {
22531        /**
22532         * Called when a hover event is dispatched to a view. This allows listeners to
22533         * get a chance to respond before the target view.
22534         *
22535         * @param v The view the hover event has been dispatched to.
22536         * @param event The MotionEvent object containing full information about
22537         *        the event.
22538         * @return True if the listener has consumed the event, false otherwise.
22539         */
22540        boolean onHover(View v, MotionEvent event);
22541    }
22542
22543    /**
22544     * Interface definition for a callback to be invoked when a generic motion event is
22545     * dispatched to this view. The callback will be invoked before the generic motion
22546     * event is given to the view.
22547     */
22548    public interface OnGenericMotionListener {
22549        /**
22550         * Called when a generic motion event is dispatched to a view. This allows listeners to
22551         * get a chance to respond before the target view.
22552         *
22553         * @param v The view the generic motion event has been dispatched to.
22554         * @param event The MotionEvent object containing full information about
22555         *        the event.
22556         * @return True if the listener has consumed the event, false otherwise.
22557         */
22558        boolean onGenericMotion(View v, MotionEvent event);
22559    }
22560
22561    /**
22562     * Interface definition for a callback to be invoked when a view has been clicked and held.
22563     */
22564    public interface OnLongClickListener {
22565        /**
22566         * Called when a view has been clicked and held.
22567         *
22568         * @param v The view that was clicked and held.
22569         *
22570         * @return true if the callback consumed the long click, false otherwise.
22571         */
22572        boolean onLongClick(View v);
22573    }
22574
22575    /**
22576     * Interface definition for a callback to be invoked when a drag is being dispatched
22577     * to this view.  The callback will be invoked before the hosting view's own
22578     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22579     * onDrag(event) behavior, it should return 'false' from this callback.
22580     *
22581     * <div class="special reference">
22582     * <h3>Developer Guides</h3>
22583     * <p>For a guide to implementing drag and drop features, read the
22584     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22585     * </div>
22586     */
22587    public interface OnDragListener {
22588        /**
22589         * Called when a drag event is dispatched to a view. This allows listeners
22590         * to get a chance to override base View behavior.
22591         *
22592         * @param v The View that received the drag event.
22593         * @param event The {@link android.view.DragEvent} object for the drag event.
22594         * @return {@code true} if the drag event was handled successfully, or {@code false}
22595         * if the drag event was not handled. Note that {@code false} will trigger the View
22596         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22597         */
22598        boolean onDrag(View v, DragEvent event);
22599    }
22600
22601    /**
22602     * Interface definition for a callback to be invoked when the focus state of
22603     * a view changed.
22604     */
22605    public interface OnFocusChangeListener {
22606        /**
22607         * Called when the focus state of a view has changed.
22608         *
22609         * @param v The view whose state has changed.
22610         * @param hasFocus The new focus state of v.
22611         */
22612        void onFocusChange(View v, boolean hasFocus);
22613    }
22614
22615    /**
22616     * Interface definition for a callback to be invoked when a view is clicked.
22617     */
22618    public interface OnClickListener {
22619        /**
22620         * Called when a view has been clicked.
22621         *
22622         * @param v The view that was clicked.
22623         */
22624        void onClick(View v);
22625    }
22626
22627    /**
22628     * Interface definition for a callback to be invoked when a view is context clicked.
22629     */
22630    public interface OnContextClickListener {
22631        /**
22632         * Called when a view is context clicked.
22633         *
22634         * @param v The view that has been context clicked.
22635         * @return true if the callback consumed the context click, false otherwise.
22636         */
22637        boolean onContextClick(View v);
22638    }
22639
22640    /**
22641     * Interface definition for a callback to be invoked when the context menu
22642     * for this view is being built.
22643     */
22644    public interface OnCreateContextMenuListener {
22645        /**
22646         * Called when the context menu for this view is being built. It is not
22647         * safe to hold onto the menu after this method returns.
22648         *
22649         * @param menu The context menu that is being built
22650         * @param v The view for which the context menu is being built
22651         * @param menuInfo Extra information about the item for which the
22652         *            context menu should be shown. This information will vary
22653         *            depending on the class of v.
22654         */
22655        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22656    }
22657
22658    /**
22659     * Interface definition for a callback to be invoked when the status bar changes
22660     * visibility.  This reports <strong>global</strong> changes to the system UI
22661     * state, not what the application is requesting.
22662     *
22663     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22664     */
22665    public interface OnSystemUiVisibilityChangeListener {
22666        /**
22667         * Called when the status bar changes visibility because of a call to
22668         * {@link View#setSystemUiVisibility(int)}.
22669         *
22670         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22671         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22672         * This tells you the <strong>global</strong> state of these UI visibility
22673         * flags, not what your app is currently applying.
22674         */
22675        public void onSystemUiVisibilityChange(int visibility);
22676    }
22677
22678    /**
22679     * Interface definition for a callback to be invoked when this view is attached
22680     * or detached from its window.
22681     */
22682    public interface OnAttachStateChangeListener {
22683        /**
22684         * Called when the view is attached to a window.
22685         * @param v The view that was attached
22686         */
22687        public void onViewAttachedToWindow(View v);
22688        /**
22689         * Called when the view is detached from a window.
22690         * @param v The view that was detached
22691         */
22692        public void onViewDetachedFromWindow(View v);
22693    }
22694
22695    /**
22696     * Listener for applying window insets on a view in a custom way.
22697     *
22698     * <p>Apps may choose to implement this interface if they want to apply custom policy
22699     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22700     * is set, its
22701     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22702     * method will be called instead of the View's own
22703     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22704     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22705     * the View's normal behavior as part of its own.</p>
22706     */
22707    public interface OnApplyWindowInsetsListener {
22708        /**
22709         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22710         * on a View, this listener method will be called instead of the view's own
22711         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22712         *
22713         * @param v The view applying window insets
22714         * @param insets The insets to apply
22715         * @return The insets supplied, minus any insets that were consumed
22716         */
22717        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22718    }
22719
22720    private final class UnsetPressedState implements Runnable {
22721        @Override
22722        public void run() {
22723            setPressed(false);
22724        }
22725    }
22726
22727    /**
22728     * Base class for derived classes that want to save and restore their own
22729     * state in {@link android.view.View#onSaveInstanceState()}.
22730     */
22731    public static class BaseSavedState extends AbsSavedState {
22732        String mStartActivityRequestWhoSaved;
22733
22734        /**
22735         * Constructor used when reading from a parcel. Reads the state of the superclass.
22736         *
22737         * @param source parcel to read from
22738         */
22739        public BaseSavedState(Parcel source) {
22740            this(source, null);
22741        }
22742
22743        /**
22744         * Constructor used when reading from a parcel using a given class loader.
22745         * Reads the state of the superclass.
22746         *
22747         * @param source parcel to read from
22748         * @param loader ClassLoader to use for reading
22749         */
22750        public BaseSavedState(Parcel source, ClassLoader loader) {
22751            super(source, loader);
22752            mStartActivityRequestWhoSaved = source.readString();
22753        }
22754
22755        /**
22756         * Constructor called by derived classes when creating their SavedState objects
22757         *
22758         * @param superState The state of the superclass of this view
22759         */
22760        public BaseSavedState(Parcelable superState) {
22761            super(superState);
22762        }
22763
22764        @Override
22765        public void writeToParcel(Parcel out, int flags) {
22766            super.writeToParcel(out, flags);
22767            out.writeString(mStartActivityRequestWhoSaved);
22768        }
22769
22770        public static final Parcelable.Creator<BaseSavedState> CREATOR
22771                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22772            @Override
22773            public BaseSavedState createFromParcel(Parcel in) {
22774                return new BaseSavedState(in);
22775            }
22776
22777            @Override
22778            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22779                return new BaseSavedState(in, loader);
22780            }
22781
22782            @Override
22783            public BaseSavedState[] newArray(int size) {
22784                return new BaseSavedState[size];
22785            }
22786        };
22787    }
22788
22789    /**
22790     * A set of information given to a view when it is attached to its parent
22791     * window.
22792     */
22793    final static class AttachInfo {
22794        interface Callbacks {
22795            void playSoundEffect(int effectId);
22796            boolean performHapticFeedback(int effectId, boolean always);
22797        }
22798
22799        /**
22800         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22801         * to a Handler. This class contains the target (View) to invalidate and
22802         * the coordinates of the dirty rectangle.
22803         *
22804         * For performance purposes, this class also implements a pool of up to
22805         * POOL_LIMIT objects that get reused. This reduces memory allocations
22806         * whenever possible.
22807         */
22808        static class InvalidateInfo {
22809            private static final int POOL_LIMIT = 10;
22810
22811            private static final SynchronizedPool<InvalidateInfo> sPool =
22812                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22813
22814            View target;
22815
22816            int left;
22817            int top;
22818            int right;
22819            int bottom;
22820
22821            public static InvalidateInfo obtain() {
22822                InvalidateInfo instance = sPool.acquire();
22823                return (instance != null) ? instance : new InvalidateInfo();
22824            }
22825
22826            public void recycle() {
22827                target = null;
22828                sPool.release(this);
22829            }
22830        }
22831
22832        final IWindowSession mSession;
22833
22834        final IWindow mWindow;
22835
22836        final IBinder mWindowToken;
22837
22838        final Display mDisplay;
22839
22840        final Callbacks mRootCallbacks;
22841
22842        IWindowId mIWindowId;
22843        WindowId mWindowId;
22844
22845        /**
22846         * The top view of the hierarchy.
22847         */
22848        View mRootView;
22849
22850        IBinder mPanelParentWindowToken;
22851
22852        boolean mHardwareAccelerated;
22853        boolean mHardwareAccelerationRequested;
22854        ThreadedRenderer mThreadedRenderer;
22855        List<RenderNode> mPendingAnimatingRenderNodes;
22856
22857        /**
22858         * The state of the display to which the window is attached, as reported
22859         * by {@link Display#getState()}.  Note that the display state constants
22860         * declared by {@link Display} do not exactly line up with the screen state
22861         * constants declared by {@link View} (there are more display states than
22862         * screen states).
22863         */
22864        int mDisplayState = Display.STATE_UNKNOWN;
22865
22866        /**
22867         * Scale factor used by the compatibility mode
22868         */
22869        float mApplicationScale;
22870
22871        /**
22872         * Indicates whether the application is in compatibility mode
22873         */
22874        boolean mScalingRequired;
22875
22876        /**
22877         * Left position of this view's window
22878         */
22879        int mWindowLeft;
22880
22881        /**
22882         * Top position of this view's window
22883         */
22884        int mWindowTop;
22885
22886        /**
22887         * Indicates whether views need to use 32-bit drawing caches
22888         */
22889        boolean mUse32BitDrawingCache;
22890
22891        /**
22892         * For windows that are full-screen but using insets to layout inside
22893         * of the screen areas, these are the current insets to appear inside
22894         * the overscan area of the display.
22895         */
22896        final Rect mOverscanInsets = new Rect();
22897
22898        /**
22899         * For windows that are full-screen but using insets to layout inside
22900         * of the screen decorations, these are the current insets for the
22901         * content of the window.
22902         */
22903        final Rect mContentInsets = new Rect();
22904
22905        /**
22906         * For windows that are full-screen but using insets to layout inside
22907         * of the screen decorations, these are the current insets for the
22908         * actual visible parts of the window.
22909         */
22910        final Rect mVisibleInsets = new Rect();
22911
22912        /**
22913         * For windows that are full-screen but using insets to layout inside
22914         * of the screen decorations, these are the current insets for the
22915         * stable system windows.
22916         */
22917        final Rect mStableInsets = new Rect();
22918
22919        /**
22920         * For windows that include areas that are not covered by real surface these are the outsets
22921         * for real surface.
22922         */
22923        final Rect mOutsets = new Rect();
22924
22925        /**
22926         * In multi-window we force show the navigation bar. Because we don't want that the surface
22927         * size changes in this mode, we instead have a flag whether the navigation bar size should
22928         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22929         */
22930        boolean mAlwaysConsumeNavBar;
22931
22932        /**
22933         * The internal insets given by this window.  This value is
22934         * supplied by the client (through
22935         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22936         * be given to the window manager when changed to be used in laying
22937         * out windows behind it.
22938         */
22939        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22940                = new ViewTreeObserver.InternalInsetsInfo();
22941
22942        /**
22943         * Set to true when mGivenInternalInsets is non-empty.
22944         */
22945        boolean mHasNonEmptyGivenInternalInsets;
22946
22947        /**
22948         * All views in the window's hierarchy that serve as scroll containers,
22949         * used to determine if the window can be resized or must be panned
22950         * to adjust for a soft input area.
22951         */
22952        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22953
22954        final KeyEvent.DispatcherState mKeyDispatchState
22955                = new KeyEvent.DispatcherState();
22956
22957        /**
22958         * Indicates whether the view's window currently has the focus.
22959         */
22960        boolean mHasWindowFocus;
22961
22962        /**
22963         * The current visibility of the window.
22964         */
22965        int mWindowVisibility;
22966
22967        /**
22968         * Indicates the time at which drawing started to occur.
22969         */
22970        long mDrawingTime;
22971
22972        /**
22973         * Indicates whether or not ignoring the DIRTY_MASK flags.
22974         */
22975        boolean mIgnoreDirtyState;
22976
22977        /**
22978         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22979         * to avoid clearing that flag prematurely.
22980         */
22981        boolean mSetIgnoreDirtyState = false;
22982
22983        /**
22984         * Indicates whether the view's window is currently in touch mode.
22985         */
22986        boolean mInTouchMode;
22987
22988        /**
22989         * Indicates whether the view has requested unbuffered input dispatching for the current
22990         * event stream.
22991         */
22992        boolean mUnbufferedDispatchRequested;
22993
22994        /**
22995         * Indicates that ViewAncestor should trigger a global layout change
22996         * the next time it performs a traversal
22997         */
22998        boolean mRecomputeGlobalAttributes;
22999
23000        /**
23001         * Always report new attributes at next traversal.
23002         */
23003        boolean mForceReportNewAttributes;
23004
23005        /**
23006         * Set during a traveral if any views want to keep the screen on.
23007         */
23008        boolean mKeepScreenOn;
23009
23010        /**
23011         * Set during a traveral if the light center needs to be updated.
23012         */
23013        boolean mNeedsUpdateLightCenter;
23014
23015        /**
23016         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23017         */
23018        int mSystemUiVisibility;
23019
23020        /**
23021         * Hack to force certain system UI visibility flags to be cleared.
23022         */
23023        int mDisabledSystemUiVisibility;
23024
23025        /**
23026         * Last global system UI visibility reported by the window manager.
23027         */
23028        int mGlobalSystemUiVisibility = -1;
23029
23030        /**
23031         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23032         * attached.
23033         */
23034        boolean mHasSystemUiListeners;
23035
23036        /**
23037         * Set if the window has requested to extend into the overscan region
23038         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23039         */
23040        boolean mOverscanRequested;
23041
23042        /**
23043         * Set if the visibility of any views has changed.
23044         */
23045        boolean mViewVisibilityChanged;
23046
23047        /**
23048         * Set to true if a view has been scrolled.
23049         */
23050        boolean mViewScrollChanged;
23051
23052        /**
23053         * Set to true if high contrast mode enabled
23054         */
23055        boolean mHighContrastText;
23056
23057        /**
23058         * Set to true if a pointer event is currently being handled.
23059         */
23060        boolean mHandlingPointerEvent;
23061
23062        /**
23063         * Global to the view hierarchy used as a temporary for dealing with
23064         * x/y points in the transparent region computations.
23065         */
23066        final int[] mTransparentLocation = new int[2];
23067
23068        /**
23069         * Global to the view hierarchy used as a temporary for dealing with
23070         * x/y points in the ViewGroup.invalidateChild implementation.
23071         */
23072        final int[] mInvalidateChildLocation = new int[2];
23073
23074        /**
23075         * Global to the view hierarchy used as a temporary for dealing with
23076         * computing absolute on-screen location.
23077         */
23078        final int[] mTmpLocation = new int[2];
23079
23080        /**
23081         * Global to the view hierarchy used as a temporary for dealing with
23082         * x/y location when view is transformed.
23083         */
23084        final float[] mTmpTransformLocation = new float[2];
23085
23086        /**
23087         * The view tree observer used to dispatch global events like
23088         * layout, pre-draw, touch mode change, etc.
23089         */
23090        final ViewTreeObserver mTreeObserver;
23091
23092        /**
23093         * A Canvas used by the view hierarchy to perform bitmap caching.
23094         */
23095        Canvas mCanvas;
23096
23097        /**
23098         * The view root impl.
23099         */
23100        final ViewRootImpl mViewRootImpl;
23101
23102        /**
23103         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23104         * handler can be used to pump events in the UI events queue.
23105         */
23106        final Handler mHandler;
23107
23108        /**
23109         * Temporary for use in computing invalidate rectangles while
23110         * calling up the hierarchy.
23111         */
23112        final Rect mTmpInvalRect = new Rect();
23113
23114        /**
23115         * Temporary for use in computing hit areas with transformed views
23116         */
23117        final RectF mTmpTransformRect = new RectF();
23118
23119        /**
23120         * Temporary for use in computing hit areas with transformed views
23121         */
23122        final RectF mTmpTransformRect1 = new RectF();
23123
23124        /**
23125         * Temporary list of rectanges.
23126         */
23127        final List<RectF> mTmpRectList = new ArrayList<>();
23128
23129        /**
23130         * Temporary for use in transforming invalidation rect
23131         */
23132        final Matrix mTmpMatrix = new Matrix();
23133
23134        /**
23135         * Temporary for use in transforming invalidation rect
23136         */
23137        final Transformation mTmpTransformation = new Transformation();
23138
23139        /**
23140         * Temporary for use in querying outlines from OutlineProviders
23141         */
23142        final Outline mTmpOutline = new Outline();
23143
23144        /**
23145         * Temporary list for use in collecting focusable descendents of a view.
23146         */
23147        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23148
23149        /**
23150         * The id of the window for accessibility purposes.
23151         */
23152        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23153
23154        /**
23155         * Flags related to accessibility processing.
23156         *
23157         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23158         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23159         */
23160        int mAccessibilityFetchFlags;
23161
23162        /**
23163         * The drawable for highlighting accessibility focus.
23164         */
23165        Drawable mAccessibilityFocusDrawable;
23166
23167        /**
23168         * Show where the margins, bounds and layout bounds are for each view.
23169         */
23170        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23171
23172        /**
23173         * Point used to compute visible regions.
23174         */
23175        final Point mPoint = new Point();
23176
23177        /**
23178         * Used to track which View originated a requestLayout() call, used when
23179         * requestLayout() is called during layout.
23180         */
23181        View mViewRequestingLayout;
23182
23183        /**
23184         * Used to track views that need (at least) a partial relayout at their current size
23185         * during the next traversal.
23186         */
23187        List<View> mPartialLayoutViews = new ArrayList<>();
23188
23189        /**
23190         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23191         * modification. Lazily assigned during ViewRootImpl layout.
23192         */
23193        List<View> mEmptyPartialLayoutViews;
23194
23195        /**
23196         * Used to track the identity of the current drag operation.
23197         */
23198        IBinder mDragToken;
23199
23200        /**
23201         * The drag shadow surface for the current drag operation.
23202         */
23203        public Surface mDragSurface;
23204
23205        /**
23206         * Creates a new set of attachment information with the specified
23207         * events handler and thread.
23208         *
23209         * @param handler the events handler the view must use
23210         */
23211        AttachInfo(IWindowSession session, IWindow window, Display display,
23212                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
23213                Context context) {
23214            mSession = session;
23215            mWindow = window;
23216            mWindowToken = window.asBinder();
23217            mDisplay = display;
23218            mViewRootImpl = viewRootImpl;
23219            mHandler = handler;
23220            mRootCallbacks = effectPlayer;
23221            mTreeObserver = new ViewTreeObserver(context);
23222        }
23223    }
23224
23225    /**
23226     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23227     * is supported. This avoids keeping too many unused fields in most
23228     * instances of View.</p>
23229     */
23230    private static class ScrollabilityCache implements Runnable {
23231
23232        /**
23233         * Scrollbars are not visible
23234         */
23235        public static final int OFF = 0;
23236
23237        /**
23238         * Scrollbars are visible
23239         */
23240        public static final int ON = 1;
23241
23242        /**
23243         * Scrollbars are fading away
23244         */
23245        public static final int FADING = 2;
23246
23247        public boolean fadeScrollBars;
23248
23249        public int fadingEdgeLength;
23250        public int scrollBarDefaultDelayBeforeFade;
23251        public int scrollBarFadeDuration;
23252
23253        public int scrollBarSize;
23254        public ScrollBarDrawable scrollBar;
23255        public float[] interpolatorValues;
23256        public View host;
23257
23258        public final Paint paint;
23259        public final Matrix matrix;
23260        public Shader shader;
23261
23262        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23263
23264        private static final float[] OPAQUE = { 255 };
23265        private static final float[] TRANSPARENT = { 0.0f };
23266
23267        /**
23268         * When fading should start. This time moves into the future every time
23269         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23270         */
23271        public long fadeStartTime;
23272
23273
23274        /**
23275         * The current state of the scrollbars: ON, OFF, or FADING
23276         */
23277        public int state = OFF;
23278
23279        private int mLastColor;
23280
23281        public final Rect mScrollBarBounds = new Rect();
23282
23283        public static final int NOT_DRAGGING = 0;
23284        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23285        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23286        public int mScrollBarDraggingState = NOT_DRAGGING;
23287
23288        public float mScrollBarDraggingPos = 0;
23289
23290        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23291            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23292            scrollBarSize = configuration.getScaledScrollBarSize();
23293            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23294            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23295
23296            paint = new Paint();
23297            matrix = new Matrix();
23298            // use use a height of 1, and then wack the matrix each time we
23299            // actually use it.
23300            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23301            paint.setShader(shader);
23302            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23303
23304            this.host = host;
23305        }
23306
23307        public void setFadeColor(int color) {
23308            if (color != mLastColor) {
23309                mLastColor = color;
23310
23311                if (color != 0) {
23312                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23313                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23314                    paint.setShader(shader);
23315                    // Restore the default transfer mode (src_over)
23316                    paint.setXfermode(null);
23317                } else {
23318                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23319                    paint.setShader(shader);
23320                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23321                }
23322            }
23323        }
23324
23325        public void run() {
23326            long now = AnimationUtils.currentAnimationTimeMillis();
23327            if (now >= fadeStartTime) {
23328
23329                // the animation fades the scrollbars out by changing
23330                // the opacity (alpha) from fully opaque to fully
23331                // transparent
23332                int nextFrame = (int) now;
23333                int framesCount = 0;
23334
23335                Interpolator interpolator = scrollBarInterpolator;
23336
23337                // Start opaque
23338                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23339
23340                // End transparent
23341                nextFrame += scrollBarFadeDuration;
23342                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23343
23344                state = FADING;
23345
23346                // Kick off the fade animation
23347                host.invalidate(true);
23348            }
23349        }
23350    }
23351
23352    /**
23353     * Resuable callback for sending
23354     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23355     */
23356    private class SendViewScrolledAccessibilityEvent implements Runnable {
23357        public volatile boolean mIsPending;
23358
23359        public void run() {
23360            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23361            mIsPending = false;
23362        }
23363    }
23364
23365    /**
23366     * <p>
23367     * This class represents a delegate that can be registered in a {@link View}
23368     * to enhance accessibility support via composition rather via inheritance.
23369     * It is specifically targeted to widget developers that extend basic View
23370     * classes i.e. classes in package android.view, that would like their
23371     * applications to be backwards compatible.
23372     * </p>
23373     * <div class="special reference">
23374     * <h3>Developer Guides</h3>
23375     * <p>For more information about making applications accessible, read the
23376     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23377     * developer guide.</p>
23378     * </div>
23379     * <p>
23380     * A scenario in which a developer would like to use an accessibility delegate
23381     * is overriding a method introduced in a later API version than the minimal API
23382     * version supported by the application. For example, the method
23383     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23384     * in API version 4 when the accessibility APIs were first introduced. If a
23385     * developer would like his application to run on API version 4 devices (assuming
23386     * all other APIs used by the application are version 4 or lower) and take advantage
23387     * of this method, instead of overriding the method which would break the application's
23388     * backwards compatibility, he can override the corresponding method in this
23389     * delegate and register the delegate in the target View if the API version of
23390     * the system is high enough, i.e. the API version is the same as or higher than the API
23391     * version that introduced
23392     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23393     * </p>
23394     * <p>
23395     * Here is an example implementation:
23396     * </p>
23397     * <code><pre><p>
23398     * if (Build.VERSION.SDK_INT >= 14) {
23399     *     // If the API version is equal of higher than the version in
23400     *     // which onInitializeAccessibilityNodeInfo was introduced we
23401     *     // register a delegate with a customized implementation.
23402     *     View view = findViewById(R.id.view_id);
23403     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23404     *         public void onInitializeAccessibilityNodeInfo(View host,
23405     *                 AccessibilityNodeInfo info) {
23406     *             // Let the default implementation populate the info.
23407     *             super.onInitializeAccessibilityNodeInfo(host, info);
23408     *             // Set some other information.
23409     *             info.setEnabled(host.isEnabled());
23410     *         }
23411     *     });
23412     * }
23413     * </code></pre></p>
23414     * <p>
23415     * This delegate contains methods that correspond to the accessibility methods
23416     * in View. If a delegate has been specified the implementation in View hands
23417     * off handling to the corresponding method in this delegate. The default
23418     * implementation the delegate methods behaves exactly as the corresponding
23419     * method in View for the case of no accessibility delegate been set. Hence,
23420     * to customize the behavior of a View method, clients can override only the
23421     * corresponding delegate method without altering the behavior of the rest
23422     * accessibility related methods of the host view.
23423     * </p>
23424     * <p>
23425     * <strong>Note:</strong> On platform versions prior to
23426     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23427     * views in the {@code android.widget.*} package are called <i>before</i>
23428     * host methods. This prevents certain properties such as class name from
23429     * being modified by overriding
23430     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23431     * as any changes will be overwritten by the host class.
23432     * <p>
23433     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23434     * methods are called <i>after</i> host methods, which all properties to be
23435     * modified without being overwritten by the host class.
23436     */
23437    public static class AccessibilityDelegate {
23438
23439        /**
23440         * Sends an accessibility event of the given type. If accessibility is not
23441         * enabled this method has no effect.
23442         * <p>
23443         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23444         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23445         * been set.
23446         * </p>
23447         *
23448         * @param host The View hosting the delegate.
23449         * @param eventType The type of the event to send.
23450         *
23451         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23452         */
23453        public void sendAccessibilityEvent(View host, int eventType) {
23454            host.sendAccessibilityEventInternal(eventType);
23455        }
23456
23457        /**
23458         * Performs the specified accessibility action on the view. For
23459         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23460         * <p>
23461         * The default implementation behaves as
23462         * {@link View#performAccessibilityAction(int, Bundle)
23463         *  View#performAccessibilityAction(int, Bundle)} for the case of
23464         *  no accessibility delegate been set.
23465         * </p>
23466         *
23467         * @param action The action to perform.
23468         * @return Whether the action was performed.
23469         *
23470         * @see View#performAccessibilityAction(int, Bundle)
23471         *      View#performAccessibilityAction(int, Bundle)
23472         */
23473        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23474            return host.performAccessibilityActionInternal(action, args);
23475        }
23476
23477        /**
23478         * Sends an accessibility event. This method behaves exactly as
23479         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23480         * empty {@link AccessibilityEvent} and does not perform a check whether
23481         * accessibility is enabled.
23482         * <p>
23483         * The default implementation behaves as
23484         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23485         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23486         * the case of no accessibility delegate been set.
23487         * </p>
23488         *
23489         * @param host The View hosting the delegate.
23490         * @param event The event to send.
23491         *
23492         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23493         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23494         */
23495        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23496            host.sendAccessibilityEventUncheckedInternal(event);
23497        }
23498
23499        /**
23500         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23501         * to its children for adding their text content to the event.
23502         * <p>
23503         * The default implementation behaves as
23504         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23505         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23506         * the case of no accessibility delegate been set.
23507         * </p>
23508         *
23509         * @param host The View hosting the delegate.
23510         * @param event The event.
23511         * @return True if the event population was completed.
23512         *
23513         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23514         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23515         */
23516        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23517            return host.dispatchPopulateAccessibilityEventInternal(event);
23518        }
23519
23520        /**
23521         * Gives a chance to the host View to populate the accessibility event with its
23522         * text content.
23523         * <p>
23524         * The default implementation behaves as
23525         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23526         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23527         * the case of no accessibility delegate been set.
23528         * </p>
23529         *
23530         * @param host The View hosting the delegate.
23531         * @param event The accessibility event which to populate.
23532         *
23533         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23534         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23535         */
23536        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23537            host.onPopulateAccessibilityEventInternal(event);
23538        }
23539
23540        /**
23541         * Initializes an {@link AccessibilityEvent} with information about the
23542         * the host View which is the event source.
23543         * <p>
23544         * The default implementation behaves as
23545         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23546         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23547         * the case of no accessibility delegate been set.
23548         * </p>
23549         *
23550         * @param host The View hosting the delegate.
23551         * @param event The event to initialize.
23552         *
23553         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23554         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23555         */
23556        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23557            host.onInitializeAccessibilityEventInternal(event);
23558        }
23559
23560        /**
23561         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23562         * <p>
23563         * The default implementation behaves as
23564         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23565         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23566         * the case of no accessibility delegate been set.
23567         * </p>
23568         *
23569         * @param host The View hosting the delegate.
23570         * @param info The instance to initialize.
23571         *
23572         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23573         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23574         */
23575        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23576            host.onInitializeAccessibilityNodeInfoInternal(info);
23577        }
23578
23579        /**
23580         * Called when a child of the host View has requested sending an
23581         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23582         * to augment the event.
23583         * <p>
23584         * The default implementation behaves as
23585         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23586         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23587         * the case of no accessibility delegate been set.
23588         * </p>
23589         *
23590         * @param host The View hosting the delegate.
23591         * @param child The child which requests sending the event.
23592         * @param event The event to be sent.
23593         * @return True if the event should be sent
23594         *
23595         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23596         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23597         */
23598        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23599                AccessibilityEvent event) {
23600            return host.onRequestSendAccessibilityEventInternal(child, event);
23601        }
23602
23603        /**
23604         * Gets the provider for managing a virtual view hierarchy rooted at this View
23605         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23606         * that explore the window content.
23607         * <p>
23608         * The default implementation behaves as
23609         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23610         * the case of no accessibility delegate been set.
23611         * </p>
23612         *
23613         * @return The provider.
23614         *
23615         * @see AccessibilityNodeProvider
23616         */
23617        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23618            return null;
23619        }
23620
23621        /**
23622         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23623         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23624         * This method is responsible for obtaining an accessibility node info from a
23625         * pool of reusable instances and calling
23626         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23627         * view to initialize the former.
23628         * <p>
23629         * <strong>Note:</strong> The client is responsible for recycling the obtained
23630         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23631         * creation.
23632         * </p>
23633         * <p>
23634         * The default implementation behaves as
23635         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23636         * the case of no accessibility delegate been set.
23637         * </p>
23638         * @return A populated {@link AccessibilityNodeInfo}.
23639         *
23640         * @see AccessibilityNodeInfo
23641         *
23642         * @hide
23643         */
23644        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23645            return host.createAccessibilityNodeInfoInternal();
23646        }
23647    }
23648
23649    private class MatchIdPredicate implements Predicate<View> {
23650        public int mId;
23651
23652        @Override
23653        public boolean apply(View view) {
23654            return (view.mID == mId);
23655        }
23656    }
23657
23658    private class MatchLabelForPredicate implements Predicate<View> {
23659        private int mLabeledId;
23660
23661        @Override
23662        public boolean apply(View view) {
23663            return (view.mLabelForId == mLabeledId);
23664        }
23665    }
23666
23667    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23668        private int mChangeTypes = 0;
23669        private boolean mPosted;
23670        private boolean mPostedWithDelay;
23671        private long mLastEventTimeMillis;
23672
23673        @Override
23674        public void run() {
23675            mPosted = false;
23676            mPostedWithDelay = false;
23677            mLastEventTimeMillis = SystemClock.uptimeMillis();
23678            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23679                final AccessibilityEvent event = AccessibilityEvent.obtain();
23680                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23681                event.setContentChangeTypes(mChangeTypes);
23682                sendAccessibilityEventUnchecked(event);
23683            }
23684            mChangeTypes = 0;
23685        }
23686
23687        public void runOrPost(int changeType) {
23688            mChangeTypes |= changeType;
23689
23690            // If this is a live region or the child of a live region, collect
23691            // all events from this frame and send them on the next frame.
23692            if (inLiveRegion()) {
23693                // If we're already posted with a delay, remove that.
23694                if (mPostedWithDelay) {
23695                    removeCallbacks(this);
23696                    mPostedWithDelay = false;
23697                }
23698                // Only post if we're not already posted.
23699                if (!mPosted) {
23700                    post(this);
23701                    mPosted = true;
23702                }
23703                return;
23704            }
23705
23706            if (mPosted) {
23707                return;
23708            }
23709
23710            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23711            final long minEventIntevalMillis =
23712                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23713            if (timeSinceLastMillis >= minEventIntevalMillis) {
23714                removeCallbacks(this);
23715                run();
23716            } else {
23717                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23718                mPostedWithDelay = true;
23719            }
23720        }
23721    }
23722
23723    private boolean inLiveRegion() {
23724        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23725            return true;
23726        }
23727
23728        ViewParent parent = getParent();
23729        while (parent instanceof View) {
23730            if (((View) parent).getAccessibilityLiveRegion()
23731                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23732                return true;
23733            }
23734            parent = parent.getParent();
23735        }
23736
23737        return false;
23738    }
23739
23740    /**
23741     * Dump all private flags in readable format, useful for documentation and
23742     * sanity checking.
23743     */
23744    private static void dumpFlags() {
23745        final HashMap<String, String> found = Maps.newHashMap();
23746        try {
23747            for (Field field : View.class.getDeclaredFields()) {
23748                final int modifiers = field.getModifiers();
23749                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23750                    if (field.getType().equals(int.class)) {
23751                        final int value = field.getInt(null);
23752                        dumpFlag(found, field.getName(), value);
23753                    } else if (field.getType().equals(int[].class)) {
23754                        final int[] values = (int[]) field.get(null);
23755                        for (int i = 0; i < values.length; i++) {
23756                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23757                        }
23758                    }
23759                }
23760            }
23761        } catch (IllegalAccessException e) {
23762            throw new RuntimeException(e);
23763        }
23764
23765        final ArrayList<String> keys = Lists.newArrayList();
23766        keys.addAll(found.keySet());
23767        Collections.sort(keys);
23768        for (String key : keys) {
23769            Log.d(VIEW_LOG_TAG, found.get(key));
23770        }
23771    }
23772
23773    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23774        // Sort flags by prefix, then by bits, always keeping unique keys
23775        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23776        final int prefix = name.indexOf('_');
23777        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23778        final String output = bits + " " + name;
23779        found.put(key, output);
23780    }
23781
23782    /** {@hide} */
23783    public void encode(@NonNull ViewHierarchyEncoder stream) {
23784        stream.beginObject(this);
23785        encodeProperties(stream);
23786        stream.endObject();
23787    }
23788
23789    /** {@hide} */
23790    @CallSuper
23791    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23792        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23793        if (resolveId instanceof String) {
23794            stream.addProperty("id", (String) resolveId);
23795        } else {
23796            stream.addProperty("id", mID);
23797        }
23798
23799        stream.addProperty("misc:transformation.alpha",
23800                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23801        stream.addProperty("misc:transitionName", getTransitionName());
23802
23803        // layout
23804        stream.addProperty("layout:left", mLeft);
23805        stream.addProperty("layout:right", mRight);
23806        stream.addProperty("layout:top", mTop);
23807        stream.addProperty("layout:bottom", mBottom);
23808        stream.addProperty("layout:width", getWidth());
23809        stream.addProperty("layout:height", getHeight());
23810        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23811        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23812        stream.addProperty("layout:hasTransientState", hasTransientState());
23813        stream.addProperty("layout:baseline", getBaseline());
23814
23815        // layout params
23816        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23817        if (layoutParams != null) {
23818            stream.addPropertyKey("layoutParams");
23819            layoutParams.encode(stream);
23820        }
23821
23822        // scrolling
23823        stream.addProperty("scrolling:scrollX", mScrollX);
23824        stream.addProperty("scrolling:scrollY", mScrollY);
23825
23826        // padding
23827        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23828        stream.addProperty("padding:paddingRight", mPaddingRight);
23829        stream.addProperty("padding:paddingTop", mPaddingTop);
23830        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23831        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23832        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23833        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23834        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23835        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23836
23837        // measurement
23838        stream.addProperty("measurement:minHeight", mMinHeight);
23839        stream.addProperty("measurement:minWidth", mMinWidth);
23840        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23841        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23842
23843        // drawing
23844        stream.addProperty("drawing:elevation", getElevation());
23845        stream.addProperty("drawing:translationX", getTranslationX());
23846        stream.addProperty("drawing:translationY", getTranslationY());
23847        stream.addProperty("drawing:translationZ", getTranslationZ());
23848        stream.addProperty("drawing:rotation", getRotation());
23849        stream.addProperty("drawing:rotationX", getRotationX());
23850        stream.addProperty("drawing:rotationY", getRotationY());
23851        stream.addProperty("drawing:scaleX", getScaleX());
23852        stream.addProperty("drawing:scaleY", getScaleY());
23853        stream.addProperty("drawing:pivotX", getPivotX());
23854        stream.addProperty("drawing:pivotY", getPivotY());
23855        stream.addProperty("drawing:opaque", isOpaque());
23856        stream.addProperty("drawing:alpha", getAlpha());
23857        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23858        stream.addProperty("drawing:shadow", hasShadow());
23859        stream.addProperty("drawing:solidColor", getSolidColor());
23860        stream.addProperty("drawing:layerType", mLayerType);
23861        stream.addProperty("drawing:willNotDraw", willNotDraw());
23862        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23863        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23864        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23865        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23866
23867        // focus
23868        stream.addProperty("focus:hasFocus", hasFocus());
23869        stream.addProperty("focus:isFocused", isFocused());
23870        stream.addProperty("focus:isFocusable", isFocusable());
23871        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23872
23873        stream.addProperty("misc:clickable", isClickable());
23874        stream.addProperty("misc:pressed", isPressed());
23875        stream.addProperty("misc:selected", isSelected());
23876        stream.addProperty("misc:touchMode", isInTouchMode());
23877        stream.addProperty("misc:hovered", isHovered());
23878        stream.addProperty("misc:activated", isActivated());
23879
23880        stream.addProperty("misc:visibility", getVisibility());
23881        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23882        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23883
23884        stream.addProperty("misc:enabled", isEnabled());
23885        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23886        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23887
23888        // theme attributes
23889        Resources.Theme theme = getContext().getTheme();
23890        if (theme != null) {
23891            stream.addPropertyKey("theme");
23892            theme.encode(stream);
23893        }
23894
23895        // view attribute information
23896        int n = mAttributes != null ? mAttributes.length : 0;
23897        stream.addProperty("meta:__attrCount__", n/2);
23898        for (int i = 0; i < n; i += 2) {
23899            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23900        }
23901
23902        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23903
23904        // text
23905        stream.addProperty("text:textDirection", getTextDirection());
23906        stream.addProperty("text:textAlignment", getTextAlignment());
23907
23908        // accessibility
23909        CharSequence contentDescription = getContentDescription();
23910        stream.addProperty("accessibility:contentDescription",
23911                contentDescription == null ? "" : contentDescription.toString());
23912        stream.addProperty("accessibility:labelFor", getLabelFor());
23913        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23914    }
23915
23916    /**
23917     * Determine if this view is rendered on a round wearable device and is the main view
23918     * on the screen.
23919     */
23920    private boolean shouldDrawRoundScrollbar() {
23921        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
23922            return false;
23923        }
23924
23925        final View rootView = getRootView();
23926        final WindowInsets insets = getRootWindowInsets();
23927
23928        int height = getHeight();
23929        int width = getWidth();
23930        int displayHeight = rootView.getHeight();
23931        int displayWidth = rootView.getWidth();
23932
23933        if (height != displayHeight || width != displayWidth) {
23934            return false;
23935        }
23936
23937        getLocationOnScreen(mAttachInfo.mTmpLocation);
23938        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
23939                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
23940    }
23941}
23942