View.java revision 82d3cd69b5b2947a01657132de86c5a4e00692f1
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.LayoutRes;
28import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.Size;
31import android.content.ClipData;
32import android.content.Context;
33import android.content.Intent;
34import android.content.res.ColorStateList;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.content.res.TypedArray;
38import android.graphics.Bitmap;
39import android.graphics.Canvas;
40import android.graphics.Insets;
41import android.graphics.Interpolator;
42import android.graphics.LinearGradient;
43import android.graphics.Matrix;
44import android.graphics.Outline;
45import android.graphics.Paint;
46import android.graphics.PixelFormat;
47import android.graphics.Point;
48import android.graphics.PorterDuff;
49import android.graphics.PorterDuffXfermode;
50import android.graphics.Rect;
51import android.graphics.RectF;
52import android.graphics.Region;
53import android.graphics.Shader;
54import android.graphics.drawable.ColorDrawable;
55import android.graphics.drawable.Drawable;
56import android.hardware.display.DisplayManagerGlobal;
57import android.os.Bundle;
58import android.os.Handler;
59import android.os.IBinder;
60import android.os.Parcel;
61import android.os.Parcelable;
62import android.os.RemoteException;
63import android.os.SystemClock;
64import android.os.SystemProperties;
65import android.os.Trace;
66import android.text.TextUtils;
67import android.util.AttributeSet;
68import android.util.FloatProperty;
69import android.util.LayoutDirection;
70import android.util.Log;
71import android.util.LongSparseLongArray;
72import android.util.Pools.SynchronizedPool;
73import android.util.Property;
74import android.util.SparseArray;
75import android.util.StateSet;
76import android.util.SuperNotCalledException;
77import android.util.TypedValue;
78import android.view.ContextMenu.ContextMenuInfo;
79import android.view.AccessibilityIterators.TextSegmentIterator;
80import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
81import android.view.AccessibilityIterators.WordTextSegmentIterator;
82import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
83import android.view.accessibility.AccessibilityEvent;
84import android.view.accessibility.AccessibilityEventSource;
85import android.view.accessibility.AccessibilityManager;
86import android.view.accessibility.AccessibilityNodeInfo;
87import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
88import android.view.accessibility.AccessibilityNodeProvider;
89import android.view.animation.Animation;
90import android.view.animation.AnimationUtils;
91import android.view.animation.Transformation;
92import android.view.inputmethod.EditorInfo;
93import android.view.inputmethod.InputConnection;
94import android.view.inputmethod.InputMethodManager;
95import android.widget.Checkable;
96import android.widget.ScrollBarDrawable;
97
98import static android.os.Build.VERSION_CODES.*;
99import static java.lang.Math.max;
100
101import com.android.internal.R;
102import com.android.internal.util.Predicate;
103import com.android.internal.view.menu.MenuBuilder;
104import com.google.android.collect.Lists;
105import com.google.android.collect.Maps;
106
107import java.lang.annotation.Retention;
108import java.lang.annotation.RetentionPolicy;
109import java.lang.ref.WeakReference;
110import java.lang.reflect.Field;
111import java.lang.reflect.InvocationTargetException;
112import java.lang.reflect.Method;
113import java.lang.reflect.Modifier;
114import java.util.ArrayList;
115import java.util.Arrays;
116import java.util.Collections;
117import java.util.HashMap;
118import java.util.List;
119import java.util.Locale;
120import java.util.Map;
121import java.util.concurrent.CopyOnWriteArrayList;
122import java.util.concurrent.atomic.AtomicInteger;
123
124/**
125 * <p>
126 * This class represents the basic building block for user interface components. A View
127 * occupies a rectangular area on the screen and is responsible for drawing and
128 * event handling. View is the base class for <em>widgets</em>, which are
129 * used to create interactive UI components (buttons, text fields, etc.). The
130 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
131 * are invisible containers that hold other Views (or other ViewGroups) and define
132 * their layout properties.
133 * </p>
134 *
135 * <div class="special reference">
136 * <h3>Developer Guides</h3>
137 * <p>For information about using this class to develop your application's user interface,
138 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
139 * </div>
140 *
141 * <a name="Using"></a>
142 * <h3>Using Views</h3>
143 * <p>
144 * All of the views in a window are arranged in a single tree. You can add views
145 * either from code or by specifying a tree of views in one or more XML layout
146 * files. There are many specialized subclasses of views that act as controls or
147 * are capable of displaying text, images, or other content.
148 * </p>
149 * <p>
150 * Once you have created a tree of views, there are typically a few types of
151 * common operations you may wish to perform:
152 * <ul>
153 * <li><strong>Set properties:</strong> for example setting the text of a
154 * {@link android.widget.TextView}. The available properties and the methods
155 * that set them will vary among the different subclasses of views. Note that
156 * properties that are known at build time can be set in the XML layout
157 * files.</li>
158 * <li><strong>Set focus:</strong> The framework will handled moving focus in
159 * response to user input. To force focus to a specific view, call
160 * {@link #requestFocus}.</li>
161 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
162 * that will be notified when something interesting happens to the view. For
163 * example, all views will let you set a listener to be notified when the view
164 * gains or loses focus. You can register such a listener using
165 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
166 * Other view subclasses offer more specialized listeners. For example, a Button
167 * exposes a listener to notify clients when the button is clicked.</li>
168 * <li><strong>Set visibility:</strong> You can hide or show views using
169 * {@link #setVisibility(int)}.</li>
170 * </ul>
171 * </p>
172 * <p><em>
173 * Note: The Android framework is responsible for measuring, laying out and
174 * drawing views. You should not call methods that perform these actions on
175 * views yourself unless you are actually implementing a
176 * {@link android.view.ViewGroup}.
177 * </em></p>
178 *
179 * <a name="Lifecycle"></a>
180 * <h3>Implementing a Custom View</h3>
181 *
182 * <p>
183 * To implement a custom view, you will usually begin by providing overrides for
184 * some of the standard methods that the framework calls on all views. You do
185 * not need to override all of these methods. In fact, you can start by just
186 * overriding {@link #onDraw(android.graphics.Canvas)}.
187 * <table border="2" width="85%" align="center" cellpadding="5">
188 *     <thead>
189 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
190 *     </thead>
191 *
192 *     <tbody>
193 *     <tr>
194 *         <td rowspan="2">Creation</td>
195 *         <td>Constructors</td>
196 *         <td>There is a form of the constructor that are called when the view
197 *         is created from code and a form that is called when the view is
198 *         inflated from a layout file. The second form should parse and apply
199 *         any attributes defined in the layout file.
200 *         </td>
201 *     </tr>
202 *     <tr>
203 *         <td><code>{@link #onFinishInflate()}</code></td>
204 *         <td>Called after a view and all of its children has been inflated
205 *         from XML.</td>
206 *     </tr>
207 *
208 *     <tr>
209 *         <td rowspan="3">Layout</td>
210 *         <td><code>{@link #onMeasure(int, int)}</code></td>
211 *         <td>Called to determine the size requirements for this view and all
212 *         of its children.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
217 *         <td>Called when this view should assign a size and position to all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
223 *         <td>Called when the size of this view has changed.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td>Drawing</td>
229 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
230 *         <td>Called when the view should render its content.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="4">Event processing</td>
236 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
237 *         <td>Called when a new hardware key event occurs.
238 *         </td>
239 *     </tr>
240 *     <tr>
241 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
242 *         <td>Called when a hardware key up event occurs.
243 *         </td>
244 *     </tr>
245 *     <tr>
246 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
247 *         <td>Called when a trackball motion event occurs.
248 *         </td>
249 *     </tr>
250 *     <tr>
251 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
252 *         <td>Called when a touch screen motion event occurs.
253 *         </td>
254 *     </tr>
255 *
256 *     <tr>
257 *         <td rowspan="2">Focus</td>
258 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
259 *         <td>Called when the view gains or loses focus.
260 *         </td>
261 *     </tr>
262 *
263 *     <tr>
264 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
265 *         <td>Called when the window containing the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td rowspan="3">Attaching</td>
271 *         <td><code>{@link #onAttachedToWindow()}</code></td>
272 *         <td>Called when the view is attached to a window.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td><code>{@link #onDetachedFromWindow}</code></td>
278 *         <td>Called when the view is detached from its window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
284 *         <td>Called when the visibility of the window containing the view
285 *         has changed.
286 *         </td>
287 *     </tr>
288 *     </tbody>
289 *
290 * </table>
291 * </p>
292 *
293 * <a name="IDs"></a>
294 * <h3>IDs</h3>
295 * Views may have an integer id associated with them. These ids are typically
296 * assigned in the layout XML files, and are used to find specific views within
297 * the view tree. A common pattern is to:
298 * <ul>
299 * <li>Define a Button in the layout file and assign it a unique ID.
300 * <pre>
301 * &lt;Button
302 *     android:id="@+id/my_button"
303 *     android:layout_width="wrap_content"
304 *     android:layout_height="wrap_content"
305 *     android:text="@string/my_button_text"/&gt;
306 * </pre></li>
307 * <li>From the onCreate method of an Activity, find the Button
308 * <pre class="prettyprint">
309 *      Button myButton = (Button) findViewById(R.id.my_button);
310 * </pre></li>
311 * </ul>
312 * <p>
313 * View IDs need not be unique throughout the tree, but it is good practice to
314 * ensure that they are at least unique within the part of the tree you are
315 * searching.
316 * </p>
317 *
318 * <a name="Position"></a>
319 * <h3>Position</h3>
320 * <p>
321 * The geometry of a view is that of a rectangle. A view has a location,
322 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
323 * two dimensions, expressed as a width and a height. The unit for location
324 * and dimensions is the pixel.
325 * </p>
326 *
327 * <p>
328 * It is possible to retrieve the location of a view by invoking the methods
329 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
330 * coordinate of the rectangle representing the view. The latter returns the
331 * top, or Y, coordinate of the rectangle representing the view. These methods
332 * both return the location of the view relative to its parent. For instance,
333 * when getLeft() returns 20, that means the view is located 20 pixels to the
334 * right of the left edge of its direct parent.
335 * </p>
336 *
337 * <p>
338 * In addition, several convenience methods are offered to avoid unnecessary
339 * computations, namely {@link #getRight()} and {@link #getBottom()}.
340 * These methods return the coordinates of the right and bottom edges of the
341 * rectangle representing the view. For instance, calling {@link #getRight()}
342 * is similar to the following computation: <code>getLeft() + getWidth()</code>
343 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
344 * </p>
345 *
346 * <a name="SizePaddingMargins"></a>
347 * <h3>Size, padding and margins</h3>
348 * <p>
349 * The size of a view is expressed with a width and a height. A view actually
350 * possess two pairs of width and height values.
351 * </p>
352 *
353 * <p>
354 * The first pair is known as <em>measured width</em> and
355 * <em>measured height</em>. These dimensions define how big a view wants to be
356 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
357 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
358 * and {@link #getMeasuredHeight()}.
359 * </p>
360 *
361 * <p>
362 * The second pair is simply known as <em>width</em> and <em>height</em>, or
363 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
364 * dimensions define the actual size of the view on screen, at drawing time and
365 * after layout. These values may, but do not have to, be different from the
366 * measured width and height. The width and height can be obtained by calling
367 * {@link #getWidth()} and {@link #getHeight()}.
368 * </p>
369 *
370 * <p>
371 * To measure its dimensions, a view takes into account its padding. The padding
372 * is expressed in pixels for the left, top, right and bottom parts of the view.
373 * Padding can be used to offset the content of the view by a specific amount of
374 * pixels. For instance, a left padding of 2 will push the view's content by
375 * 2 pixels to the right of the left edge. Padding can be set using the
376 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
377 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
378 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
379 * {@link #getPaddingEnd()}.
380 * </p>
381 *
382 * <p>
383 * Even though a view can define a padding, it does not provide any support for
384 * margins. However, view groups provide such a support. Refer to
385 * {@link android.view.ViewGroup} and
386 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
387 * </p>
388 *
389 * <a name="Layout"></a>
390 * <h3>Layout</h3>
391 * <p>
392 * Layout is a two pass process: a measure pass and a layout pass. The measuring
393 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
394 * of the view tree. Each view pushes dimension specifications down the tree
395 * during the recursion. At the end of the measure pass, every view has stored
396 * its measurements. The second pass happens in
397 * {@link #layout(int,int,int,int)} and is also top-down. During
398 * this pass each parent is responsible for positioning all of its children
399 * using the sizes computed in the measure pass.
400 * </p>
401 *
402 * <p>
403 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
404 * {@link #getMeasuredHeight()} values must be set, along with those for all of
405 * that view's descendants. A view's measured width and measured height values
406 * must respect the constraints imposed by the view's parents. This guarantees
407 * that at the end of the measure pass, all parents accept all of their
408 * children's measurements. A parent view may call measure() more than once on
409 * its children. For example, the parent may measure each child once with
410 * unspecified dimensions to find out how big they want to be, then call
411 * measure() on them again with actual numbers if the sum of all the children's
412 * unconstrained sizes is too big or too small.
413 * </p>
414 *
415 * <p>
416 * The measure pass uses two classes to communicate dimensions. The
417 * {@link MeasureSpec} class is used by views to tell their parents how they
418 * want to be measured and positioned. The base LayoutParams class just
419 * describes how big the view wants to be for both width and height. For each
420 * dimension, it can specify one of:
421 * <ul>
422 * <li> an exact number
423 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
424 * (minus padding)
425 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
426 * enclose its content (plus padding).
427 * </ul>
428 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
429 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
430 * an X and Y value.
431 * </p>
432 *
433 * <p>
434 * MeasureSpecs are used to push requirements down the tree from parent to
435 * child. A MeasureSpec can be in one of three modes:
436 * <ul>
437 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
438 * of a child view. For example, a LinearLayout may call measure() on its child
439 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
440 * tall the child view wants to be given a width of 240 pixels.
441 * <li>EXACTLY: This is used by the parent to impose an exact size on the
442 * child. The child must use this size, and guarantee that all of its
443 * descendants will fit within this size.
444 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
445 * child. The child must guarantee that it and all of its descendants will fit
446 * within this size.
447 * </ul>
448 * </p>
449 *
450 * <p>
451 * To initiate a layout, call {@link #requestLayout}. This method is typically
452 * called by a view on itself when it believes that is can no longer fit within
453 * its current bounds.
454 * </p>
455 *
456 * <a name="Drawing"></a>
457 * <h3>Drawing</h3>
458 * <p>
459 * Drawing is handled by walking the tree and recording the drawing commands of
460 * any View that needs to update. After this, the drawing commands of the
461 * entire tree are issued to screen, clipped to the newly damaged area.
462 * </p>
463 *
464 * <p>
465 * The tree is largely recorded and drawn in order, with parents drawn before
466 * (i.e., behind) their children, with siblings drawn in the order they appear
467 * in the tree. If you set a background drawable for a View, then the View will
468 * draw it before calling back to its <code>onDraw()</code> method. The child
469 * drawing order can be overridden with
470 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
471 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
472 * </p>
473 *
474 * <p>
475 * To force a view to draw, call {@link #invalidate()}.
476 * </p>
477 *
478 * <a name="EventHandlingThreading"></a>
479 * <h3>Event Handling and Threading</h3>
480 * <p>
481 * The basic cycle of a view is as follows:
482 * <ol>
483 * <li>An event comes in and is dispatched to the appropriate view. The view
484 * handles the event and notifies any listeners.</li>
485 * <li>If in the course of processing the event, the view's bounds may need
486 * to be changed, the view will call {@link #requestLayout()}.</li>
487 * <li>Similarly, if in the course of processing the event the view's appearance
488 * may need to be changed, the view will call {@link #invalidate()}.</li>
489 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
490 * the framework will take care of measuring, laying out, and drawing the tree
491 * as appropriate.</li>
492 * </ol>
493 * </p>
494 *
495 * <p><em>Note: The entire view tree is single threaded. You must always be on
496 * the UI thread when calling any method on any view.</em>
497 * If you are doing work on other threads and want to update the state of a view
498 * from that thread, you should use a {@link Handler}.
499 * </p>
500 *
501 * <a name="FocusHandling"></a>
502 * <h3>Focus Handling</h3>
503 * <p>
504 * The framework will handle routine focus movement in response to user input.
505 * This includes changing the focus as views are removed or hidden, or as new
506 * views become available. Views indicate their willingness to take focus
507 * through the {@link #isFocusable} method. To change whether a view can take
508 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
509 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
510 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
511 * </p>
512 * <p>
513 * Focus movement is based on an algorithm which finds the nearest neighbor in a
514 * given direction. In rare cases, the default algorithm may not match the
515 * intended behavior of the developer. In these situations, you can provide
516 * explicit overrides by using these XML attributes in the layout file:
517 * <pre>
518 * nextFocusDown
519 * nextFocusLeft
520 * nextFocusRight
521 * nextFocusUp
522 * </pre>
523 * </p>
524 *
525 *
526 * <p>
527 * To get a particular view to take focus, call {@link #requestFocus()}.
528 * </p>
529 *
530 * <a name="TouchMode"></a>
531 * <h3>Touch Mode</h3>
532 * <p>
533 * When a user is navigating a user interface via directional keys such as a D-pad, it is
534 * necessary to give focus to actionable items such as buttons so the user can see
535 * what will take input.  If the device has touch capabilities, however, and the user
536 * begins interacting with the interface by touching it, it is no longer necessary to
537 * always highlight, or give focus to, a particular view.  This motivates a mode
538 * for interaction named 'touch mode'.
539 * </p>
540 * <p>
541 * For a touch capable device, once the user touches the screen, the device
542 * will enter touch mode.  From this point onward, only views for which
543 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
544 * Other views that are touchable, like buttons, will not take focus when touched; they will
545 * only fire the on click listeners.
546 * </p>
547 * <p>
548 * Any time a user hits a directional key, such as a D-pad direction, the view device will
549 * exit touch mode, and find a view to take focus, so that the user may resume interacting
550 * with the user interface without touching the screen again.
551 * </p>
552 * <p>
553 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
554 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
555 * </p>
556 *
557 * <a name="Scrolling"></a>
558 * <h3>Scrolling</h3>
559 * <p>
560 * The framework provides basic support for views that wish to internally
561 * scroll their content. This includes keeping track of the X and Y scroll
562 * offset as well as mechanisms for drawing scrollbars. See
563 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
564 * {@link #awakenScrollBars()} for more details.
565 * </p>
566 *
567 * <a name="Tags"></a>
568 * <h3>Tags</h3>
569 * <p>
570 * Unlike IDs, tags are not used to identify views. Tags are essentially an
571 * extra piece of information that can be associated with a view. They are most
572 * often used as a convenience to store data related to views in the views
573 * themselves rather than by putting them in a separate structure.
574 * </p>
575 *
576 * <a name="Properties"></a>
577 * <h3>Properties</h3>
578 * <p>
579 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
580 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
581 * available both in the {@link Property} form as well as in similarly-named setter/getter
582 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
583 * be used to set persistent state associated with these rendering-related properties on the view.
584 * The properties and methods can also be used in conjunction with
585 * {@link android.animation.Animator Animator}-based animations, described more in the
586 * <a href="#Animation">Animation</a> section.
587 * </p>
588 *
589 * <a name="Animation"></a>
590 * <h3>Animation</h3>
591 * <p>
592 * Starting with Android 3.0, the preferred way of animating views is to use the
593 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
594 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
595 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
596 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
597 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
598 * makes animating these View properties particularly easy and efficient.
599 * </p>
600 * <p>
601 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
602 * You can attach an {@link Animation} object to a view using
603 * {@link #setAnimation(Animation)} or
604 * {@link #startAnimation(Animation)}. The animation can alter the scale,
605 * rotation, translation and alpha of a view over time. If the animation is
606 * attached to a view that has children, the animation will affect the entire
607 * subtree rooted by that node. When an animation is started, the framework will
608 * take care of redrawing the appropriate views until the animation completes.
609 * </p>
610 *
611 * <a name="Security"></a>
612 * <h3>Security</h3>
613 * <p>
614 * Sometimes it is essential that an application be able to verify that an action
615 * is being performed with the full knowledge and consent of the user, such as
616 * granting a permission request, making a purchase or clicking on an advertisement.
617 * Unfortunately, a malicious application could try to spoof the user into
618 * performing these actions, unaware, by concealing the intended purpose of the view.
619 * As a remedy, the framework offers a touch filtering mechanism that can be used to
620 * improve the security of views that provide access to sensitive functionality.
621 * </p><p>
622 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
623 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
624 * will discard touches that are received whenever the view's window is obscured by
625 * another visible window.  As a result, the view will not receive touches whenever a
626 * toast, dialog or other window appears above the view's window.
627 * </p><p>
628 * For more fine-grained control over security, consider overriding the
629 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
630 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
631 * </p>
632 *
633 * @attr ref android.R.styleable#View_alpha
634 * @attr ref android.R.styleable#View_background
635 * @attr ref android.R.styleable#View_clickable
636 * @attr ref android.R.styleable#View_contentDescription
637 * @attr ref android.R.styleable#View_drawingCacheQuality
638 * @attr ref android.R.styleable#View_duplicateParentState
639 * @attr ref android.R.styleable#View_id
640 * @attr ref android.R.styleable#View_requiresFadingEdge
641 * @attr ref android.R.styleable#View_fadeScrollbars
642 * @attr ref android.R.styleable#View_fadingEdgeLength
643 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
644 * @attr ref android.R.styleable#View_fitsSystemWindows
645 * @attr ref android.R.styleable#View_isScrollContainer
646 * @attr ref android.R.styleable#View_focusable
647 * @attr ref android.R.styleable#View_focusableInTouchMode
648 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
649 * @attr ref android.R.styleable#View_keepScreenOn
650 * @attr ref android.R.styleable#View_layerType
651 * @attr ref android.R.styleable#View_layoutDirection
652 * @attr ref android.R.styleable#View_longClickable
653 * @attr ref android.R.styleable#View_minHeight
654 * @attr ref android.R.styleable#View_minWidth
655 * @attr ref android.R.styleable#View_nextFocusDown
656 * @attr ref android.R.styleable#View_nextFocusLeft
657 * @attr ref android.R.styleable#View_nextFocusRight
658 * @attr ref android.R.styleable#View_nextFocusUp
659 * @attr ref android.R.styleable#View_onClick
660 * @attr ref android.R.styleable#View_padding
661 * @attr ref android.R.styleable#View_paddingBottom
662 * @attr ref android.R.styleable#View_paddingLeft
663 * @attr ref android.R.styleable#View_paddingRight
664 * @attr ref android.R.styleable#View_paddingTop
665 * @attr ref android.R.styleable#View_paddingStart
666 * @attr ref android.R.styleable#View_paddingEnd
667 * @attr ref android.R.styleable#View_saveEnabled
668 * @attr ref android.R.styleable#View_rotation
669 * @attr ref android.R.styleable#View_rotationX
670 * @attr ref android.R.styleable#View_rotationY
671 * @attr ref android.R.styleable#View_scaleX
672 * @attr ref android.R.styleable#View_scaleY
673 * @attr ref android.R.styleable#View_scrollX
674 * @attr ref android.R.styleable#View_scrollY
675 * @attr ref android.R.styleable#View_scrollbarSize
676 * @attr ref android.R.styleable#View_scrollbarStyle
677 * @attr ref android.R.styleable#View_scrollbars
678 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
679 * @attr ref android.R.styleable#View_scrollbarFadeDuration
680 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
681 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
682 * @attr ref android.R.styleable#View_scrollbarThumbVertical
683 * @attr ref android.R.styleable#View_scrollbarTrackVertical
684 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
685 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
686 * @attr ref android.R.styleable#View_stateListAnimator
687 * @attr ref android.R.styleable#View_transitionName
688 * @attr ref android.R.styleable#View_soundEffectsEnabled
689 * @attr ref android.R.styleable#View_tag
690 * @attr ref android.R.styleable#View_textAlignment
691 * @attr ref android.R.styleable#View_textDirection
692 * @attr ref android.R.styleable#View_transformPivotX
693 * @attr ref android.R.styleable#View_transformPivotY
694 * @attr ref android.R.styleable#View_translationX
695 * @attr ref android.R.styleable#View_translationY
696 * @attr ref android.R.styleable#View_translationZ
697 * @attr ref android.R.styleable#View_visibility
698 *
699 * @see android.view.ViewGroup
700 */
701public class View implements Drawable.Callback, KeyEvent.Callback,
702        AccessibilityEventSource {
703    private static final boolean DBG = false;
704
705    /**
706     * The logging tag used by this class with android.util.Log.
707     */
708    protected static final String VIEW_LOG_TAG = "View";
709
710    /**
711     * When set to true, apps will draw debugging information about their layouts.
712     *
713     * @hide
714     */
715    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
716
717    /**
718     * When set to true, this view will save its attribute data.
719     *
720     * @hide
721     */
722    public static boolean mDebugViewAttributes = false;
723
724    /**
725     * Used to mark a View that has no ID.
726     */
727    public static final int NO_ID = -1;
728
729    /**
730     * Signals that compatibility booleans have been initialized according to
731     * target SDK versions.
732     */
733    private static boolean sCompatibilityDone = false;
734
735    /**
736     * Use the old (broken) way of building MeasureSpecs.
737     */
738    private static boolean sUseBrokenMakeMeasureSpec = false;
739
740    /**
741     * Ignore any optimizations using the measure cache.
742     */
743    private static boolean sIgnoreMeasureCache = false;
744
745    /**
746     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
747     * calling setFlags.
748     */
749    private static final int NOT_FOCUSABLE = 0x00000000;
750
751    /**
752     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
753     * setFlags.
754     */
755    private static final int FOCUSABLE = 0x00000001;
756
757    /**
758     * Mask for use with setFlags indicating bits used for focus.
759     */
760    private static final int FOCUSABLE_MASK = 0x00000001;
761
762    /**
763     * This view will adjust its padding to fit sytem windows (e.g. status bar)
764     */
765    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
766
767    /** @hide */
768    @IntDef({VISIBLE, INVISIBLE, GONE})
769    @Retention(RetentionPolicy.SOURCE)
770    public @interface Visibility {}
771
772    /**
773     * This view is visible.
774     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
775     * android:visibility}.
776     */
777    public static final int VISIBLE = 0x00000000;
778
779    /**
780     * This view is invisible, but it still takes up space for layout purposes.
781     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
782     * android:visibility}.
783     */
784    public static final int INVISIBLE = 0x00000004;
785
786    /**
787     * This view is invisible, and it doesn't take any space for layout
788     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
789     * android:visibility}.
790     */
791    public static final int GONE = 0x00000008;
792
793    /**
794     * Mask for use with setFlags indicating bits used for visibility.
795     * {@hide}
796     */
797    static final int VISIBILITY_MASK = 0x0000000C;
798
799    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
800
801    /**
802     * This view is enabled. Interpretation varies by subclass.
803     * Use with ENABLED_MASK when calling setFlags.
804     * {@hide}
805     */
806    static final int ENABLED = 0x00000000;
807
808    /**
809     * This view is disabled. Interpretation varies by subclass.
810     * Use with ENABLED_MASK when calling setFlags.
811     * {@hide}
812     */
813    static final int DISABLED = 0x00000020;
814
815   /**
816    * Mask for use with setFlags indicating bits used for indicating whether
817    * this view is enabled
818    * {@hide}
819    */
820    static final int ENABLED_MASK = 0x00000020;
821
822    /**
823     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
824     * called and further optimizations will be performed. It is okay to have
825     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
826     * {@hide}
827     */
828    static final int WILL_NOT_DRAW = 0x00000080;
829
830    /**
831     * Mask for use with setFlags indicating bits used for indicating whether
832     * this view is will draw
833     * {@hide}
834     */
835    static final int DRAW_MASK = 0x00000080;
836
837    /**
838     * <p>This view doesn't show scrollbars.</p>
839     * {@hide}
840     */
841    static final int SCROLLBARS_NONE = 0x00000000;
842
843    /**
844     * <p>This view shows horizontal scrollbars.</p>
845     * {@hide}
846     */
847    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
848
849    /**
850     * <p>This view shows vertical scrollbars.</p>
851     * {@hide}
852     */
853    static final int SCROLLBARS_VERTICAL = 0x00000200;
854
855    /**
856     * <p>Mask for use with setFlags indicating bits used for indicating which
857     * scrollbars are enabled.</p>
858     * {@hide}
859     */
860    static final int SCROLLBARS_MASK = 0x00000300;
861
862    /**
863     * Indicates that the view should filter touches when its window is obscured.
864     * Refer to the class comments for more information about this security feature.
865     * {@hide}
866     */
867    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
868
869    /**
870     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
871     * that they are optional and should be skipped if the window has
872     * requested system UI flags that ignore those insets for layout.
873     */
874    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
875
876    /**
877     * <p>This view doesn't show fading edges.</p>
878     * {@hide}
879     */
880    static final int FADING_EDGE_NONE = 0x00000000;
881
882    /**
883     * <p>This view shows horizontal fading edges.</p>
884     * {@hide}
885     */
886    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
887
888    /**
889     * <p>This view shows vertical fading edges.</p>
890     * {@hide}
891     */
892    static final int FADING_EDGE_VERTICAL = 0x00002000;
893
894    /**
895     * <p>Mask for use with setFlags indicating bits used for indicating which
896     * fading edges are enabled.</p>
897     * {@hide}
898     */
899    static final int FADING_EDGE_MASK = 0x00003000;
900
901    /**
902     * <p>Indicates this view can be clicked. When clickable, a View reacts
903     * to clicks by notifying the OnClickListener.<p>
904     * {@hide}
905     */
906    static final int CLICKABLE = 0x00004000;
907
908    /**
909     * <p>Indicates this view is caching its drawing into a bitmap.</p>
910     * {@hide}
911     */
912    static final int DRAWING_CACHE_ENABLED = 0x00008000;
913
914    /**
915     * <p>Indicates that no icicle should be saved for this view.<p>
916     * {@hide}
917     */
918    static final int SAVE_DISABLED = 0x000010000;
919
920    /**
921     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
922     * property.</p>
923     * {@hide}
924     */
925    static final int SAVE_DISABLED_MASK = 0x000010000;
926
927    /**
928     * <p>Indicates that no drawing cache should ever be created for this view.<p>
929     * {@hide}
930     */
931    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
932
933    /**
934     * <p>Indicates this view can take / keep focus when int touch mode.</p>
935     * {@hide}
936     */
937    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
938
939    /** @hide */
940    @Retention(RetentionPolicy.SOURCE)
941    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
942    public @interface DrawingCacheQuality {}
943
944    /**
945     * <p>Enables low quality mode for the drawing cache.</p>
946     */
947    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
948
949    /**
950     * <p>Enables high quality mode for the drawing cache.</p>
951     */
952    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
953
954    /**
955     * <p>Enables automatic quality mode for the drawing cache.</p>
956     */
957    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
958
959    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
960            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
961    };
962
963    /**
964     * <p>Mask for use with setFlags indicating bits used for the cache
965     * quality property.</p>
966     * {@hide}
967     */
968    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
969
970    /**
971     * <p>
972     * Indicates this view can be long clicked. When long clickable, a View
973     * reacts to long clicks by notifying the OnLongClickListener or showing a
974     * context menu.
975     * </p>
976     * {@hide}
977     */
978    static final int LONG_CLICKABLE = 0x00200000;
979
980    /**
981     * <p>Indicates that this view gets its drawable states from its direct parent
982     * and ignores its original internal states.</p>
983     *
984     * @hide
985     */
986    static final int DUPLICATE_PARENT_STATE = 0x00400000;
987
988    /** @hide */
989    @IntDef({
990        SCROLLBARS_INSIDE_OVERLAY,
991        SCROLLBARS_INSIDE_INSET,
992        SCROLLBARS_OUTSIDE_OVERLAY,
993        SCROLLBARS_OUTSIDE_INSET
994    })
995    @Retention(RetentionPolicy.SOURCE)
996    public @interface ScrollBarStyle {}
997
998    /**
999     * The scrollbar style to display the scrollbars inside the content area,
1000     * without increasing the padding. The scrollbars will be overlaid with
1001     * translucency on the view's content.
1002     */
1003    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1004
1005    /**
1006     * The scrollbar style to display the scrollbars inside the padded area,
1007     * increasing the padding of the view. The scrollbars will not overlap the
1008     * content area of the view.
1009     */
1010    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1011
1012    /**
1013     * The scrollbar style to display the scrollbars at the edge of the view,
1014     * without increasing the padding. The scrollbars will be overlaid with
1015     * translucency.
1016     */
1017    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1018
1019    /**
1020     * The scrollbar style to display the scrollbars at the edge of the view,
1021     * increasing the padding of the view. The scrollbars will only overlap the
1022     * background, if any.
1023     */
1024    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1025
1026    /**
1027     * Mask to check if the scrollbar style is overlay or inset.
1028     * {@hide}
1029     */
1030    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1031
1032    /**
1033     * Mask to check if the scrollbar style is inside or outside.
1034     * {@hide}
1035     */
1036    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1037
1038    /**
1039     * Mask for scrollbar style.
1040     * {@hide}
1041     */
1042    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1043
1044    /**
1045     * View flag indicating that the screen should remain on while the
1046     * window containing this view is visible to the user.  This effectively
1047     * takes care of automatically setting the WindowManager's
1048     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1049     */
1050    public static final int KEEP_SCREEN_ON = 0x04000000;
1051
1052    /**
1053     * View flag indicating whether this view should have sound effects enabled
1054     * for events such as clicking and touching.
1055     */
1056    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1057
1058    /**
1059     * View flag indicating whether this view should have haptic feedback
1060     * enabled for events such as long presses.
1061     */
1062    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1063
1064    /**
1065     * <p>Indicates that the view hierarchy should stop saving state when
1066     * it reaches this view.  If state saving is initiated immediately at
1067     * the view, it will be allowed.
1068     * {@hide}
1069     */
1070    static final int PARENT_SAVE_DISABLED = 0x20000000;
1071
1072    /**
1073     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1074     * {@hide}
1075     */
1076    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1077
1078    /** @hide */
1079    @IntDef(flag = true,
1080            value = {
1081                FOCUSABLES_ALL,
1082                FOCUSABLES_TOUCH_MODE
1083            })
1084    @Retention(RetentionPolicy.SOURCE)
1085    public @interface FocusableMode {}
1086
1087    /**
1088     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1089     * should add all focusable Views regardless if they are focusable in touch mode.
1090     */
1091    public static final int FOCUSABLES_ALL = 0x00000000;
1092
1093    /**
1094     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1095     * should add only Views focusable in touch mode.
1096     */
1097    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1098
1099    /** @hide */
1100    @IntDef({
1101            FOCUS_BACKWARD,
1102            FOCUS_FORWARD,
1103            FOCUS_LEFT,
1104            FOCUS_UP,
1105            FOCUS_RIGHT,
1106            FOCUS_DOWN
1107    })
1108    @Retention(RetentionPolicy.SOURCE)
1109    public @interface FocusDirection {}
1110
1111    /** @hide */
1112    @IntDef({
1113            FOCUS_LEFT,
1114            FOCUS_UP,
1115            FOCUS_RIGHT,
1116            FOCUS_DOWN
1117    })
1118    @Retention(RetentionPolicy.SOURCE)
1119    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1120
1121    /**
1122     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1123     * item.
1124     */
1125    public static final int FOCUS_BACKWARD = 0x00000001;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1129     * item.
1130     */
1131    public static final int FOCUS_FORWARD = 0x00000002;
1132
1133    /**
1134     * Use with {@link #focusSearch(int)}. Move focus to the left.
1135     */
1136    public static final int FOCUS_LEFT = 0x00000011;
1137
1138    /**
1139     * Use with {@link #focusSearch(int)}. Move focus up.
1140     */
1141    public static final int FOCUS_UP = 0x00000021;
1142
1143    /**
1144     * Use with {@link #focusSearch(int)}. Move focus to the right.
1145     */
1146    public static final int FOCUS_RIGHT = 0x00000042;
1147
1148    /**
1149     * Use with {@link #focusSearch(int)}. Move focus down.
1150     */
1151    public static final int FOCUS_DOWN = 0x00000082;
1152
1153    /**
1154     * Bits of {@link #getMeasuredWidthAndState()} and
1155     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1156     */
1157    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1158
1159    /**
1160     * Bits of {@link #getMeasuredWidthAndState()} and
1161     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1162     */
1163    public static final int MEASURED_STATE_MASK = 0xff000000;
1164
1165    /**
1166     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1167     * for functions that combine both width and height into a single int,
1168     * such as {@link #getMeasuredState()} and the childState argument of
1169     * {@link #resolveSizeAndState(int, int, int)}.
1170     */
1171    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1172
1173    /**
1174     * Bit of {@link #getMeasuredWidthAndState()} and
1175     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1176     * is smaller that the space the view would like to have.
1177     */
1178    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1179
1180    /**
1181     * Base View state sets
1182     */
1183    // Singles
1184    /**
1185     * Indicates the view has no states set. States are used with
1186     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1187     * view depending on its state.
1188     *
1189     * @see android.graphics.drawable.Drawable
1190     * @see #getDrawableState()
1191     */
1192    protected static final int[] EMPTY_STATE_SET;
1193    /**
1194     * Indicates the view is enabled. States are used with
1195     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1196     * view depending on its state.
1197     *
1198     * @see android.graphics.drawable.Drawable
1199     * @see #getDrawableState()
1200     */
1201    protected static final int[] ENABLED_STATE_SET;
1202    /**
1203     * Indicates the view is focused. States are used with
1204     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1205     * view depending on its state.
1206     *
1207     * @see android.graphics.drawable.Drawable
1208     * @see #getDrawableState()
1209     */
1210    protected static final int[] FOCUSED_STATE_SET;
1211    /**
1212     * Indicates the view is selected. States are used with
1213     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1214     * view depending on its state.
1215     *
1216     * @see android.graphics.drawable.Drawable
1217     * @see #getDrawableState()
1218     */
1219    protected static final int[] SELECTED_STATE_SET;
1220    /**
1221     * Indicates the view is pressed. States are used with
1222     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1223     * view depending on its state.
1224     *
1225     * @see android.graphics.drawable.Drawable
1226     * @see #getDrawableState()
1227     */
1228    protected static final int[] PRESSED_STATE_SET;
1229    /**
1230     * Indicates the view's window has focus. States are used with
1231     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1232     * view depending on its state.
1233     *
1234     * @see android.graphics.drawable.Drawable
1235     * @see #getDrawableState()
1236     */
1237    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1238    // Doubles
1239    /**
1240     * Indicates the view is enabled and has the focus.
1241     *
1242     * @see #ENABLED_STATE_SET
1243     * @see #FOCUSED_STATE_SET
1244     */
1245    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is enabled and selected.
1248     *
1249     * @see #ENABLED_STATE_SET
1250     * @see #SELECTED_STATE_SET
1251     */
1252    protected static final int[] ENABLED_SELECTED_STATE_SET;
1253    /**
1254     * Indicates the view is enabled and that its window has focus.
1255     *
1256     * @see #ENABLED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is focused and selected.
1262     *
1263     * @see #FOCUSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     */
1266    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1267    /**
1268     * Indicates the view has the focus and that its window has the focus.
1269     *
1270     * @see #FOCUSED_STATE_SET
1271     * @see #WINDOW_FOCUSED_STATE_SET
1272     */
1273    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1274    /**
1275     * Indicates the view is selected and that its window has the focus.
1276     *
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    // Triples
1282    /**
1283     * Indicates the view is enabled, focused and selected.
1284     *
1285     * @see #ENABLED_STATE_SET
1286     * @see #FOCUSED_STATE_SET
1287     * @see #SELECTED_STATE_SET
1288     */
1289    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1290    /**
1291     * Indicates the view is enabled, focused and its window has the focus.
1292     *
1293     * @see #ENABLED_STATE_SET
1294     * @see #FOCUSED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is enabled, selected and its window has the focus.
1300     *
1301     * @see #ENABLED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is focused, selected and its window has the focus.
1308     *
1309     * @see #FOCUSED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #WINDOW_FOCUSED_STATE_SET
1312     */
1313    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is enabled, focused, selected and its window
1316     * has the focus.
1317     *
1318     * @see #ENABLED_STATE_SET
1319     * @see #FOCUSED_STATE_SET
1320     * @see #SELECTED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed and its window has the focus.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #WINDOW_FOCUSED_STATE_SET
1329     */
1330    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1331    /**
1332     * Indicates the view is pressed and selected.
1333     *
1334     * @see #PRESSED_STATE_SET
1335     * @see #SELECTED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, selected and its window has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #SELECTED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed and focused.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, focused and its window has the focus.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #FOCUSED_STATE_SET
1358     * @see #WINDOW_FOCUSED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed, focused and selected.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #SELECTED_STATE_SET
1366     * @see #FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, focused, selected and its window has the focus.
1371     *
1372     * @see #PRESSED_STATE_SET
1373     * @see #FOCUSED_STATE_SET
1374     * @see #SELECTED_STATE_SET
1375     * @see #WINDOW_FOCUSED_STATE_SET
1376     */
1377    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1378    /**
1379     * Indicates the view is pressed and enabled.
1380     *
1381     * @see #PRESSED_STATE_SET
1382     * @see #ENABLED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled and its window has the focus.
1387     *
1388     * @see #PRESSED_STATE_SET
1389     * @see #ENABLED_STATE_SET
1390     * @see #WINDOW_FOCUSED_STATE_SET
1391     */
1392    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1393    /**
1394     * Indicates the view is pressed, enabled and selected.
1395     *
1396     * @see #PRESSED_STATE_SET
1397     * @see #ENABLED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     */
1400    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1401    /**
1402     * Indicates the view is pressed, enabled, selected and its window has the
1403     * focus.
1404     *
1405     * @see #PRESSED_STATE_SET
1406     * @see #ENABLED_STATE_SET
1407     * @see #SELECTED_STATE_SET
1408     * @see #WINDOW_FOCUSED_STATE_SET
1409     */
1410    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1411    /**
1412     * Indicates the view is pressed, enabled and focused.
1413     *
1414     * @see #PRESSED_STATE_SET
1415     * @see #ENABLED_STATE_SET
1416     * @see #FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed, enabled, focused and its window has the
1421     * focus.
1422     *
1423     * @see #PRESSED_STATE_SET
1424     * @see #ENABLED_STATE_SET
1425     * @see #FOCUSED_STATE_SET
1426     * @see #WINDOW_FOCUSED_STATE_SET
1427     */
1428    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1429    /**
1430     * Indicates the view is pressed, enabled, focused and selected.
1431     *
1432     * @see #PRESSED_STATE_SET
1433     * @see #ENABLED_STATE_SET
1434     * @see #SELECTED_STATE_SET
1435     * @see #FOCUSED_STATE_SET
1436     */
1437    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1438    /**
1439     * Indicates the view is pressed, enabled, focused, selected and its window
1440     * has the focus.
1441     *
1442     * @see #PRESSED_STATE_SET
1443     * @see #ENABLED_STATE_SET
1444     * @see #SELECTED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1449
1450    static {
1451        EMPTY_STATE_SET = StateSet.get(0);
1452
1453        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1454
1455        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1456        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1457                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1458
1459        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1460        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1461                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1462        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1463                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1464        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1465                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1466                        | StateSet.VIEW_STATE_FOCUSED);
1467
1468        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1469        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1470                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1471        ENABLED_SELECTED_STATE_SET = StateSet.get(
1472                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1473        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1474                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1475                        | StateSet.VIEW_STATE_ENABLED);
1476        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1477                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1478        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1479                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1480                        | StateSet.VIEW_STATE_ENABLED);
1481        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1482                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1483                        | StateSet.VIEW_STATE_ENABLED);
1484        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1485                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1486                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1487
1488        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1489        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1490                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1491        PRESSED_SELECTED_STATE_SET = StateSet.get(
1492                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1493        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1495                        | StateSet.VIEW_STATE_PRESSED);
1496        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1497                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1498        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1499                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1500                        | StateSet.VIEW_STATE_PRESSED);
1501        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1502                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1503                        | StateSet.VIEW_STATE_PRESSED);
1504        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1505                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1506                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1507        PRESSED_ENABLED_STATE_SET = StateSet.get(
1508                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1509        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1510                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1511                        | StateSet.VIEW_STATE_PRESSED);
1512        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1513                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1514                        | StateSet.VIEW_STATE_PRESSED);
1515        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1516                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1517                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1518        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1519                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1520                        | StateSet.VIEW_STATE_PRESSED);
1521        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1522                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1523                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1524        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1525                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1526                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1527        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1528                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1529                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1530                        | StateSet.VIEW_STATE_PRESSED);
1531    }
1532
1533    /**
1534     * Accessibility event types that are dispatched for text population.
1535     */
1536    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1537            AccessibilityEvent.TYPE_VIEW_CLICKED
1538            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1539            | AccessibilityEvent.TYPE_VIEW_SELECTED
1540            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1541            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1542            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1543            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1544            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1545            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1546            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1547            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1548
1549    /**
1550     * Temporary Rect currently for use in setBackground().  This will probably
1551     * be extended in the future to hold our own class with more than just
1552     * a Rect. :)
1553     */
1554    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1555
1556    /**
1557     * Map used to store views' tags.
1558     */
1559    private SparseArray<Object> mKeyedTags;
1560
1561    /**
1562     * The next available accessibility id.
1563     */
1564    private static int sNextAccessibilityViewId;
1565
1566    /**
1567     * The animation currently associated with this view.
1568     * @hide
1569     */
1570    protected Animation mCurrentAnimation = null;
1571
1572    /**
1573     * Width as measured during measure pass.
1574     * {@hide}
1575     */
1576    @ViewDebug.ExportedProperty(category = "measurement")
1577    int mMeasuredWidth;
1578
1579    /**
1580     * Height as measured during measure pass.
1581     * {@hide}
1582     */
1583    @ViewDebug.ExportedProperty(category = "measurement")
1584    int mMeasuredHeight;
1585
1586    /**
1587     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1588     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1589     * its display list. This flag, used only when hw accelerated, allows us to clear the
1590     * flag while retaining this information until it's needed (at getDisplayList() time and
1591     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1592     *
1593     * {@hide}
1594     */
1595    boolean mRecreateDisplayList = false;
1596
1597    /**
1598     * The view's identifier.
1599     * {@hide}
1600     *
1601     * @see #setId(int)
1602     * @see #getId()
1603     */
1604    @IdRes
1605    @ViewDebug.ExportedProperty(resolveId = true)
1606    int mID = NO_ID;
1607
1608    /**
1609     * The stable ID of this view for accessibility purposes.
1610     */
1611    int mAccessibilityViewId = NO_ID;
1612
1613    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1614
1615    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1616
1617    /**
1618     * The view's tag.
1619     * {@hide}
1620     *
1621     * @see #setTag(Object)
1622     * @see #getTag()
1623     */
1624    protected Object mTag = null;
1625
1626    // for mPrivateFlags:
1627    /** {@hide} */
1628    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1629    /** {@hide} */
1630    static final int PFLAG_FOCUSED                     = 0x00000002;
1631    /** {@hide} */
1632    static final int PFLAG_SELECTED                    = 0x00000004;
1633    /** {@hide} */
1634    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1635    /** {@hide} */
1636    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1637    /** {@hide} */
1638    static final int PFLAG_DRAWN                       = 0x00000020;
1639    /**
1640     * When this flag is set, this view is running an animation on behalf of its
1641     * children and should therefore not cancel invalidate requests, even if they
1642     * lie outside of this view's bounds.
1643     *
1644     * {@hide}
1645     */
1646    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1647    /** {@hide} */
1648    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1649    /** {@hide} */
1650    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1651    /** {@hide} */
1652    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1653    /** {@hide} */
1654    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1655    /** {@hide} */
1656    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1657    /** {@hide} */
1658    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1659    /** {@hide} */
1660    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1661
1662    private static final int PFLAG_PRESSED             = 0x00004000;
1663
1664    /** {@hide} */
1665    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1666    /**
1667     * Flag used to indicate that this view should be drawn once more (and only once
1668     * more) after its animation has completed.
1669     * {@hide}
1670     */
1671    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1672
1673    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1674
1675    /**
1676     * Indicates that the View returned true when onSetAlpha() was called and that
1677     * the alpha must be restored.
1678     * {@hide}
1679     */
1680    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1681
1682    /**
1683     * Set by {@link #setScrollContainer(boolean)}.
1684     */
1685    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1686
1687    /**
1688     * Set by {@link #setScrollContainer(boolean)}.
1689     */
1690    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1691
1692    /**
1693     * View flag indicating whether this view was invalidated (fully or partially.)
1694     *
1695     * @hide
1696     */
1697    static final int PFLAG_DIRTY                       = 0x00200000;
1698
1699    /**
1700     * View flag indicating whether this view was invalidated by an opaque
1701     * invalidate request.
1702     *
1703     * @hide
1704     */
1705    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1706
1707    /**
1708     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1709     *
1710     * @hide
1711     */
1712    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1713
1714    /**
1715     * Indicates whether the background is opaque.
1716     *
1717     * @hide
1718     */
1719    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1720
1721    /**
1722     * Indicates whether the scrollbars are opaque.
1723     *
1724     * @hide
1725     */
1726    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1727
1728    /**
1729     * Indicates whether the view is opaque.
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1734
1735    /**
1736     * Indicates a prepressed state;
1737     * the short time between ACTION_DOWN and recognizing
1738     * a 'real' press. Prepressed is used to recognize quick taps
1739     * even when they are shorter than ViewConfiguration.getTapTimeout().
1740     *
1741     * @hide
1742     */
1743    private static final int PFLAG_PREPRESSED          = 0x02000000;
1744
1745    /**
1746     * Indicates whether the view is temporarily detached.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1751
1752    /**
1753     * Indicates that we should awaken scroll bars once attached
1754     *
1755     * @hide
1756     */
1757    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1758
1759    /**
1760     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1761     * @hide
1762     */
1763    private static final int PFLAG_HOVERED             = 0x10000000;
1764
1765    /**
1766     * no longer needed, should be reused
1767     */
1768    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1769
1770    /** {@hide} */
1771    static final int PFLAG_ACTIVATED                   = 0x40000000;
1772
1773    /**
1774     * Indicates that this view was specifically invalidated, not just dirtied because some
1775     * child view was invalidated. The flag is used to determine when we need to recreate
1776     * a view's display list (as opposed to just returning a reference to its existing
1777     * display list).
1778     *
1779     * @hide
1780     */
1781    static final int PFLAG_INVALIDATED                 = 0x80000000;
1782
1783    /**
1784     * Masks for mPrivateFlags2, as generated by dumpFlags():
1785     *
1786     * |-------|-------|-------|-------|
1787     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1788     *                                1  PFLAG2_DRAG_HOVERED
1789     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1790     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1791     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1792     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1793     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1794     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1795     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1796     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1797     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1798     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1799     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1800     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1801     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1802     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1803     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1804     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1805     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1806     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1807     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1808     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1809     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1810     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1811     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1812     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1813     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1814     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1815     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1816     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1817     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1818     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1819     *    1                              PFLAG2_PADDING_RESOLVED
1820     *   1                               PFLAG2_DRAWABLE_RESOLVED
1821     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1822     * |-------|-------|-------|-------|
1823     */
1824
1825    /**
1826     * Indicates that this view has reported that it can accept the current drag's content.
1827     * Cleared when the drag operation concludes.
1828     * @hide
1829     */
1830    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1831
1832    /**
1833     * Indicates that this view is currently directly under the drag location in a
1834     * drag-and-drop operation involving content that it can accept.  Cleared when
1835     * the drag exits the view, or when the drag operation concludes.
1836     * @hide
1837     */
1838    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1839
1840    /** @hide */
1841    @IntDef({
1842        LAYOUT_DIRECTION_LTR,
1843        LAYOUT_DIRECTION_RTL,
1844        LAYOUT_DIRECTION_INHERIT,
1845        LAYOUT_DIRECTION_LOCALE
1846    })
1847    @Retention(RetentionPolicy.SOURCE)
1848    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1849    public @interface LayoutDir {}
1850
1851    /** @hide */
1852    @IntDef({
1853        LAYOUT_DIRECTION_LTR,
1854        LAYOUT_DIRECTION_RTL
1855    })
1856    @Retention(RetentionPolicy.SOURCE)
1857    public @interface ResolvedLayoutDir {}
1858
1859    /**
1860     * Horizontal layout direction of this view is from Left to Right.
1861     * Use with {@link #setLayoutDirection}.
1862     */
1863    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1864
1865    /**
1866     * Horizontal layout direction of this view is from Right to Left.
1867     * Use with {@link #setLayoutDirection}.
1868     */
1869    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1870
1871    /**
1872     * Horizontal layout direction of this view is inherited from its parent.
1873     * Use with {@link #setLayoutDirection}.
1874     */
1875    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1876
1877    /**
1878     * Horizontal layout direction of this view is from deduced from the default language
1879     * script for the locale. Use with {@link #setLayoutDirection}.
1880     */
1881    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1882
1883    /**
1884     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1885     * @hide
1886     */
1887    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1888
1889    /**
1890     * Mask for use with private flags indicating bits used for horizontal layout direction.
1891     * @hide
1892     */
1893    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1894
1895    /**
1896     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1897     * right-to-left direction.
1898     * @hide
1899     */
1900    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1901
1902    /**
1903     * Indicates whether the view horizontal layout direction has been resolved.
1904     * @hide
1905     */
1906    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1907
1908    /**
1909     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1910     * @hide
1911     */
1912    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1913            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1914
1915    /*
1916     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1917     * flag value.
1918     * @hide
1919     */
1920    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1921            LAYOUT_DIRECTION_LTR,
1922            LAYOUT_DIRECTION_RTL,
1923            LAYOUT_DIRECTION_INHERIT,
1924            LAYOUT_DIRECTION_LOCALE
1925    };
1926
1927    /**
1928     * Default horizontal layout direction.
1929     */
1930    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1931
1932    /**
1933     * Default horizontal layout direction.
1934     * @hide
1935     */
1936    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1937
1938    /**
1939     * Text direction is inherited through {@link ViewGroup}
1940     */
1941    public static final int TEXT_DIRECTION_INHERIT = 0;
1942
1943    /**
1944     * Text direction is using "first strong algorithm". The first strong directional character
1945     * determines the paragraph direction. If there is no strong directional character, the
1946     * paragraph direction is the view's resolved layout direction.
1947     */
1948    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1949
1950    /**
1951     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1952     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1953     * If there are neither, the paragraph direction is the view's resolved layout direction.
1954     */
1955    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1956
1957    /**
1958     * Text direction is forced to LTR.
1959     */
1960    public static final int TEXT_DIRECTION_LTR = 3;
1961
1962    /**
1963     * Text direction is forced to RTL.
1964     */
1965    public static final int TEXT_DIRECTION_RTL = 4;
1966
1967    /**
1968     * Text direction is coming from the system Locale.
1969     */
1970    public static final int TEXT_DIRECTION_LOCALE = 5;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is LTR.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
1978
1979    /**
1980     * Text direction is using "first strong algorithm". The first strong directional character
1981     * determines the paragraph direction. If there is no strong directional character, the
1982     * paragraph direction is RTL.
1983     */
1984    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
1985
1986    /**
1987     * Default text direction is inherited
1988     */
1989    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1990
1991    /**
1992     * Default resolved text direction
1993     * @hide
1994     */
1995    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1996
1997    /**
1998     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1999     * @hide
2000     */
2001    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2002
2003    /**
2004     * Mask for use with private flags indicating bits used for text direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2008            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2009
2010    /**
2011     * Array of text direction flags for mapping attribute "textDirection" to correct
2012     * flag value.
2013     * @hide
2014     */
2015    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2016            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2017            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2018            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2019            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2020            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2021            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2022            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2023            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2024    };
2025
2026    /**
2027     * Indicates whether the view text direction has been resolved.
2028     * @hide
2029     */
2030    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2031            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2032
2033    /**
2034     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2035     * @hide
2036     */
2037    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2038
2039    /**
2040     * Mask for use with private flags indicating bits used for resolved text direction.
2041     * @hide
2042     */
2043    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2044            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2045
2046    /**
2047     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2051            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2052
2053    /** @hide */
2054    @IntDef({
2055        TEXT_ALIGNMENT_INHERIT,
2056        TEXT_ALIGNMENT_GRAVITY,
2057        TEXT_ALIGNMENT_CENTER,
2058        TEXT_ALIGNMENT_TEXT_START,
2059        TEXT_ALIGNMENT_TEXT_END,
2060        TEXT_ALIGNMENT_VIEW_START,
2061        TEXT_ALIGNMENT_VIEW_END
2062    })
2063    @Retention(RetentionPolicy.SOURCE)
2064    public @interface TextAlignment {}
2065
2066    /**
2067     * Default text alignment. The text alignment of this View is inherited from its parent.
2068     * Use with {@link #setTextAlignment(int)}
2069     */
2070    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2071
2072    /**
2073     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2074     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2075     *
2076     * Use with {@link #setTextAlignment(int)}
2077     */
2078    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2079
2080    /**
2081     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2082     *
2083     * Use with {@link #setTextAlignment(int)}
2084     */
2085    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2086
2087    /**
2088     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2089     *
2090     * Use with {@link #setTextAlignment(int)}
2091     */
2092    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2093
2094    /**
2095     * Center the paragraph, e.g. ALIGN_CENTER.
2096     *
2097     * Use with {@link #setTextAlignment(int)}
2098     */
2099    public static final int TEXT_ALIGNMENT_CENTER = 4;
2100
2101    /**
2102     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2103     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2104     *
2105     * Use with {@link #setTextAlignment(int)}
2106     */
2107    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2108
2109    /**
2110     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2111     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2112     *
2113     * Use with {@link #setTextAlignment(int)}
2114     */
2115    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2116
2117    /**
2118     * Default text alignment is inherited
2119     */
2120    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2121
2122    /**
2123     * Default resolved text alignment
2124     * @hide
2125     */
2126    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2127
2128    /**
2129      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2130      * @hide
2131      */
2132    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2133
2134    /**
2135      * Mask for use with private flags indicating bits used for text alignment.
2136      * @hide
2137      */
2138    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2139
2140    /**
2141     * Array of text direction flags for mapping attribute "textAlignment" to correct
2142     * flag value.
2143     * @hide
2144     */
2145    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2146            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2147            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2148            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2149            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2150            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2151            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2152            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2153    };
2154
2155    /**
2156     * Indicates whether the view text alignment has been resolved.
2157     * @hide
2158     */
2159    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2160
2161    /**
2162     * Bit shift to get the resolved text alignment.
2163     * @hide
2164     */
2165    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2166
2167    /**
2168     * Mask for use with private flags indicating bits used for text alignment.
2169     * @hide
2170     */
2171    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2172            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2173
2174    /**
2175     * Indicates whether if the view text alignment has been resolved to gravity
2176     */
2177    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2178            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2179
2180    // Accessiblity constants for mPrivateFlags2
2181
2182    /**
2183     * Shift for the bits in {@link #mPrivateFlags2} related to the
2184     * "importantForAccessibility" attribute.
2185     */
2186    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2187
2188    /**
2189     * Automatically determine whether a view is important for accessibility.
2190     */
2191    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2192
2193    /**
2194     * The view is important for accessibility.
2195     */
2196    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2197
2198    /**
2199     * The view is not important for accessibility.
2200     */
2201    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2202
2203    /**
2204     * The view is not important for accessibility, nor are any of its
2205     * descendant views.
2206     */
2207    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2208
2209    /**
2210     * The default whether the view is important for accessibility.
2211     */
2212    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2213
2214    /**
2215     * Mask for obtainig the bits which specify how to determine
2216     * whether a view is important for accessibility.
2217     */
2218    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2219        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2220        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2221        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2222
2223    /**
2224     * Shift for the bits in {@link #mPrivateFlags2} related to the
2225     * "accessibilityLiveRegion" attribute.
2226     */
2227    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2228
2229    /**
2230     * Live region mode specifying that accessibility services should not
2231     * automatically announce changes to this view. This is the default live
2232     * region mode for most views.
2233     * <p>
2234     * Use with {@link #setAccessibilityLiveRegion(int)}.
2235     */
2236    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2237
2238    /**
2239     * Live region mode specifying that accessibility services should announce
2240     * changes to this view.
2241     * <p>
2242     * Use with {@link #setAccessibilityLiveRegion(int)}.
2243     */
2244    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2245
2246    /**
2247     * Live region mode specifying that accessibility services should interrupt
2248     * ongoing speech to immediately announce changes to this view.
2249     * <p>
2250     * Use with {@link #setAccessibilityLiveRegion(int)}.
2251     */
2252    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2253
2254    /**
2255     * The default whether the view is important for accessibility.
2256     */
2257    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2258
2259    /**
2260     * Mask for obtaining the bits which specify a view's accessibility live
2261     * region mode.
2262     */
2263    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2264            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2265            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2266
2267    /**
2268     * Flag indicating whether a view has accessibility focus.
2269     */
2270    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2271
2272    /**
2273     * Flag whether the accessibility state of the subtree rooted at this view changed.
2274     */
2275    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2276
2277    /**
2278     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2279     * is used to check whether later changes to the view's transform should invalidate the
2280     * view to force the quickReject test to run again.
2281     */
2282    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2283
2284    /**
2285     * Flag indicating that start/end padding has been resolved into left/right padding
2286     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2287     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2288     * during measurement. In some special cases this is required such as when an adapter-based
2289     * view measures prospective children without attaching them to a window.
2290     */
2291    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2292
2293    /**
2294     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2295     */
2296    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2297
2298    /**
2299     * Indicates that the view is tracking some sort of transient state
2300     * that the app should not need to be aware of, but that the framework
2301     * should take special care to preserve.
2302     */
2303    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2304
2305    /**
2306     * Group of bits indicating that RTL properties resolution is done.
2307     */
2308    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2309            PFLAG2_TEXT_DIRECTION_RESOLVED |
2310            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2311            PFLAG2_PADDING_RESOLVED |
2312            PFLAG2_DRAWABLE_RESOLVED;
2313
2314    // There are a couple of flags left in mPrivateFlags2
2315
2316    /* End of masks for mPrivateFlags2 */
2317
2318    /**
2319     * Masks for mPrivateFlags3, as generated by dumpFlags():
2320     *
2321     * |-------|-------|-------|-------|
2322     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2323     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2324     *                               1   PFLAG3_IS_LAID_OUT
2325     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2326     *                             1     PFLAG3_CALLED_SUPER
2327     * |-------|-------|-------|-------|
2328     */
2329
2330    /**
2331     * Flag indicating that view has a transform animation set on it. This is used to track whether
2332     * an animation is cleared between successive frames, in order to tell the associated
2333     * DisplayList to clear its animation matrix.
2334     */
2335    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2336
2337    /**
2338     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2339     * animation is cleared between successive frames, in order to tell the associated
2340     * DisplayList to restore its alpha value.
2341     */
2342    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2343
2344    /**
2345     * Flag indicating that the view has been through at least one layout since it
2346     * was last attached to a window.
2347     */
2348    static final int PFLAG3_IS_LAID_OUT = 0x4;
2349
2350    /**
2351     * Flag indicating that a call to measure() was skipped and should be done
2352     * instead when layout() is invoked.
2353     */
2354    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2355
2356    /**
2357     * Flag indicating that an overridden method correctly called down to
2358     * the superclass implementation as required by the API spec.
2359     */
2360    static final int PFLAG3_CALLED_SUPER = 0x10;
2361
2362    /**
2363     * Flag indicating that we're in the process of applying window insets.
2364     */
2365    static final int PFLAG3_APPLYING_INSETS = 0x20;
2366
2367    /**
2368     * Flag indicating that we're in the process of fitting system windows using the old method.
2369     */
2370    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2371
2372    /**
2373     * Flag indicating that nested scrolling is enabled for this view.
2374     * The view will optionally cooperate with views up its parent chain to allow for
2375     * integrated nested scrolling along the same axis.
2376     */
2377    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2378
2379    /* End of masks for mPrivateFlags3 */
2380
2381    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2382
2383    /**
2384     * Always allow a user to over-scroll this view, provided it is a
2385     * view that can scroll.
2386     *
2387     * @see #getOverScrollMode()
2388     * @see #setOverScrollMode(int)
2389     */
2390    public static final int OVER_SCROLL_ALWAYS = 0;
2391
2392    /**
2393     * Allow a user to over-scroll this view only if the content is large
2394     * enough to meaningfully scroll, provided it is a view that can scroll.
2395     *
2396     * @see #getOverScrollMode()
2397     * @see #setOverScrollMode(int)
2398     */
2399    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2400
2401    /**
2402     * Never allow a user to over-scroll this view.
2403     *
2404     * @see #getOverScrollMode()
2405     * @see #setOverScrollMode(int)
2406     */
2407    public static final int OVER_SCROLL_NEVER = 2;
2408
2409    /**
2410     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2411     * requested the system UI (status bar) to be visible (the default).
2412     *
2413     * @see #setSystemUiVisibility(int)
2414     */
2415    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2416
2417    /**
2418     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2419     * system UI to enter an unobtrusive "low profile" mode.
2420     *
2421     * <p>This is for use in games, book readers, video players, or any other
2422     * "immersive" application where the usual system chrome is deemed too distracting.
2423     *
2424     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2425     *
2426     * @see #setSystemUiVisibility(int)
2427     */
2428    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2429
2430    /**
2431     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2432     * system navigation be temporarily hidden.
2433     *
2434     * <p>This is an even less obtrusive state than that called for by
2435     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2436     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2437     * those to disappear. This is useful (in conjunction with the
2438     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2439     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2440     * window flags) for displaying content using every last pixel on the display.
2441     *
2442     * <p>There is a limitation: because navigation controls are so important, the least user
2443     * interaction will cause them to reappear immediately.  When this happens, both
2444     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2445     * so that both elements reappear at the same time.
2446     *
2447     * @see #setSystemUiVisibility(int)
2448     */
2449    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2450
2451    /**
2452     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2453     * into the normal fullscreen mode so that its content can take over the screen
2454     * while still allowing the user to interact with the application.
2455     *
2456     * <p>This has the same visual effect as
2457     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2458     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2459     * meaning that non-critical screen decorations (such as the status bar) will be
2460     * hidden while the user is in the View's window, focusing the experience on
2461     * that content.  Unlike the window flag, if you are using ActionBar in
2462     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2463     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2464     * hide the action bar.
2465     *
2466     * <p>This approach to going fullscreen is best used over the window flag when
2467     * it is a transient state -- that is, the application does this at certain
2468     * points in its user interaction where it wants to allow the user to focus
2469     * on content, but not as a continuous state.  For situations where the application
2470     * would like to simply stay full screen the entire time (such as a game that
2471     * wants to take over the screen), the
2472     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2473     * is usually a better approach.  The state set here will be removed by the system
2474     * in various situations (such as the user moving to another application) like
2475     * the other system UI states.
2476     *
2477     * <p>When using this flag, the application should provide some easy facility
2478     * for the user to go out of it.  A common example would be in an e-book
2479     * reader, where tapping on the screen brings back whatever screen and UI
2480     * decorations that had been hidden while the user was immersed in reading
2481     * the book.
2482     *
2483     * @see #setSystemUiVisibility(int)
2484     */
2485    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2486
2487    /**
2488     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2489     * flags, we would like a stable view of the content insets given to
2490     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2491     * will always represent the worst case that the application can expect
2492     * as a continuous state.  In the stock Android UI this is the space for
2493     * the system bar, nav bar, and status bar, but not more transient elements
2494     * such as an input method.
2495     *
2496     * The stable layout your UI sees is based on the system UI modes you can
2497     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2498     * then you will get a stable layout for changes of the
2499     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2500     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2501     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2502     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2503     * with a stable layout.  (Note that you should avoid using
2504     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2505     *
2506     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2507     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2508     * then a hidden status bar will be considered a "stable" state for purposes
2509     * here.  This allows your UI to continually hide the status bar, while still
2510     * using the system UI flags to hide the action bar while still retaining
2511     * a stable layout.  Note that changing the window fullscreen flag will never
2512     * provide a stable layout for a clean transition.
2513     *
2514     * <p>If you are using ActionBar in
2515     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2516     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2517     * insets it adds to those given to the application.
2518     */
2519    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2520
2521    /**
2522     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2523     * to be laid out as if it has requested
2524     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2525     * allows it to avoid artifacts when switching in and out of that mode, at
2526     * the expense that some of its user interface may be covered by screen
2527     * decorations when they are shown.  You can perform layout of your inner
2528     * UI elements to account for the navigation system UI through the
2529     * {@link #fitSystemWindows(Rect)} method.
2530     */
2531    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2532
2533    /**
2534     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2535     * to be laid out as if it has requested
2536     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2537     * allows it to avoid artifacts when switching in and out of that mode, at
2538     * the expense that some of its user interface may be covered by screen
2539     * decorations when they are shown.  You can perform layout of your inner
2540     * UI elements to account for non-fullscreen system UI through the
2541     * {@link #fitSystemWindows(Rect)} method.
2542     */
2543    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2544
2545    /**
2546     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2547     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2548     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2549     * user interaction.
2550     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2551     * has an effect when used in combination with that flag.</p>
2552     */
2553    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2554
2555    /**
2556     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2557     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2558     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2559     * experience while also hiding the system bars.  If this flag is not set,
2560     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2561     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2562     * if the user swipes from the top of the screen.
2563     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2564     * system gestures, such as swiping from the top of the screen.  These transient system bars
2565     * will overlay app’s content, may have some degree of transparency, and will automatically
2566     * hide after a short timeout.
2567     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2568     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2569     * with one or both of those flags.</p>
2570     */
2571    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2572
2573    /**
2574     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2575     * is compatible with light status bar backgrounds.
2576     *
2577     * <p>For this to take effect, the window must request
2578     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2579     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2580     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2581     *         FLAG_TRANSLUCENT_STATUS}.
2582     *
2583     * @see android.R.attr#windowHasLightStatusBar
2584     */
2585    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2586
2587    /**
2588     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2589     */
2590    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2591
2592    /**
2593     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2594     */
2595    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2596
2597    /**
2598     * @hide
2599     *
2600     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2601     * out of the public fields to keep the undefined bits out of the developer's way.
2602     *
2603     * Flag to make the status bar not expandable.  Unless you also
2604     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2605     */
2606    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2607
2608    /**
2609     * @hide
2610     *
2611     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2612     * out of the public fields to keep the undefined bits out of the developer's way.
2613     *
2614     * Flag to hide notification icons and scrolling ticker text.
2615     */
2616    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2617
2618    /**
2619     * @hide
2620     *
2621     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2622     * out of the public fields to keep the undefined bits out of the developer's way.
2623     *
2624     * Flag to disable incoming notification alerts.  This will not block
2625     * icons, but it will block sound, vibrating and other visual or aural notifications.
2626     */
2627    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2628
2629    /**
2630     * @hide
2631     *
2632     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2633     * out of the public fields to keep the undefined bits out of the developer's way.
2634     *
2635     * Flag to hide only the scrolling ticker.  Note that
2636     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2637     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2638     */
2639    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2640
2641    /**
2642     * @hide
2643     *
2644     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2645     * out of the public fields to keep the undefined bits out of the developer's way.
2646     *
2647     * Flag to hide the center system info area.
2648     */
2649    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2650
2651    /**
2652     * @hide
2653     *
2654     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2655     * out of the public fields to keep the undefined bits out of the developer's way.
2656     *
2657     * Flag to hide only the home button.  Don't use this
2658     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2659     */
2660    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2661
2662    /**
2663     * @hide
2664     *
2665     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2666     * out of the public fields to keep the undefined bits out of the developer's way.
2667     *
2668     * Flag to hide only the back button. Don't use this
2669     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2670     */
2671    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2672
2673    /**
2674     * @hide
2675     *
2676     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2677     * out of the public fields to keep the undefined bits out of the developer's way.
2678     *
2679     * Flag to hide only the clock.  You might use this if your activity has
2680     * its own clock making the status bar's clock redundant.
2681     */
2682    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2683
2684    /**
2685     * @hide
2686     *
2687     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2688     * out of the public fields to keep the undefined bits out of the developer's way.
2689     *
2690     * Flag to hide only the recent apps button. Don't use this
2691     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2692     */
2693    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2694
2695    /**
2696     * @hide
2697     *
2698     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2699     * out of the public fields to keep the undefined bits out of the developer's way.
2700     *
2701     * Flag to disable the global search gesture. Don't use this
2702     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2703     */
2704    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2705
2706    /**
2707     * @hide
2708     *
2709     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2710     * out of the public fields to keep the undefined bits out of the developer's way.
2711     *
2712     * Flag to specify that the status bar is displayed in transient mode.
2713     */
2714    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2715
2716    /**
2717     * @hide
2718     *
2719     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2720     * out of the public fields to keep the undefined bits out of the developer's way.
2721     *
2722     * Flag to specify that the navigation bar is displayed in transient mode.
2723     */
2724    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2725
2726    /**
2727     * @hide
2728     *
2729     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2730     * out of the public fields to keep the undefined bits out of the developer's way.
2731     *
2732     * Flag to specify that the hidden status bar would like to be shown.
2733     */
2734    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2735
2736    /**
2737     * @hide
2738     *
2739     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2740     * out of the public fields to keep the undefined bits out of the developer's way.
2741     *
2742     * Flag to specify that the hidden navigation bar would like to be shown.
2743     */
2744    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2745
2746    /**
2747     * @hide
2748     *
2749     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2750     * out of the public fields to keep the undefined bits out of the developer's way.
2751     *
2752     * Flag to specify that the status bar is displayed in translucent mode.
2753     */
2754    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2755
2756    /**
2757     * @hide
2758     *
2759     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2760     * out of the public fields to keep the undefined bits out of the developer's way.
2761     *
2762     * Flag to specify that the navigation bar is displayed in translucent mode.
2763     */
2764    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2765
2766    /**
2767     * @hide
2768     *
2769     * Whether Recents is visible or not.
2770     */
2771    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2772
2773    /**
2774     * @hide
2775     *
2776     * Makes system ui transparent.
2777     */
2778    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2779
2780    /**
2781     * @hide
2782     */
2783    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2784
2785    /**
2786     * These are the system UI flags that can be cleared by events outside
2787     * of an application.  Currently this is just the ability to tap on the
2788     * screen while hiding the navigation bar to have it return.
2789     * @hide
2790     */
2791    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2792            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2793            | SYSTEM_UI_FLAG_FULLSCREEN;
2794
2795    /**
2796     * Flags that can impact the layout in relation to system UI.
2797     */
2798    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2799            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2800            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2801
2802    /** @hide */
2803    @IntDef(flag = true,
2804            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2805    @Retention(RetentionPolicy.SOURCE)
2806    public @interface FindViewFlags {}
2807
2808    /**
2809     * Find views that render the specified text.
2810     *
2811     * @see #findViewsWithText(ArrayList, CharSequence, int)
2812     */
2813    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2814
2815    /**
2816     * Find find views that contain the specified content description.
2817     *
2818     * @see #findViewsWithText(ArrayList, CharSequence, int)
2819     */
2820    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2821
2822    /**
2823     * Find views that contain {@link AccessibilityNodeProvider}. Such
2824     * a View is a root of virtual view hierarchy and may contain the searched
2825     * text. If this flag is set Views with providers are automatically
2826     * added and it is a responsibility of the client to call the APIs of
2827     * the provider to determine whether the virtual tree rooted at this View
2828     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2829     * representing the virtual views with this text.
2830     *
2831     * @see #findViewsWithText(ArrayList, CharSequence, int)
2832     *
2833     * @hide
2834     */
2835    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2836
2837    /**
2838     * The undefined cursor position.
2839     *
2840     * @hide
2841     */
2842    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2843
2844    /**
2845     * Indicates that the screen has changed state and is now off.
2846     *
2847     * @see #onScreenStateChanged(int)
2848     */
2849    public static final int SCREEN_STATE_OFF = 0x0;
2850
2851    /**
2852     * Indicates that the screen has changed state and is now on.
2853     *
2854     * @see #onScreenStateChanged(int)
2855     */
2856    public static final int SCREEN_STATE_ON = 0x1;
2857
2858    /**
2859     * Indicates no axis of view scrolling.
2860     */
2861    public static final int SCROLL_AXIS_NONE = 0;
2862
2863    /**
2864     * Indicates scrolling along the horizontal axis.
2865     */
2866    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2867
2868    /**
2869     * Indicates scrolling along the vertical axis.
2870     */
2871    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2872
2873    /**
2874     * Controls the over-scroll mode for this view.
2875     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2876     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2877     * and {@link #OVER_SCROLL_NEVER}.
2878     */
2879    private int mOverScrollMode;
2880
2881    /**
2882     * The parent this view is attached to.
2883     * {@hide}
2884     *
2885     * @see #getParent()
2886     */
2887    protected ViewParent mParent;
2888
2889    /**
2890     * {@hide}
2891     */
2892    AttachInfo mAttachInfo;
2893
2894    /**
2895     * {@hide}
2896     */
2897    @ViewDebug.ExportedProperty(flagMapping = {
2898        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2899                name = "FORCE_LAYOUT"),
2900        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2901                name = "LAYOUT_REQUIRED"),
2902        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2903            name = "DRAWING_CACHE_INVALID", outputIf = false),
2904        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2905        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2906        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2907        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2908    }, formatToHexString = true)
2909    int mPrivateFlags;
2910    int mPrivateFlags2;
2911    int mPrivateFlags3;
2912
2913    /**
2914     * This view's request for the visibility of the status bar.
2915     * @hide
2916     */
2917    @ViewDebug.ExportedProperty(flagMapping = {
2918        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2919                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2920                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2921        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2922                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2923                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2924        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2925                                equals = SYSTEM_UI_FLAG_VISIBLE,
2926                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2927    }, formatToHexString = true)
2928    int mSystemUiVisibility;
2929
2930    /**
2931     * Reference count for transient state.
2932     * @see #setHasTransientState(boolean)
2933     */
2934    int mTransientStateCount = 0;
2935
2936    /**
2937     * Count of how many windows this view has been attached to.
2938     */
2939    int mWindowAttachCount;
2940
2941    /**
2942     * The layout parameters associated with this view and used by the parent
2943     * {@link android.view.ViewGroup} to determine how this view should be
2944     * laid out.
2945     * {@hide}
2946     */
2947    protected ViewGroup.LayoutParams mLayoutParams;
2948
2949    /**
2950     * The view flags hold various views states.
2951     * {@hide}
2952     */
2953    @ViewDebug.ExportedProperty(formatToHexString = true)
2954    int mViewFlags;
2955
2956    static class TransformationInfo {
2957        /**
2958         * The transform matrix for the View. This transform is calculated internally
2959         * based on the translation, rotation, and scale properties.
2960         *
2961         * Do *not* use this variable directly; instead call getMatrix(), which will
2962         * load the value from the View's RenderNode.
2963         */
2964        private final Matrix mMatrix = new Matrix();
2965
2966        /**
2967         * The inverse transform matrix for the View. This transform is calculated
2968         * internally based on the translation, rotation, and scale properties.
2969         *
2970         * Do *not* use this variable directly; instead call getInverseMatrix(),
2971         * which will load the value from the View's RenderNode.
2972         */
2973        private Matrix mInverseMatrix;
2974
2975        /**
2976         * The opacity of the View. This is a value from 0 to 1, where 0 means
2977         * completely transparent and 1 means completely opaque.
2978         */
2979        @ViewDebug.ExportedProperty
2980        float mAlpha = 1f;
2981
2982        /**
2983         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2984         * property only used by transitions, which is composited with the other alpha
2985         * values to calculate the final visual alpha value.
2986         */
2987        float mTransitionAlpha = 1f;
2988    }
2989
2990    TransformationInfo mTransformationInfo;
2991
2992    /**
2993     * Current clip bounds. to which all drawing of this view are constrained.
2994     */
2995    Rect mClipBounds = null;
2996
2997    private boolean mLastIsOpaque;
2998
2999    /**
3000     * The distance in pixels from the left edge of this view's parent
3001     * to the left edge of this view.
3002     * {@hide}
3003     */
3004    @ViewDebug.ExportedProperty(category = "layout")
3005    protected int mLeft;
3006    /**
3007     * The distance in pixels from the left edge of this view's parent
3008     * to the right edge of this view.
3009     * {@hide}
3010     */
3011    @ViewDebug.ExportedProperty(category = "layout")
3012    protected int mRight;
3013    /**
3014     * The distance in pixels from the top edge of this view's parent
3015     * to the top edge of this view.
3016     * {@hide}
3017     */
3018    @ViewDebug.ExportedProperty(category = "layout")
3019    protected int mTop;
3020    /**
3021     * The distance in pixels from the top edge of this view's parent
3022     * to the bottom edge of this view.
3023     * {@hide}
3024     */
3025    @ViewDebug.ExportedProperty(category = "layout")
3026    protected int mBottom;
3027
3028    /**
3029     * The offset, in pixels, by which the content of this view is scrolled
3030     * horizontally.
3031     * {@hide}
3032     */
3033    @ViewDebug.ExportedProperty(category = "scrolling")
3034    protected int mScrollX;
3035    /**
3036     * The offset, in pixels, by which the content of this view is scrolled
3037     * vertically.
3038     * {@hide}
3039     */
3040    @ViewDebug.ExportedProperty(category = "scrolling")
3041    protected int mScrollY;
3042
3043    /**
3044     * The left padding in pixels, that is the distance in pixels between the
3045     * left edge of this view and the left edge of its content.
3046     * {@hide}
3047     */
3048    @ViewDebug.ExportedProperty(category = "padding")
3049    protected int mPaddingLeft = 0;
3050    /**
3051     * The right padding in pixels, that is the distance in pixels between the
3052     * right edge of this view and the right edge of its content.
3053     * {@hide}
3054     */
3055    @ViewDebug.ExportedProperty(category = "padding")
3056    protected int mPaddingRight = 0;
3057    /**
3058     * The top padding in pixels, that is the distance in pixels between the
3059     * top edge of this view and the top edge of its content.
3060     * {@hide}
3061     */
3062    @ViewDebug.ExportedProperty(category = "padding")
3063    protected int mPaddingTop;
3064    /**
3065     * The bottom padding in pixels, that is the distance in pixels between the
3066     * bottom edge of this view and the bottom edge of its content.
3067     * {@hide}
3068     */
3069    @ViewDebug.ExportedProperty(category = "padding")
3070    protected int mPaddingBottom;
3071
3072    /**
3073     * The layout insets in pixels, that is the distance in pixels between the
3074     * visible edges of this view its bounds.
3075     */
3076    private Insets mLayoutInsets;
3077
3078    /**
3079     * Briefly describes the view and is primarily used for accessibility support.
3080     */
3081    private CharSequence mContentDescription;
3082
3083    /**
3084     * Specifies the id of a view for which this view serves as a label for
3085     * accessibility purposes.
3086     */
3087    private int mLabelForId = View.NO_ID;
3088
3089    /**
3090     * Predicate for matching labeled view id with its label for
3091     * accessibility purposes.
3092     */
3093    private MatchLabelForPredicate mMatchLabelForPredicate;
3094
3095    /**
3096     * Specifies a view before which this one is visited in accessibility traversal.
3097     */
3098    private int mAccessibilityTraversalBeforeId = NO_ID;
3099
3100    /**
3101     * Specifies a view after which this one is visited in accessibility traversal.
3102     */
3103    private int mAccessibilityTraversalAfterId = NO_ID;
3104
3105    /**
3106     * Predicate for matching a view by its id.
3107     */
3108    private MatchIdPredicate mMatchIdPredicate;
3109
3110    /**
3111     * Cache the paddingRight set by the user to append to the scrollbar's size.
3112     *
3113     * @hide
3114     */
3115    @ViewDebug.ExportedProperty(category = "padding")
3116    protected int mUserPaddingRight;
3117
3118    /**
3119     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3120     *
3121     * @hide
3122     */
3123    @ViewDebug.ExportedProperty(category = "padding")
3124    protected int mUserPaddingBottom;
3125
3126    /**
3127     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3128     *
3129     * @hide
3130     */
3131    @ViewDebug.ExportedProperty(category = "padding")
3132    protected int mUserPaddingLeft;
3133
3134    /**
3135     * Cache the paddingStart set by the user to append to the scrollbar's size.
3136     *
3137     */
3138    @ViewDebug.ExportedProperty(category = "padding")
3139    int mUserPaddingStart;
3140
3141    /**
3142     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3143     *
3144     */
3145    @ViewDebug.ExportedProperty(category = "padding")
3146    int mUserPaddingEnd;
3147
3148    /**
3149     * Cache initial left padding.
3150     *
3151     * @hide
3152     */
3153    int mUserPaddingLeftInitial;
3154
3155    /**
3156     * Cache initial right padding.
3157     *
3158     * @hide
3159     */
3160    int mUserPaddingRightInitial;
3161
3162    /**
3163     * Default undefined padding
3164     */
3165    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3166
3167    /**
3168     * Cache if a left padding has been defined
3169     */
3170    private boolean mLeftPaddingDefined = false;
3171
3172    /**
3173     * Cache if a right padding has been defined
3174     */
3175    private boolean mRightPaddingDefined = false;
3176
3177    /**
3178     * @hide
3179     */
3180    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3181    /**
3182     * @hide
3183     */
3184    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3185
3186    private LongSparseLongArray mMeasureCache;
3187
3188    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3189    private Drawable mBackground;
3190    private TintInfo mBackgroundTint;
3191
3192    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3193    private ForegroundInfo mForegroundInfo;
3194
3195    /**
3196     * RenderNode used for backgrounds.
3197     * <p>
3198     * When non-null and valid, this is expected to contain an up-to-date copy
3199     * of the background drawable. It is cleared on temporary detach, and reset
3200     * on cleanup.
3201     */
3202    private RenderNode mBackgroundRenderNode;
3203
3204    private int mBackgroundResource;
3205    private boolean mBackgroundSizeChanged;
3206
3207    private String mTransitionName;
3208
3209    static class TintInfo {
3210        ColorStateList mTintList;
3211        PorterDuff.Mode mTintMode;
3212        boolean mHasTintMode;
3213        boolean mHasTintList;
3214    }
3215
3216    private static class ForegroundInfo {
3217        private Drawable mDrawable;
3218        private TintInfo mTintInfo;
3219        private int mGravity = Gravity.FILL;
3220        private boolean mInsidePadding = true;
3221        private boolean mBoundsChanged = true;
3222        private final Rect mSelfBounds = new Rect();
3223        private final Rect mOverlayBounds = new Rect();
3224    }
3225
3226    static class ListenerInfo {
3227        /**
3228         * Listener used to dispatch focus change events.
3229         * This field should be made private, so it is hidden from the SDK.
3230         * {@hide}
3231         */
3232        protected OnFocusChangeListener mOnFocusChangeListener;
3233
3234        /**
3235         * Listeners for layout change events.
3236         */
3237        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3238
3239        protected OnScrollChangeListener mOnScrollChangeListener;
3240
3241        /**
3242         * Listeners for attach events.
3243         */
3244        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3245
3246        /**
3247         * Listener used to dispatch click events.
3248         * This field should be made private, so it is hidden from the SDK.
3249         * {@hide}
3250         */
3251        public OnClickListener mOnClickListener;
3252
3253        /**
3254         * Listener used to dispatch long click events.
3255         * This field should be made private, so it is hidden from the SDK.
3256         * {@hide}
3257         */
3258        protected OnLongClickListener mOnLongClickListener;
3259
3260        /**
3261         * Listener used to build the context menu.
3262         * This field should be made private, so it is hidden from the SDK.
3263         * {@hide}
3264         */
3265        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3266
3267        private OnKeyListener mOnKeyListener;
3268
3269        private OnTouchListener mOnTouchListener;
3270
3271        private OnHoverListener mOnHoverListener;
3272
3273        private OnGenericMotionListener mOnGenericMotionListener;
3274
3275        private OnDragListener mOnDragListener;
3276
3277        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3278
3279        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3280    }
3281
3282    ListenerInfo mListenerInfo;
3283
3284    /**
3285     * The application environment this view lives in.
3286     * This field should be made private, so it is hidden from the SDK.
3287     * {@hide}
3288     */
3289    @ViewDebug.ExportedProperty(deepExport = true)
3290    protected Context mContext;
3291
3292    private final Resources mResources;
3293
3294    private ScrollabilityCache mScrollCache;
3295
3296    private int[] mDrawableState = null;
3297
3298    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3299
3300    /**
3301     * Animator that automatically runs based on state changes.
3302     */
3303    private StateListAnimator mStateListAnimator;
3304
3305    /**
3306     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3307     * the user may specify which view to go to next.
3308     */
3309    private int mNextFocusLeftId = View.NO_ID;
3310
3311    /**
3312     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3313     * the user may specify which view to go to next.
3314     */
3315    private int mNextFocusRightId = View.NO_ID;
3316
3317    /**
3318     * When this view has focus and the next focus is {@link #FOCUS_UP},
3319     * the user may specify which view to go to next.
3320     */
3321    private int mNextFocusUpId = View.NO_ID;
3322
3323    /**
3324     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3325     * the user may specify which view to go to next.
3326     */
3327    private int mNextFocusDownId = View.NO_ID;
3328
3329    /**
3330     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3331     * the user may specify which view to go to next.
3332     */
3333    int mNextFocusForwardId = View.NO_ID;
3334
3335    private CheckForLongPress mPendingCheckForLongPress;
3336    private CheckForTap mPendingCheckForTap = null;
3337    private PerformClick mPerformClick;
3338    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3339
3340    private UnsetPressedState mUnsetPressedState;
3341
3342    /**
3343     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3344     * up event while a long press is invoked as soon as the long press duration is reached, so
3345     * a long press could be performed before the tap is checked, in which case the tap's action
3346     * should not be invoked.
3347     */
3348    private boolean mHasPerformedLongPress;
3349
3350    /**
3351     * The minimum height of the view. We'll try our best to have the height
3352     * of this view to at least this amount.
3353     */
3354    @ViewDebug.ExportedProperty(category = "measurement")
3355    private int mMinHeight;
3356
3357    /**
3358     * The minimum width of the view. We'll try our best to have the width
3359     * of this view to at least this amount.
3360     */
3361    @ViewDebug.ExportedProperty(category = "measurement")
3362    private int mMinWidth;
3363
3364    /**
3365     * The delegate to handle touch events that are physically in this view
3366     * but should be handled by another view.
3367     */
3368    private TouchDelegate mTouchDelegate = null;
3369
3370    /**
3371     * Solid color to use as a background when creating the drawing cache. Enables
3372     * the cache to use 16 bit bitmaps instead of 32 bit.
3373     */
3374    private int mDrawingCacheBackgroundColor = 0;
3375
3376    /**
3377     * Special tree observer used when mAttachInfo is null.
3378     */
3379    private ViewTreeObserver mFloatingTreeObserver;
3380
3381    /**
3382     * Cache the touch slop from the context that created the view.
3383     */
3384    private int mTouchSlop;
3385
3386    /**
3387     * Object that handles automatic animation of view properties.
3388     */
3389    private ViewPropertyAnimator mAnimator = null;
3390
3391    /**
3392     * Flag indicating that a drag can cross window boundaries.  When
3393     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3394     * with this flag set, all visible applications will be able to participate
3395     * in the drag operation and receive the dragged content.
3396     *
3397     * @hide
3398     */
3399    public static final int DRAG_FLAG_GLOBAL = 1;
3400
3401    /**
3402     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3403     */
3404    private float mVerticalScrollFactor;
3405
3406    /**
3407     * Position of the vertical scroll bar.
3408     */
3409    private int mVerticalScrollbarPosition;
3410
3411    /**
3412     * Position the scroll bar at the default position as determined by the system.
3413     */
3414    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3415
3416    /**
3417     * Position the scroll bar along the left edge.
3418     */
3419    public static final int SCROLLBAR_POSITION_LEFT = 1;
3420
3421    /**
3422     * Position the scroll bar along the right edge.
3423     */
3424    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3425
3426    /**
3427     * Indicates that the view does not have a layer.
3428     *
3429     * @see #getLayerType()
3430     * @see #setLayerType(int, android.graphics.Paint)
3431     * @see #LAYER_TYPE_SOFTWARE
3432     * @see #LAYER_TYPE_HARDWARE
3433     */
3434    public static final int LAYER_TYPE_NONE = 0;
3435
3436    /**
3437     * <p>Indicates that the view has a software layer. A software layer is backed
3438     * by a bitmap and causes the view to be rendered using Android's software
3439     * rendering pipeline, even if hardware acceleration is enabled.</p>
3440     *
3441     * <p>Software layers have various usages:</p>
3442     * <p>When the application is not using hardware acceleration, a software layer
3443     * is useful to apply a specific color filter and/or blending mode and/or
3444     * translucency to a view and all its children.</p>
3445     * <p>When the application is using hardware acceleration, a software layer
3446     * is useful to render drawing primitives not supported by the hardware
3447     * accelerated pipeline. It can also be used to cache a complex view tree
3448     * into a texture and reduce the complexity of drawing operations. For instance,
3449     * when animating a complex view tree with a translation, a software layer can
3450     * be used to render the view tree only once.</p>
3451     * <p>Software layers should be avoided when the affected view tree updates
3452     * often. Every update will require to re-render the software layer, which can
3453     * potentially be slow (particularly when hardware acceleration is turned on
3454     * since the layer will have to be uploaded into a hardware texture after every
3455     * update.)</p>
3456     *
3457     * @see #getLayerType()
3458     * @see #setLayerType(int, android.graphics.Paint)
3459     * @see #LAYER_TYPE_NONE
3460     * @see #LAYER_TYPE_HARDWARE
3461     */
3462    public static final int LAYER_TYPE_SOFTWARE = 1;
3463
3464    /**
3465     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3466     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3467     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3468     * rendering pipeline, but only if hardware acceleration is turned on for the
3469     * view hierarchy. When hardware acceleration is turned off, hardware layers
3470     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3471     *
3472     * <p>A hardware layer is useful to apply a specific color filter and/or
3473     * blending mode and/or translucency to a view and all its children.</p>
3474     * <p>A hardware layer can be used to cache a complex view tree into a
3475     * texture and reduce the complexity of drawing operations. For instance,
3476     * when animating a complex view tree with a translation, a hardware layer can
3477     * be used to render the view tree only once.</p>
3478     * <p>A hardware layer can also be used to increase the rendering quality when
3479     * rotation transformations are applied on a view. It can also be used to
3480     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3481     *
3482     * @see #getLayerType()
3483     * @see #setLayerType(int, android.graphics.Paint)
3484     * @see #LAYER_TYPE_NONE
3485     * @see #LAYER_TYPE_SOFTWARE
3486     */
3487    public static final int LAYER_TYPE_HARDWARE = 2;
3488
3489    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3490            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3491            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3492            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3493    })
3494    int mLayerType = LAYER_TYPE_NONE;
3495    Paint mLayerPaint;
3496
3497    /**
3498     * Set to true when drawing cache is enabled and cannot be created.
3499     *
3500     * @hide
3501     */
3502    public boolean mCachingFailed;
3503    private Bitmap mDrawingCache;
3504    private Bitmap mUnscaledDrawingCache;
3505
3506    /**
3507     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3508     * <p>
3509     * When non-null and valid, this is expected to contain an up-to-date copy
3510     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3511     * cleanup.
3512     */
3513    final RenderNode mRenderNode;
3514
3515    /**
3516     * Set to true when the view is sending hover accessibility events because it
3517     * is the innermost hovered view.
3518     */
3519    private boolean mSendingHoverAccessibilityEvents;
3520
3521    /**
3522     * Delegate for injecting accessibility functionality.
3523     */
3524    AccessibilityDelegate mAccessibilityDelegate;
3525
3526    /**
3527     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3528     * and add/remove objects to/from the overlay directly through the Overlay methods.
3529     */
3530    ViewOverlay mOverlay;
3531
3532    /**
3533     * The currently active parent view for receiving delegated nested scrolling events.
3534     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3535     * by {@link #stopNestedScroll()} at the same point where we clear
3536     * requestDisallowInterceptTouchEvent.
3537     */
3538    private ViewParent mNestedScrollingParent;
3539
3540    /**
3541     * Consistency verifier for debugging purposes.
3542     * @hide
3543     */
3544    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3545            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3546                    new InputEventConsistencyVerifier(this, 0) : null;
3547
3548    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3549
3550    private int[] mTempNestedScrollConsumed;
3551
3552    /**
3553     * An overlay is going to draw this View instead of being drawn as part of this
3554     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3555     * when this view is invalidated.
3556     */
3557    GhostView mGhostView;
3558
3559    /**
3560     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3561     * @hide
3562     */
3563    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3564    public String[] mAttributes;
3565
3566    /**
3567     * Maps a Resource id to its name.
3568     */
3569    private static SparseArray<String> mAttributeMap;
3570
3571    /**
3572     * @hide
3573     */
3574    String mStartActivityRequestWho;
3575
3576    /**
3577     * Simple constructor to use when creating a view from code.
3578     *
3579     * @param context The Context the view is running in, through which it can
3580     *        access the current theme, resources, etc.
3581     */
3582    public View(Context context) {
3583        mContext = context;
3584        mResources = context != null ? context.getResources() : null;
3585        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3586        // Set some flags defaults
3587        mPrivateFlags2 =
3588                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3589                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3590                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3591                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3592                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3593                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3594        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3595        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3596        mUserPaddingStart = UNDEFINED_PADDING;
3597        mUserPaddingEnd = UNDEFINED_PADDING;
3598        mRenderNode = RenderNode.create(getClass().getName(), this);
3599
3600        if (!sCompatibilityDone && context != null) {
3601            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3602
3603            // Older apps may need this compatibility hack for measurement.
3604            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3605
3606            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3607            // of whether a layout was requested on that View.
3608            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3609
3610            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3611
3612            sCompatibilityDone = true;
3613        }
3614    }
3615
3616    /**
3617     * Constructor that is called when inflating a view from XML. This is called
3618     * when a view is being constructed from an XML file, supplying attributes
3619     * that were specified in the XML file. This version uses a default style of
3620     * 0, so the only attribute values applied are those in the Context's Theme
3621     * and the given AttributeSet.
3622     *
3623     * <p>
3624     * The method onFinishInflate() will be called after all children have been
3625     * added.
3626     *
3627     * @param context The Context the view is running in, through which it can
3628     *        access the current theme, resources, etc.
3629     * @param attrs The attributes of the XML tag that is inflating the view.
3630     * @see #View(Context, AttributeSet, int)
3631     */
3632    public View(Context context, @Nullable AttributeSet attrs) {
3633        this(context, attrs, 0);
3634    }
3635
3636    /**
3637     * Perform inflation from XML and apply a class-specific base style from a
3638     * theme attribute. This constructor of View allows subclasses to use their
3639     * own base style when they are inflating. For example, a Button class's
3640     * constructor would call this version of the super class constructor and
3641     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3642     * allows the theme's button style to modify all of the base view attributes
3643     * (in particular its background) as well as the Button class's attributes.
3644     *
3645     * @param context The Context the view is running in, through which it can
3646     *        access the current theme, resources, etc.
3647     * @param attrs The attributes of the XML tag that is inflating the view.
3648     * @param defStyleAttr An attribute in the current theme that contains a
3649     *        reference to a style resource that supplies default values for
3650     *        the view. Can be 0 to not look for defaults.
3651     * @see #View(Context, AttributeSet)
3652     */
3653    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3654        this(context, attrs, defStyleAttr, 0);
3655    }
3656
3657    /**
3658     * Perform inflation from XML and apply a class-specific base style from a
3659     * theme attribute or style resource. This constructor of View allows
3660     * subclasses to use their own base style when they are inflating.
3661     * <p>
3662     * When determining the final value of a particular attribute, there are
3663     * four inputs that come into play:
3664     * <ol>
3665     * <li>Any attribute values in the given AttributeSet.
3666     * <li>The style resource specified in the AttributeSet (named "style").
3667     * <li>The default style specified by <var>defStyleAttr</var>.
3668     * <li>The default style specified by <var>defStyleRes</var>.
3669     * <li>The base values in this theme.
3670     * </ol>
3671     * <p>
3672     * Each of these inputs is considered in-order, with the first listed taking
3673     * precedence over the following ones. In other words, if in the
3674     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3675     * , then the button's text will <em>always</em> be black, regardless of
3676     * what is specified in any of the styles.
3677     *
3678     * @param context The Context the view is running in, through which it can
3679     *        access the current theme, resources, etc.
3680     * @param attrs The attributes of the XML tag that is inflating the view.
3681     * @param defStyleAttr An attribute in the current theme that contains a
3682     *        reference to a style resource that supplies default values for
3683     *        the view. Can be 0 to not look for defaults.
3684     * @param defStyleRes A resource identifier of a style resource that
3685     *        supplies default values for the view, used only if
3686     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3687     *        to not look for defaults.
3688     * @see #View(Context, AttributeSet, int)
3689     */
3690    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3691        this(context);
3692
3693        final TypedArray a = context.obtainStyledAttributes(
3694                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3695
3696        if (mDebugViewAttributes) {
3697            saveAttributeData(attrs, a);
3698        }
3699
3700        Drawable background = null;
3701
3702        int leftPadding = -1;
3703        int topPadding = -1;
3704        int rightPadding = -1;
3705        int bottomPadding = -1;
3706        int startPadding = UNDEFINED_PADDING;
3707        int endPadding = UNDEFINED_PADDING;
3708
3709        int padding = -1;
3710
3711        int viewFlagValues = 0;
3712        int viewFlagMasks = 0;
3713
3714        boolean setScrollContainer = false;
3715
3716        int x = 0;
3717        int y = 0;
3718
3719        float tx = 0;
3720        float ty = 0;
3721        float tz = 0;
3722        float elevation = 0;
3723        float rotation = 0;
3724        float rotationX = 0;
3725        float rotationY = 0;
3726        float sx = 1f;
3727        float sy = 1f;
3728        boolean transformSet = false;
3729
3730        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3731        int overScrollMode = mOverScrollMode;
3732        boolean initializeScrollbars = false;
3733
3734        boolean startPaddingDefined = false;
3735        boolean endPaddingDefined = false;
3736        boolean leftPaddingDefined = false;
3737        boolean rightPaddingDefined = false;
3738
3739        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3740
3741        final int N = a.getIndexCount();
3742        for (int i = 0; i < N; i++) {
3743            int attr = a.getIndex(i);
3744            switch (attr) {
3745                case com.android.internal.R.styleable.View_background:
3746                    background = a.getDrawable(attr);
3747                    break;
3748                case com.android.internal.R.styleable.View_padding:
3749                    padding = a.getDimensionPixelSize(attr, -1);
3750                    mUserPaddingLeftInitial = padding;
3751                    mUserPaddingRightInitial = padding;
3752                    leftPaddingDefined = true;
3753                    rightPaddingDefined = true;
3754                    break;
3755                 case com.android.internal.R.styleable.View_paddingLeft:
3756                    leftPadding = a.getDimensionPixelSize(attr, -1);
3757                    mUserPaddingLeftInitial = leftPadding;
3758                    leftPaddingDefined = true;
3759                    break;
3760                case com.android.internal.R.styleable.View_paddingTop:
3761                    topPadding = a.getDimensionPixelSize(attr, -1);
3762                    break;
3763                case com.android.internal.R.styleable.View_paddingRight:
3764                    rightPadding = a.getDimensionPixelSize(attr, -1);
3765                    mUserPaddingRightInitial = rightPadding;
3766                    rightPaddingDefined = true;
3767                    break;
3768                case com.android.internal.R.styleable.View_paddingBottom:
3769                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3770                    break;
3771                case com.android.internal.R.styleable.View_paddingStart:
3772                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3773                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3774                    break;
3775                case com.android.internal.R.styleable.View_paddingEnd:
3776                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3777                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3778                    break;
3779                case com.android.internal.R.styleable.View_scrollX:
3780                    x = a.getDimensionPixelOffset(attr, 0);
3781                    break;
3782                case com.android.internal.R.styleable.View_scrollY:
3783                    y = a.getDimensionPixelOffset(attr, 0);
3784                    break;
3785                case com.android.internal.R.styleable.View_alpha:
3786                    setAlpha(a.getFloat(attr, 1f));
3787                    break;
3788                case com.android.internal.R.styleable.View_transformPivotX:
3789                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3790                    break;
3791                case com.android.internal.R.styleable.View_transformPivotY:
3792                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3793                    break;
3794                case com.android.internal.R.styleable.View_translationX:
3795                    tx = a.getDimensionPixelOffset(attr, 0);
3796                    transformSet = true;
3797                    break;
3798                case com.android.internal.R.styleable.View_translationY:
3799                    ty = a.getDimensionPixelOffset(attr, 0);
3800                    transformSet = true;
3801                    break;
3802                case com.android.internal.R.styleable.View_translationZ:
3803                    tz = a.getDimensionPixelOffset(attr, 0);
3804                    transformSet = true;
3805                    break;
3806                case com.android.internal.R.styleable.View_elevation:
3807                    elevation = a.getDimensionPixelOffset(attr, 0);
3808                    transformSet = true;
3809                    break;
3810                case com.android.internal.R.styleable.View_rotation:
3811                    rotation = a.getFloat(attr, 0);
3812                    transformSet = true;
3813                    break;
3814                case com.android.internal.R.styleable.View_rotationX:
3815                    rotationX = a.getFloat(attr, 0);
3816                    transformSet = true;
3817                    break;
3818                case com.android.internal.R.styleable.View_rotationY:
3819                    rotationY = a.getFloat(attr, 0);
3820                    transformSet = true;
3821                    break;
3822                case com.android.internal.R.styleable.View_scaleX:
3823                    sx = a.getFloat(attr, 1f);
3824                    transformSet = true;
3825                    break;
3826                case com.android.internal.R.styleable.View_scaleY:
3827                    sy = a.getFloat(attr, 1f);
3828                    transformSet = true;
3829                    break;
3830                case com.android.internal.R.styleable.View_id:
3831                    mID = a.getResourceId(attr, NO_ID);
3832                    break;
3833                case com.android.internal.R.styleable.View_tag:
3834                    mTag = a.getText(attr);
3835                    break;
3836                case com.android.internal.R.styleable.View_fitsSystemWindows:
3837                    if (a.getBoolean(attr, false)) {
3838                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3839                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3840                    }
3841                    break;
3842                case com.android.internal.R.styleable.View_focusable:
3843                    if (a.getBoolean(attr, false)) {
3844                        viewFlagValues |= FOCUSABLE;
3845                        viewFlagMasks |= FOCUSABLE_MASK;
3846                    }
3847                    break;
3848                case com.android.internal.R.styleable.View_focusableInTouchMode:
3849                    if (a.getBoolean(attr, false)) {
3850                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3851                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3852                    }
3853                    break;
3854                case com.android.internal.R.styleable.View_clickable:
3855                    if (a.getBoolean(attr, false)) {
3856                        viewFlagValues |= CLICKABLE;
3857                        viewFlagMasks |= CLICKABLE;
3858                    }
3859                    break;
3860                case com.android.internal.R.styleable.View_longClickable:
3861                    if (a.getBoolean(attr, false)) {
3862                        viewFlagValues |= LONG_CLICKABLE;
3863                        viewFlagMasks |= LONG_CLICKABLE;
3864                    }
3865                    break;
3866                case com.android.internal.R.styleable.View_saveEnabled:
3867                    if (!a.getBoolean(attr, true)) {
3868                        viewFlagValues |= SAVE_DISABLED;
3869                        viewFlagMasks |= SAVE_DISABLED_MASK;
3870                    }
3871                    break;
3872                case com.android.internal.R.styleable.View_duplicateParentState:
3873                    if (a.getBoolean(attr, false)) {
3874                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3875                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3876                    }
3877                    break;
3878                case com.android.internal.R.styleable.View_visibility:
3879                    final int visibility = a.getInt(attr, 0);
3880                    if (visibility != 0) {
3881                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3882                        viewFlagMasks |= VISIBILITY_MASK;
3883                    }
3884                    break;
3885                case com.android.internal.R.styleable.View_layoutDirection:
3886                    // Clear any layout direction flags (included resolved bits) already set
3887                    mPrivateFlags2 &=
3888                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3889                    // Set the layout direction flags depending on the value of the attribute
3890                    final int layoutDirection = a.getInt(attr, -1);
3891                    final int value = (layoutDirection != -1) ?
3892                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3893                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3894                    break;
3895                case com.android.internal.R.styleable.View_drawingCacheQuality:
3896                    final int cacheQuality = a.getInt(attr, 0);
3897                    if (cacheQuality != 0) {
3898                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3899                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3900                    }
3901                    break;
3902                case com.android.internal.R.styleable.View_contentDescription:
3903                    setContentDescription(a.getString(attr));
3904                    break;
3905                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3906                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3907                    break;
3908                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3909                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3910                    break;
3911                case com.android.internal.R.styleable.View_labelFor:
3912                    setLabelFor(a.getResourceId(attr, NO_ID));
3913                    break;
3914                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3915                    if (!a.getBoolean(attr, true)) {
3916                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3917                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3918                    }
3919                    break;
3920                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3921                    if (!a.getBoolean(attr, true)) {
3922                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3923                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3924                    }
3925                    break;
3926                case R.styleable.View_scrollbars:
3927                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3928                    if (scrollbars != SCROLLBARS_NONE) {
3929                        viewFlagValues |= scrollbars;
3930                        viewFlagMasks |= SCROLLBARS_MASK;
3931                        initializeScrollbars = true;
3932                    }
3933                    break;
3934                //noinspection deprecation
3935                case R.styleable.View_fadingEdge:
3936                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3937                        // Ignore the attribute starting with ICS
3938                        break;
3939                    }
3940                    // With builds < ICS, fall through and apply fading edges
3941                case R.styleable.View_requiresFadingEdge:
3942                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3943                    if (fadingEdge != FADING_EDGE_NONE) {
3944                        viewFlagValues |= fadingEdge;
3945                        viewFlagMasks |= FADING_EDGE_MASK;
3946                        initializeFadingEdgeInternal(a);
3947                    }
3948                    break;
3949                case R.styleable.View_scrollbarStyle:
3950                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3951                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3952                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3953                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3954                    }
3955                    break;
3956                case R.styleable.View_isScrollContainer:
3957                    setScrollContainer = true;
3958                    if (a.getBoolean(attr, false)) {
3959                        setScrollContainer(true);
3960                    }
3961                    break;
3962                case com.android.internal.R.styleable.View_keepScreenOn:
3963                    if (a.getBoolean(attr, false)) {
3964                        viewFlagValues |= KEEP_SCREEN_ON;
3965                        viewFlagMasks |= KEEP_SCREEN_ON;
3966                    }
3967                    break;
3968                case R.styleable.View_filterTouchesWhenObscured:
3969                    if (a.getBoolean(attr, false)) {
3970                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3971                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3972                    }
3973                    break;
3974                case R.styleable.View_nextFocusLeft:
3975                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3976                    break;
3977                case R.styleable.View_nextFocusRight:
3978                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3979                    break;
3980                case R.styleable.View_nextFocusUp:
3981                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3982                    break;
3983                case R.styleable.View_nextFocusDown:
3984                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3985                    break;
3986                case R.styleable.View_nextFocusForward:
3987                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3988                    break;
3989                case R.styleable.View_minWidth:
3990                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3991                    break;
3992                case R.styleable.View_minHeight:
3993                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3994                    break;
3995                case R.styleable.View_onClick:
3996                    if (context.isRestricted()) {
3997                        throw new IllegalStateException("The android:onClick attribute cannot "
3998                                + "be used within a restricted context");
3999                    }
4000
4001                    final String handlerName = a.getString(attr);
4002                    if (handlerName != null) {
4003                        setOnClickListener(new OnClickListener() {
4004                            private Method mHandler;
4005
4006                            public void onClick(View v) {
4007                                if (mHandler == null) {
4008                                    try {
4009                                        mHandler = getContext().getClass().getMethod(handlerName,
4010                                                View.class);
4011                                    } catch (NoSuchMethodException e) {
4012                                        int id = getId();
4013                                        String idText = id == NO_ID ? "" : " with id '"
4014                                                + getContext().getResources().getResourceEntryName(
4015                                                    id) + "'";
4016                                        throw new IllegalStateException("Could not find a method " +
4017                                                handlerName + "(View) in the activity "
4018                                                + getContext().getClass() + " for onClick handler"
4019                                                + " on view " + View.this.getClass() + idText, e);
4020                                    }
4021                                }
4022
4023                                try {
4024                                    mHandler.invoke(getContext(), View.this);
4025                                } catch (IllegalAccessException e) {
4026                                    throw new IllegalStateException("Could not execute non "
4027                                            + "public method of the activity", e);
4028                                } catch (InvocationTargetException e) {
4029                                    throw new IllegalStateException("Could not execute "
4030                                            + "method of the activity", e);
4031                                }
4032                            }
4033                        });
4034                    }
4035                    break;
4036                case R.styleable.View_overScrollMode:
4037                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4038                    break;
4039                case R.styleable.View_verticalScrollbarPosition:
4040                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4041                    break;
4042                case R.styleable.View_layerType:
4043                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4044                    break;
4045                case R.styleable.View_textDirection:
4046                    // Clear any text direction flag already set
4047                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4048                    // Set the text direction flags depending on the value of the attribute
4049                    final int textDirection = a.getInt(attr, -1);
4050                    if (textDirection != -1) {
4051                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4052                    }
4053                    break;
4054                case R.styleable.View_textAlignment:
4055                    // Clear any text alignment flag already set
4056                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4057                    // Set the text alignment flag depending on the value of the attribute
4058                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4059                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4060                    break;
4061                case R.styleable.View_importantForAccessibility:
4062                    setImportantForAccessibility(a.getInt(attr,
4063                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4064                    break;
4065                case R.styleable.View_accessibilityLiveRegion:
4066                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4067                    break;
4068                case R.styleable.View_transitionName:
4069                    setTransitionName(a.getString(attr));
4070                    break;
4071                case R.styleable.View_nestedScrollingEnabled:
4072                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4073                    break;
4074                case R.styleable.View_stateListAnimator:
4075                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4076                            a.getResourceId(attr, 0)));
4077                    break;
4078                case R.styleable.View_backgroundTint:
4079                    // This will get applied later during setBackground().
4080                    if (mBackgroundTint == null) {
4081                        mBackgroundTint = new TintInfo();
4082                    }
4083                    mBackgroundTint.mTintList = a.getColorStateList(
4084                            R.styleable.View_backgroundTint);
4085                    mBackgroundTint.mHasTintList = true;
4086                    break;
4087                case R.styleable.View_backgroundTintMode:
4088                    // This will get applied later during setBackground().
4089                    if (mBackgroundTint == null) {
4090                        mBackgroundTint = new TintInfo();
4091                    }
4092                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4093                            R.styleable.View_backgroundTintMode, -1), null);
4094                    mBackgroundTint.mHasTintMode = true;
4095                    break;
4096                case R.styleable.View_outlineProvider:
4097                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4098                            PROVIDER_BACKGROUND));
4099                    break;
4100                case R.styleable.View_foreground:
4101                    setForeground(a.getDrawable(attr));
4102                    break;
4103                case R.styleable.View_foregroundGravity:
4104                    setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4105                    break;
4106                case R.styleable.View_foregroundTintMode:
4107                    setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4108                    break;
4109                case R.styleable.View_foregroundTint:
4110                    setForegroundTintList(a.getColorStateList(attr));
4111                    break;
4112                case R.styleable.View_foregroundInsidePadding:
4113                    if (mForegroundInfo == null) {
4114                        mForegroundInfo = new ForegroundInfo();
4115                    }
4116                    mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4117                            mForegroundInfo.mInsidePadding);
4118                    break;
4119            }
4120        }
4121
4122        setOverScrollMode(overScrollMode);
4123
4124        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4125        // the resolved layout direction). Those cached values will be used later during padding
4126        // resolution.
4127        mUserPaddingStart = startPadding;
4128        mUserPaddingEnd = endPadding;
4129
4130        if (background != null) {
4131            setBackground(background);
4132        }
4133
4134        // setBackground above will record that padding is currently provided by the background.
4135        // If we have padding specified via xml, record that here instead and use it.
4136        mLeftPaddingDefined = leftPaddingDefined;
4137        mRightPaddingDefined = rightPaddingDefined;
4138
4139        if (padding >= 0) {
4140            leftPadding = padding;
4141            topPadding = padding;
4142            rightPadding = padding;
4143            bottomPadding = padding;
4144            mUserPaddingLeftInitial = padding;
4145            mUserPaddingRightInitial = padding;
4146        }
4147
4148        if (isRtlCompatibilityMode()) {
4149            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4150            // left / right padding are used if defined (meaning here nothing to do). If they are not
4151            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4152            // start / end and resolve them as left / right (layout direction is not taken into account).
4153            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4154            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4155            // defined.
4156            if (!mLeftPaddingDefined && startPaddingDefined) {
4157                leftPadding = startPadding;
4158            }
4159            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4160            if (!mRightPaddingDefined && endPaddingDefined) {
4161                rightPadding = endPadding;
4162            }
4163            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4164        } else {
4165            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4166            // values defined. Otherwise, left /right values are used.
4167            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4168            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4169            // defined.
4170            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4171
4172            if (mLeftPaddingDefined && !hasRelativePadding) {
4173                mUserPaddingLeftInitial = leftPadding;
4174            }
4175            if (mRightPaddingDefined && !hasRelativePadding) {
4176                mUserPaddingRightInitial = rightPadding;
4177            }
4178        }
4179
4180        internalSetPadding(
4181                mUserPaddingLeftInitial,
4182                topPadding >= 0 ? topPadding : mPaddingTop,
4183                mUserPaddingRightInitial,
4184                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4185
4186        if (viewFlagMasks != 0) {
4187            setFlags(viewFlagValues, viewFlagMasks);
4188        }
4189
4190        if (initializeScrollbars) {
4191            initializeScrollbarsInternal(a);
4192        }
4193
4194        a.recycle();
4195
4196        // Needs to be called after mViewFlags is set
4197        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4198            recomputePadding();
4199        }
4200
4201        if (x != 0 || y != 0) {
4202            scrollTo(x, y);
4203        }
4204
4205        if (transformSet) {
4206            setTranslationX(tx);
4207            setTranslationY(ty);
4208            setTranslationZ(tz);
4209            setElevation(elevation);
4210            setRotation(rotation);
4211            setRotationX(rotationX);
4212            setRotationY(rotationY);
4213            setScaleX(sx);
4214            setScaleY(sy);
4215        }
4216
4217        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4218            setScrollContainer(true);
4219        }
4220
4221        computeOpaqueFlags();
4222    }
4223
4224    /**
4225     * Non-public constructor for use in testing
4226     */
4227    View() {
4228        mResources = null;
4229        mRenderNode = RenderNode.create(getClass().getName(), this);
4230    }
4231
4232    private static SparseArray<String> getAttributeMap() {
4233        if (mAttributeMap == null) {
4234            mAttributeMap = new SparseArray<String>();
4235        }
4236        return mAttributeMap;
4237    }
4238
4239    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4240        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4241        mAttributes = new String[length];
4242
4243        int i = 0;
4244        if (attrs != null) {
4245            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4246                mAttributes[i] = attrs.getAttributeName(i);
4247                mAttributes[i + 1] = attrs.getAttributeValue(i);
4248            }
4249
4250        }
4251
4252        SparseArray<String> attributeMap = getAttributeMap();
4253        for (int j = 0; j < a.length(); ++j) {
4254            if (a.hasValue(j)) {
4255                try {
4256                    int resourceId = a.getResourceId(j, 0);
4257                    if (resourceId == 0) {
4258                        continue;
4259                    }
4260
4261                    String resourceName = attributeMap.get(resourceId);
4262                    if (resourceName == null) {
4263                        resourceName = a.getResources().getResourceName(resourceId);
4264                        attributeMap.put(resourceId, resourceName);
4265                    }
4266
4267                    mAttributes[i] = resourceName;
4268                    mAttributes[i + 1] = a.getText(j).toString();
4269                    i += 2;
4270                } catch (Resources.NotFoundException e) {
4271                    // if we can't get the resource name, we just ignore it
4272                }
4273            }
4274        }
4275    }
4276
4277    public String toString() {
4278        StringBuilder out = new StringBuilder(128);
4279        out.append(getClass().getName());
4280        out.append('{');
4281        out.append(Integer.toHexString(System.identityHashCode(this)));
4282        out.append(' ');
4283        switch (mViewFlags&VISIBILITY_MASK) {
4284            case VISIBLE: out.append('V'); break;
4285            case INVISIBLE: out.append('I'); break;
4286            case GONE: out.append('G'); break;
4287            default: out.append('.'); break;
4288        }
4289        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4290        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4291        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4292        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4293        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4294        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4295        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4296        out.append(' ');
4297        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4298        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4299        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4300        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4301            out.append('p');
4302        } else {
4303            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4304        }
4305        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4306        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4307        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4308        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4309        out.append(' ');
4310        out.append(mLeft);
4311        out.append(',');
4312        out.append(mTop);
4313        out.append('-');
4314        out.append(mRight);
4315        out.append(',');
4316        out.append(mBottom);
4317        final int id = getId();
4318        if (id != NO_ID) {
4319            out.append(" #");
4320            out.append(Integer.toHexString(id));
4321            final Resources r = mResources;
4322            if (Resources.resourceHasPackage(id) && r != null) {
4323                try {
4324                    String pkgname;
4325                    switch (id&0xff000000) {
4326                        case 0x7f000000:
4327                            pkgname="app";
4328                            break;
4329                        case 0x01000000:
4330                            pkgname="android";
4331                            break;
4332                        default:
4333                            pkgname = r.getResourcePackageName(id);
4334                            break;
4335                    }
4336                    String typename = r.getResourceTypeName(id);
4337                    String entryname = r.getResourceEntryName(id);
4338                    out.append(" ");
4339                    out.append(pkgname);
4340                    out.append(":");
4341                    out.append(typename);
4342                    out.append("/");
4343                    out.append(entryname);
4344                } catch (Resources.NotFoundException e) {
4345                }
4346            }
4347        }
4348        out.append("}");
4349        return out.toString();
4350    }
4351
4352    /**
4353     * <p>
4354     * Initializes the fading edges from a given set of styled attributes. This
4355     * method should be called by subclasses that need fading edges and when an
4356     * instance of these subclasses is created programmatically rather than
4357     * being inflated from XML. This method is automatically called when the XML
4358     * is inflated.
4359     * </p>
4360     *
4361     * @param a the styled attributes set to initialize the fading edges from
4362     *
4363     * @removed
4364     */
4365    protected void initializeFadingEdge(TypedArray a) {
4366        // This method probably shouldn't have been included in the SDK to begin with.
4367        // It relies on 'a' having been initialized using an attribute filter array that is
4368        // not publicly available to the SDK. The old method has been renamed
4369        // to initializeFadingEdgeInternal and hidden for framework use only;
4370        // this one initializes using defaults to make it safe to call for apps.
4371
4372        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4373
4374        initializeFadingEdgeInternal(arr);
4375
4376        arr.recycle();
4377    }
4378
4379    /**
4380     * <p>
4381     * Initializes the fading edges from a given set of styled attributes. This
4382     * method should be called by subclasses that need fading edges and when an
4383     * instance of these subclasses is created programmatically rather than
4384     * being inflated from XML. This method is automatically called when the XML
4385     * is inflated.
4386     * </p>
4387     *
4388     * @param a the styled attributes set to initialize the fading edges from
4389     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4390     */
4391    protected void initializeFadingEdgeInternal(TypedArray a) {
4392        initScrollCache();
4393
4394        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4395                R.styleable.View_fadingEdgeLength,
4396                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4397    }
4398
4399    /**
4400     * Returns the size of the vertical faded edges used to indicate that more
4401     * content in this view is visible.
4402     *
4403     * @return The size in pixels of the vertical faded edge or 0 if vertical
4404     *         faded edges are not enabled for this view.
4405     * @attr ref android.R.styleable#View_fadingEdgeLength
4406     */
4407    public int getVerticalFadingEdgeLength() {
4408        if (isVerticalFadingEdgeEnabled()) {
4409            ScrollabilityCache cache = mScrollCache;
4410            if (cache != null) {
4411                return cache.fadingEdgeLength;
4412            }
4413        }
4414        return 0;
4415    }
4416
4417    /**
4418     * Set the size of the faded edge used to indicate that more content in this
4419     * view is available.  Will not change whether the fading edge is enabled; use
4420     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4421     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4422     * for the vertical or horizontal fading edges.
4423     *
4424     * @param length The size in pixels of the faded edge used to indicate that more
4425     *        content in this view is visible.
4426     */
4427    public void setFadingEdgeLength(int length) {
4428        initScrollCache();
4429        mScrollCache.fadingEdgeLength = length;
4430    }
4431
4432    /**
4433     * Returns the size of the horizontal faded edges used to indicate that more
4434     * content in this view is visible.
4435     *
4436     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4437     *         faded edges are not enabled for this view.
4438     * @attr ref android.R.styleable#View_fadingEdgeLength
4439     */
4440    public int getHorizontalFadingEdgeLength() {
4441        if (isHorizontalFadingEdgeEnabled()) {
4442            ScrollabilityCache cache = mScrollCache;
4443            if (cache != null) {
4444                return cache.fadingEdgeLength;
4445            }
4446        }
4447        return 0;
4448    }
4449
4450    /**
4451     * Returns the width of the vertical scrollbar.
4452     *
4453     * @return The width in pixels of the vertical scrollbar or 0 if there
4454     *         is no vertical scrollbar.
4455     */
4456    public int getVerticalScrollbarWidth() {
4457        ScrollabilityCache cache = mScrollCache;
4458        if (cache != null) {
4459            ScrollBarDrawable scrollBar = cache.scrollBar;
4460            if (scrollBar != null) {
4461                int size = scrollBar.getSize(true);
4462                if (size <= 0) {
4463                    size = cache.scrollBarSize;
4464                }
4465                return size;
4466            }
4467            return 0;
4468        }
4469        return 0;
4470    }
4471
4472    /**
4473     * Returns the height of the horizontal scrollbar.
4474     *
4475     * @return The height in pixels of the horizontal scrollbar or 0 if
4476     *         there is no horizontal scrollbar.
4477     */
4478    protected int getHorizontalScrollbarHeight() {
4479        ScrollabilityCache cache = mScrollCache;
4480        if (cache != null) {
4481            ScrollBarDrawable scrollBar = cache.scrollBar;
4482            if (scrollBar != null) {
4483                int size = scrollBar.getSize(false);
4484                if (size <= 0) {
4485                    size = cache.scrollBarSize;
4486                }
4487                return size;
4488            }
4489            return 0;
4490        }
4491        return 0;
4492    }
4493
4494    /**
4495     * <p>
4496     * Initializes the scrollbars from a given set of styled attributes. This
4497     * method should be called by subclasses that need scrollbars and when an
4498     * instance of these subclasses is created programmatically rather than
4499     * being inflated from XML. This method is automatically called when the XML
4500     * is inflated.
4501     * </p>
4502     *
4503     * @param a the styled attributes set to initialize the scrollbars from
4504     *
4505     * @removed
4506     */
4507    protected void initializeScrollbars(TypedArray a) {
4508        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4509        // using the View filter array which is not available to the SDK. As such, internal
4510        // framework usage now uses initializeScrollbarsInternal and we grab a default
4511        // TypedArray with the right filter instead here.
4512        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4513
4514        initializeScrollbarsInternal(arr);
4515
4516        // We ignored the method parameter. Recycle the one we actually did use.
4517        arr.recycle();
4518    }
4519
4520    /**
4521     * <p>
4522     * Initializes the scrollbars from a given set of styled attributes. This
4523     * method should be called by subclasses that need scrollbars and when an
4524     * instance of these subclasses is created programmatically rather than
4525     * being inflated from XML. This method is automatically called when the XML
4526     * is inflated.
4527     * </p>
4528     *
4529     * @param a the styled attributes set to initialize the scrollbars from
4530     * @hide
4531     */
4532    protected void initializeScrollbarsInternal(TypedArray a) {
4533        initScrollCache();
4534
4535        final ScrollabilityCache scrollabilityCache = mScrollCache;
4536
4537        if (scrollabilityCache.scrollBar == null) {
4538            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4539            scrollabilityCache.scrollBar.setCallback(this);
4540            scrollabilityCache.scrollBar.setState(getDrawableState());
4541        }
4542
4543        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4544
4545        if (!fadeScrollbars) {
4546            scrollabilityCache.state = ScrollabilityCache.ON;
4547        }
4548        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4549
4550
4551        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4552                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4553                        .getScrollBarFadeDuration());
4554        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4555                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4556                ViewConfiguration.getScrollDefaultDelay());
4557
4558
4559        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4560                com.android.internal.R.styleable.View_scrollbarSize,
4561                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4562
4563        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4564        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4565
4566        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4567        if (thumb != null) {
4568            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4569        }
4570
4571        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4572                false);
4573        if (alwaysDraw) {
4574            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4575        }
4576
4577        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4578        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4579
4580        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4581        if (thumb != null) {
4582            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4583        }
4584
4585        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4586                false);
4587        if (alwaysDraw) {
4588            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4589        }
4590
4591        // Apply layout direction to the new Drawables if needed
4592        final int layoutDirection = getLayoutDirection();
4593        if (track != null) {
4594            track.setLayoutDirection(layoutDirection);
4595        }
4596        if (thumb != null) {
4597            thumb.setLayoutDirection(layoutDirection);
4598        }
4599
4600        // Re-apply user/background padding so that scrollbar(s) get added
4601        resolvePadding();
4602    }
4603
4604    /**
4605     * <p>
4606     * Initalizes the scrollability cache if necessary.
4607     * </p>
4608     */
4609    private void initScrollCache() {
4610        if (mScrollCache == null) {
4611            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4612        }
4613    }
4614
4615    private ScrollabilityCache getScrollCache() {
4616        initScrollCache();
4617        return mScrollCache;
4618    }
4619
4620    /**
4621     * Set the position of the vertical scroll bar. Should be one of
4622     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4623     * {@link #SCROLLBAR_POSITION_RIGHT}.
4624     *
4625     * @param position Where the vertical scroll bar should be positioned.
4626     */
4627    public void setVerticalScrollbarPosition(int position) {
4628        if (mVerticalScrollbarPosition != position) {
4629            mVerticalScrollbarPosition = position;
4630            computeOpaqueFlags();
4631            resolvePadding();
4632        }
4633    }
4634
4635    /**
4636     * @return The position where the vertical scroll bar will show, if applicable.
4637     * @see #setVerticalScrollbarPosition(int)
4638     */
4639    public int getVerticalScrollbarPosition() {
4640        return mVerticalScrollbarPosition;
4641    }
4642
4643    ListenerInfo getListenerInfo() {
4644        if (mListenerInfo != null) {
4645            return mListenerInfo;
4646        }
4647        mListenerInfo = new ListenerInfo();
4648        return mListenerInfo;
4649    }
4650
4651    /**
4652     * Register a callback to be invoked when the scroll X or Y positions of
4653     * this view change.
4654     * <p>
4655     * <b>Note:</b> Some views handle scrolling independently from View and may
4656     * have their own separate listeners for scroll-type events. For example,
4657     * {@link android.widget.ListView ListView} allows clients to register an
4658     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
4659     * to listen for changes in list scroll position.
4660     *
4661     * @param l The listener to notify when the scroll X or Y position changes.
4662     * @see android.view.View#getScrollX()
4663     * @see android.view.View#getScrollY()
4664     */
4665    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4666        getListenerInfo().mOnScrollChangeListener = l;
4667    }
4668
4669    /**
4670     * Register a callback to be invoked when focus of this view changed.
4671     *
4672     * @param l The callback that will run.
4673     */
4674    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4675        getListenerInfo().mOnFocusChangeListener = l;
4676    }
4677
4678    /**
4679     * Add a listener that will be called when the bounds of the view change due to
4680     * layout processing.
4681     *
4682     * @param listener The listener that will be called when layout bounds change.
4683     */
4684    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4685        ListenerInfo li = getListenerInfo();
4686        if (li.mOnLayoutChangeListeners == null) {
4687            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4688        }
4689        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4690            li.mOnLayoutChangeListeners.add(listener);
4691        }
4692    }
4693
4694    /**
4695     * Remove a listener for layout changes.
4696     *
4697     * @param listener The listener for layout bounds change.
4698     */
4699    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4700        ListenerInfo li = mListenerInfo;
4701        if (li == null || li.mOnLayoutChangeListeners == null) {
4702            return;
4703        }
4704        li.mOnLayoutChangeListeners.remove(listener);
4705    }
4706
4707    /**
4708     * Add a listener for attach state changes.
4709     *
4710     * This listener will be called whenever this view is attached or detached
4711     * from a window. Remove the listener using
4712     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4713     *
4714     * @param listener Listener to attach
4715     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4716     */
4717    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4718        ListenerInfo li = getListenerInfo();
4719        if (li.mOnAttachStateChangeListeners == null) {
4720            li.mOnAttachStateChangeListeners
4721                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4722        }
4723        li.mOnAttachStateChangeListeners.add(listener);
4724    }
4725
4726    /**
4727     * Remove a listener for attach state changes. The listener will receive no further
4728     * notification of window attach/detach events.
4729     *
4730     * @param listener Listener to remove
4731     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4732     */
4733    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4734        ListenerInfo li = mListenerInfo;
4735        if (li == null || li.mOnAttachStateChangeListeners == null) {
4736            return;
4737        }
4738        li.mOnAttachStateChangeListeners.remove(listener);
4739    }
4740
4741    /**
4742     * Returns the focus-change callback registered for this view.
4743     *
4744     * @return The callback, or null if one is not registered.
4745     */
4746    public OnFocusChangeListener getOnFocusChangeListener() {
4747        ListenerInfo li = mListenerInfo;
4748        return li != null ? li.mOnFocusChangeListener : null;
4749    }
4750
4751    /**
4752     * Register a callback to be invoked when this view is clicked. If this view is not
4753     * clickable, it becomes clickable.
4754     *
4755     * @param l The callback that will run
4756     *
4757     * @see #setClickable(boolean)
4758     */
4759    public void setOnClickListener(@Nullable OnClickListener l) {
4760        if (!isClickable()) {
4761            setClickable(true);
4762        }
4763        getListenerInfo().mOnClickListener = l;
4764    }
4765
4766    /**
4767     * Return whether this view has an attached OnClickListener.  Returns
4768     * true if there is a listener, false if there is none.
4769     */
4770    public boolean hasOnClickListeners() {
4771        ListenerInfo li = mListenerInfo;
4772        return (li != null && li.mOnClickListener != null);
4773    }
4774
4775    /**
4776     * Register a callback to be invoked when this view is clicked and held. If this view is not
4777     * long clickable, it becomes long clickable.
4778     *
4779     * @param l The callback that will run
4780     *
4781     * @see #setLongClickable(boolean)
4782     */
4783    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
4784        if (!isLongClickable()) {
4785            setLongClickable(true);
4786        }
4787        getListenerInfo().mOnLongClickListener = l;
4788    }
4789
4790    /**
4791     * Register a callback to be invoked when the context menu for this view is
4792     * being built. If this view is not long clickable, it becomes long clickable.
4793     *
4794     * @param l The callback that will run
4795     *
4796     */
4797    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4798        if (!isLongClickable()) {
4799            setLongClickable(true);
4800        }
4801        getListenerInfo().mOnCreateContextMenuListener = l;
4802    }
4803
4804    /**
4805     * Call this view's OnClickListener, if it is defined.  Performs all normal
4806     * actions associated with clicking: reporting accessibility event, playing
4807     * a sound, etc.
4808     *
4809     * @return True there was an assigned OnClickListener that was called, false
4810     *         otherwise is returned.
4811     */
4812    public boolean performClick() {
4813        final boolean result;
4814        final ListenerInfo li = mListenerInfo;
4815        if (li != null && li.mOnClickListener != null) {
4816            playSoundEffect(SoundEffectConstants.CLICK);
4817            li.mOnClickListener.onClick(this);
4818            result = true;
4819        } else {
4820            result = false;
4821        }
4822
4823        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4824        return result;
4825    }
4826
4827    /**
4828     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4829     * this only calls the listener, and does not do any associated clicking
4830     * actions like reporting an accessibility event.
4831     *
4832     * @return True there was an assigned OnClickListener that was called, false
4833     *         otherwise is returned.
4834     */
4835    public boolean callOnClick() {
4836        ListenerInfo li = mListenerInfo;
4837        if (li != null && li.mOnClickListener != null) {
4838            li.mOnClickListener.onClick(this);
4839            return true;
4840        }
4841        return false;
4842    }
4843
4844    /**
4845     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4846     * OnLongClickListener did not consume the event.
4847     *
4848     * @return True if one of the above receivers consumed the event, false otherwise.
4849     */
4850    public boolean performLongClick() {
4851        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4852
4853        boolean handled = false;
4854        ListenerInfo li = mListenerInfo;
4855        if (li != null && li.mOnLongClickListener != null) {
4856            handled = li.mOnLongClickListener.onLongClick(View.this);
4857        }
4858        if (!handled) {
4859            handled = showContextMenu();
4860        }
4861        if (handled) {
4862            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4863        }
4864        return handled;
4865    }
4866
4867    /**
4868     * Performs button-related actions during a touch down event.
4869     *
4870     * @param event The event.
4871     * @return True if the down was consumed.
4872     *
4873     * @hide
4874     */
4875    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4876        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
4877            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4878            showContextMenu(event.getX(), event.getY(), event.getMetaState());
4879            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
4880            return true;
4881        }
4882        return false;
4883    }
4884
4885    /**
4886     * Bring up the context menu for this view.
4887     *
4888     * @return Whether a context menu was displayed.
4889     */
4890    public boolean showContextMenu() {
4891        return getParent().showContextMenuForChild(this);
4892    }
4893
4894    /**
4895     * Bring up the context menu for this view, referring to the item under the specified point.
4896     *
4897     * @param x The referenced x coordinate.
4898     * @param y The referenced y coordinate.
4899     * @param metaState The keyboard modifiers that were pressed.
4900     * @return Whether a context menu was displayed.
4901     *
4902     * @hide
4903     */
4904    public boolean showContextMenu(float x, float y, int metaState) {
4905        return showContextMenu();
4906    }
4907
4908    /**
4909     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
4910     *
4911     * @param callback Callback that will control the lifecycle of the action mode
4912     * @return The new action mode if it is started, null otherwise
4913     *
4914     * @see ActionMode
4915     * @see #startActionMode(android.view.ActionMode.Callback, int)
4916     */
4917    public ActionMode startActionMode(ActionMode.Callback callback) {
4918        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
4919    }
4920
4921    /**
4922     * Start an action mode with the given type.
4923     *
4924     * @param callback Callback that will control the lifecycle of the action mode
4925     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
4926     * @return The new action mode if it is started, null otherwise
4927     *
4928     * @see ActionMode
4929     */
4930    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
4931        ViewParent parent = getParent();
4932        if (parent == null) return null;
4933        try {
4934            return parent.startActionModeForChild(this, callback, type);
4935        } catch (AbstractMethodError ame) {
4936            // Older implementations of custom views might not implement this.
4937            return parent.startActionModeForChild(this, callback);
4938        }
4939    }
4940
4941    /**
4942     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
4943     * Context, creating a unique View identifier to retrieve the result.
4944     *
4945     * @param intent The Intent to be started.
4946     * @param requestCode The request code to use.
4947     * @hide
4948     */
4949    public void startActivityForResult(Intent intent, int requestCode) {
4950        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
4951        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
4952    }
4953
4954    /**
4955     * If this View corresponds to the calling who, dispatches the activity result.
4956     * @param who The identifier for the targeted View to receive the result.
4957     * @param requestCode The integer request code originally supplied to
4958     *                    startActivityForResult(), allowing you to identify who this
4959     *                    result came from.
4960     * @param resultCode The integer result code returned by the child activity
4961     *                   through its setResult().
4962     * @param data An Intent, which can return result data to the caller
4963     *               (various data can be attached to Intent "extras").
4964     * @return {@code true} if the activity result was dispatched.
4965     * @hide
4966     */
4967    public boolean dispatchActivityResult(
4968            String who, int requestCode, int resultCode, Intent data) {
4969        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
4970            onActivityResult(requestCode, resultCode, data);
4971            mStartActivityRequestWho = null;
4972            return true;
4973        }
4974        return false;
4975    }
4976
4977    /**
4978     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
4979     *
4980     * @param requestCode The integer request code originally supplied to
4981     *                    startActivityForResult(), allowing you to identify who this
4982     *                    result came from.
4983     * @param resultCode The integer result code returned by the child activity
4984     *                   through its setResult().
4985     * @param data An Intent, which can return result data to the caller
4986     *               (various data can be attached to Intent "extras").
4987     * @hide
4988     */
4989    public void onActivityResult(int requestCode, int resultCode, Intent data) {
4990        // Do nothing.
4991    }
4992
4993    /**
4994     * Register a callback to be invoked when a hardware key is pressed in this view.
4995     * Key presses in software input methods will generally not trigger the methods of
4996     * this listener.
4997     * @param l the key listener to attach to this view
4998     */
4999    public void setOnKeyListener(OnKeyListener l) {
5000        getListenerInfo().mOnKeyListener = l;
5001    }
5002
5003    /**
5004     * Register a callback to be invoked when a touch event is sent to this view.
5005     * @param l the touch listener to attach to this view
5006     */
5007    public void setOnTouchListener(OnTouchListener l) {
5008        getListenerInfo().mOnTouchListener = l;
5009    }
5010
5011    /**
5012     * Register a callback to be invoked when a generic motion event is sent to this view.
5013     * @param l the generic motion listener to attach to this view
5014     */
5015    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5016        getListenerInfo().mOnGenericMotionListener = l;
5017    }
5018
5019    /**
5020     * Register a callback to be invoked when a hover event is sent to this view.
5021     * @param l the hover listener to attach to this view
5022     */
5023    public void setOnHoverListener(OnHoverListener l) {
5024        getListenerInfo().mOnHoverListener = l;
5025    }
5026
5027    /**
5028     * Register a drag event listener callback object for this View. The parameter is
5029     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5030     * View, the system calls the
5031     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5032     * @param l An implementation of {@link android.view.View.OnDragListener}.
5033     */
5034    public void setOnDragListener(OnDragListener l) {
5035        getListenerInfo().mOnDragListener = l;
5036    }
5037
5038    /**
5039     * Give this view focus. This will cause
5040     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5041     *
5042     * Note: this does not check whether this {@link View} should get focus, it just
5043     * gives it focus no matter what.  It should only be called internally by framework
5044     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5045     *
5046     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5047     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5048     *        focus moved when requestFocus() is called. It may not always
5049     *        apply, in which case use the default View.FOCUS_DOWN.
5050     * @param previouslyFocusedRect The rectangle of the view that had focus
5051     *        prior in this View's coordinate system.
5052     */
5053    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5054        if (DBG) {
5055            System.out.println(this + " requestFocus()");
5056        }
5057
5058        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5059            mPrivateFlags |= PFLAG_FOCUSED;
5060
5061            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5062
5063            if (mParent != null) {
5064                mParent.requestChildFocus(this, this);
5065            }
5066
5067            if (mAttachInfo != null) {
5068                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5069            }
5070
5071            onFocusChanged(true, direction, previouslyFocusedRect);
5072            refreshDrawableState();
5073        }
5074    }
5075
5076    /**
5077     * Populates <code>outRect</code> with the hotspot bounds. By default,
5078     * the hotspot bounds are identical to the screen bounds.
5079     *
5080     * @param outRect rect to populate with hotspot bounds
5081     * @hide Only for internal use by views and widgets.
5082     */
5083    public void getHotspotBounds(Rect outRect) {
5084        final Drawable background = getBackground();
5085        if (background != null) {
5086            background.getHotspotBounds(outRect);
5087        } else {
5088            getBoundsOnScreen(outRect);
5089        }
5090    }
5091
5092    /**
5093     * Request that a rectangle of this view be visible on the screen,
5094     * scrolling if necessary just enough.
5095     *
5096     * <p>A View should call this if it maintains some notion of which part
5097     * of its content is interesting.  For example, a text editing view
5098     * should call this when its cursor moves.
5099     *
5100     * @param rectangle The rectangle.
5101     * @return Whether any parent scrolled.
5102     */
5103    public boolean requestRectangleOnScreen(Rect rectangle) {
5104        return requestRectangleOnScreen(rectangle, false);
5105    }
5106
5107    /**
5108     * Request that a rectangle of this view be visible on the screen,
5109     * scrolling if necessary just enough.
5110     *
5111     * <p>A View should call this if it maintains some notion of which part
5112     * of its content is interesting.  For example, a text editing view
5113     * should call this when its cursor moves.
5114     *
5115     * <p>When <code>immediate</code> is set to true, scrolling will not be
5116     * animated.
5117     *
5118     * @param rectangle The rectangle.
5119     * @param immediate True to forbid animated scrolling, false otherwise
5120     * @return Whether any parent scrolled.
5121     */
5122    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5123        if (mParent == null) {
5124            return false;
5125        }
5126
5127        View child = this;
5128
5129        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5130        position.set(rectangle);
5131
5132        ViewParent parent = mParent;
5133        boolean scrolled = false;
5134        while (parent != null) {
5135            rectangle.set((int) position.left, (int) position.top,
5136                    (int) position.right, (int) position.bottom);
5137
5138            scrolled |= parent.requestChildRectangleOnScreen(child,
5139                    rectangle, immediate);
5140
5141            if (!child.hasIdentityMatrix()) {
5142                child.getMatrix().mapRect(position);
5143            }
5144
5145            position.offset(child.mLeft, child.mTop);
5146
5147            if (!(parent instanceof View)) {
5148                break;
5149            }
5150
5151            View parentView = (View) parent;
5152
5153            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5154
5155            child = parentView;
5156            parent = child.getParent();
5157        }
5158
5159        return scrolled;
5160    }
5161
5162    /**
5163     * Called when this view wants to give up focus. If focus is cleared
5164     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5165     * <p>
5166     * <strong>Note:</strong> When a View clears focus the framework is trying
5167     * to give focus to the first focusable View from the top. Hence, if this
5168     * View is the first from the top that can take focus, then all callbacks
5169     * related to clearing focus will be invoked after which the framework will
5170     * give focus to this view.
5171     * </p>
5172     */
5173    public void clearFocus() {
5174        if (DBG) {
5175            System.out.println(this + " clearFocus()");
5176        }
5177
5178        clearFocusInternal(null, true, true);
5179    }
5180
5181    /**
5182     * Clears focus from the view, optionally propagating the change up through
5183     * the parent hierarchy and requesting that the root view place new focus.
5184     *
5185     * @param propagate whether to propagate the change up through the parent
5186     *            hierarchy
5187     * @param refocus when propagate is true, specifies whether to request the
5188     *            root view place new focus
5189     */
5190    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5191        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5192            mPrivateFlags &= ~PFLAG_FOCUSED;
5193
5194            if (propagate && mParent != null) {
5195                mParent.clearChildFocus(this);
5196            }
5197
5198            onFocusChanged(false, 0, null);
5199            refreshDrawableState();
5200
5201            if (propagate && (!refocus || !rootViewRequestFocus())) {
5202                notifyGlobalFocusCleared(this);
5203            }
5204        }
5205    }
5206
5207    void notifyGlobalFocusCleared(View oldFocus) {
5208        if (oldFocus != null && mAttachInfo != null) {
5209            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5210        }
5211    }
5212
5213    boolean rootViewRequestFocus() {
5214        final View root = getRootView();
5215        return root != null && root.requestFocus();
5216    }
5217
5218    /**
5219     * Called internally by the view system when a new view is getting focus.
5220     * This is what clears the old focus.
5221     * <p>
5222     * <b>NOTE:</b> The parent view's focused child must be updated manually
5223     * after calling this method. Otherwise, the view hierarchy may be left in
5224     * an inconstent state.
5225     */
5226    void unFocus(View focused) {
5227        if (DBG) {
5228            System.out.println(this + " unFocus()");
5229        }
5230
5231        clearFocusInternal(focused, false, false);
5232    }
5233
5234    /**
5235     * Returns true if this view has focus itself, or is the ancestor of the
5236     * view that has focus.
5237     *
5238     * @return True if this view has or contains focus, false otherwise.
5239     */
5240    @ViewDebug.ExportedProperty(category = "focus")
5241    public boolean hasFocus() {
5242        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5243    }
5244
5245    /**
5246     * Returns true if this view is focusable or if it contains a reachable View
5247     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5248     * is a View whose parents do not block descendants focus.
5249     *
5250     * Only {@link #VISIBLE} views are considered focusable.
5251     *
5252     * @return True if the view is focusable or if the view contains a focusable
5253     *         View, false otherwise.
5254     *
5255     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5256     * @see ViewGroup#getTouchscreenBlocksFocus()
5257     */
5258    public boolean hasFocusable() {
5259        if (!isFocusableInTouchMode()) {
5260            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5261                final ViewGroup g = (ViewGroup) p;
5262                if (g.shouldBlockFocusForTouchscreen()) {
5263                    return false;
5264                }
5265            }
5266        }
5267        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5268    }
5269
5270    /**
5271     * Called by the view system when the focus state of this view changes.
5272     * When the focus change event is caused by directional navigation, direction
5273     * and previouslyFocusedRect provide insight into where the focus is coming from.
5274     * When overriding, be sure to call up through to the super class so that
5275     * the standard focus handling will occur.
5276     *
5277     * @param gainFocus True if the View has focus; false otherwise.
5278     * @param direction The direction focus has moved when requestFocus()
5279     *                  is called to give this view focus. Values are
5280     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5281     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5282     *                  It may not always apply, in which case use the default.
5283     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5284     *        system, of the previously focused view.  If applicable, this will be
5285     *        passed in as finer grained information about where the focus is coming
5286     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5287     */
5288    @CallSuper
5289    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5290            @Nullable Rect previouslyFocusedRect) {
5291        if (gainFocus) {
5292            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5293        } else {
5294            notifyViewAccessibilityStateChangedIfNeeded(
5295                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5296        }
5297
5298        InputMethodManager imm = InputMethodManager.peekInstance();
5299        if (!gainFocus) {
5300            if (isPressed()) {
5301                setPressed(false);
5302            }
5303            if (imm != null && mAttachInfo != null
5304                    && mAttachInfo.mHasWindowFocus) {
5305                imm.focusOut(this);
5306            }
5307            onFocusLost();
5308        } else if (imm != null && mAttachInfo != null
5309                && mAttachInfo.mHasWindowFocus) {
5310            imm.focusIn(this);
5311        }
5312
5313        invalidate(true);
5314        ListenerInfo li = mListenerInfo;
5315        if (li != null && li.mOnFocusChangeListener != null) {
5316            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5317        }
5318
5319        if (mAttachInfo != null) {
5320            mAttachInfo.mKeyDispatchState.reset(this);
5321        }
5322    }
5323
5324    /**
5325     * Sends an accessibility event of the given type. If accessibility is
5326     * not enabled this method has no effect. The default implementation calls
5327     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5328     * to populate information about the event source (this View), then calls
5329     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5330     * populate the text content of the event source including its descendants,
5331     * and last calls
5332     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5333     * on its parent to request sending of the event to interested parties.
5334     * <p>
5335     * If an {@link AccessibilityDelegate} has been specified via calling
5336     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5337     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5338     * responsible for handling this call.
5339     * </p>
5340     *
5341     * @param eventType The type of the event to send, as defined by several types from
5342     * {@link android.view.accessibility.AccessibilityEvent}, such as
5343     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5344     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5345     *
5346     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5347     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5348     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5349     * @see AccessibilityDelegate
5350     */
5351    public void sendAccessibilityEvent(int eventType) {
5352        if (mAccessibilityDelegate != null) {
5353            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5354        } else {
5355            sendAccessibilityEventInternal(eventType);
5356        }
5357    }
5358
5359    /**
5360     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5361     * {@link AccessibilityEvent} to make an announcement which is related to some
5362     * sort of a context change for which none of the events representing UI transitions
5363     * is a good fit. For example, announcing a new page in a book. If accessibility
5364     * is not enabled this method does nothing.
5365     *
5366     * @param text The announcement text.
5367     */
5368    public void announceForAccessibility(CharSequence text) {
5369        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5370            AccessibilityEvent event = AccessibilityEvent.obtain(
5371                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5372            onInitializeAccessibilityEvent(event);
5373            event.getText().add(text);
5374            event.setContentDescription(null);
5375            mParent.requestSendAccessibilityEvent(this, event);
5376        }
5377    }
5378
5379    /**
5380     * @see #sendAccessibilityEvent(int)
5381     *
5382     * Note: Called from the default {@link AccessibilityDelegate}.
5383     *
5384     * @hide
5385     */
5386    public void sendAccessibilityEventInternal(int eventType) {
5387        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5388            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5389        }
5390    }
5391
5392    /**
5393     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5394     * takes as an argument an empty {@link AccessibilityEvent} and does not
5395     * perform a check whether accessibility is enabled.
5396     * <p>
5397     * If an {@link AccessibilityDelegate} has been specified via calling
5398     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5399     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5400     * is responsible for handling this call.
5401     * </p>
5402     *
5403     * @param event The event to send.
5404     *
5405     * @see #sendAccessibilityEvent(int)
5406     */
5407    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5408        if (mAccessibilityDelegate != null) {
5409            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5410        } else {
5411            sendAccessibilityEventUncheckedInternal(event);
5412        }
5413    }
5414
5415    /**
5416     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5417     *
5418     * Note: Called from the default {@link AccessibilityDelegate}.
5419     *
5420     * @hide
5421     */
5422    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5423        if (!isShown()) {
5424            return;
5425        }
5426        onInitializeAccessibilityEvent(event);
5427        // Only a subset of accessibility events populates text content.
5428        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5429            dispatchPopulateAccessibilityEvent(event);
5430        }
5431        // In the beginning we called #isShown(), so we know that getParent() is not null.
5432        getParent().requestSendAccessibilityEvent(this, event);
5433    }
5434
5435    /**
5436     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5437     * to its children for adding their text content to the event. Note that the
5438     * event text is populated in a separate dispatch path since we add to the
5439     * event not only the text of the source but also the text of all its descendants.
5440     * A typical implementation will call
5441     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5442     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5443     * on each child. Override this method if custom population of the event text
5444     * content is required.
5445     * <p>
5446     * If an {@link AccessibilityDelegate} has been specified via calling
5447     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5448     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5449     * is responsible for handling this call.
5450     * </p>
5451     * <p>
5452     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5453     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5454     * </p>
5455     *
5456     * @param event The event.
5457     *
5458     * @return True if the event population was completed.
5459     */
5460    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5461        if (mAccessibilityDelegate != null) {
5462            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5463        } else {
5464            return dispatchPopulateAccessibilityEventInternal(event);
5465        }
5466    }
5467
5468    /**
5469     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5470     *
5471     * Note: Called from the default {@link AccessibilityDelegate}.
5472     *
5473     * @hide
5474     */
5475    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5476        onPopulateAccessibilityEvent(event);
5477        return false;
5478    }
5479
5480    /**
5481     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5482     * giving a chance to this View to populate the accessibility event with its
5483     * text content. While this method is free to modify event
5484     * attributes other than text content, doing so should normally be performed in
5485     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5486     * <p>
5487     * Example: Adding formatted date string to an accessibility event in addition
5488     *          to the text added by the super implementation:
5489     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5490     *     super.onPopulateAccessibilityEvent(event);
5491     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5492     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5493     *         mCurrentDate.getTimeInMillis(), flags);
5494     *     event.getText().add(selectedDateUtterance);
5495     * }</pre>
5496     * <p>
5497     * If an {@link AccessibilityDelegate} has been specified via calling
5498     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5499     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5500     * is responsible for handling this call.
5501     * </p>
5502     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5503     * information to the event, in case the default implementation has basic information to add.
5504     * </p>
5505     *
5506     * @param event The accessibility event which to populate.
5507     *
5508     * @see #sendAccessibilityEvent(int)
5509     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5510     */
5511    @CallSuper
5512    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5513        if (mAccessibilityDelegate != null) {
5514            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5515        } else {
5516            onPopulateAccessibilityEventInternal(event);
5517        }
5518    }
5519
5520    /**
5521     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5522     *
5523     * Note: Called from the default {@link AccessibilityDelegate}.
5524     *
5525     * @hide
5526     */
5527    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5528    }
5529
5530    /**
5531     * Initializes an {@link AccessibilityEvent} with information about
5532     * this View which is the event source. In other words, the source of
5533     * an accessibility event is the view whose state change triggered firing
5534     * the event.
5535     * <p>
5536     * Example: Setting the password property of an event in addition
5537     *          to properties set by the super implementation:
5538     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5539     *     super.onInitializeAccessibilityEvent(event);
5540     *     event.setPassword(true);
5541     * }</pre>
5542     * <p>
5543     * If an {@link AccessibilityDelegate} has been specified via calling
5544     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5545     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5546     * is responsible for handling this call.
5547     * </p>
5548     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5549     * information to the event, in case the default implementation has basic information to add.
5550     * </p>
5551     * @param event The event to initialize.
5552     *
5553     * @see #sendAccessibilityEvent(int)
5554     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5555     */
5556    @CallSuper
5557    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5558        if (mAccessibilityDelegate != null) {
5559            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5560        } else {
5561            onInitializeAccessibilityEventInternal(event);
5562        }
5563    }
5564
5565    /**
5566     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5567     *
5568     * Note: Called from the default {@link AccessibilityDelegate}.
5569     *
5570     * @hide
5571     */
5572    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5573        event.setSource(this);
5574        event.setClassName(getAccessibilityClassName());
5575        event.setPackageName(getContext().getPackageName());
5576        event.setEnabled(isEnabled());
5577        event.setContentDescription(mContentDescription);
5578
5579        switch (event.getEventType()) {
5580            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5581                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5582                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5583                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5584                event.setItemCount(focusablesTempList.size());
5585                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5586                if (mAttachInfo != null) {
5587                    focusablesTempList.clear();
5588                }
5589            } break;
5590            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5591                CharSequence text = getIterableTextForAccessibility();
5592                if (text != null && text.length() > 0) {
5593                    event.setFromIndex(getAccessibilitySelectionStart());
5594                    event.setToIndex(getAccessibilitySelectionEnd());
5595                    event.setItemCount(text.length());
5596                }
5597            } break;
5598        }
5599    }
5600
5601    /**
5602     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5603     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5604     * This method is responsible for obtaining an accessibility node info from a
5605     * pool of reusable instances and calling
5606     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5607     * initialize the former.
5608     * <p>
5609     * Note: The client is responsible for recycling the obtained instance by calling
5610     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5611     * </p>
5612     *
5613     * @return A populated {@link AccessibilityNodeInfo}.
5614     *
5615     * @see AccessibilityNodeInfo
5616     */
5617    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5618        if (mAccessibilityDelegate != null) {
5619            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5620        } else {
5621            return createAccessibilityNodeInfoInternal();
5622        }
5623    }
5624
5625    /**
5626     * @see #createAccessibilityNodeInfo()
5627     *
5628     * @hide
5629     */
5630    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5631        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5632        if (provider != null) {
5633            return provider.createAccessibilityNodeInfo(View.NO_ID);
5634        } else {
5635            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5636            onInitializeAccessibilityNodeInfo(info);
5637            return info;
5638        }
5639    }
5640
5641    /**
5642     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5643     * The base implementation sets:
5644     * <ul>
5645     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5646     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5647     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5648     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5649     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5650     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5651     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5652     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5653     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5654     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5655     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5656     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5657     * </ul>
5658     * <p>
5659     * Subclasses should override this method, call the super implementation,
5660     * and set additional attributes.
5661     * </p>
5662     * <p>
5663     * If an {@link AccessibilityDelegate} has been specified via calling
5664     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5665     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5666     * is responsible for handling this call.
5667     * </p>
5668     *
5669     * @param info The instance to initialize.
5670     */
5671    @CallSuper
5672    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5673        if (mAccessibilityDelegate != null) {
5674            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5675        } else {
5676            onInitializeAccessibilityNodeInfoInternal(info);
5677        }
5678    }
5679
5680    /**
5681     * Gets the location of this view in screen coordinates.
5682     *
5683     * @param outRect The output location
5684     * @hide
5685     */
5686    public void getBoundsOnScreen(Rect outRect) {
5687        getBoundsOnScreen(outRect, false);
5688    }
5689
5690    /**
5691     * Gets the location of this view in screen coordinates.
5692     *
5693     * @param outRect The output location
5694     * @param clipToParent Whether to clip child bounds to the parent ones.
5695     * @hide
5696     */
5697    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
5698        if (mAttachInfo == null) {
5699            return;
5700        }
5701
5702        RectF position = mAttachInfo.mTmpTransformRect;
5703        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5704
5705        if (!hasIdentityMatrix()) {
5706            getMatrix().mapRect(position);
5707        }
5708
5709        position.offset(mLeft, mTop);
5710
5711        ViewParent parent = mParent;
5712        while (parent instanceof View) {
5713            View parentView = (View) parent;
5714
5715            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5716
5717            if (clipToParent) {
5718                position.left = Math.max(position.left, 0);
5719                position.top = Math.max(position.top, 0);
5720                position.right = Math.min(position.right, parentView.getWidth());
5721                position.bottom = Math.min(position.bottom, parentView.getHeight());
5722            }
5723
5724            if (!parentView.hasIdentityMatrix()) {
5725                parentView.getMatrix().mapRect(position);
5726            }
5727
5728            position.offset(parentView.mLeft, parentView.mTop);
5729
5730            parent = parentView.mParent;
5731        }
5732
5733        if (parent instanceof ViewRootImpl) {
5734            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5735            position.offset(0, -viewRootImpl.mCurScrollY);
5736        }
5737
5738        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5739
5740        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5741                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5742    }
5743
5744    /**
5745     * Return the class name of this object to be used for accessibility purposes.
5746     * Subclasses should only override this if they are implementing something that
5747     * should be seen as a completely new class of view when used by accessibility,
5748     * unrelated to the class it is deriving from.  This is used to fill in
5749     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
5750     */
5751    public CharSequence getAccessibilityClassName() {
5752        return View.class.getName();
5753    }
5754
5755    /**
5756     * Called when assist structure is being retrieved from a view as part of
5757     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
5758     * @param structure Fill in with structured view data.  The default implementation
5759     * fills in all data that can be inferred from the view itself.
5760     */
5761    public void onProvideAssistStructure(ViewAssistStructure structure) {
5762        final int id = mID;
5763        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
5764                && (id&0x0000ffff) != 0) {
5765            String pkg, type, entry;
5766            try {
5767                final Resources res = getResources();
5768                entry = res.getResourceEntryName(id);
5769                type = res.getResourceTypeName(id);
5770                pkg = res.getResourcePackageName(id);
5771            } catch (Resources.NotFoundException e) {
5772                entry = type = pkg = null;
5773            }
5774            structure.setId(id, pkg, type, entry);
5775        } else {
5776            structure.setId(id, null, null, null);
5777        }
5778        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight-mLeft, mBottom-mTop);
5779        structure.setVisibility(getVisibility());
5780        structure.setEnabled(isEnabled());
5781        if (isClickable()) {
5782            structure.setClickable(true);
5783        }
5784        if (isFocusable()) {
5785            structure.setFocusable(true);
5786        }
5787        if (isFocused()) {
5788            structure.setFocused(true);
5789        }
5790        if (isAccessibilityFocused()) {
5791            structure.setAccessibilityFocused(true);
5792        }
5793        if (isSelected()) {
5794            structure.setSelected(true);
5795        }
5796        if (isActivated()) {
5797            structure.setActivated(true);
5798        }
5799        if (isLongClickable()) {
5800            structure.setLongClickable(true);
5801        }
5802        if (this instanceof Checkable) {
5803            structure.setCheckable(true);
5804            if (((Checkable)this).isChecked()) {
5805                structure.setChecked(true);
5806            }
5807        }
5808        structure.setClassName(getAccessibilityClassName().toString());
5809        structure.setContentDescription(getContentDescription());
5810    }
5811
5812    /**
5813     * Called when assist structure is being retrieved from a view as part of
5814     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
5815     * generate additional virtual structure under this view.  The defaullt implementation
5816     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
5817     * view's virtual accessibility nodes, if any.  You can override this for a more
5818     * optimal implementation providing this data.
5819     */
5820    public void onProvideVirtualAssistStructure(ViewAssistStructure structure) {
5821        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5822        if (provider != null) {
5823            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
5824            Log.i("View", "Provider of " + this + ": children=" + info.getChildCount());
5825            structure.setChildCount(1);
5826            ViewAssistStructure root = structure.newChild(0);
5827            populateVirtualAssistStructure(root, provider, info);
5828            info.recycle();
5829        }
5830    }
5831
5832    private void populateVirtualAssistStructure(ViewAssistStructure structure,
5833            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
5834        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
5835                null, null, null);
5836        Rect rect = structure.getTempRect();
5837        info.getBoundsInParent(rect);
5838        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
5839        structure.setVisibility(VISIBLE);
5840        structure.setEnabled(info.isEnabled());
5841        if (info.isClickable()) {
5842            structure.setClickable(true);
5843        }
5844        if (info.isFocusable()) {
5845            structure.setFocusable(true);
5846        }
5847        if (info.isFocused()) {
5848            structure.setFocused(true);
5849        }
5850        if (info.isAccessibilityFocused()) {
5851            structure.setAccessibilityFocused(true);
5852        }
5853        if (info.isSelected()) {
5854            structure.setSelected(true);
5855        }
5856        if (info.isLongClickable()) {
5857            structure.setLongClickable(true);
5858        }
5859        if (info.isCheckable()) {
5860            structure.setCheckable(true);
5861            if (info.isChecked()) {
5862                structure.setChecked(true);
5863            }
5864        }
5865        CharSequence cname = info.getClassName();
5866        structure.setClassName(cname != null ? cname.toString() : null);
5867        structure.setContentDescription(info.getContentDescription());
5868        Log.i("View", "vassist " + cname + " @ " + rect.toShortString()
5869                + " text=" + info.getText() + " cd=" + info.getContentDescription());
5870        if (info.getText() != null || info.getError() != null) {
5871            structure.setText(info.getText(), info.getTextSelectionStart(),
5872                    info.getTextSelectionEnd());
5873        }
5874        final int NCHILDREN = info.getChildCount();
5875        if (NCHILDREN > 0) {
5876            structure.setChildCount(NCHILDREN);
5877            for (int i=0; i<NCHILDREN; i++) {
5878                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
5879                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
5880                ViewAssistStructure child = structure.newChild(i);
5881                populateVirtualAssistStructure(child, provider, cinfo);
5882                cinfo.recycle();
5883            }
5884        }
5885    }
5886
5887    /**
5888     * Dispatch creation of {@link ViewAssistStructure} down the hierarchy.  The default
5889     * implementation calls {@link #onProvideAssistStructure} and
5890     * {@link #onProvideVirtualAssistStructure}.
5891     */
5892    public void dispatchProvideAssistStructure(ViewAssistStructure structure) {
5893        onProvideAssistStructure(structure);
5894        onProvideVirtualAssistStructure(structure);
5895    }
5896
5897    /**
5898     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5899     *
5900     * Note: Called from the default {@link AccessibilityDelegate}.
5901     *
5902     * @hide
5903     */
5904    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5905        Rect bounds = mAttachInfo.mTmpInvalRect;
5906
5907        getDrawingRect(bounds);
5908        info.setBoundsInParent(bounds);
5909
5910        getBoundsOnScreen(bounds, true);
5911        info.setBoundsInScreen(bounds);
5912
5913        ViewParent parent = getParentForAccessibility();
5914        if (parent instanceof View) {
5915            info.setParent((View) parent);
5916        }
5917
5918        if (mID != View.NO_ID) {
5919            View rootView = getRootView();
5920            if (rootView == null) {
5921                rootView = this;
5922            }
5923
5924            View label = rootView.findLabelForView(this, mID);
5925            if (label != null) {
5926                info.setLabeledBy(label);
5927            }
5928
5929            if ((mAttachInfo.mAccessibilityFetchFlags
5930                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5931                    && Resources.resourceHasPackage(mID)) {
5932                try {
5933                    String viewId = getResources().getResourceName(mID);
5934                    info.setViewIdResourceName(viewId);
5935                } catch (Resources.NotFoundException nfe) {
5936                    /* ignore */
5937                }
5938            }
5939        }
5940
5941        if (mLabelForId != View.NO_ID) {
5942            View rootView = getRootView();
5943            if (rootView == null) {
5944                rootView = this;
5945            }
5946            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5947            if (labeled != null) {
5948                info.setLabelFor(labeled);
5949            }
5950        }
5951
5952        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5953            View rootView = getRootView();
5954            if (rootView == null) {
5955                rootView = this;
5956            }
5957            View next = rootView.findViewInsideOutShouldExist(this,
5958                    mAccessibilityTraversalBeforeId);
5959            if (next != null) {
5960                info.setTraversalBefore(next);
5961            }
5962        }
5963
5964        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5965            View rootView = getRootView();
5966            if (rootView == null) {
5967                rootView = this;
5968            }
5969            View next = rootView.findViewInsideOutShouldExist(this,
5970                    mAccessibilityTraversalAfterId);
5971            if (next != null) {
5972                info.setTraversalAfter(next);
5973            }
5974        }
5975
5976        info.setVisibleToUser(isVisibleToUser());
5977
5978        info.setPackageName(mContext.getPackageName());
5979        info.setClassName(getAccessibilityClassName());
5980        info.setContentDescription(getContentDescription());
5981
5982        info.setEnabled(isEnabled());
5983        info.setClickable(isClickable());
5984        info.setFocusable(isFocusable());
5985        info.setFocused(isFocused());
5986        info.setAccessibilityFocused(isAccessibilityFocused());
5987        info.setSelected(isSelected());
5988        info.setLongClickable(isLongClickable());
5989        info.setLiveRegion(getAccessibilityLiveRegion());
5990
5991        // TODO: These make sense only if we are in an AdapterView but all
5992        // views can be selected. Maybe from accessibility perspective
5993        // we should report as selectable view in an AdapterView.
5994        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5995        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5996
5997        if (isFocusable()) {
5998            if (isFocused()) {
5999                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6000            } else {
6001                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6002            }
6003        }
6004
6005        if (!isAccessibilityFocused()) {
6006            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6007        } else {
6008            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6009        }
6010
6011        if (isClickable() && isEnabled()) {
6012            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6013        }
6014
6015        if (isLongClickable() && isEnabled()) {
6016            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6017        }
6018
6019        CharSequence text = getIterableTextForAccessibility();
6020        if (text != null && text.length() > 0) {
6021            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6022
6023            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6024            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6025            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6026            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6027                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6028                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6029        }
6030
6031        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6032    }
6033
6034    private View findLabelForView(View view, int labeledId) {
6035        if (mMatchLabelForPredicate == null) {
6036            mMatchLabelForPredicate = new MatchLabelForPredicate();
6037        }
6038        mMatchLabelForPredicate.mLabeledId = labeledId;
6039        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6040    }
6041
6042    /**
6043     * Computes whether this view is visible to the user. Such a view is
6044     * attached, visible, all its predecessors are visible, it is not clipped
6045     * entirely by its predecessors, and has an alpha greater than zero.
6046     *
6047     * @return Whether the view is visible on the screen.
6048     *
6049     * @hide
6050     */
6051    protected boolean isVisibleToUser() {
6052        return isVisibleToUser(null);
6053    }
6054
6055    /**
6056     * Computes whether the given portion of this view is visible to the user.
6057     * Such a view is attached, visible, all its predecessors are visible,
6058     * has an alpha greater than zero, and the specified portion is not
6059     * clipped entirely by its predecessors.
6060     *
6061     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6062     *                    <code>null</code>, and the entire view will be tested in this case.
6063     *                    When <code>true</code> is returned by the function, the actual visible
6064     *                    region will be stored in this parameter; that is, if boundInView is fully
6065     *                    contained within the view, no modification will be made, otherwise regions
6066     *                    outside of the visible area of the view will be clipped.
6067     *
6068     * @return Whether the specified portion of the view is visible on the screen.
6069     *
6070     * @hide
6071     */
6072    protected boolean isVisibleToUser(Rect boundInView) {
6073        if (mAttachInfo != null) {
6074            // Attached to invisible window means this view is not visible.
6075            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6076                return false;
6077            }
6078            // An invisible predecessor or one with alpha zero means
6079            // that this view is not visible to the user.
6080            Object current = this;
6081            while (current instanceof View) {
6082                View view = (View) current;
6083                // We have attach info so this view is attached and there is no
6084                // need to check whether we reach to ViewRootImpl on the way up.
6085                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6086                        view.getVisibility() != VISIBLE) {
6087                    return false;
6088                }
6089                current = view.mParent;
6090            }
6091            // Check if the view is entirely covered by its predecessors.
6092            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6093            Point offset = mAttachInfo.mPoint;
6094            if (!getGlobalVisibleRect(visibleRect, offset)) {
6095                return false;
6096            }
6097            // Check if the visible portion intersects the rectangle of interest.
6098            if (boundInView != null) {
6099                visibleRect.offset(-offset.x, -offset.y);
6100                return boundInView.intersect(visibleRect);
6101            }
6102            return true;
6103        }
6104        return false;
6105    }
6106
6107    /**
6108     * Returns the delegate for implementing accessibility support via
6109     * composition. For more details see {@link AccessibilityDelegate}.
6110     *
6111     * @return The delegate, or null if none set.
6112     *
6113     * @hide
6114     */
6115    public AccessibilityDelegate getAccessibilityDelegate() {
6116        return mAccessibilityDelegate;
6117    }
6118
6119    /**
6120     * Sets a delegate for implementing accessibility support via composition as
6121     * opposed to inheritance. The delegate's primary use is for implementing
6122     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6123     *
6124     * @param delegate The delegate instance.
6125     *
6126     * @see AccessibilityDelegate
6127     */
6128    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6129        mAccessibilityDelegate = delegate;
6130    }
6131
6132    /**
6133     * Gets the provider for managing a virtual view hierarchy rooted at this View
6134     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6135     * that explore the window content.
6136     * <p>
6137     * If this method returns an instance, this instance is responsible for managing
6138     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6139     * View including the one representing the View itself. Similarly the returned
6140     * instance is responsible for performing accessibility actions on any virtual
6141     * view or the root view itself.
6142     * </p>
6143     * <p>
6144     * If an {@link AccessibilityDelegate} has been specified via calling
6145     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6146     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6147     * is responsible for handling this call.
6148     * </p>
6149     *
6150     * @return The provider.
6151     *
6152     * @see AccessibilityNodeProvider
6153     */
6154    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6155        if (mAccessibilityDelegate != null) {
6156            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6157        } else {
6158            return null;
6159        }
6160    }
6161
6162    /**
6163     * Gets the unique identifier of this view on the screen for accessibility purposes.
6164     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6165     *
6166     * @return The view accessibility id.
6167     *
6168     * @hide
6169     */
6170    public int getAccessibilityViewId() {
6171        if (mAccessibilityViewId == NO_ID) {
6172            mAccessibilityViewId = sNextAccessibilityViewId++;
6173        }
6174        return mAccessibilityViewId;
6175    }
6176
6177    /**
6178     * Gets the unique identifier of the window in which this View reseides.
6179     *
6180     * @return The window accessibility id.
6181     *
6182     * @hide
6183     */
6184    public int getAccessibilityWindowId() {
6185        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6186                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6187    }
6188
6189    /**
6190     * Gets the {@link View} description. It briefly describes the view and is
6191     * primarily used for accessibility support. Set this property to enable
6192     * better accessibility support for your application. This is especially
6193     * true for views that do not have textual representation (For example,
6194     * ImageButton).
6195     *
6196     * @return The content description.
6197     *
6198     * @attr ref android.R.styleable#View_contentDescription
6199     */
6200    @ViewDebug.ExportedProperty(category = "accessibility")
6201    public CharSequence getContentDescription() {
6202        return mContentDescription;
6203    }
6204
6205    /**
6206     * Sets the {@link View} description. It briefly describes the view and is
6207     * primarily used for accessibility support. Set this property to enable
6208     * better accessibility support for your application. This is especially
6209     * true for views that do not have textual representation (For example,
6210     * ImageButton).
6211     *
6212     * @param contentDescription The content description.
6213     *
6214     * @attr ref android.R.styleable#View_contentDescription
6215     */
6216    @RemotableViewMethod
6217    public void setContentDescription(CharSequence contentDescription) {
6218        if (mContentDescription == null) {
6219            if (contentDescription == null) {
6220                return;
6221            }
6222        } else if (mContentDescription.equals(contentDescription)) {
6223            return;
6224        }
6225        mContentDescription = contentDescription;
6226        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6227        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6228            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6229            notifySubtreeAccessibilityStateChangedIfNeeded();
6230        } else {
6231            notifyViewAccessibilityStateChangedIfNeeded(
6232                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6233        }
6234    }
6235
6236    /**
6237     * Sets the id of a view before which this one is visited in accessibility traversal.
6238     * A screen-reader must visit the content of this view before the content of the one
6239     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6240     * will traverse the entire content of B before traversing the entire content of A,
6241     * regardles of what traversal strategy it is using.
6242     * <p>
6243     * Views that do not have specified before/after relationships are traversed in order
6244     * determined by the screen-reader.
6245     * </p>
6246     * <p>
6247     * Setting that this view is before a view that is not important for accessibility
6248     * or if this view is not important for accessibility will have no effect as the
6249     * screen-reader is not aware of unimportant views.
6250     * </p>
6251     *
6252     * @param beforeId The id of a view this one precedes in accessibility traversal.
6253     *
6254     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6255     *
6256     * @see #setImportantForAccessibility(int)
6257     */
6258    @RemotableViewMethod
6259    public void setAccessibilityTraversalBefore(int beforeId) {
6260        if (mAccessibilityTraversalBeforeId == beforeId) {
6261            return;
6262        }
6263        mAccessibilityTraversalBeforeId = beforeId;
6264        notifyViewAccessibilityStateChangedIfNeeded(
6265                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6266    }
6267
6268    /**
6269     * Gets the id of a view before which this one is visited in accessibility traversal.
6270     *
6271     * @return The id of a view this one precedes in accessibility traversal if
6272     *         specified, otherwise {@link #NO_ID}.
6273     *
6274     * @see #setAccessibilityTraversalBefore(int)
6275     */
6276    public int getAccessibilityTraversalBefore() {
6277        return mAccessibilityTraversalBeforeId;
6278    }
6279
6280    /**
6281     * Sets the id of a view after which this one is visited in accessibility traversal.
6282     * A screen-reader must visit the content of the other view before the content of this
6283     * one. For example, if view B is set to be after view A, then a screen-reader
6284     * will traverse the entire content of A before traversing the entire content of B,
6285     * regardles of what traversal strategy it is using.
6286     * <p>
6287     * Views that do not have specified before/after relationships are traversed in order
6288     * determined by the screen-reader.
6289     * </p>
6290     * <p>
6291     * Setting that this view is after a view that is not important for accessibility
6292     * or if this view is not important for accessibility will have no effect as the
6293     * screen-reader is not aware of unimportant views.
6294     * </p>
6295     *
6296     * @param afterId The id of a view this one succedees in accessibility traversal.
6297     *
6298     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6299     *
6300     * @see #setImportantForAccessibility(int)
6301     */
6302    @RemotableViewMethod
6303    public void setAccessibilityTraversalAfter(int afterId) {
6304        if (mAccessibilityTraversalAfterId == afterId) {
6305            return;
6306        }
6307        mAccessibilityTraversalAfterId = afterId;
6308        notifyViewAccessibilityStateChangedIfNeeded(
6309                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6310    }
6311
6312    /**
6313     * Gets the id of a view after which this one is visited in accessibility traversal.
6314     *
6315     * @return The id of a view this one succeedes in accessibility traversal if
6316     *         specified, otherwise {@link #NO_ID}.
6317     *
6318     * @see #setAccessibilityTraversalAfter(int)
6319     */
6320    public int getAccessibilityTraversalAfter() {
6321        return mAccessibilityTraversalAfterId;
6322    }
6323
6324    /**
6325     * Gets the id of a view for which this view serves as a label for
6326     * accessibility purposes.
6327     *
6328     * @return The labeled view id.
6329     */
6330    @ViewDebug.ExportedProperty(category = "accessibility")
6331    public int getLabelFor() {
6332        return mLabelForId;
6333    }
6334
6335    /**
6336     * Sets the id of a view for which this view serves as a label for
6337     * accessibility purposes.
6338     *
6339     * @param id The labeled view id.
6340     */
6341    @RemotableViewMethod
6342    public void setLabelFor(@IdRes int id) {
6343        if (mLabelForId == id) {
6344            return;
6345        }
6346        mLabelForId = id;
6347        if (mLabelForId != View.NO_ID
6348                && mID == View.NO_ID) {
6349            mID = generateViewId();
6350        }
6351        notifyViewAccessibilityStateChangedIfNeeded(
6352                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6353    }
6354
6355    /**
6356     * Invoked whenever this view loses focus, either by losing window focus or by losing
6357     * focus within its window. This method can be used to clear any state tied to the
6358     * focus. For instance, if a button is held pressed with the trackball and the window
6359     * loses focus, this method can be used to cancel the press.
6360     *
6361     * Subclasses of View overriding this method should always call super.onFocusLost().
6362     *
6363     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6364     * @see #onWindowFocusChanged(boolean)
6365     *
6366     * @hide pending API council approval
6367     */
6368    @CallSuper
6369    protected void onFocusLost() {
6370        resetPressedState();
6371    }
6372
6373    private void resetPressedState() {
6374        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6375            return;
6376        }
6377
6378        if (isPressed()) {
6379            setPressed(false);
6380
6381            if (!mHasPerformedLongPress) {
6382                removeLongPressCallback();
6383            }
6384        }
6385    }
6386
6387    /**
6388     * Returns true if this view has focus
6389     *
6390     * @return True if this view has focus, false otherwise.
6391     */
6392    @ViewDebug.ExportedProperty(category = "focus")
6393    public boolean isFocused() {
6394        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6395    }
6396
6397    /**
6398     * Find the view in the hierarchy rooted at this view that currently has
6399     * focus.
6400     *
6401     * @return The view that currently has focus, or null if no focused view can
6402     *         be found.
6403     */
6404    public View findFocus() {
6405        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6406    }
6407
6408    /**
6409     * Indicates whether this view is one of the set of scrollable containers in
6410     * its window.
6411     *
6412     * @return whether this view is one of the set of scrollable containers in
6413     * its window
6414     *
6415     * @attr ref android.R.styleable#View_isScrollContainer
6416     */
6417    public boolean isScrollContainer() {
6418        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6419    }
6420
6421    /**
6422     * Change whether this view is one of the set of scrollable containers in
6423     * its window.  This will be used to determine whether the window can
6424     * resize or must pan when a soft input area is open -- scrollable
6425     * containers allow the window to use resize mode since the container
6426     * will appropriately shrink.
6427     *
6428     * @attr ref android.R.styleable#View_isScrollContainer
6429     */
6430    public void setScrollContainer(boolean isScrollContainer) {
6431        if (isScrollContainer) {
6432            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6433                mAttachInfo.mScrollContainers.add(this);
6434                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6435            }
6436            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6437        } else {
6438            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6439                mAttachInfo.mScrollContainers.remove(this);
6440            }
6441            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6442        }
6443    }
6444
6445    /**
6446     * Returns the quality of the drawing cache.
6447     *
6448     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6449     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6450     *
6451     * @see #setDrawingCacheQuality(int)
6452     * @see #setDrawingCacheEnabled(boolean)
6453     * @see #isDrawingCacheEnabled()
6454     *
6455     * @attr ref android.R.styleable#View_drawingCacheQuality
6456     */
6457    @DrawingCacheQuality
6458    public int getDrawingCacheQuality() {
6459        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6460    }
6461
6462    /**
6463     * Set the drawing cache quality of this view. This value is used only when the
6464     * drawing cache is enabled
6465     *
6466     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6467     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6468     *
6469     * @see #getDrawingCacheQuality()
6470     * @see #setDrawingCacheEnabled(boolean)
6471     * @see #isDrawingCacheEnabled()
6472     *
6473     * @attr ref android.R.styleable#View_drawingCacheQuality
6474     */
6475    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6476        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6477    }
6478
6479    /**
6480     * Returns whether the screen should remain on, corresponding to the current
6481     * value of {@link #KEEP_SCREEN_ON}.
6482     *
6483     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6484     *
6485     * @see #setKeepScreenOn(boolean)
6486     *
6487     * @attr ref android.R.styleable#View_keepScreenOn
6488     */
6489    public boolean getKeepScreenOn() {
6490        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6491    }
6492
6493    /**
6494     * Controls whether the screen should remain on, modifying the
6495     * value of {@link #KEEP_SCREEN_ON}.
6496     *
6497     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6498     *
6499     * @see #getKeepScreenOn()
6500     *
6501     * @attr ref android.R.styleable#View_keepScreenOn
6502     */
6503    public void setKeepScreenOn(boolean keepScreenOn) {
6504        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6505    }
6506
6507    /**
6508     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6509     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6510     *
6511     * @attr ref android.R.styleable#View_nextFocusLeft
6512     */
6513    public int getNextFocusLeftId() {
6514        return mNextFocusLeftId;
6515    }
6516
6517    /**
6518     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6519     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6520     * decide automatically.
6521     *
6522     * @attr ref android.R.styleable#View_nextFocusLeft
6523     */
6524    public void setNextFocusLeftId(int nextFocusLeftId) {
6525        mNextFocusLeftId = nextFocusLeftId;
6526    }
6527
6528    /**
6529     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6530     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6531     *
6532     * @attr ref android.R.styleable#View_nextFocusRight
6533     */
6534    public int getNextFocusRightId() {
6535        return mNextFocusRightId;
6536    }
6537
6538    /**
6539     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6540     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6541     * decide automatically.
6542     *
6543     * @attr ref android.R.styleable#View_nextFocusRight
6544     */
6545    public void setNextFocusRightId(int nextFocusRightId) {
6546        mNextFocusRightId = nextFocusRightId;
6547    }
6548
6549    /**
6550     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6551     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6552     *
6553     * @attr ref android.R.styleable#View_nextFocusUp
6554     */
6555    public int getNextFocusUpId() {
6556        return mNextFocusUpId;
6557    }
6558
6559    /**
6560     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6561     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6562     * decide automatically.
6563     *
6564     * @attr ref android.R.styleable#View_nextFocusUp
6565     */
6566    public void setNextFocusUpId(int nextFocusUpId) {
6567        mNextFocusUpId = nextFocusUpId;
6568    }
6569
6570    /**
6571     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6572     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6573     *
6574     * @attr ref android.R.styleable#View_nextFocusDown
6575     */
6576    public int getNextFocusDownId() {
6577        return mNextFocusDownId;
6578    }
6579
6580    /**
6581     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6582     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6583     * decide automatically.
6584     *
6585     * @attr ref android.R.styleable#View_nextFocusDown
6586     */
6587    public void setNextFocusDownId(int nextFocusDownId) {
6588        mNextFocusDownId = nextFocusDownId;
6589    }
6590
6591    /**
6592     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6593     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6594     *
6595     * @attr ref android.R.styleable#View_nextFocusForward
6596     */
6597    public int getNextFocusForwardId() {
6598        return mNextFocusForwardId;
6599    }
6600
6601    /**
6602     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6603     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6604     * decide automatically.
6605     *
6606     * @attr ref android.R.styleable#View_nextFocusForward
6607     */
6608    public void setNextFocusForwardId(int nextFocusForwardId) {
6609        mNextFocusForwardId = nextFocusForwardId;
6610    }
6611
6612    /**
6613     * Returns the visibility of this view and all of its ancestors
6614     *
6615     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6616     */
6617    public boolean isShown() {
6618        View current = this;
6619        //noinspection ConstantConditions
6620        do {
6621            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6622                return false;
6623            }
6624            ViewParent parent = current.mParent;
6625            if (parent == null) {
6626                return false; // We are not attached to the view root
6627            }
6628            if (!(parent instanceof View)) {
6629                return true;
6630            }
6631            current = (View) parent;
6632        } while (current != null);
6633
6634        return false;
6635    }
6636
6637    /**
6638     * Called by the view hierarchy when the content insets for a window have
6639     * changed, to allow it to adjust its content to fit within those windows.
6640     * The content insets tell you the space that the status bar, input method,
6641     * and other system windows infringe on the application's window.
6642     *
6643     * <p>You do not normally need to deal with this function, since the default
6644     * window decoration given to applications takes care of applying it to the
6645     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6646     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6647     * and your content can be placed under those system elements.  You can then
6648     * use this method within your view hierarchy if you have parts of your UI
6649     * which you would like to ensure are not being covered.
6650     *
6651     * <p>The default implementation of this method simply applies the content
6652     * insets to the view's padding, consuming that content (modifying the
6653     * insets to be 0), and returning true.  This behavior is off by default, but can
6654     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6655     *
6656     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6657     * insets object is propagated down the hierarchy, so any changes made to it will
6658     * be seen by all following views (including potentially ones above in
6659     * the hierarchy since this is a depth-first traversal).  The first view
6660     * that returns true will abort the entire traversal.
6661     *
6662     * <p>The default implementation works well for a situation where it is
6663     * used with a container that covers the entire window, allowing it to
6664     * apply the appropriate insets to its content on all edges.  If you need
6665     * a more complicated layout (such as two different views fitting system
6666     * windows, one on the top of the window, and one on the bottom),
6667     * you can override the method and handle the insets however you would like.
6668     * Note that the insets provided by the framework are always relative to the
6669     * far edges of the window, not accounting for the location of the called view
6670     * within that window.  (In fact when this method is called you do not yet know
6671     * where the layout will place the view, as it is done before layout happens.)
6672     *
6673     * <p>Note: unlike many View methods, there is no dispatch phase to this
6674     * call.  If you are overriding it in a ViewGroup and want to allow the
6675     * call to continue to your children, you must be sure to call the super
6676     * implementation.
6677     *
6678     * <p>Here is a sample layout that makes use of fitting system windows
6679     * to have controls for a video view placed inside of the window decorations
6680     * that it hides and shows.  This can be used with code like the second
6681     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6682     *
6683     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6684     *
6685     * @param insets Current content insets of the window.  Prior to
6686     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6687     * the insets or else you and Android will be unhappy.
6688     *
6689     * @return {@code true} if this view applied the insets and it should not
6690     * continue propagating further down the hierarchy, {@code false} otherwise.
6691     * @see #getFitsSystemWindows()
6692     * @see #setFitsSystemWindows(boolean)
6693     * @see #setSystemUiVisibility(int)
6694     *
6695     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6696     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6697     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6698     * to implement handling their own insets.
6699     */
6700    protected boolean fitSystemWindows(Rect insets) {
6701        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6702            if (insets == null) {
6703                // Null insets by definition have already been consumed.
6704                // This call cannot apply insets since there are none to apply,
6705                // so return false.
6706                return false;
6707            }
6708            // If we're not in the process of dispatching the newer apply insets call,
6709            // that means we're not in the compatibility path. Dispatch into the newer
6710            // apply insets path and take things from there.
6711            try {
6712                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6713                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6714            } finally {
6715                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6716            }
6717        } else {
6718            // We're being called from the newer apply insets path.
6719            // Perform the standard fallback behavior.
6720            return fitSystemWindowsInt(insets);
6721        }
6722    }
6723
6724    private boolean fitSystemWindowsInt(Rect insets) {
6725        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6726            mUserPaddingStart = UNDEFINED_PADDING;
6727            mUserPaddingEnd = UNDEFINED_PADDING;
6728            Rect localInsets = sThreadLocal.get();
6729            if (localInsets == null) {
6730                localInsets = new Rect();
6731                sThreadLocal.set(localInsets);
6732            }
6733            boolean res = computeFitSystemWindows(insets, localInsets);
6734            mUserPaddingLeftInitial = localInsets.left;
6735            mUserPaddingRightInitial = localInsets.right;
6736            internalSetPadding(localInsets.left, localInsets.top,
6737                    localInsets.right, localInsets.bottom);
6738            return res;
6739        }
6740        return false;
6741    }
6742
6743    /**
6744     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6745     *
6746     * <p>This method should be overridden by views that wish to apply a policy different from or
6747     * in addition to the default behavior. Clients that wish to force a view subtree
6748     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6749     *
6750     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6751     * it will be called during dispatch instead of this method. The listener may optionally
6752     * call this method from its own implementation if it wishes to apply the view's default
6753     * insets policy in addition to its own.</p>
6754     *
6755     * <p>Implementations of this method should either return the insets parameter unchanged
6756     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6757     * that this view applied itself. This allows new inset types added in future platform
6758     * versions to pass through existing implementations unchanged without being erroneously
6759     * consumed.</p>
6760     *
6761     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6762     * property is set then the view will consume the system window insets and apply them
6763     * as padding for the view.</p>
6764     *
6765     * @param insets Insets to apply
6766     * @return The supplied insets with any applied insets consumed
6767     */
6768    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6769        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6770            // We weren't called from within a direct call to fitSystemWindows,
6771            // call into it as a fallback in case we're in a class that overrides it
6772            // and has logic to perform.
6773            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6774                return insets.consumeSystemWindowInsets();
6775            }
6776        } else {
6777            // We were called from within a direct call to fitSystemWindows.
6778            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6779                return insets.consumeSystemWindowInsets();
6780            }
6781        }
6782        return insets;
6783    }
6784
6785    /**
6786     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6787     * window insets to this view. The listener's
6788     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6789     * method will be called instead of the view's
6790     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6791     *
6792     * @param listener Listener to set
6793     *
6794     * @see #onApplyWindowInsets(WindowInsets)
6795     */
6796    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6797        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6798    }
6799
6800    /**
6801     * Request to apply the given window insets to this view or another view in its subtree.
6802     *
6803     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6804     * obscured by window decorations or overlays. This can include the status and navigation bars,
6805     * action bars, input methods and more. New inset categories may be added in the future.
6806     * The method returns the insets provided minus any that were applied by this view or its
6807     * children.</p>
6808     *
6809     * <p>Clients wishing to provide custom behavior should override the
6810     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6811     * {@link OnApplyWindowInsetsListener} via the
6812     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6813     * method.</p>
6814     *
6815     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6816     * </p>
6817     *
6818     * @param insets Insets to apply
6819     * @return The provided insets minus the insets that were consumed
6820     */
6821    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6822        try {
6823            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6824            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6825                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6826            } else {
6827                return onApplyWindowInsets(insets);
6828            }
6829        } finally {
6830            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6831        }
6832    }
6833
6834    /**
6835     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
6836     * only available if the view is attached.
6837     *
6838     * @return WindowInsets from the top of the view hierarchy or null if View is detached
6839     */
6840    public WindowInsets getRootWindowInsets() {
6841        if (mAttachInfo != null) {
6842            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
6843        }
6844        return null;
6845    }
6846
6847    /**
6848     * @hide Compute the insets that should be consumed by this view and the ones
6849     * that should propagate to those under it.
6850     */
6851    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6852        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6853                || mAttachInfo == null
6854                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6855                        && !mAttachInfo.mOverscanRequested)) {
6856            outLocalInsets.set(inoutInsets);
6857            inoutInsets.set(0, 0, 0, 0);
6858            return true;
6859        } else {
6860            // The application wants to take care of fitting system window for
6861            // the content...  however we still need to take care of any overscan here.
6862            final Rect overscan = mAttachInfo.mOverscanInsets;
6863            outLocalInsets.set(overscan);
6864            inoutInsets.left -= overscan.left;
6865            inoutInsets.top -= overscan.top;
6866            inoutInsets.right -= overscan.right;
6867            inoutInsets.bottom -= overscan.bottom;
6868            return false;
6869        }
6870    }
6871
6872    /**
6873     * Compute insets that should be consumed by this view and the ones that should propagate
6874     * to those under it.
6875     *
6876     * @param in Insets currently being processed by this View, likely received as a parameter
6877     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6878     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6879     *                       by this view
6880     * @return Insets that should be passed along to views under this one
6881     */
6882    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6883        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6884                || mAttachInfo == null
6885                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6886            outLocalInsets.set(in.getSystemWindowInsets());
6887            return in.consumeSystemWindowInsets();
6888        } else {
6889            outLocalInsets.set(0, 0, 0, 0);
6890            return in;
6891        }
6892    }
6893
6894    /**
6895     * Sets whether or not this view should account for system screen decorations
6896     * such as the status bar and inset its content; that is, controlling whether
6897     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6898     * executed.  See that method for more details.
6899     *
6900     * <p>Note that if you are providing your own implementation of
6901     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6902     * flag to true -- your implementation will be overriding the default
6903     * implementation that checks this flag.
6904     *
6905     * @param fitSystemWindows If true, then the default implementation of
6906     * {@link #fitSystemWindows(Rect)} will be executed.
6907     *
6908     * @attr ref android.R.styleable#View_fitsSystemWindows
6909     * @see #getFitsSystemWindows()
6910     * @see #fitSystemWindows(Rect)
6911     * @see #setSystemUiVisibility(int)
6912     */
6913    public void setFitsSystemWindows(boolean fitSystemWindows) {
6914        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6915    }
6916
6917    /**
6918     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6919     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6920     * will be executed.
6921     *
6922     * @return {@code true} if the default implementation of
6923     * {@link #fitSystemWindows(Rect)} will be executed.
6924     *
6925     * @attr ref android.R.styleable#View_fitsSystemWindows
6926     * @see #setFitsSystemWindows(boolean)
6927     * @see #fitSystemWindows(Rect)
6928     * @see #setSystemUiVisibility(int)
6929     */
6930    @ViewDebug.ExportedProperty
6931    public boolean getFitsSystemWindows() {
6932        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6933    }
6934
6935    /** @hide */
6936    public boolean fitsSystemWindows() {
6937        return getFitsSystemWindows();
6938    }
6939
6940    /**
6941     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6942     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6943     */
6944    public void requestFitSystemWindows() {
6945        if (mParent != null) {
6946            mParent.requestFitSystemWindows();
6947        }
6948    }
6949
6950    /**
6951     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6952     */
6953    public void requestApplyInsets() {
6954        requestFitSystemWindows();
6955    }
6956
6957    /**
6958     * For use by PhoneWindow to make its own system window fitting optional.
6959     * @hide
6960     */
6961    public void makeOptionalFitsSystemWindows() {
6962        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6963    }
6964
6965    /**
6966     * Returns the visibility status for this view.
6967     *
6968     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6969     * @attr ref android.R.styleable#View_visibility
6970     */
6971    @ViewDebug.ExportedProperty(mapping = {
6972        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6973        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6974        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6975    })
6976    @Visibility
6977    public int getVisibility() {
6978        return mViewFlags & VISIBILITY_MASK;
6979    }
6980
6981    /**
6982     * Set the enabled state of this view.
6983     *
6984     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6985     * @attr ref android.R.styleable#View_visibility
6986     */
6987    @RemotableViewMethod
6988    public void setVisibility(@Visibility int visibility) {
6989        setFlags(visibility, VISIBILITY_MASK);
6990    }
6991
6992    /**
6993     * Returns the enabled status for this view. The interpretation of the
6994     * enabled state varies by subclass.
6995     *
6996     * @return True if this view is enabled, false otherwise.
6997     */
6998    @ViewDebug.ExportedProperty
6999    public boolean isEnabled() {
7000        return (mViewFlags & ENABLED_MASK) == ENABLED;
7001    }
7002
7003    /**
7004     * Set the enabled state of this view. The interpretation of the enabled
7005     * state varies by subclass.
7006     *
7007     * @param enabled True if this view is enabled, false otherwise.
7008     */
7009    @RemotableViewMethod
7010    public void setEnabled(boolean enabled) {
7011        if (enabled == isEnabled()) return;
7012
7013        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7014
7015        /*
7016         * The View most likely has to change its appearance, so refresh
7017         * the drawable state.
7018         */
7019        refreshDrawableState();
7020
7021        // Invalidate too, since the default behavior for views is to be
7022        // be drawn at 50% alpha rather than to change the drawable.
7023        invalidate(true);
7024
7025        if (!enabled) {
7026            cancelPendingInputEvents();
7027        }
7028    }
7029
7030    /**
7031     * Set whether this view can receive the focus.
7032     *
7033     * Setting this to false will also ensure that this view is not focusable
7034     * in touch mode.
7035     *
7036     * @param focusable If true, this view can receive the focus.
7037     *
7038     * @see #setFocusableInTouchMode(boolean)
7039     * @attr ref android.R.styleable#View_focusable
7040     */
7041    public void setFocusable(boolean focusable) {
7042        if (!focusable) {
7043            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7044        }
7045        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7046    }
7047
7048    /**
7049     * Set whether this view can receive focus while in touch mode.
7050     *
7051     * Setting this to true will also ensure that this view is focusable.
7052     *
7053     * @param focusableInTouchMode If true, this view can receive the focus while
7054     *   in touch mode.
7055     *
7056     * @see #setFocusable(boolean)
7057     * @attr ref android.R.styleable#View_focusableInTouchMode
7058     */
7059    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7060        // Focusable in touch mode should always be set before the focusable flag
7061        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7062        // which, in touch mode, will not successfully request focus on this view
7063        // because the focusable in touch mode flag is not set
7064        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7065        if (focusableInTouchMode) {
7066            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7067        }
7068    }
7069
7070    /**
7071     * Set whether this view should have sound effects enabled for events such as
7072     * clicking and touching.
7073     *
7074     * <p>You may wish to disable sound effects for a view if you already play sounds,
7075     * for instance, a dial key that plays dtmf tones.
7076     *
7077     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7078     * @see #isSoundEffectsEnabled()
7079     * @see #playSoundEffect(int)
7080     * @attr ref android.R.styleable#View_soundEffectsEnabled
7081     */
7082    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7083        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7084    }
7085
7086    /**
7087     * @return whether this view should have sound effects enabled for events such as
7088     *     clicking and touching.
7089     *
7090     * @see #setSoundEffectsEnabled(boolean)
7091     * @see #playSoundEffect(int)
7092     * @attr ref android.R.styleable#View_soundEffectsEnabled
7093     */
7094    @ViewDebug.ExportedProperty
7095    public boolean isSoundEffectsEnabled() {
7096        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7097    }
7098
7099    /**
7100     * Set whether this view should have haptic feedback for events such as
7101     * long presses.
7102     *
7103     * <p>You may wish to disable haptic feedback if your view already controls
7104     * its own haptic feedback.
7105     *
7106     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7107     * @see #isHapticFeedbackEnabled()
7108     * @see #performHapticFeedback(int)
7109     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7110     */
7111    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7112        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7113    }
7114
7115    /**
7116     * @return whether this view should have haptic feedback enabled for events
7117     * long presses.
7118     *
7119     * @see #setHapticFeedbackEnabled(boolean)
7120     * @see #performHapticFeedback(int)
7121     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7122     */
7123    @ViewDebug.ExportedProperty
7124    public boolean isHapticFeedbackEnabled() {
7125        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7126    }
7127
7128    /**
7129     * Returns the layout direction for this view.
7130     *
7131     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7132     *   {@link #LAYOUT_DIRECTION_RTL},
7133     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7134     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7135     *
7136     * @attr ref android.R.styleable#View_layoutDirection
7137     *
7138     * @hide
7139     */
7140    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7141        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7142        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7143        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7144        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7145    })
7146    @LayoutDir
7147    public int getRawLayoutDirection() {
7148        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7149    }
7150
7151    /**
7152     * Set the layout direction for this view. This will propagate a reset of layout direction
7153     * resolution to the view's children and resolve layout direction for this view.
7154     *
7155     * @param layoutDirection the layout direction to set. Should be one of:
7156     *
7157     * {@link #LAYOUT_DIRECTION_LTR},
7158     * {@link #LAYOUT_DIRECTION_RTL},
7159     * {@link #LAYOUT_DIRECTION_INHERIT},
7160     * {@link #LAYOUT_DIRECTION_LOCALE}.
7161     *
7162     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7163     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7164     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7165     *
7166     * @attr ref android.R.styleable#View_layoutDirection
7167     */
7168    @RemotableViewMethod
7169    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7170        if (getRawLayoutDirection() != layoutDirection) {
7171            // Reset the current layout direction and the resolved one
7172            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7173            resetRtlProperties();
7174            // Set the new layout direction (filtered)
7175            mPrivateFlags2 |=
7176                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7177            // We need to resolve all RTL properties as they all depend on layout direction
7178            resolveRtlPropertiesIfNeeded();
7179            requestLayout();
7180            invalidate(true);
7181        }
7182    }
7183
7184    /**
7185     * Returns the resolved layout direction for this view.
7186     *
7187     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7188     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7189     *
7190     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7191     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7192     *
7193     * @attr ref android.R.styleable#View_layoutDirection
7194     */
7195    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7196        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7197        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7198    })
7199    @ResolvedLayoutDir
7200    public int getLayoutDirection() {
7201        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7202        if (targetSdkVersion < JELLY_BEAN_MR1) {
7203            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7204            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7205        }
7206        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7207                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7208    }
7209
7210    /**
7211     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7212     * layout attribute and/or the inherited value from the parent
7213     *
7214     * @return true if the layout is right-to-left.
7215     *
7216     * @hide
7217     */
7218    @ViewDebug.ExportedProperty(category = "layout")
7219    public boolean isLayoutRtl() {
7220        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7221    }
7222
7223    /**
7224     * Indicates whether the view is currently tracking transient state that the
7225     * app should not need to concern itself with saving and restoring, but that
7226     * the framework should take special note to preserve when possible.
7227     *
7228     * <p>A view with transient state cannot be trivially rebound from an external
7229     * data source, such as an adapter binding item views in a list. This may be
7230     * because the view is performing an animation, tracking user selection
7231     * of content, or similar.</p>
7232     *
7233     * @return true if the view has transient state
7234     */
7235    @ViewDebug.ExportedProperty(category = "layout")
7236    public boolean hasTransientState() {
7237        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7238    }
7239
7240    /**
7241     * Set whether this view is currently tracking transient state that the
7242     * framework should attempt to preserve when possible. This flag is reference counted,
7243     * so every call to setHasTransientState(true) should be paired with a later call
7244     * to setHasTransientState(false).
7245     *
7246     * <p>A view with transient state cannot be trivially rebound from an external
7247     * data source, such as an adapter binding item views in a list. This may be
7248     * because the view is performing an animation, tracking user selection
7249     * of content, or similar.</p>
7250     *
7251     * @param hasTransientState true if this view has transient state
7252     */
7253    public void setHasTransientState(boolean hasTransientState) {
7254        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7255                mTransientStateCount - 1;
7256        if (mTransientStateCount < 0) {
7257            mTransientStateCount = 0;
7258            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7259                    "unmatched pair of setHasTransientState calls");
7260        } else if ((hasTransientState && mTransientStateCount == 1) ||
7261                (!hasTransientState && mTransientStateCount == 0)) {
7262            // update flag if we've just incremented up from 0 or decremented down to 0
7263            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7264                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7265            if (mParent != null) {
7266                try {
7267                    mParent.childHasTransientStateChanged(this, hasTransientState);
7268                } catch (AbstractMethodError e) {
7269                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7270                            " does not fully implement ViewParent", e);
7271                }
7272            }
7273        }
7274    }
7275
7276    /**
7277     * Returns true if this view is currently attached to a window.
7278     */
7279    public boolean isAttachedToWindow() {
7280        return mAttachInfo != null;
7281    }
7282
7283    /**
7284     * Returns true if this view has been through at least one layout since it
7285     * was last attached to or detached from a window.
7286     */
7287    public boolean isLaidOut() {
7288        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7289    }
7290
7291    /**
7292     * If this view doesn't do any drawing on its own, set this flag to
7293     * allow further optimizations. By default, this flag is not set on
7294     * View, but could be set on some View subclasses such as ViewGroup.
7295     *
7296     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7297     * you should clear this flag.
7298     *
7299     * @param willNotDraw whether or not this View draw on its own
7300     */
7301    public void setWillNotDraw(boolean willNotDraw) {
7302        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7303    }
7304
7305    /**
7306     * Returns whether or not this View draws on its own.
7307     *
7308     * @return true if this view has nothing to draw, false otherwise
7309     */
7310    @ViewDebug.ExportedProperty(category = "drawing")
7311    public boolean willNotDraw() {
7312        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7313    }
7314
7315    /**
7316     * When a View's drawing cache is enabled, drawing is redirected to an
7317     * offscreen bitmap. Some views, like an ImageView, must be able to
7318     * bypass this mechanism if they already draw a single bitmap, to avoid
7319     * unnecessary usage of the memory.
7320     *
7321     * @param willNotCacheDrawing true if this view does not cache its
7322     *        drawing, false otherwise
7323     */
7324    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7325        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7326    }
7327
7328    /**
7329     * Returns whether or not this View can cache its drawing or not.
7330     *
7331     * @return true if this view does not cache its drawing, false otherwise
7332     */
7333    @ViewDebug.ExportedProperty(category = "drawing")
7334    public boolean willNotCacheDrawing() {
7335        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7336    }
7337
7338    /**
7339     * Indicates whether this view reacts to click events or not.
7340     *
7341     * @return true if the view is clickable, false otherwise
7342     *
7343     * @see #setClickable(boolean)
7344     * @attr ref android.R.styleable#View_clickable
7345     */
7346    @ViewDebug.ExportedProperty
7347    public boolean isClickable() {
7348        return (mViewFlags & CLICKABLE) == CLICKABLE;
7349    }
7350
7351    /**
7352     * Enables or disables click events for this view. When a view
7353     * is clickable it will change its state to "pressed" on every click.
7354     * Subclasses should set the view clickable to visually react to
7355     * user's clicks.
7356     *
7357     * @param clickable true to make the view clickable, false otherwise
7358     *
7359     * @see #isClickable()
7360     * @attr ref android.R.styleable#View_clickable
7361     */
7362    public void setClickable(boolean clickable) {
7363        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7364    }
7365
7366    /**
7367     * Indicates whether this view reacts to long click events or not.
7368     *
7369     * @return true if the view is long clickable, false otherwise
7370     *
7371     * @see #setLongClickable(boolean)
7372     * @attr ref android.R.styleable#View_longClickable
7373     */
7374    public boolean isLongClickable() {
7375        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7376    }
7377
7378    /**
7379     * Enables or disables long click events for this view. When a view is long
7380     * clickable it reacts to the user holding down the button for a longer
7381     * duration than a tap. This event can either launch the listener or a
7382     * context menu.
7383     *
7384     * @param longClickable true to make the view long clickable, false otherwise
7385     * @see #isLongClickable()
7386     * @attr ref android.R.styleable#View_longClickable
7387     */
7388    public void setLongClickable(boolean longClickable) {
7389        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7390    }
7391
7392    /**
7393     * Sets the pressed state for this view and provides a touch coordinate for
7394     * animation hinting.
7395     *
7396     * @param pressed Pass true to set the View's internal state to "pressed",
7397     *            or false to reverts the View's internal state from a
7398     *            previously set "pressed" state.
7399     * @param x The x coordinate of the touch that caused the press
7400     * @param y The y coordinate of the touch that caused the press
7401     */
7402    private void setPressed(boolean pressed, float x, float y) {
7403        if (pressed) {
7404            drawableHotspotChanged(x, y);
7405        }
7406
7407        setPressed(pressed);
7408    }
7409
7410    /**
7411     * Sets the pressed state for this view.
7412     *
7413     * @see #isClickable()
7414     * @see #setClickable(boolean)
7415     *
7416     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7417     *        the View's internal state from a previously set "pressed" state.
7418     */
7419    public void setPressed(boolean pressed) {
7420        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7421
7422        if (pressed) {
7423            mPrivateFlags |= PFLAG_PRESSED;
7424        } else {
7425            mPrivateFlags &= ~PFLAG_PRESSED;
7426        }
7427
7428        if (needsRefresh) {
7429            refreshDrawableState();
7430        }
7431        dispatchSetPressed(pressed);
7432    }
7433
7434    /**
7435     * Dispatch setPressed to all of this View's children.
7436     *
7437     * @see #setPressed(boolean)
7438     *
7439     * @param pressed The new pressed state
7440     */
7441    protected void dispatchSetPressed(boolean pressed) {
7442    }
7443
7444    /**
7445     * Indicates whether the view is currently in pressed state. Unless
7446     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7447     * the pressed state.
7448     *
7449     * @see #setPressed(boolean)
7450     * @see #isClickable()
7451     * @see #setClickable(boolean)
7452     *
7453     * @return true if the view is currently pressed, false otherwise
7454     */
7455    @ViewDebug.ExportedProperty
7456    public boolean isPressed() {
7457        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7458    }
7459
7460    /**
7461     * Indicates whether this view will save its state (that is,
7462     * whether its {@link #onSaveInstanceState} method will be called).
7463     *
7464     * @return Returns true if the view state saving is enabled, else false.
7465     *
7466     * @see #setSaveEnabled(boolean)
7467     * @attr ref android.R.styleable#View_saveEnabled
7468     */
7469    public boolean isSaveEnabled() {
7470        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7471    }
7472
7473    /**
7474     * Controls whether the saving of this view's state is
7475     * enabled (that is, whether its {@link #onSaveInstanceState} method
7476     * will be called).  Note that even if freezing is enabled, the
7477     * view still must have an id assigned to it (via {@link #setId(int)})
7478     * for its state to be saved.  This flag can only disable the
7479     * saving of this view; any child views may still have their state saved.
7480     *
7481     * @param enabled Set to false to <em>disable</em> state saving, or true
7482     * (the default) to allow it.
7483     *
7484     * @see #isSaveEnabled()
7485     * @see #setId(int)
7486     * @see #onSaveInstanceState()
7487     * @attr ref android.R.styleable#View_saveEnabled
7488     */
7489    public void setSaveEnabled(boolean enabled) {
7490        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7491    }
7492
7493    /**
7494     * Gets whether the framework should discard touches when the view's
7495     * window is obscured by another visible window.
7496     * Refer to the {@link View} security documentation for more details.
7497     *
7498     * @return True if touch filtering is enabled.
7499     *
7500     * @see #setFilterTouchesWhenObscured(boolean)
7501     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7502     */
7503    @ViewDebug.ExportedProperty
7504    public boolean getFilterTouchesWhenObscured() {
7505        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7506    }
7507
7508    /**
7509     * Sets whether the framework should discard touches when the view's
7510     * window is obscured by another visible window.
7511     * Refer to the {@link View} security documentation for more details.
7512     *
7513     * @param enabled True if touch filtering should be enabled.
7514     *
7515     * @see #getFilterTouchesWhenObscured
7516     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7517     */
7518    public void setFilterTouchesWhenObscured(boolean enabled) {
7519        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7520                FILTER_TOUCHES_WHEN_OBSCURED);
7521    }
7522
7523    /**
7524     * Indicates whether the entire hierarchy under this view will save its
7525     * state when a state saving traversal occurs from its parent.  The default
7526     * is true; if false, these views will not be saved unless
7527     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7528     *
7529     * @return Returns true if the view state saving from parent is enabled, else false.
7530     *
7531     * @see #setSaveFromParentEnabled(boolean)
7532     */
7533    public boolean isSaveFromParentEnabled() {
7534        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7535    }
7536
7537    /**
7538     * Controls whether the entire hierarchy under this view will save its
7539     * state when a state saving traversal occurs from its parent.  The default
7540     * is true; if false, these views will not be saved unless
7541     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7542     *
7543     * @param enabled Set to false to <em>disable</em> state saving, or true
7544     * (the default) to allow it.
7545     *
7546     * @see #isSaveFromParentEnabled()
7547     * @see #setId(int)
7548     * @see #onSaveInstanceState()
7549     */
7550    public void setSaveFromParentEnabled(boolean enabled) {
7551        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7552    }
7553
7554
7555    /**
7556     * Returns whether this View is able to take focus.
7557     *
7558     * @return True if this view can take focus, or false otherwise.
7559     * @attr ref android.R.styleable#View_focusable
7560     */
7561    @ViewDebug.ExportedProperty(category = "focus")
7562    public final boolean isFocusable() {
7563        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7564    }
7565
7566    /**
7567     * When a view is focusable, it may not want to take focus when in touch mode.
7568     * For example, a button would like focus when the user is navigating via a D-pad
7569     * so that the user can click on it, but once the user starts touching the screen,
7570     * the button shouldn't take focus
7571     * @return Whether the view is focusable in touch mode.
7572     * @attr ref android.R.styleable#View_focusableInTouchMode
7573     */
7574    @ViewDebug.ExportedProperty
7575    public final boolean isFocusableInTouchMode() {
7576        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7577    }
7578
7579    /**
7580     * Find the nearest view in the specified direction that can take focus.
7581     * This does not actually give focus to that view.
7582     *
7583     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7584     *
7585     * @return The nearest focusable in the specified direction, or null if none
7586     *         can be found.
7587     */
7588    public View focusSearch(@FocusRealDirection int direction) {
7589        if (mParent != null) {
7590            return mParent.focusSearch(this, direction);
7591        } else {
7592            return null;
7593        }
7594    }
7595
7596    /**
7597     * This method is the last chance for the focused view and its ancestors to
7598     * respond to an arrow key. This is called when the focused view did not
7599     * consume the key internally, nor could the view system find a new view in
7600     * the requested direction to give focus to.
7601     *
7602     * @param focused The currently focused view.
7603     * @param direction The direction focus wants to move. One of FOCUS_UP,
7604     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7605     * @return True if the this view consumed this unhandled move.
7606     */
7607    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7608        return false;
7609    }
7610
7611    /**
7612     * If a user manually specified the next view id for a particular direction,
7613     * use the root to look up the view.
7614     * @param root The root view of the hierarchy containing this view.
7615     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7616     * or FOCUS_BACKWARD.
7617     * @return The user specified next view, or null if there is none.
7618     */
7619    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7620        switch (direction) {
7621            case FOCUS_LEFT:
7622                if (mNextFocusLeftId == View.NO_ID) return null;
7623                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7624            case FOCUS_RIGHT:
7625                if (mNextFocusRightId == View.NO_ID) return null;
7626                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7627            case FOCUS_UP:
7628                if (mNextFocusUpId == View.NO_ID) return null;
7629                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7630            case FOCUS_DOWN:
7631                if (mNextFocusDownId == View.NO_ID) return null;
7632                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7633            case FOCUS_FORWARD:
7634                if (mNextFocusForwardId == View.NO_ID) return null;
7635                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7636            case FOCUS_BACKWARD: {
7637                if (mID == View.NO_ID) return null;
7638                final int id = mID;
7639                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7640                    @Override
7641                    public boolean apply(View t) {
7642                        return t.mNextFocusForwardId == id;
7643                    }
7644                });
7645            }
7646        }
7647        return null;
7648    }
7649
7650    private View findViewInsideOutShouldExist(View root, int id) {
7651        if (mMatchIdPredicate == null) {
7652            mMatchIdPredicate = new MatchIdPredicate();
7653        }
7654        mMatchIdPredicate.mId = id;
7655        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7656        if (result == null) {
7657            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7658        }
7659        return result;
7660    }
7661
7662    /**
7663     * Find and return all focusable views that are descendants of this view,
7664     * possibly including this view if it is focusable itself.
7665     *
7666     * @param direction The direction of the focus
7667     * @return A list of focusable views
7668     */
7669    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7670        ArrayList<View> result = new ArrayList<View>(24);
7671        addFocusables(result, direction);
7672        return result;
7673    }
7674
7675    /**
7676     * Add any focusable views that are descendants of this view (possibly
7677     * including this view if it is focusable itself) to views.  If we are in touch mode,
7678     * only add views that are also focusable in touch mode.
7679     *
7680     * @param views Focusable views found so far
7681     * @param direction The direction of the focus
7682     */
7683    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7684        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7685    }
7686
7687    /**
7688     * Adds any focusable views that are descendants of this view (possibly
7689     * including this view if it is focusable itself) to views. This method
7690     * adds all focusable views regardless if we are in touch mode or
7691     * only views focusable in touch mode if we are in touch mode or
7692     * only views that can take accessibility focus if accessibility is enabled
7693     * depending on the focusable mode parameter.
7694     *
7695     * @param views Focusable views found so far or null if all we are interested is
7696     *        the number of focusables.
7697     * @param direction The direction of the focus.
7698     * @param focusableMode The type of focusables to be added.
7699     *
7700     * @see #FOCUSABLES_ALL
7701     * @see #FOCUSABLES_TOUCH_MODE
7702     */
7703    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7704            @FocusableMode int focusableMode) {
7705        if (views == null) {
7706            return;
7707        }
7708        if (!isFocusable()) {
7709            return;
7710        }
7711        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7712                && isInTouchMode() && !isFocusableInTouchMode()) {
7713            return;
7714        }
7715        views.add(this);
7716    }
7717
7718    /**
7719     * Finds the Views that contain given text. The containment is case insensitive.
7720     * The search is performed by either the text that the View renders or the content
7721     * description that describes the view for accessibility purposes and the view does
7722     * not render or both. Clients can specify how the search is to be performed via
7723     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7724     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7725     *
7726     * @param outViews The output list of matching Views.
7727     * @param searched The text to match against.
7728     *
7729     * @see #FIND_VIEWS_WITH_TEXT
7730     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7731     * @see #setContentDescription(CharSequence)
7732     */
7733    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7734            @FindViewFlags int flags) {
7735        if (getAccessibilityNodeProvider() != null) {
7736            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7737                outViews.add(this);
7738            }
7739        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7740                && (searched != null && searched.length() > 0)
7741                && (mContentDescription != null && mContentDescription.length() > 0)) {
7742            String searchedLowerCase = searched.toString().toLowerCase();
7743            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7744            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7745                outViews.add(this);
7746            }
7747        }
7748    }
7749
7750    /**
7751     * Find and return all touchable views that are descendants of this view,
7752     * possibly including this view if it is touchable itself.
7753     *
7754     * @return A list of touchable views
7755     */
7756    public ArrayList<View> getTouchables() {
7757        ArrayList<View> result = new ArrayList<View>();
7758        addTouchables(result);
7759        return result;
7760    }
7761
7762    /**
7763     * Add any touchable views that are descendants of this view (possibly
7764     * including this view if it is touchable itself) to views.
7765     *
7766     * @param views Touchable views found so far
7767     */
7768    public void addTouchables(ArrayList<View> views) {
7769        final int viewFlags = mViewFlags;
7770
7771        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7772                && (viewFlags & ENABLED_MASK) == ENABLED) {
7773            views.add(this);
7774        }
7775    }
7776
7777    /**
7778     * Returns whether this View is accessibility focused.
7779     *
7780     * @return True if this View is accessibility focused.
7781     */
7782    public boolean isAccessibilityFocused() {
7783        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7784    }
7785
7786    /**
7787     * Call this to try to give accessibility focus to this view.
7788     *
7789     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7790     * returns false or the view is no visible or the view already has accessibility
7791     * focus.
7792     *
7793     * See also {@link #focusSearch(int)}, which is what you call to say that you
7794     * have focus, and you want your parent to look for the next one.
7795     *
7796     * @return Whether this view actually took accessibility focus.
7797     *
7798     * @hide
7799     */
7800    public boolean requestAccessibilityFocus() {
7801        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7802        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7803            return false;
7804        }
7805        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7806            return false;
7807        }
7808        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7809            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7810            ViewRootImpl viewRootImpl = getViewRootImpl();
7811            if (viewRootImpl != null) {
7812                viewRootImpl.setAccessibilityFocus(this, null);
7813            }
7814            invalidate();
7815            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7816            return true;
7817        }
7818        return false;
7819    }
7820
7821    /**
7822     * Call this to try to clear accessibility focus of this view.
7823     *
7824     * See also {@link #focusSearch(int)}, which is what you call to say that you
7825     * have focus, and you want your parent to look for the next one.
7826     *
7827     * @hide
7828     */
7829    public void clearAccessibilityFocus() {
7830        clearAccessibilityFocusNoCallbacks();
7831        // Clear the global reference of accessibility focus if this
7832        // view or any of its descendants had accessibility focus.
7833        ViewRootImpl viewRootImpl = getViewRootImpl();
7834        if (viewRootImpl != null) {
7835            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7836            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7837                viewRootImpl.setAccessibilityFocus(null, null);
7838            }
7839        }
7840    }
7841
7842    private void sendAccessibilityHoverEvent(int eventType) {
7843        // Since we are not delivering to a client accessibility events from not
7844        // important views (unless the clinet request that) we need to fire the
7845        // event from the deepest view exposed to the client. As a consequence if
7846        // the user crosses a not exposed view the client will see enter and exit
7847        // of the exposed predecessor followed by and enter and exit of that same
7848        // predecessor when entering and exiting the not exposed descendant. This
7849        // is fine since the client has a clear idea which view is hovered at the
7850        // price of a couple more events being sent. This is a simple and
7851        // working solution.
7852        View source = this;
7853        while (true) {
7854            if (source.includeForAccessibility()) {
7855                source.sendAccessibilityEvent(eventType);
7856                return;
7857            }
7858            ViewParent parent = source.getParent();
7859            if (parent instanceof View) {
7860                source = (View) parent;
7861            } else {
7862                return;
7863            }
7864        }
7865    }
7866
7867    /**
7868     * Clears accessibility focus without calling any callback methods
7869     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7870     * is used for clearing accessibility focus when giving this focus to
7871     * another view.
7872     */
7873    void clearAccessibilityFocusNoCallbacks() {
7874        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7875            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7876            invalidate();
7877            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7878        }
7879    }
7880
7881    /**
7882     * Call this to try to give focus to a specific view or to one of its
7883     * descendants.
7884     *
7885     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7886     * false), or if it is focusable and it is not focusable in touch mode
7887     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7888     *
7889     * See also {@link #focusSearch(int)}, which is what you call to say that you
7890     * have focus, and you want your parent to look for the next one.
7891     *
7892     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7893     * {@link #FOCUS_DOWN} and <code>null</code>.
7894     *
7895     * @return Whether this view or one of its descendants actually took focus.
7896     */
7897    public final boolean requestFocus() {
7898        return requestFocus(View.FOCUS_DOWN);
7899    }
7900
7901    /**
7902     * Call this to try to give focus to a specific view or to one of its
7903     * descendants and give it a hint about what direction focus is heading.
7904     *
7905     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7906     * false), or if it is focusable and it is not focusable in touch mode
7907     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7908     *
7909     * See also {@link #focusSearch(int)}, which is what you call to say that you
7910     * have focus, and you want your parent to look for the next one.
7911     *
7912     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7913     * <code>null</code> set for the previously focused rectangle.
7914     *
7915     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7916     * @return Whether this view or one of its descendants actually took focus.
7917     */
7918    public final boolean requestFocus(int direction) {
7919        return requestFocus(direction, null);
7920    }
7921
7922    /**
7923     * Call this to try to give focus to a specific view or to one of its descendants
7924     * and give it hints about the direction and a specific rectangle that the focus
7925     * is coming from.  The rectangle can help give larger views a finer grained hint
7926     * about where focus is coming from, and therefore, where to show selection, or
7927     * forward focus change internally.
7928     *
7929     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7930     * false), or if it is focusable and it is not focusable in touch mode
7931     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7932     *
7933     * A View will not take focus if it is not visible.
7934     *
7935     * A View will not take focus if one of its parents has
7936     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7937     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7938     *
7939     * See also {@link #focusSearch(int)}, which is what you call to say that you
7940     * have focus, and you want your parent to look for the next one.
7941     *
7942     * You may wish to override this method if your custom {@link View} has an internal
7943     * {@link View} that it wishes to forward the request to.
7944     *
7945     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7946     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7947     *        to give a finer grained hint about where focus is coming from.  May be null
7948     *        if there is no hint.
7949     * @return Whether this view or one of its descendants actually took focus.
7950     */
7951    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7952        return requestFocusNoSearch(direction, previouslyFocusedRect);
7953    }
7954
7955    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7956        // need to be focusable
7957        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7958                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7959            return false;
7960        }
7961
7962        // need to be focusable in touch mode if in touch mode
7963        if (isInTouchMode() &&
7964            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7965               return false;
7966        }
7967
7968        // need to not have any parents blocking us
7969        if (hasAncestorThatBlocksDescendantFocus()) {
7970            return false;
7971        }
7972
7973        handleFocusGainInternal(direction, previouslyFocusedRect);
7974        return true;
7975    }
7976
7977    /**
7978     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7979     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
7980     * touch mode to request focus when they are touched.
7981     *
7982     * @return Whether this view or one of its descendants actually took focus.
7983     *
7984     * @see #isInTouchMode()
7985     *
7986     */
7987    public final boolean requestFocusFromTouch() {
7988        // Leave touch mode if we need to
7989        if (isInTouchMode()) {
7990            ViewRootImpl viewRoot = getViewRootImpl();
7991            if (viewRoot != null) {
7992                viewRoot.ensureTouchMode(false);
7993            }
7994        }
7995        return requestFocus(View.FOCUS_DOWN);
7996    }
7997
7998    /**
7999     * @return Whether any ancestor of this view blocks descendant focus.
8000     */
8001    private boolean hasAncestorThatBlocksDescendantFocus() {
8002        final boolean focusableInTouchMode = isFocusableInTouchMode();
8003        ViewParent ancestor = mParent;
8004        while (ancestor instanceof ViewGroup) {
8005            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8006            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8007                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8008                return true;
8009            } else {
8010                ancestor = vgAncestor.getParent();
8011            }
8012        }
8013        return false;
8014    }
8015
8016    /**
8017     * Gets the mode for determining whether this View is important for accessibility
8018     * which is if it fires accessibility events and if it is reported to
8019     * accessibility services that query the screen.
8020     *
8021     * @return The mode for determining whether a View is important for accessibility.
8022     *
8023     * @attr ref android.R.styleable#View_importantForAccessibility
8024     *
8025     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8026     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8027     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8028     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8029     */
8030    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8031            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8032            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8033            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8034            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8035                    to = "noHideDescendants")
8036        })
8037    public int getImportantForAccessibility() {
8038        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8039                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8040    }
8041
8042    /**
8043     * Sets the live region mode for this view. This indicates to accessibility
8044     * services whether they should automatically notify the user about changes
8045     * to the view's content description or text, or to the content descriptions
8046     * or text of the view's children (where applicable).
8047     * <p>
8048     * For example, in a login screen with a TextView that displays an "incorrect
8049     * password" notification, that view should be marked as a live region with
8050     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8051     * <p>
8052     * To disable change notifications for this view, use
8053     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8054     * mode for most views.
8055     * <p>
8056     * To indicate that the user should be notified of changes, use
8057     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8058     * <p>
8059     * If the view's changes should interrupt ongoing speech and notify the user
8060     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8061     *
8062     * @param mode The live region mode for this view, one of:
8063     *        <ul>
8064     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8065     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8066     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8067     *        </ul>
8068     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8069     */
8070    public void setAccessibilityLiveRegion(int mode) {
8071        if (mode != getAccessibilityLiveRegion()) {
8072            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8073            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8074                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8075            notifyViewAccessibilityStateChangedIfNeeded(
8076                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8077        }
8078    }
8079
8080    /**
8081     * Gets the live region mode for this View.
8082     *
8083     * @return The live region mode for the view.
8084     *
8085     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8086     *
8087     * @see #setAccessibilityLiveRegion(int)
8088     */
8089    public int getAccessibilityLiveRegion() {
8090        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8091                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8092    }
8093
8094    /**
8095     * Sets how to determine whether this view is important for accessibility
8096     * which is if it fires accessibility events and if it is reported to
8097     * accessibility services that query the screen.
8098     *
8099     * @param mode How to determine whether this view is important for accessibility.
8100     *
8101     * @attr ref android.R.styleable#View_importantForAccessibility
8102     *
8103     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8104     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8105     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8106     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8107     */
8108    public void setImportantForAccessibility(int mode) {
8109        final int oldMode = getImportantForAccessibility();
8110        if (mode != oldMode) {
8111            // If we're moving between AUTO and another state, we might not need
8112            // to send a subtree changed notification. We'll store the computed
8113            // importance, since we'll need to check it later to make sure.
8114            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8115                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8116            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8117            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8118            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8119                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8120            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8121                notifySubtreeAccessibilityStateChangedIfNeeded();
8122            } else {
8123                notifyViewAccessibilityStateChangedIfNeeded(
8124                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8125            }
8126        }
8127    }
8128
8129    /**
8130     * Computes whether this view should be exposed for accessibility. In
8131     * general, views that are interactive or provide information are exposed
8132     * while views that serve only as containers are hidden.
8133     * <p>
8134     * If an ancestor of this view has importance
8135     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8136     * returns <code>false</code>.
8137     * <p>
8138     * Otherwise, the value is computed according to the view's
8139     * {@link #getImportantForAccessibility()} value:
8140     * <ol>
8141     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8142     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8143     * </code>
8144     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8145     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8146     * view satisfies any of the following:
8147     * <ul>
8148     * <li>Is actionable, e.g. {@link #isClickable()},
8149     * {@link #isLongClickable()}, or {@link #isFocusable()}
8150     * <li>Has an {@link AccessibilityDelegate}
8151     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8152     * {@link OnKeyListener}, etc.
8153     * <li>Is an accessibility live region, e.g.
8154     * {@link #getAccessibilityLiveRegion()} is not
8155     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8156     * </ul>
8157     * </ol>
8158     *
8159     * @return Whether the view is exposed for accessibility.
8160     * @see #setImportantForAccessibility(int)
8161     * @see #getImportantForAccessibility()
8162     */
8163    public boolean isImportantForAccessibility() {
8164        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8165                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8166        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8167                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8168            return false;
8169        }
8170
8171        // Check parent mode to ensure we're not hidden.
8172        ViewParent parent = mParent;
8173        while (parent instanceof View) {
8174            if (((View) parent).getImportantForAccessibility()
8175                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8176                return false;
8177            }
8178            parent = parent.getParent();
8179        }
8180
8181        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8182                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8183                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8184    }
8185
8186    /**
8187     * Gets the parent for accessibility purposes. Note that the parent for
8188     * accessibility is not necessary the immediate parent. It is the first
8189     * predecessor that is important for accessibility.
8190     *
8191     * @return The parent for accessibility purposes.
8192     */
8193    public ViewParent getParentForAccessibility() {
8194        if (mParent instanceof View) {
8195            View parentView = (View) mParent;
8196            if (parentView.includeForAccessibility()) {
8197                return mParent;
8198            } else {
8199                return mParent.getParentForAccessibility();
8200            }
8201        }
8202        return null;
8203    }
8204
8205    /**
8206     * Adds the children of a given View for accessibility. Since some Views are
8207     * not important for accessibility the children for accessibility are not
8208     * necessarily direct children of the view, rather they are the first level of
8209     * descendants important for accessibility.
8210     *
8211     * @param children The list of children for accessibility.
8212     */
8213    public void addChildrenForAccessibility(ArrayList<View> children) {
8214
8215    }
8216
8217    /**
8218     * Whether to regard this view for accessibility. A view is regarded for
8219     * accessibility if it is important for accessibility or the querying
8220     * accessibility service has explicitly requested that view not
8221     * important for accessibility are regarded.
8222     *
8223     * @return Whether to regard the view for accessibility.
8224     *
8225     * @hide
8226     */
8227    public boolean includeForAccessibility() {
8228        if (mAttachInfo != null) {
8229            return (mAttachInfo.mAccessibilityFetchFlags
8230                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8231                    || isImportantForAccessibility();
8232        }
8233        return false;
8234    }
8235
8236    /**
8237     * Returns whether the View is considered actionable from
8238     * accessibility perspective. Such view are important for
8239     * accessibility.
8240     *
8241     * @return True if the view is actionable for accessibility.
8242     *
8243     * @hide
8244     */
8245    public boolean isActionableForAccessibility() {
8246        return (isClickable() || isLongClickable() || isFocusable());
8247    }
8248
8249    /**
8250     * Returns whether the View has registered callbacks which makes it
8251     * important for accessibility.
8252     *
8253     * @return True if the view is actionable for accessibility.
8254     */
8255    private boolean hasListenersForAccessibility() {
8256        ListenerInfo info = getListenerInfo();
8257        return mTouchDelegate != null || info.mOnKeyListener != null
8258                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8259                || info.mOnHoverListener != null || info.mOnDragListener != null;
8260    }
8261
8262    /**
8263     * Notifies that the accessibility state of this view changed. The change
8264     * is local to this view and does not represent structural changes such
8265     * as children and parent. For example, the view became focusable. The
8266     * notification is at at most once every
8267     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8268     * to avoid unnecessary load to the system. Also once a view has a pending
8269     * notification this method is a NOP until the notification has been sent.
8270     *
8271     * @hide
8272     */
8273    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8274        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8275            return;
8276        }
8277        if (mSendViewStateChangedAccessibilityEvent == null) {
8278            mSendViewStateChangedAccessibilityEvent =
8279                    new SendViewStateChangedAccessibilityEvent();
8280        }
8281        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8282    }
8283
8284    /**
8285     * Notifies that the accessibility state of this view changed. The change
8286     * is *not* local to this view and does represent structural changes such
8287     * as children and parent. For example, the view size changed. The
8288     * notification is at at most once every
8289     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8290     * to avoid unnecessary load to the system. Also once a view has a pending
8291     * notification this method is a NOP until the notification has been sent.
8292     *
8293     * @hide
8294     */
8295    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8296        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8297            return;
8298        }
8299        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8300            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8301            if (mParent != null) {
8302                try {
8303                    mParent.notifySubtreeAccessibilityStateChanged(
8304                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8305                } catch (AbstractMethodError e) {
8306                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8307                            " does not fully implement ViewParent", e);
8308                }
8309            }
8310        }
8311    }
8312
8313    /**
8314     * Reset the flag indicating the accessibility state of the subtree rooted
8315     * at this view changed.
8316     */
8317    void resetSubtreeAccessibilityStateChanged() {
8318        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8319    }
8320
8321    /**
8322     * Report an accessibility action to this view's parents for delegated processing.
8323     *
8324     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8325     * call this method to delegate an accessibility action to a supporting parent. If the parent
8326     * returns true from its
8327     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8328     * method this method will return true to signify that the action was consumed.</p>
8329     *
8330     * <p>This method is useful for implementing nested scrolling child views. If
8331     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8332     * a custom view implementation may invoke this method to allow a parent to consume the
8333     * scroll first. If this method returns true the custom view should skip its own scrolling
8334     * behavior.</p>
8335     *
8336     * @param action Accessibility action to delegate
8337     * @param arguments Optional action arguments
8338     * @return true if the action was consumed by a parent
8339     */
8340    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8341        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8342            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8343                return true;
8344            }
8345        }
8346        return false;
8347    }
8348
8349    /**
8350     * Performs the specified accessibility action on the view. For
8351     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8352     * <p>
8353     * If an {@link AccessibilityDelegate} has been specified via calling
8354     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8355     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8356     * is responsible for handling this call.
8357     * </p>
8358     *
8359     * <p>The default implementation will delegate
8360     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8361     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8362     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8363     *
8364     * @param action The action to perform.
8365     * @param arguments Optional action arguments.
8366     * @return Whether the action was performed.
8367     */
8368    public boolean performAccessibilityAction(int action, Bundle arguments) {
8369      if (mAccessibilityDelegate != null) {
8370          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8371      } else {
8372          return performAccessibilityActionInternal(action, arguments);
8373      }
8374    }
8375
8376   /**
8377    * @see #performAccessibilityAction(int, Bundle)
8378    *
8379    * Note: Called from the default {@link AccessibilityDelegate}.
8380    *
8381    * @hide
8382    */
8383    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8384        if (isNestedScrollingEnabled()
8385                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8386                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
8387            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8388                return true;
8389            }
8390        }
8391
8392        switch (action) {
8393            case AccessibilityNodeInfo.ACTION_CLICK: {
8394                if (isClickable()) {
8395                    performClick();
8396                    return true;
8397                }
8398            } break;
8399            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8400                if (isLongClickable()) {
8401                    performLongClick();
8402                    return true;
8403                }
8404            } break;
8405            case AccessibilityNodeInfo.ACTION_FOCUS: {
8406                if (!hasFocus()) {
8407                    // Get out of touch mode since accessibility
8408                    // wants to move focus around.
8409                    getViewRootImpl().ensureTouchMode(false);
8410                    return requestFocus();
8411                }
8412            } break;
8413            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8414                if (hasFocus()) {
8415                    clearFocus();
8416                    return !isFocused();
8417                }
8418            } break;
8419            case AccessibilityNodeInfo.ACTION_SELECT: {
8420                if (!isSelected()) {
8421                    setSelected(true);
8422                    return isSelected();
8423                }
8424            } break;
8425            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8426                if (isSelected()) {
8427                    setSelected(false);
8428                    return !isSelected();
8429                }
8430            } break;
8431            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8432                if (!isAccessibilityFocused()) {
8433                    return requestAccessibilityFocus();
8434                }
8435            } break;
8436            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8437                if (isAccessibilityFocused()) {
8438                    clearAccessibilityFocus();
8439                    return true;
8440                }
8441            } break;
8442            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8443                if (arguments != null) {
8444                    final int granularity = arguments.getInt(
8445                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8446                    final boolean extendSelection = arguments.getBoolean(
8447                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8448                    return traverseAtGranularity(granularity, true, extendSelection);
8449                }
8450            } break;
8451            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8452                if (arguments != null) {
8453                    final int granularity = arguments.getInt(
8454                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8455                    final boolean extendSelection = arguments.getBoolean(
8456                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8457                    return traverseAtGranularity(granularity, false, extendSelection);
8458                }
8459            } break;
8460            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8461                CharSequence text = getIterableTextForAccessibility();
8462                if (text == null) {
8463                    return false;
8464                }
8465                final int start = (arguments != null) ? arguments.getInt(
8466                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8467                final int end = (arguments != null) ? arguments.getInt(
8468                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8469                // Only cursor position can be specified (selection length == 0)
8470                if ((getAccessibilitySelectionStart() != start
8471                        || getAccessibilitySelectionEnd() != end)
8472                        && (start == end)) {
8473                    setAccessibilitySelection(start, end);
8474                    notifyViewAccessibilityStateChangedIfNeeded(
8475                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8476                    return true;
8477                }
8478            } break;
8479            case R.id.accessibilityActionShowOnScreen: {
8480                if (mAttachInfo != null) {
8481                    final Rect r = mAttachInfo.mTmpInvalRect;
8482                    getDrawingRect(r);
8483                    return requestRectangleOnScreen(r, true);
8484                }
8485            } break;
8486        }
8487        return false;
8488    }
8489
8490    private boolean traverseAtGranularity(int granularity, boolean forward,
8491            boolean extendSelection) {
8492        CharSequence text = getIterableTextForAccessibility();
8493        if (text == null || text.length() == 0) {
8494            return false;
8495        }
8496        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8497        if (iterator == null) {
8498            return false;
8499        }
8500        int current = getAccessibilitySelectionEnd();
8501        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8502            current = forward ? 0 : text.length();
8503        }
8504        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8505        if (range == null) {
8506            return false;
8507        }
8508        final int segmentStart = range[0];
8509        final int segmentEnd = range[1];
8510        int selectionStart;
8511        int selectionEnd;
8512        if (extendSelection && isAccessibilitySelectionExtendable()) {
8513            selectionStart = getAccessibilitySelectionStart();
8514            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8515                selectionStart = forward ? segmentStart : segmentEnd;
8516            }
8517            selectionEnd = forward ? segmentEnd : segmentStart;
8518        } else {
8519            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8520        }
8521        setAccessibilitySelection(selectionStart, selectionEnd);
8522        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8523                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8524        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8525        return true;
8526    }
8527
8528    /**
8529     * Gets the text reported for accessibility purposes.
8530     *
8531     * @return The accessibility text.
8532     *
8533     * @hide
8534     */
8535    public CharSequence getIterableTextForAccessibility() {
8536        return getContentDescription();
8537    }
8538
8539    /**
8540     * Gets whether accessibility selection can be extended.
8541     *
8542     * @return If selection is extensible.
8543     *
8544     * @hide
8545     */
8546    public boolean isAccessibilitySelectionExtendable() {
8547        return false;
8548    }
8549
8550    /**
8551     * @hide
8552     */
8553    public int getAccessibilitySelectionStart() {
8554        return mAccessibilityCursorPosition;
8555    }
8556
8557    /**
8558     * @hide
8559     */
8560    public int getAccessibilitySelectionEnd() {
8561        return getAccessibilitySelectionStart();
8562    }
8563
8564    /**
8565     * @hide
8566     */
8567    public void setAccessibilitySelection(int start, int end) {
8568        if (start ==  end && end == mAccessibilityCursorPosition) {
8569            return;
8570        }
8571        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8572            mAccessibilityCursorPosition = start;
8573        } else {
8574            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8575        }
8576        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8577    }
8578
8579    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8580            int fromIndex, int toIndex) {
8581        if (mParent == null) {
8582            return;
8583        }
8584        AccessibilityEvent event = AccessibilityEvent.obtain(
8585                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8586        onInitializeAccessibilityEvent(event);
8587        onPopulateAccessibilityEvent(event);
8588        event.setFromIndex(fromIndex);
8589        event.setToIndex(toIndex);
8590        event.setAction(action);
8591        event.setMovementGranularity(granularity);
8592        mParent.requestSendAccessibilityEvent(this, event);
8593    }
8594
8595    /**
8596     * @hide
8597     */
8598    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8599        switch (granularity) {
8600            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8601                CharSequence text = getIterableTextForAccessibility();
8602                if (text != null && text.length() > 0) {
8603                    CharacterTextSegmentIterator iterator =
8604                        CharacterTextSegmentIterator.getInstance(
8605                                mContext.getResources().getConfiguration().locale);
8606                    iterator.initialize(text.toString());
8607                    return iterator;
8608                }
8609            } break;
8610            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8611                CharSequence text = getIterableTextForAccessibility();
8612                if (text != null && text.length() > 0) {
8613                    WordTextSegmentIterator iterator =
8614                        WordTextSegmentIterator.getInstance(
8615                                mContext.getResources().getConfiguration().locale);
8616                    iterator.initialize(text.toString());
8617                    return iterator;
8618                }
8619            } break;
8620            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8621                CharSequence text = getIterableTextForAccessibility();
8622                if (text != null && text.length() > 0) {
8623                    ParagraphTextSegmentIterator iterator =
8624                        ParagraphTextSegmentIterator.getInstance();
8625                    iterator.initialize(text.toString());
8626                    return iterator;
8627                }
8628            } break;
8629        }
8630        return null;
8631    }
8632
8633    /**
8634     * @hide
8635     */
8636    public void dispatchStartTemporaryDetach() {
8637        onStartTemporaryDetach();
8638    }
8639
8640    /**
8641     * This is called when a container is going to temporarily detach a child, with
8642     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8643     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8644     * {@link #onDetachedFromWindow()} when the container is done.
8645     */
8646    public void onStartTemporaryDetach() {
8647        removeUnsetPressCallback();
8648        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8649    }
8650
8651    /**
8652     * @hide
8653     */
8654    public void dispatchFinishTemporaryDetach() {
8655        onFinishTemporaryDetach();
8656    }
8657
8658    /**
8659     * Called after {@link #onStartTemporaryDetach} when the container is done
8660     * changing the view.
8661     */
8662    public void onFinishTemporaryDetach() {
8663    }
8664
8665    /**
8666     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8667     * for this view's window.  Returns null if the view is not currently attached
8668     * to the window.  Normally you will not need to use this directly, but
8669     * just use the standard high-level event callbacks like
8670     * {@link #onKeyDown(int, KeyEvent)}.
8671     */
8672    public KeyEvent.DispatcherState getKeyDispatcherState() {
8673        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8674    }
8675
8676    /**
8677     * Dispatch a key event before it is processed by any input method
8678     * associated with the view hierarchy.  This can be used to intercept
8679     * key events in special situations before the IME consumes them; a
8680     * typical example would be handling the BACK key to update the application's
8681     * UI instead of allowing the IME to see it and close itself.
8682     *
8683     * @param event The key event to be dispatched.
8684     * @return True if the event was handled, false otherwise.
8685     */
8686    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8687        return onKeyPreIme(event.getKeyCode(), event);
8688    }
8689
8690    /**
8691     * Dispatch a key event to the next view on the focus path. This path runs
8692     * from the top of the view tree down to the currently focused view. If this
8693     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8694     * the next node down the focus path. This method also fires any key
8695     * listeners.
8696     *
8697     * @param event The key event to be dispatched.
8698     * @return True if the event was handled, false otherwise.
8699     */
8700    public boolean dispatchKeyEvent(KeyEvent event) {
8701        if (mInputEventConsistencyVerifier != null) {
8702            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8703        }
8704
8705        // Give any attached key listener a first crack at the event.
8706        //noinspection SimplifiableIfStatement
8707        ListenerInfo li = mListenerInfo;
8708        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8709                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8710            return true;
8711        }
8712
8713        if (event.dispatch(this, mAttachInfo != null
8714                ? mAttachInfo.mKeyDispatchState : null, this)) {
8715            return true;
8716        }
8717
8718        if (mInputEventConsistencyVerifier != null) {
8719            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8720        }
8721        return false;
8722    }
8723
8724    /**
8725     * Dispatches a key shortcut event.
8726     *
8727     * @param event The key event to be dispatched.
8728     * @return True if the event was handled by the view, false otherwise.
8729     */
8730    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8731        return onKeyShortcut(event.getKeyCode(), event);
8732    }
8733
8734    /**
8735     * Pass the touch screen motion event down to the target view, or this
8736     * view if it is the target.
8737     *
8738     * @param event The motion event to be dispatched.
8739     * @return True if the event was handled by the view, false otherwise.
8740     */
8741    public boolean dispatchTouchEvent(MotionEvent event) {
8742        // If the event should be handled by accessibility focus first.
8743        if (event.isTargetAccessibilityFocus()) {
8744            // We don't have focus or no virtual descendant has it, do not handle the event.
8745            if (!isAccessibilityFocusedViewOrHost()) {
8746                return false;
8747            }
8748            // We have focus and got the event, then use normal event dispatch.
8749            event.setTargetAccessibilityFocus(false);
8750        }
8751
8752        boolean result = false;
8753
8754        if (mInputEventConsistencyVerifier != null) {
8755            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8756        }
8757
8758        final int actionMasked = event.getActionMasked();
8759        if (actionMasked == MotionEvent.ACTION_DOWN) {
8760            // Defensive cleanup for new gesture
8761            stopNestedScroll();
8762        }
8763
8764        if (onFilterTouchEventForSecurity(event)) {
8765            //noinspection SimplifiableIfStatement
8766            ListenerInfo li = mListenerInfo;
8767            if (li != null && li.mOnTouchListener != null
8768                    && (mViewFlags & ENABLED_MASK) == ENABLED
8769                    && li.mOnTouchListener.onTouch(this, event)) {
8770                result = true;
8771            }
8772
8773            if (!result && onTouchEvent(event)) {
8774                result = true;
8775            }
8776        }
8777
8778        if (!result && mInputEventConsistencyVerifier != null) {
8779            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8780        }
8781
8782        // Clean up after nested scrolls if this is the end of a gesture;
8783        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8784        // of the gesture.
8785        if (actionMasked == MotionEvent.ACTION_UP ||
8786                actionMasked == MotionEvent.ACTION_CANCEL ||
8787                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8788            stopNestedScroll();
8789        }
8790
8791        return result;
8792    }
8793
8794    boolean isAccessibilityFocusedViewOrHost() {
8795        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
8796                .getAccessibilityFocusedHost() == this);
8797    }
8798
8799    /**
8800     * Filter the touch event to apply security policies.
8801     *
8802     * @param event The motion event to be filtered.
8803     * @return True if the event should be dispatched, false if the event should be dropped.
8804     *
8805     * @see #getFilterTouchesWhenObscured
8806     */
8807    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8808        //noinspection RedundantIfStatement
8809        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8810                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8811            // Window is obscured, drop this touch.
8812            return false;
8813        }
8814        return true;
8815    }
8816
8817    /**
8818     * Pass a trackball motion event down to the focused view.
8819     *
8820     * @param event The motion event to be dispatched.
8821     * @return True if the event was handled by the view, false otherwise.
8822     */
8823    public boolean dispatchTrackballEvent(MotionEvent event) {
8824        if (mInputEventConsistencyVerifier != null) {
8825            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8826        }
8827
8828        return onTrackballEvent(event);
8829    }
8830
8831    /**
8832     * Dispatch a generic motion event.
8833     * <p>
8834     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8835     * are delivered to the view under the pointer.  All other generic motion events are
8836     * delivered to the focused view.  Hover events are handled specially and are delivered
8837     * to {@link #onHoverEvent(MotionEvent)}.
8838     * </p>
8839     *
8840     * @param event The motion event to be dispatched.
8841     * @return True if the event was handled by the view, false otherwise.
8842     */
8843    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8844        if (mInputEventConsistencyVerifier != null) {
8845            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8846        }
8847
8848        final int source = event.getSource();
8849        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8850            final int action = event.getAction();
8851            if (action == MotionEvent.ACTION_HOVER_ENTER
8852                    || action == MotionEvent.ACTION_HOVER_MOVE
8853                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8854                if (dispatchHoverEvent(event)) {
8855                    return true;
8856                }
8857            } else if (dispatchGenericPointerEvent(event)) {
8858                return true;
8859            }
8860        } else if (dispatchGenericFocusedEvent(event)) {
8861            return true;
8862        }
8863
8864        if (dispatchGenericMotionEventInternal(event)) {
8865            return true;
8866        }
8867
8868        if (mInputEventConsistencyVerifier != null) {
8869            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8870        }
8871        return false;
8872    }
8873
8874    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8875        //noinspection SimplifiableIfStatement
8876        ListenerInfo li = mListenerInfo;
8877        if (li != null && li.mOnGenericMotionListener != null
8878                && (mViewFlags & ENABLED_MASK) == ENABLED
8879                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8880            return true;
8881        }
8882
8883        if (onGenericMotionEvent(event)) {
8884            return true;
8885        }
8886
8887        if (mInputEventConsistencyVerifier != null) {
8888            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8889        }
8890        return false;
8891    }
8892
8893    /**
8894     * Dispatch a hover event.
8895     * <p>
8896     * Do not call this method directly.
8897     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8898     * </p>
8899     *
8900     * @param event The motion event to be dispatched.
8901     * @return True if the event was handled by the view, false otherwise.
8902     */
8903    protected boolean dispatchHoverEvent(MotionEvent event) {
8904        ListenerInfo li = mListenerInfo;
8905        //noinspection SimplifiableIfStatement
8906        if (li != null && li.mOnHoverListener != null
8907                && (mViewFlags & ENABLED_MASK) == ENABLED
8908                && li.mOnHoverListener.onHover(this, event)) {
8909            return true;
8910        }
8911
8912        return onHoverEvent(event);
8913    }
8914
8915    /**
8916     * Returns true if the view has a child to which it has recently sent
8917     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8918     * it does not have a hovered child, then it must be the innermost hovered view.
8919     * @hide
8920     */
8921    protected boolean hasHoveredChild() {
8922        return false;
8923    }
8924
8925    /**
8926     * Dispatch a generic motion event to the view under the first pointer.
8927     * <p>
8928     * Do not call this method directly.
8929     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8930     * </p>
8931     *
8932     * @param event The motion event to be dispatched.
8933     * @return True if the event was handled by the view, false otherwise.
8934     */
8935    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8936        return false;
8937    }
8938
8939    /**
8940     * Dispatch a generic motion event to the currently focused view.
8941     * <p>
8942     * Do not call this method directly.
8943     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8944     * </p>
8945     *
8946     * @param event The motion event to be dispatched.
8947     * @return True if the event was handled by the view, false otherwise.
8948     */
8949    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8950        return false;
8951    }
8952
8953    /**
8954     * Dispatch a pointer event.
8955     * <p>
8956     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8957     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8958     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8959     * and should not be expected to handle other pointing device features.
8960     * </p>
8961     *
8962     * @param event The motion event to be dispatched.
8963     * @return True if the event was handled by the view, false otherwise.
8964     * @hide
8965     */
8966    public final boolean dispatchPointerEvent(MotionEvent event) {
8967        if (event.isTouchEvent()) {
8968            return dispatchTouchEvent(event);
8969        } else {
8970            return dispatchGenericMotionEvent(event);
8971        }
8972    }
8973
8974    /**
8975     * Called when the window containing this view gains or loses window focus.
8976     * ViewGroups should override to route to their children.
8977     *
8978     * @param hasFocus True if the window containing this view now has focus,
8979     *        false otherwise.
8980     */
8981    public void dispatchWindowFocusChanged(boolean hasFocus) {
8982        onWindowFocusChanged(hasFocus);
8983    }
8984
8985    /**
8986     * Called when the window containing this view gains or loses focus.  Note
8987     * that this is separate from view focus: to receive key events, both
8988     * your view and its window must have focus.  If a window is displayed
8989     * on top of yours that takes input focus, then your own window will lose
8990     * focus but the view focus will remain unchanged.
8991     *
8992     * @param hasWindowFocus True if the window containing this view now has
8993     *        focus, false otherwise.
8994     */
8995    public void onWindowFocusChanged(boolean hasWindowFocus) {
8996        InputMethodManager imm = InputMethodManager.peekInstance();
8997        if (!hasWindowFocus) {
8998            if (isPressed()) {
8999                setPressed(false);
9000            }
9001            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9002                imm.focusOut(this);
9003            }
9004            removeLongPressCallback();
9005            removeTapCallback();
9006            onFocusLost();
9007        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9008            imm.focusIn(this);
9009        }
9010        refreshDrawableState();
9011    }
9012
9013    /**
9014     * Returns true if this view is in a window that currently has window focus.
9015     * Note that this is not the same as the view itself having focus.
9016     *
9017     * @return True if this view is in a window that currently has window focus.
9018     */
9019    public boolean hasWindowFocus() {
9020        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9021    }
9022
9023    /**
9024     * Dispatch a view visibility change down the view hierarchy.
9025     * ViewGroups should override to route to their children.
9026     * @param changedView The view whose visibility changed. Could be 'this' or
9027     * an ancestor view.
9028     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9029     * {@link #INVISIBLE} or {@link #GONE}.
9030     */
9031    protected void dispatchVisibilityChanged(@NonNull View changedView,
9032            @Visibility int visibility) {
9033        onVisibilityChanged(changedView, visibility);
9034    }
9035
9036    /**
9037     * Called when the visibility of the view or an ancestor of the view has
9038     * changed.
9039     *
9040     * @param changedView The view whose visibility changed. May be
9041     *                    {@code this} or an ancestor view.
9042     * @param visibility The new visibility, one of {@link #VISIBLE},
9043     *                   {@link #INVISIBLE} or {@link #GONE}.
9044     */
9045    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9046        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9047        if (visible) {
9048            if (mAttachInfo != null) {
9049                initialAwakenScrollBars();
9050            } else {
9051                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
9052            }
9053        }
9054
9055        final Drawable dr = mBackground;
9056        if (dr != null && visible != dr.isVisible()) {
9057            dr.setVisible(visible, false);
9058        }
9059        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9060        if (fg != null && visible != fg.isVisible()) {
9061            fg.setVisible(visible, false);
9062        }
9063    }
9064
9065    /**
9066     * Dispatch a hint about whether this view is displayed. For instance, when
9067     * a View moves out of the screen, it might receives a display hint indicating
9068     * the view is not displayed. Applications should not <em>rely</em> on this hint
9069     * as there is no guarantee that they will receive one.
9070     *
9071     * @param hint A hint about whether or not this view is displayed:
9072     * {@link #VISIBLE} or {@link #INVISIBLE}.
9073     */
9074    public void dispatchDisplayHint(@Visibility int hint) {
9075        onDisplayHint(hint);
9076    }
9077
9078    /**
9079     * Gives this view a hint about whether is displayed or not. For instance, when
9080     * a View moves out of the screen, it might receives a display hint indicating
9081     * the view is not displayed. Applications should not <em>rely</em> on this hint
9082     * as there is no guarantee that they will receive one.
9083     *
9084     * @param hint A hint about whether or not this view is displayed:
9085     * {@link #VISIBLE} or {@link #INVISIBLE}.
9086     */
9087    protected void onDisplayHint(@Visibility int hint) {
9088    }
9089
9090    /**
9091     * Dispatch a window visibility change down the view hierarchy.
9092     * ViewGroups should override to route to their children.
9093     *
9094     * @param visibility The new visibility of the window.
9095     *
9096     * @see #onWindowVisibilityChanged(int)
9097     */
9098    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9099        onWindowVisibilityChanged(visibility);
9100    }
9101
9102    /**
9103     * Called when the window containing has change its visibility
9104     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9105     * that this tells you whether or not your window is being made visible
9106     * to the window manager; this does <em>not</em> tell you whether or not
9107     * your window is obscured by other windows on the screen, even if it
9108     * is itself visible.
9109     *
9110     * @param visibility The new visibility of the window.
9111     */
9112    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9113        if (visibility == VISIBLE) {
9114            initialAwakenScrollBars();
9115        }
9116    }
9117
9118    /**
9119     * Returns the current visibility of the window this view is attached to
9120     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9121     *
9122     * @return Returns the current visibility of the view's window.
9123     */
9124    @Visibility
9125    public int getWindowVisibility() {
9126        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9127    }
9128
9129    /**
9130     * Retrieve the overall visible display size in which the window this view is
9131     * attached to has been positioned in.  This takes into account screen
9132     * decorations above the window, for both cases where the window itself
9133     * is being position inside of them or the window is being placed under
9134     * then and covered insets are used for the window to position its content
9135     * inside.  In effect, this tells you the available area where content can
9136     * be placed and remain visible to users.
9137     *
9138     * <p>This function requires an IPC back to the window manager to retrieve
9139     * the requested information, so should not be used in performance critical
9140     * code like drawing.
9141     *
9142     * @param outRect Filled in with the visible display frame.  If the view
9143     * is not attached to a window, this is simply the raw display size.
9144     */
9145    public void getWindowVisibleDisplayFrame(Rect outRect) {
9146        if (mAttachInfo != null) {
9147            try {
9148                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9149            } catch (RemoteException e) {
9150                return;
9151            }
9152            // XXX This is really broken, and probably all needs to be done
9153            // in the window manager, and we need to know more about whether
9154            // we want the area behind or in front of the IME.
9155            final Rect insets = mAttachInfo.mVisibleInsets;
9156            outRect.left += insets.left;
9157            outRect.top += insets.top;
9158            outRect.right -= insets.right;
9159            outRect.bottom -= insets.bottom;
9160            return;
9161        }
9162        // The view is not attached to a display so we don't have a context.
9163        // Make a best guess about the display size.
9164        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9165        d.getRectSize(outRect);
9166    }
9167
9168    /**
9169     * Dispatch a notification about a resource configuration change down
9170     * the view hierarchy.
9171     * ViewGroups should override to route to their children.
9172     *
9173     * @param newConfig The new resource configuration.
9174     *
9175     * @see #onConfigurationChanged(android.content.res.Configuration)
9176     */
9177    public void dispatchConfigurationChanged(Configuration newConfig) {
9178        onConfigurationChanged(newConfig);
9179    }
9180
9181    /**
9182     * Called when the current configuration of the resources being used
9183     * by the application have changed.  You can use this to decide when
9184     * to reload resources that can changed based on orientation and other
9185     * configuration characteristics.  You only need to use this if you are
9186     * not relying on the normal {@link android.app.Activity} mechanism of
9187     * recreating the activity instance upon a configuration change.
9188     *
9189     * @param newConfig The new resource configuration.
9190     */
9191    protected void onConfigurationChanged(Configuration newConfig) {
9192    }
9193
9194    /**
9195     * Private function to aggregate all per-view attributes in to the view
9196     * root.
9197     */
9198    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9199        performCollectViewAttributes(attachInfo, visibility);
9200    }
9201
9202    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9203        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9204            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9205                attachInfo.mKeepScreenOn = true;
9206            }
9207            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9208            ListenerInfo li = mListenerInfo;
9209            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9210                attachInfo.mHasSystemUiListeners = true;
9211            }
9212        }
9213    }
9214
9215    void needGlobalAttributesUpdate(boolean force) {
9216        final AttachInfo ai = mAttachInfo;
9217        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9218            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9219                    || ai.mHasSystemUiListeners) {
9220                ai.mRecomputeGlobalAttributes = true;
9221            }
9222        }
9223    }
9224
9225    /**
9226     * Returns whether the device is currently in touch mode.  Touch mode is entered
9227     * once the user begins interacting with the device by touch, and affects various
9228     * things like whether focus is always visible to the user.
9229     *
9230     * @return Whether the device is in touch mode.
9231     */
9232    @ViewDebug.ExportedProperty
9233    public boolean isInTouchMode() {
9234        if (mAttachInfo != null) {
9235            return mAttachInfo.mInTouchMode;
9236        } else {
9237            return ViewRootImpl.isInTouchMode();
9238        }
9239    }
9240
9241    /**
9242     * Returns the context the view is running in, through which it can
9243     * access the current theme, resources, etc.
9244     *
9245     * @return The view's Context.
9246     */
9247    @ViewDebug.CapturedViewProperty
9248    public final Context getContext() {
9249        return mContext;
9250    }
9251
9252    /**
9253     * Handle a key event before it is processed by any input method
9254     * associated with the view hierarchy.  This can be used to intercept
9255     * key events in special situations before the IME consumes them; a
9256     * typical example would be handling the BACK key to update the application's
9257     * UI instead of allowing the IME to see it and close itself.
9258     *
9259     * @param keyCode The value in event.getKeyCode().
9260     * @param event Description of the key event.
9261     * @return If you handled the event, return true. If you want to allow the
9262     *         event to be handled by the next receiver, return false.
9263     */
9264    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9265        return false;
9266    }
9267
9268    /**
9269     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9270     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9271     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9272     * is released, if the view is enabled and clickable.
9273     *
9274     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9275     * although some may elect to do so in some situations. Do not rely on this to
9276     * catch software key presses.
9277     *
9278     * @param keyCode A key code that represents the button pressed, from
9279     *                {@link android.view.KeyEvent}.
9280     * @param event   The KeyEvent object that defines the button action.
9281     */
9282    public boolean onKeyDown(int keyCode, KeyEvent event) {
9283        boolean result = false;
9284
9285        if (KeyEvent.isConfirmKey(keyCode)) {
9286            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9287                return true;
9288            }
9289            // Long clickable items don't necessarily have to be clickable
9290            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9291                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9292                    (event.getRepeatCount() == 0)) {
9293                setPressed(true);
9294                checkForLongClick(0);
9295                return true;
9296            }
9297        }
9298        return result;
9299    }
9300
9301    /**
9302     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9303     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9304     * the event).
9305     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9306     * although some may elect to do so in some situations. Do not rely on this to
9307     * catch software key presses.
9308     */
9309    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9310        return false;
9311    }
9312
9313    /**
9314     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9315     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9316     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9317     * {@link KeyEvent#KEYCODE_ENTER} is released.
9318     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9319     * although some may elect to do so in some situations. Do not rely on this to
9320     * catch software key presses.
9321     *
9322     * @param keyCode A key code that represents the button pressed, from
9323     *                {@link android.view.KeyEvent}.
9324     * @param event   The KeyEvent object that defines the button action.
9325     */
9326    public boolean onKeyUp(int keyCode, KeyEvent event) {
9327        if (KeyEvent.isConfirmKey(keyCode)) {
9328            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9329                return true;
9330            }
9331            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9332                setPressed(false);
9333
9334                if (!mHasPerformedLongPress) {
9335                    // This is a tap, so remove the longpress check
9336                    removeLongPressCallback();
9337                    return performClick();
9338                }
9339            }
9340        }
9341        return false;
9342    }
9343
9344    /**
9345     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9346     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9347     * the event).
9348     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9349     * although some may elect to do so in some situations. Do not rely on this to
9350     * catch software key presses.
9351     *
9352     * @param keyCode     A key code that represents the button pressed, from
9353     *                    {@link android.view.KeyEvent}.
9354     * @param repeatCount The number of times the action was made.
9355     * @param event       The KeyEvent object that defines the button action.
9356     */
9357    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9358        return false;
9359    }
9360
9361    /**
9362     * Called on the focused view when a key shortcut event is not handled.
9363     * Override this method to implement local key shortcuts for the View.
9364     * Key shortcuts can also be implemented by setting the
9365     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9366     *
9367     * @param keyCode The value in event.getKeyCode().
9368     * @param event Description of the key event.
9369     * @return If you handled the event, return true. If you want to allow the
9370     *         event to be handled by the next receiver, return false.
9371     */
9372    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9373        return false;
9374    }
9375
9376    /**
9377     * Check whether the called view is a text editor, in which case it
9378     * would make sense to automatically display a soft input window for
9379     * it.  Subclasses should override this if they implement
9380     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9381     * a call on that method would return a non-null InputConnection, and
9382     * they are really a first-class editor that the user would normally
9383     * start typing on when the go into a window containing your view.
9384     *
9385     * <p>The default implementation always returns false.  This does
9386     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9387     * will not be called or the user can not otherwise perform edits on your
9388     * view; it is just a hint to the system that this is not the primary
9389     * purpose of this view.
9390     *
9391     * @return Returns true if this view is a text editor, else false.
9392     */
9393    public boolean onCheckIsTextEditor() {
9394        return false;
9395    }
9396
9397    /**
9398     * Create a new InputConnection for an InputMethod to interact
9399     * with the view.  The default implementation returns null, since it doesn't
9400     * support input methods.  You can override this to implement such support.
9401     * This is only needed for views that take focus and text input.
9402     *
9403     * <p>When implementing this, you probably also want to implement
9404     * {@link #onCheckIsTextEditor()} to indicate you will return a
9405     * non-null InputConnection.</p>
9406     *
9407     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9408     * object correctly and in its entirety, so that the connected IME can rely
9409     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9410     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9411     * must be filled in with the correct cursor position for IMEs to work correctly
9412     * with your application.</p>
9413     *
9414     * @param outAttrs Fill in with attribute information about the connection.
9415     */
9416    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9417        return null;
9418    }
9419
9420    /**
9421     * Called by the {@link android.view.inputmethod.InputMethodManager}
9422     * when a view who is not the current
9423     * input connection target is trying to make a call on the manager.  The
9424     * default implementation returns false; you can override this to return
9425     * true for certain views if you are performing InputConnection proxying
9426     * to them.
9427     * @param view The View that is making the InputMethodManager call.
9428     * @return Return true to allow the call, false to reject.
9429     */
9430    public boolean checkInputConnectionProxy(View view) {
9431        return false;
9432    }
9433
9434    /**
9435     * Show the context menu for this view. It is not safe to hold on to the
9436     * menu after returning from this method.
9437     *
9438     * You should normally not overload this method. Overload
9439     * {@link #onCreateContextMenu(ContextMenu)} or define an
9440     * {@link OnCreateContextMenuListener} to add items to the context menu.
9441     *
9442     * @param menu The context menu to populate
9443     */
9444    public void createContextMenu(ContextMenu menu) {
9445        ContextMenuInfo menuInfo = getContextMenuInfo();
9446
9447        // Sets the current menu info so all items added to menu will have
9448        // my extra info set.
9449        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9450
9451        onCreateContextMenu(menu);
9452        ListenerInfo li = mListenerInfo;
9453        if (li != null && li.mOnCreateContextMenuListener != null) {
9454            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9455        }
9456
9457        // Clear the extra information so subsequent items that aren't mine don't
9458        // have my extra info.
9459        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9460
9461        if (mParent != null) {
9462            mParent.createContextMenu(menu);
9463        }
9464    }
9465
9466    /**
9467     * Views should implement this if they have extra information to associate
9468     * with the context menu. The return result is supplied as a parameter to
9469     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9470     * callback.
9471     *
9472     * @return Extra information about the item for which the context menu
9473     *         should be shown. This information will vary across different
9474     *         subclasses of View.
9475     */
9476    protected ContextMenuInfo getContextMenuInfo() {
9477        return null;
9478    }
9479
9480    /**
9481     * Views should implement this if the view itself is going to add items to
9482     * the context menu.
9483     *
9484     * @param menu the context menu to populate
9485     */
9486    protected void onCreateContextMenu(ContextMenu menu) {
9487    }
9488
9489    /**
9490     * Implement this method to handle trackball motion events.  The
9491     * <em>relative</em> movement of the trackball since the last event
9492     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9493     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9494     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9495     * they will often be fractional values, representing the more fine-grained
9496     * movement information available from a trackball).
9497     *
9498     * @param event The motion event.
9499     * @return True if the event was handled, false otherwise.
9500     */
9501    public boolean onTrackballEvent(MotionEvent event) {
9502        return false;
9503    }
9504
9505    /**
9506     * Implement this method to handle generic motion events.
9507     * <p>
9508     * Generic motion events describe joystick movements, mouse hovers, track pad
9509     * touches, scroll wheel movements and other input events.  The
9510     * {@link MotionEvent#getSource() source} of the motion event specifies
9511     * the class of input that was received.  Implementations of this method
9512     * must examine the bits in the source before processing the event.
9513     * The following code example shows how this is done.
9514     * </p><p>
9515     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9516     * are delivered to the view under the pointer.  All other generic motion events are
9517     * delivered to the focused view.
9518     * </p>
9519     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9520     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9521     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9522     *             // process the joystick movement...
9523     *             return true;
9524     *         }
9525     *     }
9526     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9527     *         switch (event.getAction()) {
9528     *             case MotionEvent.ACTION_HOVER_MOVE:
9529     *                 // process the mouse hover movement...
9530     *                 return true;
9531     *             case MotionEvent.ACTION_SCROLL:
9532     *                 // process the scroll wheel movement...
9533     *                 return true;
9534     *         }
9535     *     }
9536     *     return super.onGenericMotionEvent(event);
9537     * }</pre>
9538     *
9539     * @param event The generic motion event being processed.
9540     * @return True if the event was handled, false otherwise.
9541     */
9542    public boolean onGenericMotionEvent(MotionEvent event) {
9543        return false;
9544    }
9545
9546    /**
9547     * Implement this method to handle hover events.
9548     * <p>
9549     * This method is called whenever a pointer is hovering into, over, or out of the
9550     * bounds of a view and the view is not currently being touched.
9551     * Hover events are represented as pointer events with action
9552     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9553     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9554     * </p>
9555     * <ul>
9556     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9557     * when the pointer enters the bounds of the view.</li>
9558     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9559     * when the pointer has already entered the bounds of the view and has moved.</li>
9560     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9561     * when the pointer has exited the bounds of the view or when the pointer is
9562     * about to go down due to a button click, tap, or similar user action that
9563     * causes the view to be touched.</li>
9564     * </ul>
9565     * <p>
9566     * The view should implement this method to return true to indicate that it is
9567     * handling the hover event, such as by changing its drawable state.
9568     * </p><p>
9569     * The default implementation calls {@link #setHovered} to update the hovered state
9570     * of the view when a hover enter or hover exit event is received, if the view
9571     * is enabled and is clickable.  The default implementation also sends hover
9572     * accessibility events.
9573     * </p>
9574     *
9575     * @param event The motion event that describes the hover.
9576     * @return True if the view handled the hover event.
9577     *
9578     * @see #isHovered
9579     * @see #setHovered
9580     * @see #onHoverChanged
9581     */
9582    public boolean onHoverEvent(MotionEvent event) {
9583        // The root view may receive hover (or touch) events that are outside the bounds of
9584        // the window.  This code ensures that we only send accessibility events for
9585        // hovers that are actually within the bounds of the root view.
9586        final int action = event.getActionMasked();
9587        if (!mSendingHoverAccessibilityEvents) {
9588            if ((action == MotionEvent.ACTION_HOVER_ENTER
9589                    || action == MotionEvent.ACTION_HOVER_MOVE)
9590                    && !hasHoveredChild()
9591                    && pointInView(event.getX(), event.getY())) {
9592                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9593                mSendingHoverAccessibilityEvents = true;
9594            }
9595        } else {
9596            if (action == MotionEvent.ACTION_HOVER_EXIT
9597                    || (action == MotionEvent.ACTION_MOVE
9598                            && !pointInView(event.getX(), event.getY()))) {
9599                mSendingHoverAccessibilityEvents = false;
9600                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9601            }
9602        }
9603
9604        if (isHoverable()) {
9605            switch (action) {
9606                case MotionEvent.ACTION_HOVER_ENTER:
9607                    setHovered(true);
9608                    break;
9609                case MotionEvent.ACTION_HOVER_EXIT:
9610                    setHovered(false);
9611                    break;
9612            }
9613
9614            // Dispatch the event to onGenericMotionEvent before returning true.
9615            // This is to provide compatibility with existing applications that
9616            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9617            // break because of the new default handling for hoverable views
9618            // in onHoverEvent.
9619            // Note that onGenericMotionEvent will be called by default when
9620            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9621            dispatchGenericMotionEventInternal(event);
9622            // The event was already handled by calling setHovered(), so always
9623            // return true.
9624            return true;
9625        }
9626
9627        return false;
9628    }
9629
9630    /**
9631     * Returns true if the view should handle {@link #onHoverEvent}
9632     * by calling {@link #setHovered} to change its hovered state.
9633     *
9634     * @return True if the view is hoverable.
9635     */
9636    private boolean isHoverable() {
9637        final int viewFlags = mViewFlags;
9638        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9639            return false;
9640        }
9641
9642        return (viewFlags & CLICKABLE) == CLICKABLE
9643                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9644    }
9645
9646    /**
9647     * Returns true if the view is currently hovered.
9648     *
9649     * @return True if the view is currently hovered.
9650     *
9651     * @see #setHovered
9652     * @see #onHoverChanged
9653     */
9654    @ViewDebug.ExportedProperty
9655    public boolean isHovered() {
9656        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9657    }
9658
9659    /**
9660     * Sets whether the view is currently hovered.
9661     * <p>
9662     * Calling this method also changes the drawable state of the view.  This
9663     * enables the view to react to hover by using different drawable resources
9664     * to change its appearance.
9665     * </p><p>
9666     * The {@link #onHoverChanged} method is called when the hovered state changes.
9667     * </p>
9668     *
9669     * @param hovered True if the view is hovered.
9670     *
9671     * @see #isHovered
9672     * @see #onHoverChanged
9673     */
9674    public void setHovered(boolean hovered) {
9675        if (hovered) {
9676            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9677                mPrivateFlags |= PFLAG_HOVERED;
9678                refreshDrawableState();
9679                onHoverChanged(true);
9680            }
9681        } else {
9682            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9683                mPrivateFlags &= ~PFLAG_HOVERED;
9684                refreshDrawableState();
9685                onHoverChanged(false);
9686            }
9687        }
9688    }
9689
9690    /**
9691     * Implement this method to handle hover state changes.
9692     * <p>
9693     * This method is called whenever the hover state changes as a result of a
9694     * call to {@link #setHovered}.
9695     * </p>
9696     *
9697     * @param hovered The current hover state, as returned by {@link #isHovered}.
9698     *
9699     * @see #isHovered
9700     * @see #setHovered
9701     */
9702    public void onHoverChanged(boolean hovered) {
9703    }
9704
9705    /**
9706     * Implement this method to handle touch screen motion events.
9707     * <p>
9708     * If this method is used to detect click actions, it is recommended that
9709     * the actions be performed by implementing and calling
9710     * {@link #performClick()}. This will ensure consistent system behavior,
9711     * including:
9712     * <ul>
9713     * <li>obeying click sound preferences
9714     * <li>dispatching OnClickListener calls
9715     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9716     * accessibility features are enabled
9717     * </ul>
9718     *
9719     * @param event The motion event.
9720     * @return True if the event was handled, false otherwise.
9721     */
9722    public boolean onTouchEvent(MotionEvent event) {
9723        final float x = event.getX();
9724        final float y = event.getY();
9725        final int viewFlags = mViewFlags;
9726
9727        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9728            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9729                setPressed(false);
9730            }
9731            // A disabled view that is clickable still consumes the touch
9732            // events, it just doesn't respond to them.
9733            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9734                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9735        }
9736
9737        if (mTouchDelegate != null) {
9738            if (mTouchDelegate.onTouchEvent(event)) {
9739                return true;
9740            }
9741        }
9742
9743        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9744                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9745            switch (event.getAction()) {
9746                case MotionEvent.ACTION_UP:
9747                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9748                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9749                        // take focus if we don't have it already and we should in
9750                        // touch mode.
9751                        boolean focusTaken = false;
9752                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9753                            focusTaken = requestFocus();
9754                        }
9755
9756                        if (prepressed) {
9757                            // The button is being released before we actually
9758                            // showed it as pressed.  Make it show the pressed
9759                            // state now (before scheduling the click) to ensure
9760                            // the user sees it.
9761                            setPressed(true, x, y);
9762                       }
9763
9764                        if (!mHasPerformedLongPress) {
9765                            // This is a tap, so remove the longpress check
9766                            removeLongPressCallback();
9767
9768                            // Only perform take click actions if we were in the pressed state
9769                            if (!focusTaken) {
9770                                // Use a Runnable and post this rather than calling
9771                                // performClick directly. This lets other visual state
9772                                // of the view update before click actions start.
9773                                if (mPerformClick == null) {
9774                                    mPerformClick = new PerformClick();
9775                                }
9776                                if (!post(mPerformClick)) {
9777                                    performClick();
9778                                }
9779                            }
9780                        }
9781
9782                        if (mUnsetPressedState == null) {
9783                            mUnsetPressedState = new UnsetPressedState();
9784                        }
9785
9786                        if (prepressed) {
9787                            postDelayed(mUnsetPressedState,
9788                                    ViewConfiguration.getPressedStateDuration());
9789                        } else if (!post(mUnsetPressedState)) {
9790                            // If the post failed, unpress right now
9791                            mUnsetPressedState.run();
9792                        }
9793
9794                        removeTapCallback();
9795                    }
9796                    break;
9797
9798                case MotionEvent.ACTION_DOWN:
9799                    mHasPerformedLongPress = false;
9800
9801                    if (performButtonActionOnTouchDown(event)) {
9802                        break;
9803                    }
9804
9805                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9806                    boolean isInScrollingContainer = isInScrollingContainer();
9807
9808                    // For views inside a scrolling container, delay the pressed feedback for
9809                    // a short period in case this is a scroll.
9810                    if (isInScrollingContainer) {
9811                        mPrivateFlags |= PFLAG_PREPRESSED;
9812                        if (mPendingCheckForTap == null) {
9813                            mPendingCheckForTap = new CheckForTap();
9814                        }
9815                        mPendingCheckForTap.x = event.getX();
9816                        mPendingCheckForTap.y = event.getY();
9817                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9818                    } else {
9819                        // Not inside a scrolling container, so show the feedback right away
9820                        setPressed(true, x, y);
9821                        checkForLongClick(0);
9822                    }
9823                    break;
9824
9825                case MotionEvent.ACTION_CANCEL:
9826                    setPressed(false);
9827                    removeTapCallback();
9828                    removeLongPressCallback();
9829                    break;
9830
9831                case MotionEvent.ACTION_MOVE:
9832                    drawableHotspotChanged(x, y);
9833
9834                    // Be lenient about moving outside of buttons
9835                    if (!pointInView(x, y, mTouchSlop)) {
9836                        // Outside button
9837                        removeTapCallback();
9838                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9839                            // Remove any future long press/tap checks
9840                            removeLongPressCallback();
9841
9842                            setPressed(false);
9843                        }
9844                    }
9845                    break;
9846            }
9847
9848            return true;
9849        }
9850
9851        return false;
9852    }
9853
9854    /**
9855     * @hide
9856     */
9857    public boolean isInScrollingContainer() {
9858        ViewParent p = getParent();
9859        while (p != null && p instanceof ViewGroup) {
9860            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9861                return true;
9862            }
9863            p = p.getParent();
9864        }
9865        return false;
9866    }
9867
9868    /**
9869     * Remove the longpress detection timer.
9870     */
9871    private void removeLongPressCallback() {
9872        if (mPendingCheckForLongPress != null) {
9873          removeCallbacks(mPendingCheckForLongPress);
9874        }
9875    }
9876
9877    /**
9878     * Remove the pending click action
9879     */
9880    private void removePerformClickCallback() {
9881        if (mPerformClick != null) {
9882            removeCallbacks(mPerformClick);
9883        }
9884    }
9885
9886    /**
9887     * Remove the prepress detection timer.
9888     */
9889    private void removeUnsetPressCallback() {
9890        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9891            setPressed(false);
9892            removeCallbacks(mUnsetPressedState);
9893        }
9894    }
9895
9896    /**
9897     * Remove the tap detection timer.
9898     */
9899    private void removeTapCallback() {
9900        if (mPendingCheckForTap != null) {
9901            mPrivateFlags &= ~PFLAG_PREPRESSED;
9902            removeCallbacks(mPendingCheckForTap);
9903        }
9904    }
9905
9906    /**
9907     * Cancels a pending long press.  Your subclass can use this if you
9908     * want the context menu to come up if the user presses and holds
9909     * at the same place, but you don't want it to come up if they press
9910     * and then move around enough to cause scrolling.
9911     */
9912    public void cancelLongPress() {
9913        removeLongPressCallback();
9914
9915        /*
9916         * The prepressed state handled by the tap callback is a display
9917         * construct, but the tap callback will post a long press callback
9918         * less its own timeout. Remove it here.
9919         */
9920        removeTapCallback();
9921    }
9922
9923    /**
9924     * Remove the pending callback for sending a
9925     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9926     */
9927    private void removeSendViewScrolledAccessibilityEventCallback() {
9928        if (mSendViewScrolledAccessibilityEvent != null) {
9929            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9930            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9931        }
9932    }
9933
9934    /**
9935     * Sets the TouchDelegate for this View.
9936     */
9937    public void setTouchDelegate(TouchDelegate delegate) {
9938        mTouchDelegate = delegate;
9939    }
9940
9941    /**
9942     * Gets the TouchDelegate for this View.
9943     */
9944    public TouchDelegate getTouchDelegate() {
9945        return mTouchDelegate;
9946    }
9947
9948    /**
9949     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9950     *
9951     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9952     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9953     * available. This method should only be called for touch events.
9954     *
9955     * <p class="note">This api is not intended for most applications. Buffered dispatch
9956     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9957     * streams will not improve your input latency. Side effects include: increased latency,
9958     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9959     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9960     * you.</p>
9961     */
9962    public final void requestUnbufferedDispatch(MotionEvent event) {
9963        final int action = event.getAction();
9964        if (mAttachInfo == null
9965                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9966                || !event.isTouchEvent()) {
9967            return;
9968        }
9969        mAttachInfo.mUnbufferedDispatchRequested = true;
9970    }
9971
9972    /**
9973     * Set flags controlling behavior of this view.
9974     *
9975     * @param flags Constant indicating the value which should be set
9976     * @param mask Constant indicating the bit range that should be changed
9977     */
9978    void setFlags(int flags, int mask) {
9979        final boolean accessibilityEnabled =
9980                AccessibilityManager.getInstance(mContext).isEnabled();
9981        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9982
9983        int old = mViewFlags;
9984        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9985
9986        int changed = mViewFlags ^ old;
9987        if (changed == 0) {
9988            return;
9989        }
9990        int privateFlags = mPrivateFlags;
9991
9992        /* Check if the FOCUSABLE bit has changed */
9993        if (((changed & FOCUSABLE_MASK) != 0) &&
9994                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9995            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9996                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9997                /* Give up focus if we are no longer focusable */
9998                clearFocus();
9999            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10000                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10001                /*
10002                 * Tell the view system that we are now available to take focus
10003                 * if no one else already has it.
10004                 */
10005                if (mParent != null) mParent.focusableViewAvailable(this);
10006            }
10007        }
10008
10009        final int newVisibility = flags & VISIBILITY_MASK;
10010        if (newVisibility == VISIBLE) {
10011            if ((changed & VISIBILITY_MASK) != 0) {
10012                /*
10013                 * If this view is becoming visible, invalidate it in case it changed while
10014                 * it was not visible. Marking it drawn ensures that the invalidation will
10015                 * go through.
10016                 */
10017                mPrivateFlags |= PFLAG_DRAWN;
10018                invalidate(true);
10019
10020                needGlobalAttributesUpdate(true);
10021
10022                // a view becoming visible is worth notifying the parent
10023                // about in case nothing has focus.  even if this specific view
10024                // isn't focusable, it may contain something that is, so let
10025                // the root view try to give this focus if nothing else does.
10026                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10027                    mParent.focusableViewAvailable(this);
10028                }
10029            }
10030        }
10031
10032        /* Check if the GONE bit has changed */
10033        if ((changed & GONE) != 0) {
10034            needGlobalAttributesUpdate(false);
10035            requestLayout();
10036
10037            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10038                if (hasFocus()) clearFocus();
10039                clearAccessibilityFocus();
10040                destroyDrawingCache();
10041                if (mParent instanceof View) {
10042                    // GONE views noop invalidation, so invalidate the parent
10043                    ((View) mParent).invalidate(true);
10044                }
10045                // Mark the view drawn to ensure that it gets invalidated properly the next
10046                // time it is visible and gets invalidated
10047                mPrivateFlags |= PFLAG_DRAWN;
10048            }
10049            if (mAttachInfo != null) {
10050                mAttachInfo.mViewVisibilityChanged = true;
10051            }
10052        }
10053
10054        /* Check if the VISIBLE bit has changed */
10055        if ((changed & INVISIBLE) != 0) {
10056            needGlobalAttributesUpdate(false);
10057            /*
10058             * If this view is becoming invisible, set the DRAWN flag so that
10059             * the next invalidate() will not be skipped.
10060             */
10061            mPrivateFlags |= PFLAG_DRAWN;
10062
10063            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10064                // root view becoming invisible shouldn't clear focus and accessibility focus
10065                if (getRootView() != this) {
10066                    if (hasFocus()) clearFocus();
10067                    clearAccessibilityFocus();
10068                }
10069            }
10070            if (mAttachInfo != null) {
10071                mAttachInfo.mViewVisibilityChanged = true;
10072            }
10073        }
10074
10075        if ((changed & VISIBILITY_MASK) != 0) {
10076            // If the view is invisible, cleanup its display list to free up resources
10077            if (newVisibility != VISIBLE && mAttachInfo != null) {
10078                cleanupDraw();
10079            }
10080
10081            if (mParent instanceof ViewGroup) {
10082                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10083                        (changed & VISIBILITY_MASK), newVisibility);
10084                ((View) mParent).invalidate(true);
10085            } else if (mParent != null) {
10086                mParent.invalidateChild(this, null);
10087            }
10088            dispatchVisibilityChanged(this, newVisibility);
10089
10090            notifySubtreeAccessibilityStateChangedIfNeeded();
10091        }
10092
10093        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10094            destroyDrawingCache();
10095        }
10096
10097        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10098            destroyDrawingCache();
10099            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10100            invalidateParentCaches();
10101        }
10102
10103        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10104            destroyDrawingCache();
10105            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10106        }
10107
10108        if ((changed & DRAW_MASK) != 0) {
10109            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10110                if (mBackground != null) {
10111                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10112                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
10113                } else {
10114                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10115                }
10116            } else {
10117                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10118            }
10119            requestLayout();
10120            invalidate(true);
10121        }
10122
10123        if ((changed & KEEP_SCREEN_ON) != 0) {
10124            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10125                mParent.recomputeViewAttributes(this);
10126            }
10127        }
10128
10129        if (accessibilityEnabled) {
10130            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10131                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
10132                if (oldIncludeForAccessibility != includeForAccessibility()) {
10133                    notifySubtreeAccessibilityStateChangedIfNeeded();
10134                } else {
10135                    notifyViewAccessibilityStateChangedIfNeeded(
10136                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10137                }
10138            } else if ((changed & ENABLED_MASK) != 0) {
10139                notifyViewAccessibilityStateChangedIfNeeded(
10140                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10141            }
10142        }
10143    }
10144
10145    /**
10146     * Change the view's z order in the tree, so it's on top of other sibling
10147     * views. This ordering change may affect layout, if the parent container
10148     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10149     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10150     * method should be followed by calls to {@link #requestLayout()} and
10151     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10152     * with the new child ordering.
10153     *
10154     * @see ViewGroup#bringChildToFront(View)
10155     */
10156    public void bringToFront() {
10157        if (mParent != null) {
10158            mParent.bringChildToFront(this);
10159        }
10160    }
10161
10162    /**
10163     * This is called in response to an internal scroll in this view (i.e., the
10164     * view scrolled its own contents). This is typically as a result of
10165     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10166     * called.
10167     *
10168     * @param l Current horizontal scroll origin.
10169     * @param t Current vertical scroll origin.
10170     * @param oldl Previous horizontal scroll origin.
10171     * @param oldt Previous vertical scroll origin.
10172     */
10173    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10174        notifySubtreeAccessibilityStateChangedIfNeeded();
10175
10176        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10177            postSendViewScrolledAccessibilityEventCallback();
10178        }
10179
10180        mBackgroundSizeChanged = true;
10181        if (mForegroundInfo != null) {
10182            mForegroundInfo.mBoundsChanged = true;
10183        }
10184
10185        final AttachInfo ai = mAttachInfo;
10186        if (ai != null) {
10187            ai.mViewScrollChanged = true;
10188        }
10189
10190        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10191            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10192        }
10193    }
10194
10195    /**
10196     * Interface definition for a callback to be invoked when the scroll
10197     * X or Y positions of a view change.
10198     * <p>
10199     * <b>Note:</b> Some views handle scrolling independently from View and may
10200     * have their own separate listeners for scroll-type events. For example,
10201     * {@link android.widget.ListView ListView} allows clients to register an
10202     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10203     * to listen for changes in list scroll position.
10204     *
10205     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10206     */
10207    public interface OnScrollChangeListener {
10208        /**
10209         * Called when the scroll position of a view changes.
10210         *
10211         * @param v The view whose scroll position has changed.
10212         * @param scrollX Current horizontal scroll origin.
10213         * @param scrollY Current vertical scroll origin.
10214         * @param oldScrollX Previous horizontal scroll origin.
10215         * @param oldScrollY Previous vertical scroll origin.
10216         */
10217        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10218    }
10219
10220    /**
10221     * Interface definition for a callback to be invoked when the layout bounds of a view
10222     * changes due to layout processing.
10223     */
10224    public interface OnLayoutChangeListener {
10225        /**
10226         * Called when the layout bounds of a view changes due to layout processing.
10227         *
10228         * @param v The view whose bounds have changed.
10229         * @param left The new value of the view's left property.
10230         * @param top The new value of the view's top property.
10231         * @param right The new value of the view's right property.
10232         * @param bottom The new value of the view's bottom property.
10233         * @param oldLeft The previous value of the view's left property.
10234         * @param oldTop The previous value of the view's top property.
10235         * @param oldRight The previous value of the view's right property.
10236         * @param oldBottom The previous value of the view's bottom property.
10237         */
10238        void onLayoutChange(View v, int left, int top, int right, int bottom,
10239            int oldLeft, int oldTop, int oldRight, int oldBottom);
10240    }
10241
10242    /**
10243     * This is called during layout when the size of this view has changed. If
10244     * you were just added to the view hierarchy, you're called with the old
10245     * values of 0.
10246     *
10247     * @param w Current width of this view.
10248     * @param h Current height of this view.
10249     * @param oldw Old width of this view.
10250     * @param oldh Old height of this view.
10251     */
10252    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10253    }
10254
10255    /**
10256     * Called by draw to draw the child views. This may be overridden
10257     * by derived classes to gain control just before its children are drawn
10258     * (but after its own view has been drawn).
10259     * @param canvas the canvas on which to draw the view
10260     */
10261    protected void dispatchDraw(Canvas canvas) {
10262
10263    }
10264
10265    /**
10266     * Gets the parent of this view. Note that the parent is a
10267     * ViewParent and not necessarily a View.
10268     *
10269     * @return Parent of this view.
10270     */
10271    public final ViewParent getParent() {
10272        return mParent;
10273    }
10274
10275    /**
10276     * Set the horizontal scrolled position of your view. This will cause a call to
10277     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10278     * invalidated.
10279     * @param value the x position to scroll to
10280     */
10281    public void setScrollX(int value) {
10282        scrollTo(value, mScrollY);
10283    }
10284
10285    /**
10286     * Set the vertical scrolled position of your view. This will cause a call to
10287     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10288     * invalidated.
10289     * @param value the y position to scroll to
10290     */
10291    public void setScrollY(int value) {
10292        scrollTo(mScrollX, value);
10293    }
10294
10295    /**
10296     * Return the scrolled left position of this view. This is the left edge of
10297     * the displayed part of your view. You do not need to draw any pixels
10298     * farther left, since those are outside of the frame of your view on
10299     * screen.
10300     *
10301     * @return The left edge of the displayed part of your view, in pixels.
10302     */
10303    public final int getScrollX() {
10304        return mScrollX;
10305    }
10306
10307    /**
10308     * Return the scrolled top position of this view. This is the top edge of
10309     * the displayed part of your view. You do not need to draw any pixels above
10310     * it, since those are outside of the frame of your view on screen.
10311     *
10312     * @return The top edge of the displayed part of your view, in pixels.
10313     */
10314    public final int getScrollY() {
10315        return mScrollY;
10316    }
10317
10318    /**
10319     * Return the width of the your view.
10320     *
10321     * @return The width of your view, in pixels.
10322     */
10323    @ViewDebug.ExportedProperty(category = "layout")
10324    public final int getWidth() {
10325        return mRight - mLeft;
10326    }
10327
10328    /**
10329     * Return the height of your view.
10330     *
10331     * @return The height of your view, in pixels.
10332     */
10333    @ViewDebug.ExportedProperty(category = "layout")
10334    public final int getHeight() {
10335        return mBottom - mTop;
10336    }
10337
10338    /**
10339     * Return the visible drawing bounds of your view. Fills in the output
10340     * rectangle with the values from getScrollX(), getScrollY(),
10341     * getWidth(), and getHeight(). These bounds do not account for any
10342     * transformation properties currently set on the view, such as
10343     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10344     *
10345     * @param outRect The (scrolled) drawing bounds of the view.
10346     */
10347    public void getDrawingRect(Rect outRect) {
10348        outRect.left = mScrollX;
10349        outRect.top = mScrollY;
10350        outRect.right = mScrollX + (mRight - mLeft);
10351        outRect.bottom = mScrollY + (mBottom - mTop);
10352    }
10353
10354    /**
10355     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10356     * raw width component (that is the result is masked by
10357     * {@link #MEASURED_SIZE_MASK}).
10358     *
10359     * @return The raw measured width of this view.
10360     */
10361    public final int getMeasuredWidth() {
10362        return mMeasuredWidth & MEASURED_SIZE_MASK;
10363    }
10364
10365    /**
10366     * Return the full width measurement information for this view as computed
10367     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10368     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10369     * This should be used during measurement and layout calculations only. Use
10370     * {@link #getWidth()} to see how wide a view is after layout.
10371     *
10372     * @return The measured width of this view as a bit mask.
10373     */
10374    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10375            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10376                    name = "MEASURED_STATE_TOO_SMALL"),
10377    })
10378    public final int getMeasuredWidthAndState() {
10379        return mMeasuredWidth;
10380    }
10381
10382    /**
10383     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10384     * raw width component (that is the result is masked by
10385     * {@link #MEASURED_SIZE_MASK}).
10386     *
10387     * @return The raw measured height of this view.
10388     */
10389    public final int getMeasuredHeight() {
10390        return mMeasuredHeight & MEASURED_SIZE_MASK;
10391    }
10392
10393    /**
10394     * Return the full height measurement information for this view as computed
10395     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10396     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10397     * This should be used during measurement and layout calculations only. Use
10398     * {@link #getHeight()} to see how wide a view is after layout.
10399     *
10400     * @return The measured width of this view as a bit mask.
10401     */
10402    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10403            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10404                    name = "MEASURED_STATE_TOO_SMALL"),
10405    })
10406    public final int getMeasuredHeightAndState() {
10407        return mMeasuredHeight;
10408    }
10409
10410    /**
10411     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10412     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10413     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10414     * and the height component is at the shifted bits
10415     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10416     */
10417    public final int getMeasuredState() {
10418        return (mMeasuredWidth&MEASURED_STATE_MASK)
10419                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10420                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10421    }
10422
10423    /**
10424     * The transform matrix of this view, which is calculated based on the current
10425     * rotation, scale, and pivot properties.
10426     *
10427     * @see #getRotation()
10428     * @see #getScaleX()
10429     * @see #getScaleY()
10430     * @see #getPivotX()
10431     * @see #getPivotY()
10432     * @return The current transform matrix for the view
10433     */
10434    public Matrix getMatrix() {
10435        ensureTransformationInfo();
10436        final Matrix matrix = mTransformationInfo.mMatrix;
10437        mRenderNode.getMatrix(matrix);
10438        return matrix;
10439    }
10440
10441    /**
10442     * Returns true if the transform matrix is the identity matrix.
10443     * Recomputes the matrix if necessary.
10444     *
10445     * @return True if the transform matrix is the identity matrix, false otherwise.
10446     */
10447    final boolean hasIdentityMatrix() {
10448        return mRenderNode.hasIdentityMatrix();
10449    }
10450
10451    void ensureTransformationInfo() {
10452        if (mTransformationInfo == null) {
10453            mTransformationInfo = new TransformationInfo();
10454        }
10455    }
10456
10457   /**
10458     * Utility method to retrieve the inverse of the current mMatrix property.
10459     * We cache the matrix to avoid recalculating it when transform properties
10460     * have not changed.
10461     *
10462     * @return The inverse of the current matrix of this view.
10463     * @hide
10464     */
10465    public final Matrix getInverseMatrix() {
10466        ensureTransformationInfo();
10467        if (mTransformationInfo.mInverseMatrix == null) {
10468            mTransformationInfo.mInverseMatrix = new Matrix();
10469        }
10470        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10471        mRenderNode.getInverseMatrix(matrix);
10472        return matrix;
10473    }
10474
10475    /**
10476     * Gets the distance along the Z axis from the camera to this view.
10477     *
10478     * @see #setCameraDistance(float)
10479     *
10480     * @return The distance along the Z axis.
10481     */
10482    public float getCameraDistance() {
10483        final float dpi = mResources.getDisplayMetrics().densityDpi;
10484        return -(mRenderNode.getCameraDistance() * dpi);
10485    }
10486
10487    /**
10488     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10489     * views are drawn) from the camera to this view. The camera's distance
10490     * affects 3D transformations, for instance rotations around the X and Y
10491     * axis. If the rotationX or rotationY properties are changed and this view is
10492     * large (more than half the size of the screen), it is recommended to always
10493     * use a camera distance that's greater than the height (X axis rotation) or
10494     * the width (Y axis rotation) of this view.</p>
10495     *
10496     * <p>The distance of the camera from the view plane can have an affect on the
10497     * perspective distortion of the view when it is rotated around the x or y axis.
10498     * For example, a large distance will result in a large viewing angle, and there
10499     * will not be much perspective distortion of the view as it rotates. A short
10500     * distance may cause much more perspective distortion upon rotation, and can
10501     * also result in some drawing artifacts if the rotated view ends up partially
10502     * behind the camera (which is why the recommendation is to use a distance at
10503     * least as far as the size of the view, if the view is to be rotated.)</p>
10504     *
10505     * <p>The distance is expressed in "depth pixels." The default distance depends
10506     * on the screen density. For instance, on a medium density display, the
10507     * default distance is 1280. On a high density display, the default distance
10508     * is 1920.</p>
10509     *
10510     * <p>If you want to specify a distance that leads to visually consistent
10511     * results across various densities, use the following formula:</p>
10512     * <pre>
10513     * float scale = context.getResources().getDisplayMetrics().density;
10514     * view.setCameraDistance(distance * scale);
10515     * </pre>
10516     *
10517     * <p>The density scale factor of a high density display is 1.5,
10518     * and 1920 = 1280 * 1.5.</p>
10519     *
10520     * @param distance The distance in "depth pixels", if negative the opposite
10521     *        value is used
10522     *
10523     * @see #setRotationX(float)
10524     * @see #setRotationY(float)
10525     */
10526    public void setCameraDistance(float distance) {
10527        final float dpi = mResources.getDisplayMetrics().densityDpi;
10528
10529        invalidateViewProperty(true, false);
10530        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10531        invalidateViewProperty(false, false);
10532
10533        invalidateParentIfNeededAndWasQuickRejected();
10534    }
10535
10536    /**
10537     * The degrees that the view is rotated around the pivot point.
10538     *
10539     * @see #setRotation(float)
10540     * @see #getPivotX()
10541     * @see #getPivotY()
10542     *
10543     * @return The degrees of rotation.
10544     */
10545    @ViewDebug.ExportedProperty(category = "drawing")
10546    public float getRotation() {
10547        return mRenderNode.getRotation();
10548    }
10549
10550    /**
10551     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10552     * result in clockwise rotation.
10553     *
10554     * @param rotation The degrees of rotation.
10555     *
10556     * @see #getRotation()
10557     * @see #getPivotX()
10558     * @see #getPivotY()
10559     * @see #setRotationX(float)
10560     * @see #setRotationY(float)
10561     *
10562     * @attr ref android.R.styleable#View_rotation
10563     */
10564    public void setRotation(float rotation) {
10565        if (rotation != getRotation()) {
10566            // Double-invalidation is necessary to capture view's old and new areas
10567            invalidateViewProperty(true, false);
10568            mRenderNode.setRotation(rotation);
10569            invalidateViewProperty(false, true);
10570
10571            invalidateParentIfNeededAndWasQuickRejected();
10572            notifySubtreeAccessibilityStateChangedIfNeeded();
10573        }
10574    }
10575
10576    /**
10577     * The degrees that the view is rotated around the vertical axis through the pivot point.
10578     *
10579     * @see #getPivotX()
10580     * @see #getPivotY()
10581     * @see #setRotationY(float)
10582     *
10583     * @return The degrees of Y rotation.
10584     */
10585    @ViewDebug.ExportedProperty(category = "drawing")
10586    public float getRotationY() {
10587        return mRenderNode.getRotationY();
10588    }
10589
10590    /**
10591     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10592     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10593     * down the y axis.
10594     *
10595     * When rotating large views, it is recommended to adjust the camera distance
10596     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10597     *
10598     * @param rotationY The degrees of Y rotation.
10599     *
10600     * @see #getRotationY()
10601     * @see #getPivotX()
10602     * @see #getPivotY()
10603     * @see #setRotation(float)
10604     * @see #setRotationX(float)
10605     * @see #setCameraDistance(float)
10606     *
10607     * @attr ref android.R.styleable#View_rotationY
10608     */
10609    public void setRotationY(float rotationY) {
10610        if (rotationY != getRotationY()) {
10611            invalidateViewProperty(true, false);
10612            mRenderNode.setRotationY(rotationY);
10613            invalidateViewProperty(false, true);
10614
10615            invalidateParentIfNeededAndWasQuickRejected();
10616            notifySubtreeAccessibilityStateChangedIfNeeded();
10617        }
10618    }
10619
10620    /**
10621     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10622     *
10623     * @see #getPivotX()
10624     * @see #getPivotY()
10625     * @see #setRotationX(float)
10626     *
10627     * @return The degrees of X rotation.
10628     */
10629    @ViewDebug.ExportedProperty(category = "drawing")
10630    public float getRotationX() {
10631        return mRenderNode.getRotationX();
10632    }
10633
10634    /**
10635     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10636     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10637     * x axis.
10638     *
10639     * When rotating large views, it is recommended to adjust the camera distance
10640     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10641     *
10642     * @param rotationX The degrees of X rotation.
10643     *
10644     * @see #getRotationX()
10645     * @see #getPivotX()
10646     * @see #getPivotY()
10647     * @see #setRotation(float)
10648     * @see #setRotationY(float)
10649     * @see #setCameraDistance(float)
10650     *
10651     * @attr ref android.R.styleable#View_rotationX
10652     */
10653    public void setRotationX(float rotationX) {
10654        if (rotationX != getRotationX()) {
10655            invalidateViewProperty(true, false);
10656            mRenderNode.setRotationX(rotationX);
10657            invalidateViewProperty(false, true);
10658
10659            invalidateParentIfNeededAndWasQuickRejected();
10660            notifySubtreeAccessibilityStateChangedIfNeeded();
10661        }
10662    }
10663
10664    /**
10665     * The amount that the view is scaled in x around the pivot point, as a proportion of
10666     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10667     *
10668     * <p>By default, this is 1.0f.
10669     *
10670     * @see #getPivotX()
10671     * @see #getPivotY()
10672     * @return The scaling factor.
10673     */
10674    @ViewDebug.ExportedProperty(category = "drawing")
10675    public float getScaleX() {
10676        return mRenderNode.getScaleX();
10677    }
10678
10679    /**
10680     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10681     * the view's unscaled width. A value of 1 means that no scaling is applied.
10682     *
10683     * @param scaleX The scaling factor.
10684     * @see #getPivotX()
10685     * @see #getPivotY()
10686     *
10687     * @attr ref android.R.styleable#View_scaleX
10688     */
10689    public void setScaleX(float scaleX) {
10690        if (scaleX != getScaleX()) {
10691            invalidateViewProperty(true, false);
10692            mRenderNode.setScaleX(scaleX);
10693            invalidateViewProperty(false, true);
10694
10695            invalidateParentIfNeededAndWasQuickRejected();
10696            notifySubtreeAccessibilityStateChangedIfNeeded();
10697        }
10698    }
10699
10700    /**
10701     * The amount that the view is scaled in y around the pivot point, as a proportion of
10702     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10703     *
10704     * <p>By default, this is 1.0f.
10705     *
10706     * @see #getPivotX()
10707     * @see #getPivotY()
10708     * @return The scaling factor.
10709     */
10710    @ViewDebug.ExportedProperty(category = "drawing")
10711    public float getScaleY() {
10712        return mRenderNode.getScaleY();
10713    }
10714
10715    /**
10716     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10717     * the view's unscaled width. A value of 1 means that no scaling is applied.
10718     *
10719     * @param scaleY The scaling factor.
10720     * @see #getPivotX()
10721     * @see #getPivotY()
10722     *
10723     * @attr ref android.R.styleable#View_scaleY
10724     */
10725    public void setScaleY(float scaleY) {
10726        if (scaleY != getScaleY()) {
10727            invalidateViewProperty(true, false);
10728            mRenderNode.setScaleY(scaleY);
10729            invalidateViewProperty(false, true);
10730
10731            invalidateParentIfNeededAndWasQuickRejected();
10732            notifySubtreeAccessibilityStateChangedIfNeeded();
10733        }
10734    }
10735
10736    /**
10737     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10738     * and {@link #setScaleX(float) scaled}.
10739     *
10740     * @see #getRotation()
10741     * @see #getScaleX()
10742     * @see #getScaleY()
10743     * @see #getPivotY()
10744     * @return The x location of the pivot point.
10745     *
10746     * @attr ref android.R.styleable#View_transformPivotX
10747     */
10748    @ViewDebug.ExportedProperty(category = "drawing")
10749    public float getPivotX() {
10750        return mRenderNode.getPivotX();
10751    }
10752
10753    /**
10754     * Sets the x location of the point around which the view is
10755     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10756     * By default, the pivot point is centered on the object.
10757     * Setting this property disables this behavior and causes the view to use only the
10758     * explicitly set pivotX and pivotY values.
10759     *
10760     * @param pivotX The x location of the pivot point.
10761     * @see #getRotation()
10762     * @see #getScaleX()
10763     * @see #getScaleY()
10764     * @see #getPivotY()
10765     *
10766     * @attr ref android.R.styleable#View_transformPivotX
10767     */
10768    public void setPivotX(float pivotX) {
10769        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10770            invalidateViewProperty(true, false);
10771            mRenderNode.setPivotX(pivotX);
10772            invalidateViewProperty(false, true);
10773
10774            invalidateParentIfNeededAndWasQuickRejected();
10775        }
10776    }
10777
10778    /**
10779     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10780     * and {@link #setScaleY(float) scaled}.
10781     *
10782     * @see #getRotation()
10783     * @see #getScaleX()
10784     * @see #getScaleY()
10785     * @see #getPivotY()
10786     * @return The y location of the pivot point.
10787     *
10788     * @attr ref android.R.styleable#View_transformPivotY
10789     */
10790    @ViewDebug.ExportedProperty(category = "drawing")
10791    public float getPivotY() {
10792        return mRenderNode.getPivotY();
10793    }
10794
10795    /**
10796     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10797     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10798     * Setting this property disables this behavior and causes the view to use only the
10799     * explicitly set pivotX and pivotY values.
10800     *
10801     * @param pivotY The y location of the pivot point.
10802     * @see #getRotation()
10803     * @see #getScaleX()
10804     * @see #getScaleY()
10805     * @see #getPivotY()
10806     *
10807     * @attr ref android.R.styleable#View_transformPivotY
10808     */
10809    public void setPivotY(float pivotY) {
10810        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10811            invalidateViewProperty(true, false);
10812            mRenderNode.setPivotY(pivotY);
10813            invalidateViewProperty(false, true);
10814
10815            invalidateParentIfNeededAndWasQuickRejected();
10816        }
10817    }
10818
10819    /**
10820     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10821     * completely transparent and 1 means the view is completely opaque.
10822     *
10823     * <p>By default this is 1.0f.
10824     * @return The opacity of the view.
10825     */
10826    @ViewDebug.ExportedProperty(category = "drawing")
10827    public float getAlpha() {
10828        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10829    }
10830
10831    /**
10832     * Returns whether this View has content which overlaps.
10833     *
10834     * <p>This function, intended to be overridden by specific View types, is an optimization when
10835     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10836     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10837     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10838     * directly. An example of overlapping rendering is a TextView with a background image, such as
10839     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10840     * ImageView with only the foreground image. The default implementation returns true; subclasses
10841     * should override if they have cases which can be optimized.</p>
10842     *
10843     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10844     * necessitates that a View return true if it uses the methods internally without passing the
10845     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10846     *
10847     * @return true if the content in this view might overlap, false otherwise.
10848     */
10849    @ViewDebug.ExportedProperty(category = "drawing")
10850    public boolean hasOverlappingRendering() {
10851        return true;
10852    }
10853
10854    /**
10855     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10856     * completely transparent and 1 means the view is completely opaque.</p>
10857     *
10858     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10859     * performance implications, especially for large views. It is best to use the alpha property
10860     * sparingly and transiently, as in the case of fading animations.</p>
10861     *
10862     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10863     * strongly recommended for performance reasons to either override
10864     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10865     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10866     *
10867     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10868     * responsible for applying the opacity itself.</p>
10869     *
10870     * <p>Note that if the view is backed by a
10871     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10872     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10873     * 1.0 will supersede the alpha of the layer paint.</p>
10874     *
10875     * @param alpha The opacity of the view.
10876     *
10877     * @see #hasOverlappingRendering()
10878     * @see #setLayerType(int, android.graphics.Paint)
10879     *
10880     * @attr ref android.R.styleable#View_alpha
10881     */
10882    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
10883        ensureTransformationInfo();
10884        if (mTransformationInfo.mAlpha != alpha) {
10885            mTransformationInfo.mAlpha = alpha;
10886            if (onSetAlpha((int) (alpha * 255))) {
10887                mPrivateFlags |= PFLAG_ALPHA_SET;
10888                // subclass is handling alpha - don't optimize rendering cache invalidation
10889                invalidateParentCaches();
10890                invalidate(true);
10891            } else {
10892                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10893                invalidateViewProperty(true, false);
10894                mRenderNode.setAlpha(getFinalAlpha());
10895                notifyViewAccessibilityStateChangedIfNeeded(
10896                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10897            }
10898        }
10899    }
10900
10901    /**
10902     * Faster version of setAlpha() which performs the same steps except there are
10903     * no calls to invalidate(). The caller of this function should perform proper invalidation
10904     * on the parent and this object. The return value indicates whether the subclass handles
10905     * alpha (the return value for onSetAlpha()).
10906     *
10907     * @param alpha The new value for the alpha property
10908     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10909     *         the new value for the alpha property is different from the old value
10910     */
10911    boolean setAlphaNoInvalidation(float alpha) {
10912        ensureTransformationInfo();
10913        if (mTransformationInfo.mAlpha != alpha) {
10914            mTransformationInfo.mAlpha = alpha;
10915            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10916            if (subclassHandlesAlpha) {
10917                mPrivateFlags |= PFLAG_ALPHA_SET;
10918                return true;
10919            } else {
10920                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10921                mRenderNode.setAlpha(getFinalAlpha());
10922            }
10923        }
10924        return false;
10925    }
10926
10927    /**
10928     * This property is hidden and intended only for use by the Fade transition, which
10929     * animates it to produce a visual translucency that does not side-effect (or get
10930     * affected by) the real alpha property. This value is composited with the other
10931     * alpha value (and the AlphaAnimation value, when that is present) to produce
10932     * a final visual translucency result, which is what is passed into the DisplayList.
10933     *
10934     * @hide
10935     */
10936    public void setTransitionAlpha(float alpha) {
10937        ensureTransformationInfo();
10938        if (mTransformationInfo.mTransitionAlpha != alpha) {
10939            mTransformationInfo.mTransitionAlpha = alpha;
10940            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10941            invalidateViewProperty(true, false);
10942            mRenderNode.setAlpha(getFinalAlpha());
10943        }
10944    }
10945
10946    /**
10947     * Calculates the visual alpha of this view, which is a combination of the actual
10948     * alpha value and the transitionAlpha value (if set).
10949     */
10950    private float getFinalAlpha() {
10951        if (mTransformationInfo != null) {
10952            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10953        }
10954        return 1;
10955    }
10956
10957    /**
10958     * This property is hidden and intended only for use by the Fade transition, which
10959     * animates it to produce a visual translucency that does not side-effect (or get
10960     * affected by) the real alpha property. This value is composited with the other
10961     * alpha value (and the AlphaAnimation value, when that is present) to produce
10962     * a final visual translucency result, which is what is passed into the DisplayList.
10963     *
10964     * @hide
10965     */
10966    @ViewDebug.ExportedProperty(category = "drawing")
10967    public float getTransitionAlpha() {
10968        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10969    }
10970
10971    /**
10972     * Top position of this view relative to its parent.
10973     *
10974     * @return The top of this view, in pixels.
10975     */
10976    @ViewDebug.CapturedViewProperty
10977    public final int getTop() {
10978        return mTop;
10979    }
10980
10981    /**
10982     * Sets the top position of this view relative to its parent. This method is meant to be called
10983     * by the layout system and should not generally be called otherwise, because the property
10984     * may be changed at any time by the layout.
10985     *
10986     * @param top The top of this view, in pixels.
10987     */
10988    public final void setTop(int top) {
10989        if (top != mTop) {
10990            final boolean matrixIsIdentity = hasIdentityMatrix();
10991            if (matrixIsIdentity) {
10992                if (mAttachInfo != null) {
10993                    int minTop;
10994                    int yLoc;
10995                    if (top < mTop) {
10996                        minTop = top;
10997                        yLoc = top - mTop;
10998                    } else {
10999                        minTop = mTop;
11000                        yLoc = 0;
11001                    }
11002                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11003                }
11004            } else {
11005                // Double-invalidation is necessary to capture view's old and new areas
11006                invalidate(true);
11007            }
11008
11009            int width = mRight - mLeft;
11010            int oldHeight = mBottom - mTop;
11011
11012            mTop = top;
11013            mRenderNode.setTop(mTop);
11014
11015            sizeChange(width, mBottom - mTop, width, oldHeight);
11016
11017            if (!matrixIsIdentity) {
11018                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11019                invalidate(true);
11020            }
11021            mBackgroundSizeChanged = true;
11022            if (mForegroundInfo != null) {
11023                mForegroundInfo.mBoundsChanged = true;
11024            }
11025            invalidateParentIfNeeded();
11026            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11027                // View was rejected last time it was drawn by its parent; this may have changed
11028                invalidateParentIfNeeded();
11029            }
11030        }
11031    }
11032
11033    /**
11034     * Bottom position of this view relative to its parent.
11035     *
11036     * @return The bottom of this view, in pixels.
11037     */
11038    @ViewDebug.CapturedViewProperty
11039    public final int getBottom() {
11040        return mBottom;
11041    }
11042
11043    /**
11044     * True if this view has changed since the last time being drawn.
11045     *
11046     * @return The dirty state of this view.
11047     */
11048    public boolean isDirty() {
11049        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11050    }
11051
11052    /**
11053     * Sets the bottom position of this view relative to its parent. This method is meant to be
11054     * called by the layout system and should not generally be called otherwise, because the
11055     * property may be changed at any time by the layout.
11056     *
11057     * @param bottom The bottom of this view, in pixels.
11058     */
11059    public final void setBottom(int bottom) {
11060        if (bottom != mBottom) {
11061            final boolean matrixIsIdentity = hasIdentityMatrix();
11062            if (matrixIsIdentity) {
11063                if (mAttachInfo != null) {
11064                    int maxBottom;
11065                    if (bottom < mBottom) {
11066                        maxBottom = mBottom;
11067                    } else {
11068                        maxBottom = bottom;
11069                    }
11070                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11071                }
11072            } else {
11073                // Double-invalidation is necessary to capture view's old and new areas
11074                invalidate(true);
11075            }
11076
11077            int width = mRight - mLeft;
11078            int oldHeight = mBottom - mTop;
11079
11080            mBottom = bottom;
11081            mRenderNode.setBottom(mBottom);
11082
11083            sizeChange(width, mBottom - mTop, width, oldHeight);
11084
11085            if (!matrixIsIdentity) {
11086                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11087                invalidate(true);
11088            }
11089            mBackgroundSizeChanged = true;
11090            if (mForegroundInfo != null) {
11091                mForegroundInfo.mBoundsChanged = true;
11092            }
11093            invalidateParentIfNeeded();
11094            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11095                // View was rejected last time it was drawn by its parent; this may have changed
11096                invalidateParentIfNeeded();
11097            }
11098        }
11099    }
11100
11101    /**
11102     * Left position of this view relative to its parent.
11103     *
11104     * @return The left edge of this view, in pixels.
11105     */
11106    @ViewDebug.CapturedViewProperty
11107    public final int getLeft() {
11108        return mLeft;
11109    }
11110
11111    /**
11112     * Sets the left position of this view relative to its parent. This method is meant to be called
11113     * by the layout system and should not generally be called otherwise, because the property
11114     * may be changed at any time by the layout.
11115     *
11116     * @param left The left of this view, in pixels.
11117     */
11118    public final void setLeft(int left) {
11119        if (left != mLeft) {
11120            final boolean matrixIsIdentity = hasIdentityMatrix();
11121            if (matrixIsIdentity) {
11122                if (mAttachInfo != null) {
11123                    int minLeft;
11124                    int xLoc;
11125                    if (left < mLeft) {
11126                        minLeft = left;
11127                        xLoc = left - mLeft;
11128                    } else {
11129                        minLeft = mLeft;
11130                        xLoc = 0;
11131                    }
11132                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11133                }
11134            } else {
11135                // Double-invalidation is necessary to capture view's old and new areas
11136                invalidate(true);
11137            }
11138
11139            int oldWidth = mRight - mLeft;
11140            int height = mBottom - mTop;
11141
11142            mLeft = left;
11143            mRenderNode.setLeft(left);
11144
11145            sizeChange(mRight - mLeft, height, oldWidth, height);
11146
11147            if (!matrixIsIdentity) {
11148                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11149                invalidate(true);
11150            }
11151            mBackgroundSizeChanged = true;
11152            if (mForegroundInfo != null) {
11153                mForegroundInfo.mBoundsChanged = true;
11154            }
11155            invalidateParentIfNeeded();
11156            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11157                // View was rejected last time it was drawn by its parent; this may have changed
11158                invalidateParentIfNeeded();
11159            }
11160        }
11161    }
11162
11163    /**
11164     * Right position of this view relative to its parent.
11165     *
11166     * @return The right edge of this view, in pixels.
11167     */
11168    @ViewDebug.CapturedViewProperty
11169    public final int getRight() {
11170        return mRight;
11171    }
11172
11173    /**
11174     * Sets the right position of this view relative to its parent. This method is meant to be called
11175     * by the layout system and should not generally be called otherwise, because the property
11176     * may be changed at any time by the layout.
11177     *
11178     * @param right The right of this view, in pixels.
11179     */
11180    public final void setRight(int right) {
11181        if (right != mRight) {
11182            final boolean matrixIsIdentity = hasIdentityMatrix();
11183            if (matrixIsIdentity) {
11184                if (mAttachInfo != null) {
11185                    int maxRight;
11186                    if (right < mRight) {
11187                        maxRight = mRight;
11188                    } else {
11189                        maxRight = right;
11190                    }
11191                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11192                }
11193            } else {
11194                // Double-invalidation is necessary to capture view's old and new areas
11195                invalidate(true);
11196            }
11197
11198            int oldWidth = mRight - mLeft;
11199            int height = mBottom - mTop;
11200
11201            mRight = right;
11202            mRenderNode.setRight(mRight);
11203
11204            sizeChange(mRight - mLeft, height, oldWidth, height);
11205
11206            if (!matrixIsIdentity) {
11207                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11208                invalidate(true);
11209            }
11210            mBackgroundSizeChanged = true;
11211            if (mForegroundInfo != null) {
11212                mForegroundInfo.mBoundsChanged = true;
11213            }
11214            invalidateParentIfNeeded();
11215            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11216                // View was rejected last time it was drawn by its parent; this may have changed
11217                invalidateParentIfNeeded();
11218            }
11219        }
11220    }
11221
11222    /**
11223     * The visual x position of this view, in pixels. This is equivalent to the
11224     * {@link #setTranslationX(float) translationX} property plus the current
11225     * {@link #getLeft() left} property.
11226     *
11227     * @return The visual x position of this view, in pixels.
11228     */
11229    @ViewDebug.ExportedProperty(category = "drawing")
11230    public float getX() {
11231        return mLeft + getTranslationX();
11232    }
11233
11234    /**
11235     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11236     * {@link #setTranslationX(float) translationX} property to be the difference between
11237     * the x value passed in and the current {@link #getLeft() left} property.
11238     *
11239     * @param x The visual x position of this view, in pixels.
11240     */
11241    public void setX(float x) {
11242        setTranslationX(x - mLeft);
11243    }
11244
11245    /**
11246     * The visual y position of this view, in pixels. This is equivalent to the
11247     * {@link #setTranslationY(float) translationY} property plus the current
11248     * {@link #getTop() top} property.
11249     *
11250     * @return The visual y position of this view, in pixels.
11251     */
11252    @ViewDebug.ExportedProperty(category = "drawing")
11253    public float getY() {
11254        return mTop + getTranslationY();
11255    }
11256
11257    /**
11258     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11259     * {@link #setTranslationY(float) translationY} property to be the difference between
11260     * the y value passed in and the current {@link #getTop() top} property.
11261     *
11262     * @param y The visual y position of this view, in pixels.
11263     */
11264    public void setY(float y) {
11265        setTranslationY(y - mTop);
11266    }
11267
11268    /**
11269     * The visual z position of this view, in pixels. This is equivalent to the
11270     * {@link #setTranslationZ(float) translationZ} property plus the current
11271     * {@link #getElevation() elevation} property.
11272     *
11273     * @return The visual z position of this view, in pixels.
11274     */
11275    @ViewDebug.ExportedProperty(category = "drawing")
11276    public float getZ() {
11277        return getElevation() + getTranslationZ();
11278    }
11279
11280    /**
11281     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11282     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11283     * the x value passed in and the current {@link #getElevation() elevation} property.
11284     *
11285     * @param z The visual z position of this view, in pixels.
11286     */
11287    public void setZ(float z) {
11288        setTranslationZ(z - getElevation());
11289    }
11290
11291    /**
11292     * The base elevation of this view relative to its parent, in pixels.
11293     *
11294     * @return The base depth position of the view, in pixels.
11295     */
11296    @ViewDebug.ExportedProperty(category = "drawing")
11297    public float getElevation() {
11298        return mRenderNode.getElevation();
11299    }
11300
11301    /**
11302     * Sets the base elevation of this view, in pixels.
11303     *
11304     * @attr ref android.R.styleable#View_elevation
11305     */
11306    public void setElevation(float elevation) {
11307        if (elevation != getElevation()) {
11308            invalidateViewProperty(true, false);
11309            mRenderNode.setElevation(elevation);
11310            invalidateViewProperty(false, true);
11311
11312            invalidateParentIfNeededAndWasQuickRejected();
11313        }
11314    }
11315
11316    /**
11317     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11318     * This position is post-layout, in addition to wherever the object's
11319     * layout placed it.
11320     *
11321     * @return The horizontal position of this view relative to its left position, in pixels.
11322     */
11323    @ViewDebug.ExportedProperty(category = "drawing")
11324    public float getTranslationX() {
11325        return mRenderNode.getTranslationX();
11326    }
11327
11328    /**
11329     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11330     * This effectively positions the object post-layout, in addition to wherever the object's
11331     * layout placed it.
11332     *
11333     * @param translationX The horizontal position of this view relative to its left position,
11334     * in pixels.
11335     *
11336     * @attr ref android.R.styleable#View_translationX
11337     */
11338    public void setTranslationX(float translationX) {
11339        if (translationX != getTranslationX()) {
11340            invalidateViewProperty(true, false);
11341            mRenderNode.setTranslationX(translationX);
11342            invalidateViewProperty(false, true);
11343
11344            invalidateParentIfNeededAndWasQuickRejected();
11345            notifySubtreeAccessibilityStateChangedIfNeeded();
11346        }
11347    }
11348
11349    /**
11350     * The vertical location of this view relative to its {@link #getTop() top} position.
11351     * This position is post-layout, in addition to wherever the object's
11352     * layout placed it.
11353     *
11354     * @return The vertical position of this view relative to its top position,
11355     * in pixels.
11356     */
11357    @ViewDebug.ExportedProperty(category = "drawing")
11358    public float getTranslationY() {
11359        return mRenderNode.getTranslationY();
11360    }
11361
11362    /**
11363     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11364     * This effectively positions the object post-layout, in addition to wherever the object's
11365     * layout placed it.
11366     *
11367     * @param translationY The vertical position of this view relative to its top position,
11368     * in pixels.
11369     *
11370     * @attr ref android.R.styleable#View_translationY
11371     */
11372    public void setTranslationY(float translationY) {
11373        if (translationY != getTranslationY()) {
11374            invalidateViewProperty(true, false);
11375            mRenderNode.setTranslationY(translationY);
11376            invalidateViewProperty(false, true);
11377
11378            invalidateParentIfNeededAndWasQuickRejected();
11379            notifySubtreeAccessibilityStateChangedIfNeeded();
11380        }
11381    }
11382
11383    /**
11384     * The depth location of this view relative to its {@link #getElevation() elevation}.
11385     *
11386     * @return The depth of this view relative to its elevation.
11387     */
11388    @ViewDebug.ExportedProperty(category = "drawing")
11389    public float getTranslationZ() {
11390        return mRenderNode.getTranslationZ();
11391    }
11392
11393    /**
11394     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11395     *
11396     * @attr ref android.R.styleable#View_translationZ
11397     */
11398    public void setTranslationZ(float translationZ) {
11399        if (translationZ != getTranslationZ()) {
11400            invalidateViewProperty(true, false);
11401            mRenderNode.setTranslationZ(translationZ);
11402            invalidateViewProperty(false, true);
11403
11404            invalidateParentIfNeededAndWasQuickRejected();
11405        }
11406    }
11407
11408    /** @hide */
11409    public void setAnimationMatrix(Matrix matrix) {
11410        invalidateViewProperty(true, false);
11411        mRenderNode.setAnimationMatrix(matrix);
11412        invalidateViewProperty(false, true);
11413
11414        invalidateParentIfNeededAndWasQuickRejected();
11415    }
11416
11417    /**
11418     * Returns the current StateListAnimator if exists.
11419     *
11420     * @return StateListAnimator or null if it does not exists
11421     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11422     */
11423    public StateListAnimator getStateListAnimator() {
11424        return mStateListAnimator;
11425    }
11426
11427    /**
11428     * Attaches the provided StateListAnimator to this View.
11429     * <p>
11430     * Any previously attached StateListAnimator will be detached.
11431     *
11432     * @param stateListAnimator The StateListAnimator to update the view
11433     * @see {@link android.animation.StateListAnimator}
11434     */
11435    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11436        if (mStateListAnimator == stateListAnimator) {
11437            return;
11438        }
11439        if (mStateListAnimator != null) {
11440            mStateListAnimator.setTarget(null);
11441        }
11442        mStateListAnimator = stateListAnimator;
11443        if (stateListAnimator != null) {
11444            stateListAnimator.setTarget(this);
11445            if (isAttachedToWindow()) {
11446                stateListAnimator.setState(getDrawableState());
11447            }
11448        }
11449    }
11450
11451    /**
11452     * Returns whether the Outline should be used to clip the contents of the View.
11453     * <p>
11454     * Note that this flag will only be respected if the View's Outline returns true from
11455     * {@link Outline#canClip()}.
11456     *
11457     * @see #setOutlineProvider(ViewOutlineProvider)
11458     * @see #setClipToOutline(boolean)
11459     */
11460    public final boolean getClipToOutline() {
11461        return mRenderNode.getClipToOutline();
11462    }
11463
11464    /**
11465     * Sets whether the View's Outline should be used to clip the contents of the View.
11466     * <p>
11467     * Only a single non-rectangular clip can be applied on a View at any time.
11468     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11469     * circular reveal} animation take priority over Outline clipping, and
11470     * child Outline clipping takes priority over Outline clipping done by a
11471     * parent.
11472     * <p>
11473     * Note that this flag will only be respected if the View's Outline returns true from
11474     * {@link Outline#canClip()}.
11475     *
11476     * @see #setOutlineProvider(ViewOutlineProvider)
11477     * @see #getClipToOutline()
11478     */
11479    public void setClipToOutline(boolean clipToOutline) {
11480        damageInParent();
11481        if (getClipToOutline() != clipToOutline) {
11482            mRenderNode.setClipToOutline(clipToOutline);
11483        }
11484    }
11485
11486    // correspond to the enum values of View_outlineProvider
11487    private static final int PROVIDER_BACKGROUND = 0;
11488    private static final int PROVIDER_NONE = 1;
11489    private static final int PROVIDER_BOUNDS = 2;
11490    private static final int PROVIDER_PADDED_BOUNDS = 3;
11491    private void setOutlineProviderFromAttribute(int providerInt) {
11492        switch (providerInt) {
11493            case PROVIDER_BACKGROUND:
11494                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11495                break;
11496            case PROVIDER_NONE:
11497                setOutlineProvider(null);
11498                break;
11499            case PROVIDER_BOUNDS:
11500                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11501                break;
11502            case PROVIDER_PADDED_BOUNDS:
11503                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11504                break;
11505        }
11506    }
11507
11508    /**
11509     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11510     * the shape of the shadow it casts, and enables outline clipping.
11511     * <p>
11512     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11513     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11514     * outline provider with this method allows this behavior to be overridden.
11515     * <p>
11516     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11517     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11518     * <p>
11519     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11520     *
11521     * @see #setClipToOutline(boolean)
11522     * @see #getClipToOutline()
11523     * @see #getOutlineProvider()
11524     */
11525    public void setOutlineProvider(ViewOutlineProvider provider) {
11526        mOutlineProvider = provider;
11527        invalidateOutline();
11528    }
11529
11530    /**
11531     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11532     * that defines the shape of the shadow it casts, and enables outline clipping.
11533     *
11534     * @see #setOutlineProvider(ViewOutlineProvider)
11535     */
11536    public ViewOutlineProvider getOutlineProvider() {
11537        return mOutlineProvider;
11538    }
11539
11540    /**
11541     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11542     *
11543     * @see #setOutlineProvider(ViewOutlineProvider)
11544     */
11545    public void invalidateOutline() {
11546        rebuildOutline();
11547
11548        notifySubtreeAccessibilityStateChangedIfNeeded();
11549        invalidateViewProperty(false, false);
11550    }
11551
11552    /**
11553     * Internal version of {@link #invalidateOutline()} which invalidates the
11554     * outline without invalidating the view itself. This is intended to be called from
11555     * within methods in the View class itself which are the result of the view being
11556     * invalidated already. For example, when we are drawing the background of a View,
11557     * we invalidate the outline in case it changed in the meantime, but we do not
11558     * need to invalidate the view because we're already drawing the background as part
11559     * of drawing the view in response to an earlier invalidation of the view.
11560     */
11561    private void rebuildOutline() {
11562        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11563        if (mAttachInfo == null) return;
11564
11565        if (mOutlineProvider == null) {
11566            // no provider, remove outline
11567            mRenderNode.setOutline(null);
11568        } else {
11569            final Outline outline = mAttachInfo.mTmpOutline;
11570            outline.setEmpty();
11571            outline.setAlpha(1.0f);
11572
11573            mOutlineProvider.getOutline(this, outline);
11574            mRenderNode.setOutline(outline);
11575        }
11576    }
11577
11578    /**
11579     * HierarchyViewer only
11580     *
11581     * @hide
11582     */
11583    @ViewDebug.ExportedProperty(category = "drawing")
11584    public boolean hasShadow() {
11585        return mRenderNode.hasShadow();
11586    }
11587
11588
11589    /** @hide */
11590    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11591        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11592        invalidateViewProperty(false, false);
11593    }
11594
11595    /**
11596     * Hit rectangle in parent's coordinates
11597     *
11598     * @param outRect The hit rectangle of the view.
11599     */
11600    public void getHitRect(Rect outRect) {
11601        if (hasIdentityMatrix() || mAttachInfo == null) {
11602            outRect.set(mLeft, mTop, mRight, mBottom);
11603        } else {
11604            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11605            tmpRect.set(0, 0, getWidth(), getHeight());
11606            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11607            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11608                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11609        }
11610    }
11611
11612    /**
11613     * Determines whether the given point, in local coordinates is inside the view.
11614     */
11615    /*package*/ final boolean pointInView(float localX, float localY) {
11616        return localX >= 0 && localX < (mRight - mLeft)
11617                && localY >= 0 && localY < (mBottom - mTop);
11618    }
11619
11620    /**
11621     * Utility method to determine whether the given point, in local coordinates,
11622     * is inside the view, where the area of the view is expanded by the slop factor.
11623     * This method is called while processing touch-move events to determine if the event
11624     * is still within the view.
11625     *
11626     * @hide
11627     */
11628    public boolean pointInView(float localX, float localY, float slop) {
11629        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11630                localY < ((mBottom - mTop) + slop);
11631    }
11632
11633    /**
11634     * When a view has focus and the user navigates away from it, the next view is searched for
11635     * starting from the rectangle filled in by this method.
11636     *
11637     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11638     * of the view.  However, if your view maintains some idea of internal selection,
11639     * such as a cursor, or a selected row or column, you should override this method and
11640     * fill in a more specific rectangle.
11641     *
11642     * @param r The rectangle to fill in, in this view's coordinates.
11643     */
11644    public void getFocusedRect(Rect r) {
11645        getDrawingRect(r);
11646    }
11647
11648    /**
11649     * If some part of this view is not clipped by any of its parents, then
11650     * return that area in r in global (root) coordinates. To convert r to local
11651     * coordinates (without taking possible View rotations into account), offset
11652     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11653     * If the view is completely clipped or translated out, return false.
11654     *
11655     * @param r If true is returned, r holds the global coordinates of the
11656     *        visible portion of this view.
11657     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11658     *        between this view and its root. globalOffet may be null.
11659     * @return true if r is non-empty (i.e. part of the view is visible at the
11660     *         root level.
11661     */
11662    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11663        int width = mRight - mLeft;
11664        int height = mBottom - mTop;
11665        if (width > 0 && height > 0) {
11666            r.set(0, 0, width, height);
11667            if (globalOffset != null) {
11668                globalOffset.set(-mScrollX, -mScrollY);
11669            }
11670            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11671        }
11672        return false;
11673    }
11674
11675    public final boolean getGlobalVisibleRect(Rect r) {
11676        return getGlobalVisibleRect(r, null);
11677    }
11678
11679    public final boolean getLocalVisibleRect(Rect r) {
11680        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11681        if (getGlobalVisibleRect(r, offset)) {
11682            r.offset(-offset.x, -offset.y); // make r local
11683            return true;
11684        }
11685        return false;
11686    }
11687
11688    /**
11689     * Offset this view's vertical location by the specified number of pixels.
11690     *
11691     * @param offset the number of pixels to offset the view by
11692     */
11693    public void offsetTopAndBottom(int offset) {
11694        if (offset != 0) {
11695            final boolean matrixIsIdentity = hasIdentityMatrix();
11696            if (matrixIsIdentity) {
11697                if (isHardwareAccelerated()) {
11698                    invalidateViewProperty(false, false);
11699                } else {
11700                    final ViewParent p = mParent;
11701                    if (p != null && mAttachInfo != null) {
11702                        final Rect r = mAttachInfo.mTmpInvalRect;
11703                        int minTop;
11704                        int maxBottom;
11705                        int yLoc;
11706                        if (offset < 0) {
11707                            minTop = mTop + offset;
11708                            maxBottom = mBottom;
11709                            yLoc = offset;
11710                        } else {
11711                            minTop = mTop;
11712                            maxBottom = mBottom + offset;
11713                            yLoc = 0;
11714                        }
11715                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11716                        p.invalidateChild(this, r);
11717                    }
11718                }
11719            } else {
11720                invalidateViewProperty(false, false);
11721            }
11722
11723            mTop += offset;
11724            mBottom += offset;
11725            mRenderNode.offsetTopAndBottom(offset);
11726            if (isHardwareAccelerated()) {
11727                invalidateViewProperty(false, false);
11728            } else {
11729                if (!matrixIsIdentity) {
11730                    invalidateViewProperty(false, true);
11731                }
11732                invalidateParentIfNeeded();
11733            }
11734            notifySubtreeAccessibilityStateChangedIfNeeded();
11735        }
11736    }
11737
11738    /**
11739     * Offset this view's horizontal location by the specified amount of pixels.
11740     *
11741     * @param offset the number of pixels to offset the view by
11742     */
11743    public void offsetLeftAndRight(int offset) {
11744        if (offset != 0) {
11745            final boolean matrixIsIdentity = hasIdentityMatrix();
11746            if (matrixIsIdentity) {
11747                if (isHardwareAccelerated()) {
11748                    invalidateViewProperty(false, false);
11749                } else {
11750                    final ViewParent p = mParent;
11751                    if (p != null && mAttachInfo != null) {
11752                        final Rect r = mAttachInfo.mTmpInvalRect;
11753                        int minLeft;
11754                        int maxRight;
11755                        if (offset < 0) {
11756                            minLeft = mLeft + offset;
11757                            maxRight = mRight;
11758                        } else {
11759                            minLeft = mLeft;
11760                            maxRight = mRight + offset;
11761                        }
11762                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11763                        p.invalidateChild(this, r);
11764                    }
11765                }
11766            } else {
11767                invalidateViewProperty(false, false);
11768            }
11769
11770            mLeft += offset;
11771            mRight += offset;
11772            mRenderNode.offsetLeftAndRight(offset);
11773            if (isHardwareAccelerated()) {
11774                invalidateViewProperty(false, false);
11775            } else {
11776                if (!matrixIsIdentity) {
11777                    invalidateViewProperty(false, true);
11778                }
11779                invalidateParentIfNeeded();
11780            }
11781            notifySubtreeAccessibilityStateChangedIfNeeded();
11782        }
11783    }
11784
11785    /**
11786     * Get the LayoutParams associated with this view. All views should have
11787     * layout parameters. These supply parameters to the <i>parent</i> of this
11788     * view specifying how it should be arranged. There are many subclasses of
11789     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11790     * of ViewGroup that are responsible for arranging their children.
11791     *
11792     * This method may return null if this View is not attached to a parent
11793     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11794     * was not invoked successfully. When a View is attached to a parent
11795     * ViewGroup, this method must not return null.
11796     *
11797     * @return The LayoutParams associated with this view, or null if no
11798     *         parameters have been set yet
11799     */
11800    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11801    public ViewGroup.LayoutParams getLayoutParams() {
11802        return mLayoutParams;
11803    }
11804
11805    /**
11806     * Set the layout parameters associated with this view. These supply
11807     * parameters to the <i>parent</i> of this view specifying how it should be
11808     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11809     * correspond to the different subclasses of ViewGroup that are responsible
11810     * for arranging their children.
11811     *
11812     * @param params The layout parameters for this view, cannot be null
11813     */
11814    public void setLayoutParams(ViewGroup.LayoutParams params) {
11815        if (params == null) {
11816            throw new NullPointerException("Layout parameters cannot be null");
11817        }
11818        mLayoutParams = params;
11819        resolveLayoutParams();
11820        if (mParent instanceof ViewGroup) {
11821            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11822        }
11823        requestLayout();
11824    }
11825
11826    /**
11827     * Resolve the layout parameters depending on the resolved layout direction
11828     *
11829     * @hide
11830     */
11831    public void resolveLayoutParams() {
11832        if (mLayoutParams != null) {
11833            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11834        }
11835    }
11836
11837    /**
11838     * Set the scrolled position of your view. This will cause a call to
11839     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11840     * invalidated.
11841     * @param x the x position to scroll to
11842     * @param y the y position to scroll to
11843     */
11844    public void scrollTo(int x, int y) {
11845        if (mScrollX != x || mScrollY != y) {
11846            int oldX = mScrollX;
11847            int oldY = mScrollY;
11848            mScrollX = x;
11849            mScrollY = y;
11850            invalidateParentCaches();
11851            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11852            if (!awakenScrollBars()) {
11853                postInvalidateOnAnimation();
11854            }
11855        }
11856    }
11857
11858    /**
11859     * Move the scrolled position of your view. This will cause a call to
11860     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11861     * invalidated.
11862     * @param x the amount of pixels to scroll by horizontally
11863     * @param y the amount of pixels to scroll by vertically
11864     */
11865    public void scrollBy(int x, int y) {
11866        scrollTo(mScrollX + x, mScrollY + y);
11867    }
11868
11869    /**
11870     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11871     * animation to fade the scrollbars out after a default delay. If a subclass
11872     * provides animated scrolling, the start delay should equal the duration
11873     * of the scrolling animation.</p>
11874     *
11875     * <p>The animation starts only if at least one of the scrollbars is
11876     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11877     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11878     * this method returns true, and false otherwise. If the animation is
11879     * started, this method calls {@link #invalidate()}; in that case the
11880     * caller should not call {@link #invalidate()}.</p>
11881     *
11882     * <p>This method should be invoked every time a subclass directly updates
11883     * the scroll parameters.</p>
11884     *
11885     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11886     * and {@link #scrollTo(int, int)}.</p>
11887     *
11888     * @return true if the animation is played, false otherwise
11889     *
11890     * @see #awakenScrollBars(int)
11891     * @see #scrollBy(int, int)
11892     * @see #scrollTo(int, int)
11893     * @see #isHorizontalScrollBarEnabled()
11894     * @see #isVerticalScrollBarEnabled()
11895     * @see #setHorizontalScrollBarEnabled(boolean)
11896     * @see #setVerticalScrollBarEnabled(boolean)
11897     */
11898    protected boolean awakenScrollBars() {
11899        return mScrollCache != null &&
11900                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11901    }
11902
11903    /**
11904     * Trigger the scrollbars to draw.
11905     * This method differs from awakenScrollBars() only in its default duration.
11906     * initialAwakenScrollBars() will show the scroll bars for longer than
11907     * usual to give the user more of a chance to notice them.
11908     *
11909     * @return true if the animation is played, false otherwise.
11910     */
11911    private boolean initialAwakenScrollBars() {
11912        return mScrollCache != null &&
11913                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11914    }
11915
11916    /**
11917     * <p>
11918     * Trigger the scrollbars to draw. When invoked this method starts an
11919     * animation to fade the scrollbars out after a fixed delay. If a subclass
11920     * provides animated scrolling, the start delay should equal the duration of
11921     * the scrolling animation.
11922     * </p>
11923     *
11924     * <p>
11925     * The animation starts only if at least one of the scrollbars is enabled,
11926     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11927     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11928     * this method returns true, and false otherwise. If the animation is
11929     * started, this method calls {@link #invalidate()}; in that case the caller
11930     * should not call {@link #invalidate()}.
11931     * </p>
11932     *
11933     * <p>
11934     * This method should be invoked every time a subclass directly updates the
11935     * scroll parameters.
11936     * </p>
11937     *
11938     * @param startDelay the delay, in milliseconds, after which the animation
11939     *        should start; when the delay is 0, the animation starts
11940     *        immediately
11941     * @return true if the animation is played, false otherwise
11942     *
11943     * @see #scrollBy(int, int)
11944     * @see #scrollTo(int, int)
11945     * @see #isHorizontalScrollBarEnabled()
11946     * @see #isVerticalScrollBarEnabled()
11947     * @see #setHorizontalScrollBarEnabled(boolean)
11948     * @see #setVerticalScrollBarEnabled(boolean)
11949     */
11950    protected boolean awakenScrollBars(int startDelay) {
11951        return awakenScrollBars(startDelay, true);
11952    }
11953
11954    /**
11955     * <p>
11956     * Trigger the scrollbars to draw. When invoked this method starts an
11957     * animation to fade the scrollbars out after a fixed delay. If a subclass
11958     * provides animated scrolling, the start delay should equal the duration of
11959     * the scrolling animation.
11960     * </p>
11961     *
11962     * <p>
11963     * The animation starts only if at least one of the scrollbars is enabled,
11964     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11965     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11966     * this method returns true, and false otherwise. If the animation is
11967     * started, this method calls {@link #invalidate()} if the invalidate parameter
11968     * is set to true; in that case the caller
11969     * should not call {@link #invalidate()}.
11970     * </p>
11971     *
11972     * <p>
11973     * This method should be invoked every time a subclass directly updates the
11974     * scroll parameters.
11975     * </p>
11976     *
11977     * @param startDelay the delay, in milliseconds, after which the animation
11978     *        should start; when the delay is 0, the animation starts
11979     *        immediately
11980     *
11981     * @param invalidate Whether this method should call invalidate
11982     *
11983     * @return true if the animation is played, false otherwise
11984     *
11985     * @see #scrollBy(int, int)
11986     * @see #scrollTo(int, int)
11987     * @see #isHorizontalScrollBarEnabled()
11988     * @see #isVerticalScrollBarEnabled()
11989     * @see #setHorizontalScrollBarEnabled(boolean)
11990     * @see #setVerticalScrollBarEnabled(boolean)
11991     */
11992    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11993        final ScrollabilityCache scrollCache = mScrollCache;
11994
11995        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11996            return false;
11997        }
11998
11999        if (scrollCache.scrollBar == null) {
12000            scrollCache.scrollBar = new ScrollBarDrawable();
12001            scrollCache.scrollBar.setCallback(this);
12002            scrollCache.scrollBar.setState(getDrawableState());
12003        }
12004
12005        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12006
12007            if (invalidate) {
12008                // Invalidate to show the scrollbars
12009                postInvalidateOnAnimation();
12010            }
12011
12012            if (scrollCache.state == ScrollabilityCache.OFF) {
12013                // FIXME: this is copied from WindowManagerService.
12014                // We should get this value from the system when it
12015                // is possible to do so.
12016                final int KEY_REPEAT_FIRST_DELAY = 750;
12017                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12018            }
12019
12020            // Tell mScrollCache when we should start fading. This may
12021            // extend the fade start time if one was already scheduled
12022            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12023            scrollCache.fadeStartTime = fadeStartTime;
12024            scrollCache.state = ScrollabilityCache.ON;
12025
12026            // Schedule our fader to run, unscheduling any old ones first
12027            if (mAttachInfo != null) {
12028                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12029                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12030            }
12031
12032            return true;
12033        }
12034
12035        return false;
12036    }
12037
12038    /**
12039     * Do not invalidate views which are not visible and which are not running an animation. They
12040     * will not get drawn and they should not set dirty flags as if they will be drawn
12041     */
12042    private boolean skipInvalidate() {
12043        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12044                (!(mParent instanceof ViewGroup) ||
12045                        !((ViewGroup) mParent).isViewTransitioning(this));
12046    }
12047
12048    /**
12049     * Mark the area defined by dirty as needing to be drawn. If the view is
12050     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12051     * point in the future.
12052     * <p>
12053     * This must be called from a UI thread. To call from a non-UI thread, call
12054     * {@link #postInvalidate()}.
12055     * <p>
12056     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12057     * {@code dirty}.
12058     *
12059     * @param dirty the rectangle representing the bounds of the dirty region
12060     */
12061    public void invalidate(Rect dirty) {
12062        final int scrollX = mScrollX;
12063        final int scrollY = mScrollY;
12064        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12065                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12066    }
12067
12068    /**
12069     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12070     * coordinates of the dirty rect are relative to the view. If the view is
12071     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12072     * point in the future.
12073     * <p>
12074     * This must be called from a UI thread. To call from a non-UI thread, call
12075     * {@link #postInvalidate()}.
12076     *
12077     * @param l the left position of the dirty region
12078     * @param t the top position of the dirty region
12079     * @param r the right position of the dirty region
12080     * @param b the bottom position of the dirty region
12081     */
12082    public void invalidate(int l, int t, int r, int b) {
12083        final int scrollX = mScrollX;
12084        final int scrollY = mScrollY;
12085        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12086    }
12087
12088    /**
12089     * Invalidate the whole view. If the view is visible,
12090     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12091     * the future.
12092     * <p>
12093     * This must be called from a UI thread. To call from a non-UI thread, call
12094     * {@link #postInvalidate()}.
12095     */
12096    public void invalidate() {
12097        invalidate(true);
12098    }
12099
12100    /**
12101     * This is where the invalidate() work actually happens. A full invalidate()
12102     * causes the drawing cache to be invalidated, but this function can be
12103     * called with invalidateCache set to false to skip that invalidation step
12104     * for cases that do not need it (for example, a component that remains at
12105     * the same dimensions with the same content).
12106     *
12107     * @param invalidateCache Whether the drawing cache for this view should be
12108     *            invalidated as well. This is usually true for a full
12109     *            invalidate, but may be set to false if the View's contents or
12110     *            dimensions have not changed.
12111     */
12112    void invalidate(boolean invalidateCache) {
12113        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12114    }
12115
12116    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12117            boolean fullInvalidate) {
12118        if (mGhostView != null) {
12119            mGhostView.invalidate(true);
12120            return;
12121        }
12122
12123        if (skipInvalidate()) {
12124            return;
12125        }
12126
12127        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12128                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12129                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12130                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12131            if (fullInvalidate) {
12132                mLastIsOpaque = isOpaque();
12133                mPrivateFlags &= ~PFLAG_DRAWN;
12134            }
12135
12136            mPrivateFlags |= PFLAG_DIRTY;
12137
12138            if (invalidateCache) {
12139                mPrivateFlags |= PFLAG_INVALIDATED;
12140                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12141            }
12142
12143            // Propagate the damage rectangle to the parent view.
12144            final AttachInfo ai = mAttachInfo;
12145            final ViewParent p = mParent;
12146            if (p != null && ai != null && l < r && t < b) {
12147                final Rect damage = ai.mTmpInvalRect;
12148                damage.set(l, t, r, b);
12149                p.invalidateChild(this, damage);
12150            }
12151
12152            // Damage the entire projection receiver, if necessary.
12153            if (mBackground != null && mBackground.isProjected()) {
12154                final View receiver = getProjectionReceiver();
12155                if (receiver != null) {
12156                    receiver.damageInParent();
12157                }
12158            }
12159
12160            // Damage the entire IsolatedZVolume receiving this view's shadow.
12161            if (isHardwareAccelerated() && getZ() != 0) {
12162                damageShadowReceiver();
12163            }
12164        }
12165    }
12166
12167    /**
12168     * @return this view's projection receiver, or {@code null} if none exists
12169     */
12170    private View getProjectionReceiver() {
12171        ViewParent p = getParent();
12172        while (p != null && p instanceof View) {
12173            final View v = (View) p;
12174            if (v.isProjectionReceiver()) {
12175                return v;
12176            }
12177            p = p.getParent();
12178        }
12179
12180        return null;
12181    }
12182
12183    /**
12184     * @return whether the view is a projection receiver
12185     */
12186    private boolean isProjectionReceiver() {
12187        return mBackground != null;
12188    }
12189
12190    /**
12191     * Damage area of the screen that can be covered by this View's shadow.
12192     *
12193     * This method will guarantee that any changes to shadows cast by a View
12194     * are damaged on the screen for future redraw.
12195     */
12196    private void damageShadowReceiver() {
12197        final AttachInfo ai = mAttachInfo;
12198        if (ai != null) {
12199            ViewParent p = getParent();
12200            if (p != null && p instanceof ViewGroup) {
12201                final ViewGroup vg = (ViewGroup) p;
12202                vg.damageInParent();
12203            }
12204        }
12205    }
12206
12207    /**
12208     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12209     * set any flags or handle all of the cases handled by the default invalidation methods.
12210     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12211     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12212     * walk up the hierarchy, transforming the dirty rect as necessary.
12213     *
12214     * The method also handles normal invalidation logic if display list properties are not
12215     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12216     * backup approach, to handle these cases used in the various property-setting methods.
12217     *
12218     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12219     * are not being used in this view
12220     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12221     * list properties are not being used in this view
12222     */
12223    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12224        if (!isHardwareAccelerated()
12225                || !mRenderNode.isValid()
12226                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12227            if (invalidateParent) {
12228                invalidateParentCaches();
12229            }
12230            if (forceRedraw) {
12231                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12232            }
12233            invalidate(false);
12234        } else {
12235            damageInParent();
12236        }
12237        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12238            damageShadowReceiver();
12239        }
12240    }
12241
12242    /**
12243     * Tells the parent view to damage this view's bounds.
12244     *
12245     * @hide
12246     */
12247    protected void damageInParent() {
12248        final AttachInfo ai = mAttachInfo;
12249        final ViewParent p = mParent;
12250        if (p != null && ai != null) {
12251            final Rect r = ai.mTmpInvalRect;
12252            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12253            if (mParent instanceof ViewGroup) {
12254                ((ViewGroup) mParent).damageChild(this, r);
12255            } else {
12256                mParent.invalidateChild(this, r);
12257            }
12258        }
12259    }
12260
12261    /**
12262     * Utility method to transform a given Rect by the current matrix of this view.
12263     */
12264    void transformRect(final Rect rect) {
12265        if (!getMatrix().isIdentity()) {
12266            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12267            boundingRect.set(rect);
12268            getMatrix().mapRect(boundingRect);
12269            rect.set((int) Math.floor(boundingRect.left),
12270                    (int) Math.floor(boundingRect.top),
12271                    (int) Math.ceil(boundingRect.right),
12272                    (int) Math.ceil(boundingRect.bottom));
12273        }
12274    }
12275
12276    /**
12277     * Used to indicate that the parent of this view should clear its caches. This functionality
12278     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12279     * which is necessary when various parent-managed properties of the view change, such as
12280     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12281     * clears the parent caches and does not causes an invalidate event.
12282     *
12283     * @hide
12284     */
12285    protected void invalidateParentCaches() {
12286        if (mParent instanceof View) {
12287            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12288        }
12289    }
12290
12291    /**
12292     * Used to indicate that the parent of this view should be invalidated. This functionality
12293     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12294     * which is necessary when various parent-managed properties of the view change, such as
12295     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12296     * an invalidation event to the parent.
12297     *
12298     * @hide
12299     */
12300    protected void invalidateParentIfNeeded() {
12301        if (isHardwareAccelerated() && mParent instanceof View) {
12302            ((View) mParent).invalidate(true);
12303        }
12304    }
12305
12306    /**
12307     * @hide
12308     */
12309    protected void invalidateParentIfNeededAndWasQuickRejected() {
12310        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12311            // View was rejected last time it was drawn by its parent; this may have changed
12312            invalidateParentIfNeeded();
12313        }
12314    }
12315
12316    /**
12317     * Indicates whether this View is opaque. An opaque View guarantees that it will
12318     * draw all the pixels overlapping its bounds using a fully opaque color.
12319     *
12320     * Subclasses of View should override this method whenever possible to indicate
12321     * whether an instance is opaque. Opaque Views are treated in a special way by
12322     * the View hierarchy, possibly allowing it to perform optimizations during
12323     * invalidate/draw passes.
12324     *
12325     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12326     */
12327    @ViewDebug.ExportedProperty(category = "drawing")
12328    public boolean isOpaque() {
12329        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12330                getFinalAlpha() >= 1.0f;
12331    }
12332
12333    /**
12334     * @hide
12335     */
12336    protected void computeOpaqueFlags() {
12337        // Opaque if:
12338        //   - Has a background
12339        //   - Background is opaque
12340        //   - Doesn't have scrollbars or scrollbars overlay
12341
12342        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12343            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12344        } else {
12345            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12346        }
12347
12348        final int flags = mViewFlags;
12349        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12350                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12351                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12352            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12353        } else {
12354            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12355        }
12356    }
12357
12358    /**
12359     * @hide
12360     */
12361    protected boolean hasOpaqueScrollbars() {
12362        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12363    }
12364
12365    /**
12366     * @return A handler associated with the thread running the View. This
12367     * handler can be used to pump events in the UI events queue.
12368     */
12369    public Handler getHandler() {
12370        final AttachInfo attachInfo = mAttachInfo;
12371        if (attachInfo != null) {
12372            return attachInfo.mHandler;
12373        }
12374        return null;
12375    }
12376
12377    /**
12378     * Gets the view root associated with the View.
12379     * @return The view root, or null if none.
12380     * @hide
12381     */
12382    public ViewRootImpl getViewRootImpl() {
12383        if (mAttachInfo != null) {
12384            return mAttachInfo.mViewRootImpl;
12385        }
12386        return null;
12387    }
12388
12389    /**
12390     * @hide
12391     */
12392    public HardwareRenderer getHardwareRenderer() {
12393        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12394    }
12395
12396    /**
12397     * <p>Causes the Runnable to be added to the message queue.
12398     * The runnable will be run on the user interface thread.</p>
12399     *
12400     * @param action The Runnable that will be executed.
12401     *
12402     * @return Returns true if the Runnable was successfully placed in to the
12403     *         message queue.  Returns false on failure, usually because the
12404     *         looper processing the message queue is exiting.
12405     *
12406     * @see #postDelayed
12407     * @see #removeCallbacks
12408     */
12409    public boolean post(Runnable action) {
12410        final AttachInfo attachInfo = mAttachInfo;
12411        if (attachInfo != null) {
12412            return attachInfo.mHandler.post(action);
12413        }
12414        // Assume that post will succeed later
12415        ViewRootImpl.getRunQueue().post(action);
12416        return true;
12417    }
12418
12419    /**
12420     * <p>Causes the Runnable to be added to the message queue, to be run
12421     * after the specified amount of time elapses.
12422     * The runnable will be run on the user interface thread.</p>
12423     *
12424     * @param action The Runnable that will be executed.
12425     * @param delayMillis The delay (in milliseconds) until the Runnable
12426     *        will be executed.
12427     *
12428     * @return true if the Runnable was successfully placed in to the
12429     *         message queue.  Returns false on failure, usually because the
12430     *         looper processing the message queue is exiting.  Note that a
12431     *         result of true does not mean the Runnable will be processed --
12432     *         if the looper is quit before the delivery time of the message
12433     *         occurs then the message will be dropped.
12434     *
12435     * @see #post
12436     * @see #removeCallbacks
12437     */
12438    public boolean postDelayed(Runnable action, long delayMillis) {
12439        final AttachInfo attachInfo = mAttachInfo;
12440        if (attachInfo != null) {
12441            return attachInfo.mHandler.postDelayed(action, delayMillis);
12442        }
12443        // Assume that post will succeed later
12444        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12445        return true;
12446    }
12447
12448    /**
12449     * <p>Causes the Runnable to execute on the next animation time step.
12450     * The runnable will be run on the user interface thread.</p>
12451     *
12452     * @param action The Runnable that will be executed.
12453     *
12454     * @see #postOnAnimationDelayed
12455     * @see #removeCallbacks
12456     */
12457    public void postOnAnimation(Runnable action) {
12458        final AttachInfo attachInfo = mAttachInfo;
12459        if (attachInfo != null) {
12460            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12461                    Choreographer.CALLBACK_ANIMATION, action, null);
12462        } else {
12463            // Assume that post will succeed later
12464            ViewRootImpl.getRunQueue().post(action);
12465        }
12466    }
12467
12468    /**
12469     * <p>Causes the Runnable to execute on the next animation time step,
12470     * after the specified amount of time elapses.
12471     * The runnable will be run on the user interface thread.</p>
12472     *
12473     * @param action The Runnable that will be executed.
12474     * @param delayMillis The delay (in milliseconds) until the Runnable
12475     *        will be executed.
12476     *
12477     * @see #postOnAnimation
12478     * @see #removeCallbacks
12479     */
12480    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12481        final AttachInfo attachInfo = mAttachInfo;
12482        if (attachInfo != null) {
12483            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12484                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12485        } else {
12486            // Assume that post will succeed later
12487            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12488        }
12489    }
12490
12491    /**
12492     * <p>Removes the specified Runnable from the message queue.</p>
12493     *
12494     * @param action The Runnable to remove from the message handling queue
12495     *
12496     * @return true if this view could ask the Handler to remove the Runnable,
12497     *         false otherwise. When the returned value is true, the Runnable
12498     *         may or may not have been actually removed from the message queue
12499     *         (for instance, if the Runnable was not in the queue already.)
12500     *
12501     * @see #post
12502     * @see #postDelayed
12503     * @see #postOnAnimation
12504     * @see #postOnAnimationDelayed
12505     */
12506    public boolean removeCallbacks(Runnable action) {
12507        if (action != null) {
12508            final AttachInfo attachInfo = mAttachInfo;
12509            if (attachInfo != null) {
12510                attachInfo.mHandler.removeCallbacks(action);
12511                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12512                        Choreographer.CALLBACK_ANIMATION, action, null);
12513            }
12514            // Assume that post will succeed later
12515            ViewRootImpl.getRunQueue().removeCallbacks(action);
12516        }
12517        return true;
12518    }
12519
12520    /**
12521     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12522     * Use this to invalidate the View from a non-UI thread.</p>
12523     *
12524     * <p>This method can be invoked from outside of the UI thread
12525     * only when this View is attached to a window.</p>
12526     *
12527     * @see #invalidate()
12528     * @see #postInvalidateDelayed(long)
12529     */
12530    public void postInvalidate() {
12531        postInvalidateDelayed(0);
12532    }
12533
12534    /**
12535     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12536     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12537     *
12538     * <p>This method can be invoked from outside of the UI thread
12539     * only when this View is attached to a window.</p>
12540     *
12541     * @param left The left coordinate of the rectangle to invalidate.
12542     * @param top The top coordinate of the rectangle to invalidate.
12543     * @param right The right coordinate of the rectangle to invalidate.
12544     * @param bottom The bottom coordinate of the rectangle to invalidate.
12545     *
12546     * @see #invalidate(int, int, int, int)
12547     * @see #invalidate(Rect)
12548     * @see #postInvalidateDelayed(long, int, int, int, int)
12549     */
12550    public void postInvalidate(int left, int top, int right, int bottom) {
12551        postInvalidateDelayed(0, left, top, right, bottom);
12552    }
12553
12554    /**
12555     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12556     * loop. Waits for the specified amount of time.</p>
12557     *
12558     * <p>This method can be invoked from outside of the UI thread
12559     * only when this View is attached to a window.</p>
12560     *
12561     * @param delayMilliseconds the duration in milliseconds to delay the
12562     *         invalidation by
12563     *
12564     * @see #invalidate()
12565     * @see #postInvalidate()
12566     */
12567    public void postInvalidateDelayed(long delayMilliseconds) {
12568        // We try only with the AttachInfo because there's no point in invalidating
12569        // if we are not attached to our window
12570        final AttachInfo attachInfo = mAttachInfo;
12571        if (attachInfo != null) {
12572            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12573        }
12574    }
12575
12576    /**
12577     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12578     * through the event loop. Waits for the specified amount of time.</p>
12579     *
12580     * <p>This method can be invoked from outside of the UI thread
12581     * only when this View is attached to a window.</p>
12582     *
12583     * @param delayMilliseconds the duration in milliseconds to delay the
12584     *         invalidation by
12585     * @param left The left coordinate of the rectangle to invalidate.
12586     * @param top The top coordinate of the rectangle to invalidate.
12587     * @param right The right coordinate of the rectangle to invalidate.
12588     * @param bottom The bottom coordinate of the rectangle to invalidate.
12589     *
12590     * @see #invalidate(int, int, int, int)
12591     * @see #invalidate(Rect)
12592     * @see #postInvalidate(int, int, int, int)
12593     */
12594    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12595            int right, int bottom) {
12596
12597        // We try only with the AttachInfo because there's no point in invalidating
12598        // if we are not attached to our window
12599        final AttachInfo attachInfo = mAttachInfo;
12600        if (attachInfo != null) {
12601            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12602            info.target = this;
12603            info.left = left;
12604            info.top = top;
12605            info.right = right;
12606            info.bottom = bottom;
12607
12608            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12609        }
12610    }
12611
12612    /**
12613     * <p>Cause an invalidate to happen on the next animation time step, typically the
12614     * next display frame.</p>
12615     *
12616     * <p>This method can be invoked from outside of the UI thread
12617     * only when this View is attached to a window.</p>
12618     *
12619     * @see #invalidate()
12620     */
12621    public void postInvalidateOnAnimation() {
12622        // We try only with the AttachInfo because there's no point in invalidating
12623        // if we are not attached to our window
12624        final AttachInfo attachInfo = mAttachInfo;
12625        if (attachInfo != null) {
12626            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12627        }
12628    }
12629
12630    /**
12631     * <p>Cause an invalidate of the specified area to happen on the next animation
12632     * time step, typically the next display frame.</p>
12633     *
12634     * <p>This method can be invoked from outside of the UI thread
12635     * only when this View is attached to a window.</p>
12636     *
12637     * @param left The left coordinate of the rectangle to invalidate.
12638     * @param top The top coordinate of the rectangle to invalidate.
12639     * @param right The right coordinate of the rectangle to invalidate.
12640     * @param bottom The bottom coordinate of the rectangle to invalidate.
12641     *
12642     * @see #invalidate(int, int, int, int)
12643     * @see #invalidate(Rect)
12644     */
12645    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12646        // We try only with the AttachInfo because there's no point in invalidating
12647        // if we are not attached to our window
12648        final AttachInfo attachInfo = mAttachInfo;
12649        if (attachInfo != null) {
12650            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12651            info.target = this;
12652            info.left = left;
12653            info.top = top;
12654            info.right = right;
12655            info.bottom = bottom;
12656
12657            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12658        }
12659    }
12660
12661    /**
12662     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12663     * This event is sent at most once every
12664     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12665     */
12666    private void postSendViewScrolledAccessibilityEventCallback() {
12667        if (mSendViewScrolledAccessibilityEvent == null) {
12668            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12669        }
12670        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12671            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12672            postDelayed(mSendViewScrolledAccessibilityEvent,
12673                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12674        }
12675    }
12676
12677    /**
12678     * Called by a parent to request that a child update its values for mScrollX
12679     * and mScrollY if necessary. This will typically be done if the child is
12680     * animating a scroll using a {@link android.widget.Scroller Scroller}
12681     * object.
12682     */
12683    public void computeScroll() {
12684    }
12685
12686    /**
12687     * <p>Indicate whether the horizontal edges are faded when the view is
12688     * scrolled horizontally.</p>
12689     *
12690     * @return true if the horizontal edges should are faded on scroll, false
12691     *         otherwise
12692     *
12693     * @see #setHorizontalFadingEdgeEnabled(boolean)
12694     *
12695     * @attr ref android.R.styleable#View_requiresFadingEdge
12696     */
12697    public boolean isHorizontalFadingEdgeEnabled() {
12698        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12699    }
12700
12701    /**
12702     * <p>Define whether the horizontal edges should be faded when this view
12703     * is scrolled horizontally.</p>
12704     *
12705     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12706     *                                    be faded when the view is scrolled
12707     *                                    horizontally
12708     *
12709     * @see #isHorizontalFadingEdgeEnabled()
12710     *
12711     * @attr ref android.R.styleable#View_requiresFadingEdge
12712     */
12713    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12714        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12715            if (horizontalFadingEdgeEnabled) {
12716                initScrollCache();
12717            }
12718
12719            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12720        }
12721    }
12722
12723    /**
12724     * <p>Indicate whether the vertical edges are faded when the view is
12725     * scrolled horizontally.</p>
12726     *
12727     * @return true if the vertical edges should are faded on scroll, false
12728     *         otherwise
12729     *
12730     * @see #setVerticalFadingEdgeEnabled(boolean)
12731     *
12732     * @attr ref android.R.styleable#View_requiresFadingEdge
12733     */
12734    public boolean isVerticalFadingEdgeEnabled() {
12735        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12736    }
12737
12738    /**
12739     * <p>Define whether the vertical edges should be faded when this view
12740     * is scrolled vertically.</p>
12741     *
12742     * @param verticalFadingEdgeEnabled true if the vertical edges should
12743     *                                  be faded when the view is scrolled
12744     *                                  vertically
12745     *
12746     * @see #isVerticalFadingEdgeEnabled()
12747     *
12748     * @attr ref android.R.styleable#View_requiresFadingEdge
12749     */
12750    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12751        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12752            if (verticalFadingEdgeEnabled) {
12753                initScrollCache();
12754            }
12755
12756            mViewFlags ^= FADING_EDGE_VERTICAL;
12757        }
12758    }
12759
12760    /**
12761     * Returns the strength, or intensity, of the top faded edge. The strength is
12762     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12763     * returns 0.0 or 1.0 but no value in between.
12764     *
12765     * Subclasses should override this method to provide a smoother fade transition
12766     * when scrolling occurs.
12767     *
12768     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12769     */
12770    protected float getTopFadingEdgeStrength() {
12771        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12772    }
12773
12774    /**
12775     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12776     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12777     * returns 0.0 or 1.0 but no value in between.
12778     *
12779     * Subclasses should override this method to provide a smoother fade transition
12780     * when scrolling occurs.
12781     *
12782     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12783     */
12784    protected float getBottomFadingEdgeStrength() {
12785        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12786                computeVerticalScrollRange() ? 1.0f : 0.0f;
12787    }
12788
12789    /**
12790     * Returns the strength, or intensity, of the left faded edge. The strength is
12791     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12792     * returns 0.0 or 1.0 but no value in between.
12793     *
12794     * Subclasses should override this method to provide a smoother fade transition
12795     * when scrolling occurs.
12796     *
12797     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12798     */
12799    protected float getLeftFadingEdgeStrength() {
12800        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12801    }
12802
12803    /**
12804     * Returns the strength, or intensity, of the right faded edge. The strength is
12805     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12806     * returns 0.0 or 1.0 but no value in between.
12807     *
12808     * Subclasses should override this method to provide a smoother fade transition
12809     * when scrolling occurs.
12810     *
12811     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12812     */
12813    protected float getRightFadingEdgeStrength() {
12814        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12815                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12816    }
12817
12818    /**
12819     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12820     * scrollbar is not drawn by default.</p>
12821     *
12822     * @return true if the horizontal scrollbar should be painted, false
12823     *         otherwise
12824     *
12825     * @see #setHorizontalScrollBarEnabled(boolean)
12826     */
12827    public boolean isHorizontalScrollBarEnabled() {
12828        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12829    }
12830
12831    /**
12832     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12833     * scrollbar is not drawn by default.</p>
12834     *
12835     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12836     *                                   be painted
12837     *
12838     * @see #isHorizontalScrollBarEnabled()
12839     */
12840    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12841        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12842            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12843            computeOpaqueFlags();
12844            resolvePadding();
12845        }
12846    }
12847
12848    /**
12849     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12850     * scrollbar is not drawn by default.</p>
12851     *
12852     * @return true if the vertical scrollbar should be painted, false
12853     *         otherwise
12854     *
12855     * @see #setVerticalScrollBarEnabled(boolean)
12856     */
12857    public boolean isVerticalScrollBarEnabled() {
12858        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12859    }
12860
12861    /**
12862     * <p>Define whether the vertical scrollbar should be drawn or not. The
12863     * scrollbar is not drawn by default.</p>
12864     *
12865     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12866     *                                 be painted
12867     *
12868     * @see #isVerticalScrollBarEnabled()
12869     */
12870    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12871        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12872            mViewFlags ^= SCROLLBARS_VERTICAL;
12873            computeOpaqueFlags();
12874            resolvePadding();
12875        }
12876    }
12877
12878    /**
12879     * @hide
12880     */
12881    protected void recomputePadding() {
12882        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12883    }
12884
12885    /**
12886     * Define whether scrollbars will fade when the view is not scrolling.
12887     *
12888     * @param fadeScrollbars whether to enable fading
12889     *
12890     * @attr ref android.R.styleable#View_fadeScrollbars
12891     */
12892    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12893        initScrollCache();
12894        final ScrollabilityCache scrollabilityCache = mScrollCache;
12895        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12896        if (fadeScrollbars) {
12897            scrollabilityCache.state = ScrollabilityCache.OFF;
12898        } else {
12899            scrollabilityCache.state = ScrollabilityCache.ON;
12900        }
12901    }
12902
12903    /**
12904     *
12905     * Returns true if scrollbars will fade when this view is not scrolling
12906     *
12907     * @return true if scrollbar fading is enabled
12908     *
12909     * @attr ref android.R.styleable#View_fadeScrollbars
12910     */
12911    public boolean isScrollbarFadingEnabled() {
12912        return mScrollCache != null && mScrollCache.fadeScrollBars;
12913    }
12914
12915    /**
12916     *
12917     * Returns the delay before scrollbars fade.
12918     *
12919     * @return the delay before scrollbars fade
12920     *
12921     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12922     */
12923    public int getScrollBarDefaultDelayBeforeFade() {
12924        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12925                mScrollCache.scrollBarDefaultDelayBeforeFade;
12926    }
12927
12928    /**
12929     * Define the delay before scrollbars fade.
12930     *
12931     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12932     *
12933     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12934     */
12935    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12936        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12937    }
12938
12939    /**
12940     *
12941     * Returns the scrollbar fade duration.
12942     *
12943     * @return the scrollbar fade duration
12944     *
12945     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12946     */
12947    public int getScrollBarFadeDuration() {
12948        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12949                mScrollCache.scrollBarFadeDuration;
12950    }
12951
12952    /**
12953     * Define the scrollbar fade duration.
12954     *
12955     * @param scrollBarFadeDuration - the scrollbar fade duration
12956     *
12957     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12958     */
12959    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12960        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12961    }
12962
12963    /**
12964     *
12965     * Returns the scrollbar size.
12966     *
12967     * @return the scrollbar size
12968     *
12969     * @attr ref android.R.styleable#View_scrollbarSize
12970     */
12971    public int getScrollBarSize() {
12972        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12973                mScrollCache.scrollBarSize;
12974    }
12975
12976    /**
12977     * Define the scrollbar size.
12978     *
12979     * @param scrollBarSize - the scrollbar size
12980     *
12981     * @attr ref android.R.styleable#View_scrollbarSize
12982     */
12983    public void setScrollBarSize(int scrollBarSize) {
12984        getScrollCache().scrollBarSize = scrollBarSize;
12985    }
12986
12987    /**
12988     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12989     * inset. When inset, they add to the padding of the view. And the scrollbars
12990     * can be drawn inside the padding area or on the edge of the view. For example,
12991     * if a view has a background drawable and you want to draw the scrollbars
12992     * inside the padding specified by the drawable, you can use
12993     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12994     * appear at the edge of the view, ignoring the padding, then you can use
12995     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12996     * @param style the style of the scrollbars. Should be one of
12997     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12998     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12999     * @see #SCROLLBARS_INSIDE_OVERLAY
13000     * @see #SCROLLBARS_INSIDE_INSET
13001     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13002     * @see #SCROLLBARS_OUTSIDE_INSET
13003     *
13004     * @attr ref android.R.styleable#View_scrollbarStyle
13005     */
13006    public void setScrollBarStyle(@ScrollBarStyle int style) {
13007        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13008            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13009            computeOpaqueFlags();
13010            resolvePadding();
13011        }
13012    }
13013
13014    /**
13015     * <p>Returns the current scrollbar style.</p>
13016     * @return the current scrollbar style
13017     * @see #SCROLLBARS_INSIDE_OVERLAY
13018     * @see #SCROLLBARS_INSIDE_INSET
13019     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13020     * @see #SCROLLBARS_OUTSIDE_INSET
13021     *
13022     * @attr ref android.R.styleable#View_scrollbarStyle
13023     */
13024    @ViewDebug.ExportedProperty(mapping = {
13025            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13026            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13027            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13028            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13029    })
13030    @ScrollBarStyle
13031    public int getScrollBarStyle() {
13032        return mViewFlags & SCROLLBARS_STYLE_MASK;
13033    }
13034
13035    /**
13036     * <p>Compute the horizontal range that the horizontal scrollbar
13037     * represents.</p>
13038     *
13039     * <p>The range is expressed in arbitrary units that must be the same as the
13040     * units used by {@link #computeHorizontalScrollExtent()} and
13041     * {@link #computeHorizontalScrollOffset()}.</p>
13042     *
13043     * <p>The default range is the drawing width of this view.</p>
13044     *
13045     * @return the total horizontal range represented by the horizontal
13046     *         scrollbar
13047     *
13048     * @see #computeHorizontalScrollExtent()
13049     * @see #computeHorizontalScrollOffset()
13050     * @see android.widget.ScrollBarDrawable
13051     */
13052    protected int computeHorizontalScrollRange() {
13053        return getWidth();
13054    }
13055
13056    /**
13057     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13058     * within the horizontal range. This value is used to compute the position
13059     * of the thumb within the scrollbar's track.</p>
13060     *
13061     * <p>The range is expressed in arbitrary units that must be the same as the
13062     * units used by {@link #computeHorizontalScrollRange()} and
13063     * {@link #computeHorizontalScrollExtent()}.</p>
13064     *
13065     * <p>The default offset is the scroll offset of this view.</p>
13066     *
13067     * @return the horizontal offset of the scrollbar's thumb
13068     *
13069     * @see #computeHorizontalScrollRange()
13070     * @see #computeHorizontalScrollExtent()
13071     * @see android.widget.ScrollBarDrawable
13072     */
13073    protected int computeHorizontalScrollOffset() {
13074        return mScrollX;
13075    }
13076
13077    /**
13078     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13079     * within the horizontal range. This value is used to compute the length
13080     * of the thumb within the scrollbar's track.</p>
13081     *
13082     * <p>The range is expressed in arbitrary units that must be the same as the
13083     * units used by {@link #computeHorizontalScrollRange()} and
13084     * {@link #computeHorizontalScrollOffset()}.</p>
13085     *
13086     * <p>The default extent is the drawing width of this view.</p>
13087     *
13088     * @return the horizontal extent of the scrollbar's thumb
13089     *
13090     * @see #computeHorizontalScrollRange()
13091     * @see #computeHorizontalScrollOffset()
13092     * @see android.widget.ScrollBarDrawable
13093     */
13094    protected int computeHorizontalScrollExtent() {
13095        return getWidth();
13096    }
13097
13098    /**
13099     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13100     *
13101     * <p>The range is expressed in arbitrary units that must be the same as the
13102     * units used by {@link #computeVerticalScrollExtent()} and
13103     * {@link #computeVerticalScrollOffset()}.</p>
13104     *
13105     * @return the total vertical range represented by the vertical scrollbar
13106     *
13107     * <p>The default range is the drawing height of this view.</p>
13108     *
13109     * @see #computeVerticalScrollExtent()
13110     * @see #computeVerticalScrollOffset()
13111     * @see android.widget.ScrollBarDrawable
13112     */
13113    protected int computeVerticalScrollRange() {
13114        return getHeight();
13115    }
13116
13117    /**
13118     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13119     * within the horizontal range. This value is used to compute the position
13120     * of the thumb within the scrollbar's track.</p>
13121     *
13122     * <p>The range is expressed in arbitrary units that must be the same as the
13123     * units used by {@link #computeVerticalScrollRange()} and
13124     * {@link #computeVerticalScrollExtent()}.</p>
13125     *
13126     * <p>The default offset is the scroll offset of this view.</p>
13127     *
13128     * @return the vertical offset of the scrollbar's thumb
13129     *
13130     * @see #computeVerticalScrollRange()
13131     * @see #computeVerticalScrollExtent()
13132     * @see android.widget.ScrollBarDrawable
13133     */
13134    protected int computeVerticalScrollOffset() {
13135        return mScrollY;
13136    }
13137
13138    /**
13139     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13140     * within the vertical range. This value is used to compute the length
13141     * of the thumb within the scrollbar's track.</p>
13142     *
13143     * <p>The range is expressed in arbitrary units that must be the same as the
13144     * units used by {@link #computeVerticalScrollRange()} and
13145     * {@link #computeVerticalScrollOffset()}.</p>
13146     *
13147     * <p>The default extent is the drawing height of this view.</p>
13148     *
13149     * @return the vertical extent of the scrollbar's thumb
13150     *
13151     * @see #computeVerticalScrollRange()
13152     * @see #computeVerticalScrollOffset()
13153     * @see android.widget.ScrollBarDrawable
13154     */
13155    protected int computeVerticalScrollExtent() {
13156        return getHeight();
13157    }
13158
13159    /**
13160     * Check if this view can be scrolled horizontally in a certain direction.
13161     *
13162     * @param direction Negative to check scrolling left, positive to check scrolling right.
13163     * @return true if this view can be scrolled in the specified direction, false otherwise.
13164     */
13165    public boolean canScrollHorizontally(int direction) {
13166        final int offset = computeHorizontalScrollOffset();
13167        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13168        if (range == 0) return false;
13169        if (direction < 0) {
13170            return offset > 0;
13171        } else {
13172            return offset < range - 1;
13173        }
13174    }
13175
13176    /**
13177     * Check if this view can be scrolled vertically in a certain direction.
13178     *
13179     * @param direction Negative to check scrolling up, positive to check scrolling down.
13180     * @return true if this view can be scrolled in the specified direction, false otherwise.
13181     */
13182    public boolean canScrollVertically(int direction) {
13183        final int offset = computeVerticalScrollOffset();
13184        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13185        if (range == 0) return false;
13186        if (direction < 0) {
13187            return offset > 0;
13188        } else {
13189            return offset < range - 1;
13190        }
13191    }
13192
13193    /**
13194     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13195     * scrollbars are painted only if they have been awakened first.</p>
13196     *
13197     * @param canvas the canvas on which to draw the scrollbars
13198     *
13199     * @see #awakenScrollBars(int)
13200     */
13201    protected final void onDrawScrollBars(Canvas canvas) {
13202        // scrollbars are drawn only when the animation is running
13203        final ScrollabilityCache cache = mScrollCache;
13204        if (cache != null) {
13205
13206            int state = cache.state;
13207
13208            if (state == ScrollabilityCache.OFF) {
13209                return;
13210            }
13211
13212            boolean invalidate = false;
13213
13214            if (state == ScrollabilityCache.FADING) {
13215                // We're fading -- get our fade interpolation
13216                if (cache.interpolatorValues == null) {
13217                    cache.interpolatorValues = new float[1];
13218                }
13219
13220                float[] values = cache.interpolatorValues;
13221
13222                // Stops the animation if we're done
13223                if (cache.scrollBarInterpolator.timeToValues(values) ==
13224                        Interpolator.Result.FREEZE_END) {
13225                    cache.state = ScrollabilityCache.OFF;
13226                } else {
13227                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13228                }
13229
13230                // This will make the scroll bars inval themselves after
13231                // drawing. We only want this when we're fading so that
13232                // we prevent excessive redraws
13233                invalidate = true;
13234            } else {
13235                // We're just on -- but we may have been fading before so
13236                // reset alpha
13237                cache.scrollBar.mutate().setAlpha(255);
13238            }
13239
13240
13241            final int viewFlags = mViewFlags;
13242
13243            final boolean drawHorizontalScrollBar =
13244                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13245            final boolean drawVerticalScrollBar =
13246                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13247                && !isVerticalScrollBarHidden();
13248
13249            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13250                final int width = mRight - mLeft;
13251                final int height = mBottom - mTop;
13252
13253                final ScrollBarDrawable scrollBar = cache.scrollBar;
13254
13255                final int scrollX = mScrollX;
13256                final int scrollY = mScrollY;
13257                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13258
13259                int left;
13260                int top;
13261                int right;
13262                int bottom;
13263
13264                if (drawHorizontalScrollBar) {
13265                    int size = scrollBar.getSize(false);
13266                    if (size <= 0) {
13267                        size = cache.scrollBarSize;
13268                    }
13269
13270                    scrollBar.setParameters(computeHorizontalScrollRange(),
13271                                            computeHorizontalScrollOffset(),
13272                                            computeHorizontalScrollExtent(), false);
13273                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13274                            getVerticalScrollbarWidth() : 0;
13275                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13276                    left = scrollX + (mPaddingLeft & inside);
13277                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13278                    bottom = top + size;
13279                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13280                    if (invalidate) {
13281                        invalidate(left, top, right, bottom);
13282                    }
13283                }
13284
13285                if (drawVerticalScrollBar) {
13286                    int size = scrollBar.getSize(true);
13287                    if (size <= 0) {
13288                        size = cache.scrollBarSize;
13289                    }
13290
13291                    scrollBar.setParameters(computeVerticalScrollRange(),
13292                                            computeVerticalScrollOffset(),
13293                                            computeVerticalScrollExtent(), true);
13294                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13295                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13296                        verticalScrollbarPosition = isLayoutRtl() ?
13297                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13298                    }
13299                    switch (verticalScrollbarPosition) {
13300                        default:
13301                        case SCROLLBAR_POSITION_RIGHT:
13302                            left = scrollX + width - size - (mUserPaddingRight & inside);
13303                            break;
13304                        case SCROLLBAR_POSITION_LEFT:
13305                            left = scrollX + (mUserPaddingLeft & inside);
13306                            break;
13307                    }
13308                    top = scrollY + (mPaddingTop & inside);
13309                    right = left + size;
13310                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13311                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13312                    if (invalidate) {
13313                        invalidate(left, top, right, bottom);
13314                    }
13315                }
13316            }
13317        }
13318    }
13319
13320    /**
13321     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13322     * FastScroller is visible.
13323     * @return whether to temporarily hide the vertical scrollbar
13324     * @hide
13325     */
13326    protected boolean isVerticalScrollBarHidden() {
13327        return false;
13328    }
13329
13330    /**
13331     * <p>Draw the horizontal scrollbar if
13332     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13333     *
13334     * @param canvas the canvas on which to draw the scrollbar
13335     * @param scrollBar the scrollbar's drawable
13336     *
13337     * @see #isHorizontalScrollBarEnabled()
13338     * @see #computeHorizontalScrollRange()
13339     * @see #computeHorizontalScrollExtent()
13340     * @see #computeHorizontalScrollOffset()
13341     * @see android.widget.ScrollBarDrawable
13342     * @hide
13343     */
13344    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13345            int l, int t, int r, int b) {
13346        scrollBar.setBounds(l, t, r, b);
13347        scrollBar.draw(canvas);
13348    }
13349
13350    /**
13351     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13352     * returns true.</p>
13353     *
13354     * @param canvas the canvas on which to draw the scrollbar
13355     * @param scrollBar the scrollbar's drawable
13356     *
13357     * @see #isVerticalScrollBarEnabled()
13358     * @see #computeVerticalScrollRange()
13359     * @see #computeVerticalScrollExtent()
13360     * @see #computeVerticalScrollOffset()
13361     * @see android.widget.ScrollBarDrawable
13362     * @hide
13363     */
13364    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13365            int l, int t, int r, int b) {
13366        scrollBar.setBounds(l, t, r, b);
13367        scrollBar.draw(canvas);
13368    }
13369
13370    /**
13371     * Implement this to do your drawing.
13372     *
13373     * @param canvas the canvas on which the background will be drawn
13374     */
13375    protected void onDraw(Canvas canvas) {
13376    }
13377
13378    /*
13379     * Caller is responsible for calling requestLayout if necessary.
13380     * (This allows addViewInLayout to not request a new layout.)
13381     */
13382    void assignParent(ViewParent parent) {
13383        if (mParent == null) {
13384            mParent = parent;
13385        } else if (parent == null) {
13386            mParent = null;
13387        } else {
13388            throw new RuntimeException("view " + this + " being added, but"
13389                    + " it already has a parent");
13390        }
13391    }
13392
13393    /**
13394     * This is called when the view is attached to a window.  At this point it
13395     * has a Surface and will start drawing.  Note that this function is
13396     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13397     * however it may be called any time before the first onDraw -- including
13398     * before or after {@link #onMeasure(int, int)}.
13399     *
13400     * @see #onDetachedFromWindow()
13401     */
13402    @CallSuper
13403    protected void onAttachedToWindow() {
13404        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13405            mParent.requestTransparentRegion(this);
13406        }
13407
13408        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13409            initialAwakenScrollBars();
13410            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13411        }
13412
13413        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13414
13415        jumpDrawablesToCurrentState();
13416
13417        resetSubtreeAccessibilityStateChanged();
13418
13419        // rebuild, since Outline not maintained while View is detached
13420        rebuildOutline();
13421
13422        if (isFocused()) {
13423            InputMethodManager imm = InputMethodManager.peekInstance();
13424            if (imm != null) {
13425                imm.focusIn(this);
13426            }
13427        }
13428    }
13429
13430    /**
13431     * Resolve all RTL related properties.
13432     *
13433     * @return true if resolution of RTL properties has been done
13434     *
13435     * @hide
13436     */
13437    public boolean resolveRtlPropertiesIfNeeded() {
13438        if (!needRtlPropertiesResolution()) return false;
13439
13440        // Order is important here: LayoutDirection MUST be resolved first
13441        if (!isLayoutDirectionResolved()) {
13442            resolveLayoutDirection();
13443            resolveLayoutParams();
13444        }
13445        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13446        if (!isTextDirectionResolved()) {
13447            resolveTextDirection();
13448        }
13449        if (!isTextAlignmentResolved()) {
13450            resolveTextAlignment();
13451        }
13452        // Should resolve Drawables before Padding because we need the layout direction of the
13453        // Drawable to correctly resolve Padding.
13454        if (!areDrawablesResolved()) {
13455            resolveDrawables();
13456        }
13457        if (!isPaddingResolved()) {
13458            resolvePadding();
13459        }
13460        onRtlPropertiesChanged(getLayoutDirection());
13461        return true;
13462    }
13463
13464    /**
13465     * Reset resolution of all RTL related properties.
13466     *
13467     * @hide
13468     */
13469    public void resetRtlProperties() {
13470        resetResolvedLayoutDirection();
13471        resetResolvedTextDirection();
13472        resetResolvedTextAlignment();
13473        resetResolvedPadding();
13474        resetResolvedDrawables();
13475    }
13476
13477    /**
13478     * @see #onScreenStateChanged(int)
13479     */
13480    void dispatchScreenStateChanged(int screenState) {
13481        onScreenStateChanged(screenState);
13482    }
13483
13484    /**
13485     * This method is called whenever the state of the screen this view is
13486     * attached to changes. A state change will usually occurs when the screen
13487     * turns on or off (whether it happens automatically or the user does it
13488     * manually.)
13489     *
13490     * @param screenState The new state of the screen. Can be either
13491     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13492     */
13493    public void onScreenStateChanged(int screenState) {
13494    }
13495
13496    /**
13497     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13498     */
13499    private boolean hasRtlSupport() {
13500        return mContext.getApplicationInfo().hasRtlSupport();
13501    }
13502
13503    /**
13504     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13505     * RTL not supported)
13506     */
13507    private boolean isRtlCompatibilityMode() {
13508        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13509        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13510    }
13511
13512    /**
13513     * @return true if RTL properties need resolution.
13514     *
13515     */
13516    private boolean needRtlPropertiesResolution() {
13517        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13518    }
13519
13520    /**
13521     * Called when any RTL property (layout direction or text direction or text alignment) has
13522     * been changed.
13523     *
13524     * Subclasses need to override this method to take care of cached information that depends on the
13525     * resolved layout direction, or to inform child views that inherit their layout direction.
13526     *
13527     * The default implementation does nothing.
13528     *
13529     * @param layoutDirection the direction of the layout
13530     *
13531     * @see #LAYOUT_DIRECTION_LTR
13532     * @see #LAYOUT_DIRECTION_RTL
13533     */
13534    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13535    }
13536
13537    /**
13538     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13539     * that the parent directionality can and will be resolved before its children.
13540     *
13541     * @return true if resolution has been done, false otherwise.
13542     *
13543     * @hide
13544     */
13545    public boolean resolveLayoutDirection() {
13546        // Clear any previous layout direction resolution
13547        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13548
13549        if (hasRtlSupport()) {
13550            // Set resolved depending on layout direction
13551            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13552                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13553                case LAYOUT_DIRECTION_INHERIT:
13554                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13555                    // later to get the correct resolved value
13556                    if (!canResolveLayoutDirection()) return false;
13557
13558                    // Parent has not yet resolved, LTR is still the default
13559                    try {
13560                        if (!mParent.isLayoutDirectionResolved()) return false;
13561
13562                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13563                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13564                        }
13565                    } catch (AbstractMethodError e) {
13566                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13567                                " does not fully implement ViewParent", e);
13568                    }
13569                    break;
13570                case LAYOUT_DIRECTION_RTL:
13571                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13572                    break;
13573                case LAYOUT_DIRECTION_LOCALE:
13574                    if((LAYOUT_DIRECTION_RTL ==
13575                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13576                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13577                    }
13578                    break;
13579                default:
13580                    // Nothing to do, LTR by default
13581            }
13582        }
13583
13584        // Set to resolved
13585        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13586        return true;
13587    }
13588
13589    /**
13590     * Check if layout direction resolution can be done.
13591     *
13592     * @return true if layout direction resolution can be done otherwise return false.
13593     */
13594    public boolean canResolveLayoutDirection() {
13595        switch (getRawLayoutDirection()) {
13596            case LAYOUT_DIRECTION_INHERIT:
13597                if (mParent != null) {
13598                    try {
13599                        return mParent.canResolveLayoutDirection();
13600                    } catch (AbstractMethodError e) {
13601                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13602                                " does not fully implement ViewParent", e);
13603                    }
13604                }
13605                return false;
13606
13607            default:
13608                return true;
13609        }
13610    }
13611
13612    /**
13613     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13614     * {@link #onMeasure(int, int)}.
13615     *
13616     * @hide
13617     */
13618    public void resetResolvedLayoutDirection() {
13619        // Reset the current resolved bits
13620        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13621    }
13622
13623    /**
13624     * @return true if the layout direction is inherited.
13625     *
13626     * @hide
13627     */
13628    public boolean isLayoutDirectionInherited() {
13629        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13630    }
13631
13632    /**
13633     * @return true if layout direction has been resolved.
13634     */
13635    public boolean isLayoutDirectionResolved() {
13636        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13637    }
13638
13639    /**
13640     * Return if padding has been resolved
13641     *
13642     * @hide
13643     */
13644    boolean isPaddingResolved() {
13645        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13646    }
13647
13648    /**
13649     * Resolves padding depending on layout direction, if applicable, and
13650     * recomputes internal padding values to adjust for scroll bars.
13651     *
13652     * @hide
13653     */
13654    public void resolvePadding() {
13655        final int resolvedLayoutDirection = getLayoutDirection();
13656
13657        if (!isRtlCompatibilityMode()) {
13658            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13659            // If start / end padding are defined, they will be resolved (hence overriding) to
13660            // left / right or right / left depending on the resolved layout direction.
13661            // If start / end padding are not defined, use the left / right ones.
13662            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13663                Rect padding = sThreadLocal.get();
13664                if (padding == null) {
13665                    padding = new Rect();
13666                    sThreadLocal.set(padding);
13667                }
13668                mBackground.getPadding(padding);
13669                if (!mLeftPaddingDefined) {
13670                    mUserPaddingLeftInitial = padding.left;
13671                }
13672                if (!mRightPaddingDefined) {
13673                    mUserPaddingRightInitial = padding.right;
13674                }
13675            }
13676            switch (resolvedLayoutDirection) {
13677                case LAYOUT_DIRECTION_RTL:
13678                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13679                        mUserPaddingRight = mUserPaddingStart;
13680                    } else {
13681                        mUserPaddingRight = mUserPaddingRightInitial;
13682                    }
13683                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13684                        mUserPaddingLeft = mUserPaddingEnd;
13685                    } else {
13686                        mUserPaddingLeft = mUserPaddingLeftInitial;
13687                    }
13688                    break;
13689                case LAYOUT_DIRECTION_LTR:
13690                default:
13691                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13692                        mUserPaddingLeft = mUserPaddingStart;
13693                    } else {
13694                        mUserPaddingLeft = mUserPaddingLeftInitial;
13695                    }
13696                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13697                        mUserPaddingRight = mUserPaddingEnd;
13698                    } else {
13699                        mUserPaddingRight = mUserPaddingRightInitial;
13700                    }
13701            }
13702
13703            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13704        }
13705
13706        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13707        onRtlPropertiesChanged(resolvedLayoutDirection);
13708
13709        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13710    }
13711
13712    /**
13713     * Reset the resolved layout direction.
13714     *
13715     * @hide
13716     */
13717    public void resetResolvedPadding() {
13718        resetResolvedPaddingInternal();
13719    }
13720
13721    /**
13722     * Used when we only want to reset *this* view's padding and not trigger overrides
13723     * in ViewGroup that reset children too.
13724     */
13725    void resetResolvedPaddingInternal() {
13726        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13727    }
13728
13729    /**
13730     * This is called when the view is detached from a window.  At this point it
13731     * no longer has a surface for drawing.
13732     *
13733     * @see #onAttachedToWindow()
13734     */
13735    @CallSuper
13736    protected void onDetachedFromWindow() {
13737    }
13738
13739    /**
13740     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13741     * after onDetachedFromWindow().
13742     *
13743     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13744     * The super method should be called at the end of the overridden method to ensure
13745     * subclasses are destroyed first
13746     *
13747     * @hide
13748     */
13749    @CallSuper
13750    protected void onDetachedFromWindowInternal() {
13751        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13752        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13753
13754        removeUnsetPressCallback();
13755        removeLongPressCallback();
13756        removePerformClickCallback();
13757        removeSendViewScrolledAccessibilityEventCallback();
13758        stopNestedScroll();
13759
13760        // Anything that started animating right before detach should already
13761        // be in its final state when re-attached.
13762        jumpDrawablesToCurrentState();
13763
13764        destroyDrawingCache();
13765
13766        cleanupDraw();
13767        mCurrentAnimation = null;
13768    }
13769
13770    private void cleanupDraw() {
13771        resetDisplayList();
13772        if (mAttachInfo != null) {
13773            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13774        }
13775    }
13776
13777    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13778    }
13779
13780    /**
13781     * @return The number of times this view has been attached to a window
13782     */
13783    protected int getWindowAttachCount() {
13784        return mWindowAttachCount;
13785    }
13786
13787    /**
13788     * Retrieve a unique token identifying the window this view is attached to.
13789     * @return Return the window's token for use in
13790     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13791     */
13792    public IBinder getWindowToken() {
13793        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13794    }
13795
13796    /**
13797     * Retrieve the {@link WindowId} for the window this view is
13798     * currently attached to.
13799     */
13800    public WindowId getWindowId() {
13801        if (mAttachInfo == null) {
13802            return null;
13803        }
13804        if (mAttachInfo.mWindowId == null) {
13805            try {
13806                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13807                        mAttachInfo.mWindowToken);
13808                mAttachInfo.mWindowId = new WindowId(
13809                        mAttachInfo.mIWindowId);
13810            } catch (RemoteException e) {
13811            }
13812        }
13813        return mAttachInfo.mWindowId;
13814    }
13815
13816    /**
13817     * Retrieve a unique token identifying the top-level "real" window of
13818     * the window that this view is attached to.  That is, this is like
13819     * {@link #getWindowToken}, except if the window this view in is a panel
13820     * window (attached to another containing window), then the token of
13821     * the containing window is returned instead.
13822     *
13823     * @return Returns the associated window token, either
13824     * {@link #getWindowToken()} or the containing window's token.
13825     */
13826    public IBinder getApplicationWindowToken() {
13827        AttachInfo ai = mAttachInfo;
13828        if (ai != null) {
13829            IBinder appWindowToken = ai.mPanelParentWindowToken;
13830            if (appWindowToken == null) {
13831                appWindowToken = ai.mWindowToken;
13832            }
13833            return appWindowToken;
13834        }
13835        return null;
13836    }
13837
13838    /**
13839     * Gets the logical display to which the view's window has been attached.
13840     *
13841     * @return The logical display, or null if the view is not currently attached to a window.
13842     */
13843    public Display getDisplay() {
13844        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13845    }
13846
13847    /**
13848     * Retrieve private session object this view hierarchy is using to
13849     * communicate with the window manager.
13850     * @return the session object to communicate with the window manager
13851     */
13852    /*package*/ IWindowSession getWindowSession() {
13853        return mAttachInfo != null ? mAttachInfo.mSession : null;
13854    }
13855
13856    /**
13857     * @param info the {@link android.view.View.AttachInfo} to associated with
13858     *        this view
13859     */
13860    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13861        //System.out.println("Attached! " + this);
13862        mAttachInfo = info;
13863        if (mOverlay != null) {
13864            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13865        }
13866        mWindowAttachCount++;
13867        // We will need to evaluate the drawable state at least once.
13868        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13869        if (mFloatingTreeObserver != null) {
13870            info.mTreeObserver.merge(mFloatingTreeObserver);
13871            mFloatingTreeObserver = null;
13872        }
13873        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13874            mAttachInfo.mScrollContainers.add(this);
13875            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13876        }
13877        performCollectViewAttributes(mAttachInfo, visibility);
13878        onAttachedToWindow();
13879
13880        ListenerInfo li = mListenerInfo;
13881        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13882                li != null ? li.mOnAttachStateChangeListeners : null;
13883        if (listeners != null && listeners.size() > 0) {
13884            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13885            // perform the dispatching. The iterator is a safe guard against listeners that
13886            // could mutate the list by calling the various add/remove methods. This prevents
13887            // the array from being modified while we iterate it.
13888            for (OnAttachStateChangeListener listener : listeners) {
13889                listener.onViewAttachedToWindow(this);
13890            }
13891        }
13892
13893        int vis = info.mWindowVisibility;
13894        if (vis != GONE) {
13895            onWindowVisibilityChanged(vis);
13896        }
13897        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13898            // If nobody has evaluated the drawable state yet, then do it now.
13899            refreshDrawableState();
13900        }
13901        needGlobalAttributesUpdate(false);
13902    }
13903
13904    void dispatchDetachedFromWindow() {
13905        AttachInfo info = mAttachInfo;
13906        if (info != null) {
13907            int vis = info.mWindowVisibility;
13908            if (vis != GONE) {
13909                onWindowVisibilityChanged(GONE);
13910            }
13911        }
13912
13913        onDetachedFromWindow();
13914        onDetachedFromWindowInternal();
13915
13916        ListenerInfo li = mListenerInfo;
13917        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13918                li != null ? li.mOnAttachStateChangeListeners : null;
13919        if (listeners != null && listeners.size() > 0) {
13920            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13921            // perform the dispatching. The iterator is a safe guard against listeners that
13922            // could mutate the list by calling the various add/remove methods. This prevents
13923            // the array from being modified while we iterate it.
13924            for (OnAttachStateChangeListener listener : listeners) {
13925                listener.onViewDetachedFromWindow(this);
13926            }
13927        }
13928
13929        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13930            mAttachInfo.mScrollContainers.remove(this);
13931            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13932        }
13933
13934        mAttachInfo = null;
13935        if (mOverlay != null) {
13936            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13937        }
13938    }
13939
13940    /**
13941     * Cancel any deferred high-level input events that were previously posted to the event queue.
13942     *
13943     * <p>Many views post high-level events such as click handlers to the event queue
13944     * to run deferred in order to preserve a desired user experience - clearing visible
13945     * pressed states before executing, etc. This method will abort any events of this nature
13946     * that are currently in flight.</p>
13947     *
13948     * <p>Custom views that generate their own high-level deferred input events should override
13949     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13950     *
13951     * <p>This will also cancel pending input events for any child views.</p>
13952     *
13953     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13954     * This will not impact newer events posted after this call that may occur as a result of
13955     * lower-level input events still waiting in the queue. If you are trying to prevent
13956     * double-submitted  events for the duration of some sort of asynchronous transaction
13957     * you should also take other steps to protect against unexpected double inputs e.g. calling
13958     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13959     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13960     */
13961    public final void cancelPendingInputEvents() {
13962        dispatchCancelPendingInputEvents();
13963    }
13964
13965    /**
13966     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13967     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13968     */
13969    void dispatchCancelPendingInputEvents() {
13970        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13971        onCancelPendingInputEvents();
13972        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13973            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13974                    " did not call through to super.onCancelPendingInputEvents()");
13975        }
13976    }
13977
13978    /**
13979     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13980     * a parent view.
13981     *
13982     * <p>This method is responsible for removing any pending high-level input events that were
13983     * posted to the event queue to run later. Custom view classes that post their own deferred
13984     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13985     * {@link android.os.Handler} should override this method, call
13986     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13987     * </p>
13988     */
13989    public void onCancelPendingInputEvents() {
13990        removePerformClickCallback();
13991        cancelLongPress();
13992        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13993    }
13994
13995    /**
13996     * Store this view hierarchy's frozen state into the given container.
13997     *
13998     * @param container The SparseArray in which to save the view's state.
13999     *
14000     * @see #restoreHierarchyState(android.util.SparseArray)
14001     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14002     * @see #onSaveInstanceState()
14003     */
14004    public void saveHierarchyState(SparseArray<Parcelable> container) {
14005        dispatchSaveInstanceState(container);
14006    }
14007
14008    /**
14009     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14010     * this view and its children. May be overridden to modify how freezing happens to a
14011     * view's children; for example, some views may want to not store state for their children.
14012     *
14013     * @param container The SparseArray in which to save the view's state.
14014     *
14015     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14016     * @see #saveHierarchyState(android.util.SparseArray)
14017     * @see #onSaveInstanceState()
14018     */
14019    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14020        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14021            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14022            Parcelable state = onSaveInstanceState();
14023            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14024                throw new IllegalStateException(
14025                        "Derived class did not call super.onSaveInstanceState()");
14026            }
14027            if (state != null) {
14028                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14029                // + ": " + state);
14030                container.put(mID, state);
14031            }
14032        }
14033    }
14034
14035    /**
14036     * Hook allowing a view to generate a representation of its internal state
14037     * that can later be used to create a new instance with that same state.
14038     * This state should only contain information that is not persistent or can
14039     * not be reconstructed later. For example, you will never store your
14040     * current position on screen because that will be computed again when a
14041     * new instance of the view is placed in its view hierarchy.
14042     * <p>
14043     * Some examples of things you may store here: the current cursor position
14044     * in a text view (but usually not the text itself since that is stored in a
14045     * content provider or other persistent storage), the currently selected
14046     * item in a list view.
14047     *
14048     * @return Returns a Parcelable object containing the view's current dynamic
14049     *         state, or null if there is nothing interesting to save. The
14050     *         default implementation returns null.
14051     * @see #onRestoreInstanceState(android.os.Parcelable)
14052     * @see #saveHierarchyState(android.util.SparseArray)
14053     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14054     * @see #setSaveEnabled(boolean)
14055     */
14056    @CallSuper
14057    protected Parcelable onSaveInstanceState() {
14058        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14059        if (mStartActivityRequestWho != null) {
14060            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14061            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14062            return state;
14063        }
14064        return BaseSavedState.EMPTY_STATE;
14065    }
14066
14067    /**
14068     * Restore this view hierarchy's frozen state from the given container.
14069     *
14070     * @param container The SparseArray which holds previously frozen states.
14071     *
14072     * @see #saveHierarchyState(android.util.SparseArray)
14073     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14074     * @see #onRestoreInstanceState(android.os.Parcelable)
14075     */
14076    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14077        dispatchRestoreInstanceState(container);
14078    }
14079
14080    /**
14081     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14082     * state for this view and its children. May be overridden to modify how restoring
14083     * happens to a view's children; for example, some views may want to not store state
14084     * for their children.
14085     *
14086     * @param container The SparseArray which holds previously saved state.
14087     *
14088     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14089     * @see #restoreHierarchyState(android.util.SparseArray)
14090     * @see #onRestoreInstanceState(android.os.Parcelable)
14091     */
14092    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14093        if (mID != NO_ID) {
14094            Parcelable state = container.get(mID);
14095            if (state != null) {
14096                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14097                // + ": " + state);
14098                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14099                onRestoreInstanceState(state);
14100                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14101                    throw new IllegalStateException(
14102                            "Derived class did not call super.onRestoreInstanceState()");
14103                }
14104            }
14105        }
14106    }
14107
14108    /**
14109     * Hook allowing a view to re-apply a representation of its internal state that had previously
14110     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14111     * null state.
14112     *
14113     * @param state The frozen state that had previously been returned by
14114     *        {@link #onSaveInstanceState}.
14115     *
14116     * @see #onSaveInstanceState()
14117     * @see #restoreHierarchyState(android.util.SparseArray)
14118     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14119     */
14120    @CallSuper
14121    protected void onRestoreInstanceState(Parcelable state) {
14122        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14123        if (state != null && !(state instanceof AbsSavedState)) {
14124            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14125                    + "received " + state.getClass().toString() + " instead. This usually happens "
14126                    + "when two views of different type have the same id in the same hierarchy. "
14127                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14128                    + "other views do not use the same id.");
14129        }
14130        if (state != null && state instanceof BaseSavedState) {
14131            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14132        }
14133    }
14134
14135    /**
14136     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14137     *
14138     * @return the drawing start time in milliseconds
14139     */
14140    public long getDrawingTime() {
14141        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14142    }
14143
14144    /**
14145     * <p>Enables or disables the duplication of the parent's state into this view. When
14146     * duplication is enabled, this view gets its drawable state from its parent rather
14147     * than from its own internal properties.</p>
14148     *
14149     * <p>Note: in the current implementation, setting this property to true after the
14150     * view was added to a ViewGroup might have no effect at all. This property should
14151     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14152     *
14153     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14154     * property is enabled, an exception will be thrown.</p>
14155     *
14156     * <p>Note: if the child view uses and updates additional states which are unknown to the
14157     * parent, these states should not be affected by this method.</p>
14158     *
14159     * @param enabled True to enable duplication of the parent's drawable state, false
14160     *                to disable it.
14161     *
14162     * @see #getDrawableState()
14163     * @see #isDuplicateParentStateEnabled()
14164     */
14165    public void setDuplicateParentStateEnabled(boolean enabled) {
14166        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14167    }
14168
14169    /**
14170     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14171     *
14172     * @return True if this view's drawable state is duplicated from the parent,
14173     *         false otherwise
14174     *
14175     * @see #getDrawableState()
14176     * @see #setDuplicateParentStateEnabled(boolean)
14177     */
14178    public boolean isDuplicateParentStateEnabled() {
14179        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14180    }
14181
14182    /**
14183     * <p>Specifies the type of layer backing this view. The layer can be
14184     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14185     * {@link #LAYER_TYPE_HARDWARE}.</p>
14186     *
14187     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14188     * instance that controls how the layer is composed on screen. The following
14189     * properties of the paint are taken into account when composing the layer:</p>
14190     * <ul>
14191     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14192     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14193     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14194     * </ul>
14195     *
14196     * <p>If this view has an alpha value set to < 1.0 by calling
14197     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14198     * by this view's alpha value.</p>
14199     *
14200     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14201     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14202     * for more information on when and how to use layers.</p>
14203     *
14204     * @param layerType The type of layer to use with this view, must be one of
14205     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14206     *        {@link #LAYER_TYPE_HARDWARE}
14207     * @param paint The paint used to compose the layer. This argument is optional
14208     *        and can be null. It is ignored when the layer type is
14209     *        {@link #LAYER_TYPE_NONE}
14210     *
14211     * @see #getLayerType()
14212     * @see #LAYER_TYPE_NONE
14213     * @see #LAYER_TYPE_SOFTWARE
14214     * @see #LAYER_TYPE_HARDWARE
14215     * @see #setAlpha(float)
14216     *
14217     * @attr ref android.R.styleable#View_layerType
14218     */
14219    public void setLayerType(int layerType, Paint paint) {
14220        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14221            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14222                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14223        }
14224
14225        boolean typeChanged = mRenderNode.setLayerType(layerType);
14226
14227        if (!typeChanged) {
14228            setLayerPaint(paint);
14229            return;
14230        }
14231
14232        // Destroy any previous software drawing cache if needed
14233        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14234            destroyDrawingCache();
14235        }
14236
14237        mLayerType = layerType;
14238        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14239        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14240        mRenderNode.setLayerPaint(mLayerPaint);
14241
14242        // draw() behaves differently if we are on a layer, so we need to
14243        // invalidate() here
14244        invalidateParentCaches();
14245        invalidate(true);
14246    }
14247
14248    /**
14249     * Updates the {@link Paint} object used with the current layer (used only if the current
14250     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14251     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14252     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14253     * ensure that the view gets redrawn immediately.
14254     *
14255     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14256     * instance that controls how the layer is composed on screen. The following
14257     * properties of the paint are taken into account when composing the layer:</p>
14258     * <ul>
14259     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14260     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14261     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14262     * </ul>
14263     *
14264     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14265     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14266     *
14267     * @param paint The paint used to compose the layer. This argument is optional
14268     *        and can be null. It is ignored when the layer type is
14269     *        {@link #LAYER_TYPE_NONE}
14270     *
14271     * @see #setLayerType(int, android.graphics.Paint)
14272     */
14273    public void setLayerPaint(Paint paint) {
14274        int layerType = getLayerType();
14275        if (layerType != LAYER_TYPE_NONE) {
14276            mLayerPaint = paint == null ? new Paint() : paint;
14277            if (layerType == LAYER_TYPE_HARDWARE) {
14278                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14279                    invalidateViewProperty(false, false);
14280                }
14281            } else {
14282                invalidate();
14283            }
14284        }
14285    }
14286
14287    /**
14288     * Indicates whether this view has a static layer. A view with layer type
14289     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
14290     * dynamic.
14291     */
14292    boolean hasStaticLayer() {
14293        return true;
14294    }
14295
14296    /**
14297     * Indicates what type of layer is currently associated with this view. By default
14298     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14299     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14300     * for more information on the different types of layers.
14301     *
14302     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14303     *         {@link #LAYER_TYPE_HARDWARE}
14304     *
14305     * @see #setLayerType(int, android.graphics.Paint)
14306     * @see #buildLayer()
14307     * @see #LAYER_TYPE_NONE
14308     * @see #LAYER_TYPE_SOFTWARE
14309     * @see #LAYER_TYPE_HARDWARE
14310     */
14311    public int getLayerType() {
14312        return mLayerType;
14313    }
14314
14315    /**
14316     * Forces this view's layer to be created and this view to be rendered
14317     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14318     * invoking this method will have no effect.
14319     *
14320     * This method can for instance be used to render a view into its layer before
14321     * starting an animation. If this view is complex, rendering into the layer
14322     * before starting the animation will avoid skipping frames.
14323     *
14324     * @throws IllegalStateException If this view is not attached to a window
14325     *
14326     * @see #setLayerType(int, android.graphics.Paint)
14327     */
14328    public void buildLayer() {
14329        if (mLayerType == LAYER_TYPE_NONE) return;
14330
14331        final AttachInfo attachInfo = mAttachInfo;
14332        if (attachInfo == null) {
14333            throw new IllegalStateException("This view must be attached to a window first");
14334        }
14335
14336        if (getWidth() == 0 || getHeight() == 0) {
14337            return;
14338        }
14339
14340        switch (mLayerType) {
14341            case LAYER_TYPE_HARDWARE:
14342                updateDisplayListIfDirty();
14343                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14344                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14345                }
14346                break;
14347            case LAYER_TYPE_SOFTWARE:
14348                buildDrawingCache(true);
14349                break;
14350        }
14351    }
14352
14353    /**
14354     * If this View draws with a HardwareLayer, returns it.
14355     * Otherwise returns null
14356     *
14357     * TODO: Only TextureView uses this, can we eliminate it?
14358     */
14359    HardwareLayer getHardwareLayer() {
14360        return null;
14361    }
14362
14363    /**
14364     * Destroys all hardware rendering resources. This method is invoked
14365     * when the system needs to reclaim resources. Upon execution of this
14366     * method, you should free any OpenGL resources created by the view.
14367     *
14368     * Note: you <strong>must</strong> call
14369     * <code>super.destroyHardwareResources()</code> when overriding
14370     * this method.
14371     *
14372     * @hide
14373     */
14374    @CallSuper
14375    protected void destroyHardwareResources() {
14376        // Although the Layer will be destroyed by RenderNode, we want to release
14377        // the staging display list, which is also a signal to RenderNode that it's
14378        // safe to free its copy of the display list as it knows that we will
14379        // push an updated DisplayList if we try to draw again
14380        resetDisplayList();
14381    }
14382
14383    /**
14384     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14385     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14386     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14387     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14388     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14389     * null.</p>
14390     *
14391     * <p>Enabling the drawing cache is similar to
14392     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14393     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14394     * drawing cache has no effect on rendering because the system uses a different mechanism
14395     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14396     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14397     * for information on how to enable software and hardware layers.</p>
14398     *
14399     * <p>This API can be used to manually generate
14400     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14401     * {@link #getDrawingCache()}.</p>
14402     *
14403     * @param enabled true to enable the drawing cache, false otherwise
14404     *
14405     * @see #isDrawingCacheEnabled()
14406     * @see #getDrawingCache()
14407     * @see #buildDrawingCache()
14408     * @see #setLayerType(int, android.graphics.Paint)
14409     */
14410    public void setDrawingCacheEnabled(boolean enabled) {
14411        mCachingFailed = false;
14412        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14413    }
14414
14415    /**
14416     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14417     *
14418     * @return true if the drawing cache is enabled
14419     *
14420     * @see #setDrawingCacheEnabled(boolean)
14421     * @see #getDrawingCache()
14422     */
14423    @ViewDebug.ExportedProperty(category = "drawing")
14424    public boolean isDrawingCacheEnabled() {
14425        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14426    }
14427
14428    /**
14429     * Debugging utility which recursively outputs the dirty state of a view and its
14430     * descendants.
14431     *
14432     * @hide
14433     */
14434    @SuppressWarnings({"UnusedDeclaration"})
14435    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14436        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14437                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14438                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14439                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14440        if (clear) {
14441            mPrivateFlags &= clearMask;
14442        }
14443        if (this instanceof ViewGroup) {
14444            ViewGroup parent = (ViewGroup) this;
14445            final int count = parent.getChildCount();
14446            for (int i = 0; i < count; i++) {
14447                final View child = parent.getChildAt(i);
14448                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14449            }
14450        }
14451    }
14452
14453    /**
14454     * This method is used by ViewGroup to cause its children to restore or recreate their
14455     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14456     * to recreate its own display list, which would happen if it went through the normal
14457     * draw/dispatchDraw mechanisms.
14458     *
14459     * @hide
14460     */
14461    protected void dispatchGetDisplayList() {}
14462
14463    /**
14464     * A view that is not attached or hardware accelerated cannot create a display list.
14465     * This method checks these conditions and returns the appropriate result.
14466     *
14467     * @return true if view has the ability to create a display list, false otherwise.
14468     *
14469     * @hide
14470     */
14471    public boolean canHaveDisplayList() {
14472        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14473    }
14474
14475    private void updateDisplayListIfDirty() {
14476        final RenderNode renderNode = mRenderNode;
14477        if (!canHaveDisplayList()) {
14478            // can't populate RenderNode, don't try
14479            return;
14480        }
14481
14482        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14483                || !renderNode.isValid()
14484                || (mRecreateDisplayList)) {
14485            // Don't need to recreate the display list, just need to tell our
14486            // children to restore/recreate theirs
14487            if (renderNode.isValid()
14488                    && !mRecreateDisplayList) {
14489                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14490                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14491                dispatchGetDisplayList();
14492
14493                return; // no work needed
14494            }
14495
14496            // If we got here, we're recreating it. Mark it as such to ensure that
14497            // we copy in child display lists into ours in drawChild()
14498            mRecreateDisplayList = true;
14499
14500            int width = mRight - mLeft;
14501            int height = mBottom - mTop;
14502            int layerType = getLayerType();
14503
14504            final DisplayListCanvas canvas = renderNode.start(width, height);
14505            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14506
14507            try {
14508                final HardwareLayer layer = getHardwareLayer();
14509                if (layer != null && layer.isValid()) {
14510                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14511                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14512                    buildDrawingCache(true);
14513                    Bitmap cache = getDrawingCache(true);
14514                    if (cache != null) {
14515                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14516                    }
14517                } else {
14518                    computeScroll();
14519
14520                    canvas.translate(-mScrollX, -mScrollY);
14521                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14522                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14523
14524                    // Fast path for layouts with no backgrounds
14525                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14526                        dispatchDraw(canvas);
14527                        if (mOverlay != null && !mOverlay.isEmpty()) {
14528                            mOverlay.getOverlayView().draw(canvas);
14529                        }
14530                    } else {
14531                        draw(canvas);
14532                    }
14533                }
14534            } finally {
14535                renderNode.end(canvas);
14536                setDisplayListProperties(renderNode);
14537            }
14538        } else {
14539            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14540            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14541        }
14542    }
14543
14544    /**
14545     * Returns a RenderNode with View draw content recorded, which can be
14546     * used to draw this view again without executing its draw method.
14547     *
14548     * @return A RenderNode ready to replay, or null if caching is not enabled.
14549     *
14550     * @hide
14551     */
14552    public RenderNode getDisplayList() {
14553        updateDisplayListIfDirty();
14554        return mRenderNode;
14555    }
14556
14557    private void resetDisplayList() {
14558        if (mRenderNode.isValid()) {
14559            mRenderNode.destroyDisplayListData();
14560        }
14561
14562        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14563            mBackgroundRenderNode.destroyDisplayListData();
14564        }
14565    }
14566
14567    /**
14568     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14569     *
14570     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14571     *
14572     * @see #getDrawingCache(boolean)
14573     */
14574    public Bitmap getDrawingCache() {
14575        return getDrawingCache(false);
14576    }
14577
14578    /**
14579     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14580     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14581     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14582     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14583     * request the drawing cache by calling this method and draw it on screen if the
14584     * returned bitmap is not null.</p>
14585     *
14586     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14587     * this method will create a bitmap of the same size as this view. Because this bitmap
14588     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14589     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14590     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14591     * size than the view. This implies that your application must be able to handle this
14592     * size.</p>
14593     *
14594     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14595     *        the current density of the screen when the application is in compatibility
14596     *        mode.
14597     *
14598     * @return A bitmap representing this view or null if cache is disabled.
14599     *
14600     * @see #setDrawingCacheEnabled(boolean)
14601     * @see #isDrawingCacheEnabled()
14602     * @see #buildDrawingCache(boolean)
14603     * @see #destroyDrawingCache()
14604     */
14605    public Bitmap getDrawingCache(boolean autoScale) {
14606        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14607            return null;
14608        }
14609        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14610            buildDrawingCache(autoScale);
14611        }
14612        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14613    }
14614
14615    /**
14616     * <p>Frees the resources used by the drawing cache. If you call
14617     * {@link #buildDrawingCache()} manually without calling
14618     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14619     * should cleanup the cache with this method afterwards.</p>
14620     *
14621     * @see #setDrawingCacheEnabled(boolean)
14622     * @see #buildDrawingCache()
14623     * @see #getDrawingCache()
14624     */
14625    public void destroyDrawingCache() {
14626        if (mDrawingCache != null) {
14627            mDrawingCache.recycle();
14628            mDrawingCache = null;
14629        }
14630        if (mUnscaledDrawingCache != null) {
14631            mUnscaledDrawingCache.recycle();
14632            mUnscaledDrawingCache = null;
14633        }
14634    }
14635
14636    /**
14637     * Setting a solid background color for the drawing cache's bitmaps will improve
14638     * performance and memory usage. Note, though that this should only be used if this
14639     * view will always be drawn on top of a solid color.
14640     *
14641     * @param color The background color to use for the drawing cache's bitmap
14642     *
14643     * @see #setDrawingCacheEnabled(boolean)
14644     * @see #buildDrawingCache()
14645     * @see #getDrawingCache()
14646     */
14647    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
14648        if (color != mDrawingCacheBackgroundColor) {
14649            mDrawingCacheBackgroundColor = color;
14650            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14651        }
14652    }
14653
14654    /**
14655     * @see #setDrawingCacheBackgroundColor(int)
14656     *
14657     * @return The background color to used for the drawing cache's bitmap
14658     */
14659    @ColorInt
14660    public int getDrawingCacheBackgroundColor() {
14661        return mDrawingCacheBackgroundColor;
14662    }
14663
14664    /**
14665     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14666     *
14667     * @see #buildDrawingCache(boolean)
14668     */
14669    public void buildDrawingCache() {
14670        buildDrawingCache(false);
14671    }
14672
14673    /**
14674     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14675     *
14676     * <p>If you call {@link #buildDrawingCache()} manually without calling
14677     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14678     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14679     *
14680     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14681     * this method will create a bitmap of the same size as this view. Because this bitmap
14682     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14683     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14684     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14685     * size than the view. This implies that your application must be able to handle this
14686     * size.</p>
14687     *
14688     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14689     * you do not need the drawing cache bitmap, calling this method will increase memory
14690     * usage and cause the view to be rendered in software once, thus negatively impacting
14691     * performance.</p>
14692     *
14693     * @see #getDrawingCache()
14694     * @see #destroyDrawingCache()
14695     */
14696    public void buildDrawingCache(boolean autoScale) {
14697        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14698                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14699            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14700                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14701                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14702            }
14703            try {
14704                buildDrawingCacheImpl(autoScale);
14705            } finally {
14706                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14707            }
14708        }
14709    }
14710
14711    /**
14712     * private, internal implementation of buildDrawingCache, used to enable tracing
14713     */
14714    private void buildDrawingCacheImpl(boolean autoScale) {
14715        mCachingFailed = false;
14716
14717        int width = mRight - mLeft;
14718        int height = mBottom - mTop;
14719
14720        final AttachInfo attachInfo = mAttachInfo;
14721        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14722
14723        if (autoScale && scalingRequired) {
14724            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14725            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14726        }
14727
14728        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14729        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14730        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14731
14732        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14733        final long drawingCacheSize =
14734                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14735        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14736            if (width > 0 && height > 0) {
14737                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14738                        + projectedBitmapSize + " bytes, only "
14739                        + drawingCacheSize + " available");
14740            }
14741            destroyDrawingCache();
14742            mCachingFailed = true;
14743            return;
14744        }
14745
14746        boolean clear = true;
14747        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14748
14749        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14750            Bitmap.Config quality;
14751            if (!opaque) {
14752                // Never pick ARGB_4444 because it looks awful
14753                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14754                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14755                    case DRAWING_CACHE_QUALITY_AUTO:
14756                    case DRAWING_CACHE_QUALITY_LOW:
14757                    case DRAWING_CACHE_QUALITY_HIGH:
14758                    default:
14759                        quality = Bitmap.Config.ARGB_8888;
14760                        break;
14761                }
14762            } else {
14763                // Optimization for translucent windows
14764                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14765                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14766            }
14767
14768            // Try to cleanup memory
14769            if (bitmap != null) bitmap.recycle();
14770
14771            try {
14772                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14773                        width, height, quality);
14774                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14775                if (autoScale) {
14776                    mDrawingCache = bitmap;
14777                } else {
14778                    mUnscaledDrawingCache = bitmap;
14779                }
14780                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14781            } catch (OutOfMemoryError e) {
14782                // If there is not enough memory to create the bitmap cache, just
14783                // ignore the issue as bitmap caches are not required to draw the
14784                // view hierarchy
14785                if (autoScale) {
14786                    mDrawingCache = null;
14787                } else {
14788                    mUnscaledDrawingCache = null;
14789                }
14790                mCachingFailed = true;
14791                return;
14792            }
14793
14794            clear = drawingCacheBackgroundColor != 0;
14795        }
14796
14797        Canvas canvas;
14798        if (attachInfo != null) {
14799            canvas = attachInfo.mCanvas;
14800            if (canvas == null) {
14801                canvas = new Canvas();
14802            }
14803            canvas.setBitmap(bitmap);
14804            // Temporarily clobber the cached Canvas in case one of our children
14805            // is also using a drawing cache. Without this, the children would
14806            // steal the canvas by attaching their own bitmap to it and bad, bad
14807            // thing would happen (invisible views, corrupted drawings, etc.)
14808            attachInfo.mCanvas = null;
14809        } else {
14810            // This case should hopefully never or seldom happen
14811            canvas = new Canvas(bitmap);
14812        }
14813
14814        if (clear) {
14815            bitmap.eraseColor(drawingCacheBackgroundColor);
14816        }
14817
14818        computeScroll();
14819        final int restoreCount = canvas.save();
14820
14821        if (autoScale && scalingRequired) {
14822            final float scale = attachInfo.mApplicationScale;
14823            canvas.scale(scale, scale);
14824        }
14825
14826        canvas.translate(-mScrollX, -mScrollY);
14827
14828        mPrivateFlags |= PFLAG_DRAWN;
14829        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14830                mLayerType != LAYER_TYPE_NONE) {
14831            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14832        }
14833
14834        // Fast path for layouts with no backgrounds
14835        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14836            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14837            dispatchDraw(canvas);
14838            if (mOverlay != null && !mOverlay.isEmpty()) {
14839                mOverlay.getOverlayView().draw(canvas);
14840            }
14841        } else {
14842            draw(canvas);
14843        }
14844
14845        canvas.restoreToCount(restoreCount);
14846        canvas.setBitmap(null);
14847
14848        if (attachInfo != null) {
14849            // Restore the cached Canvas for our siblings
14850            attachInfo.mCanvas = canvas;
14851        }
14852    }
14853
14854    /**
14855     * Create a snapshot of the view into a bitmap.  We should probably make
14856     * some form of this public, but should think about the API.
14857     */
14858    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14859        int width = mRight - mLeft;
14860        int height = mBottom - mTop;
14861
14862        final AttachInfo attachInfo = mAttachInfo;
14863        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14864        width = (int) ((width * scale) + 0.5f);
14865        height = (int) ((height * scale) + 0.5f);
14866
14867        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14868                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14869        if (bitmap == null) {
14870            throw new OutOfMemoryError();
14871        }
14872
14873        Resources resources = getResources();
14874        if (resources != null) {
14875            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14876        }
14877
14878        Canvas canvas;
14879        if (attachInfo != null) {
14880            canvas = attachInfo.mCanvas;
14881            if (canvas == null) {
14882                canvas = new Canvas();
14883            }
14884            canvas.setBitmap(bitmap);
14885            // Temporarily clobber the cached Canvas in case one of our children
14886            // is also using a drawing cache. Without this, the children would
14887            // steal the canvas by attaching their own bitmap to it and bad, bad
14888            // things would happen (invisible views, corrupted drawings, etc.)
14889            attachInfo.mCanvas = null;
14890        } else {
14891            // This case should hopefully never or seldom happen
14892            canvas = new Canvas(bitmap);
14893        }
14894
14895        if ((backgroundColor & 0xff000000) != 0) {
14896            bitmap.eraseColor(backgroundColor);
14897        }
14898
14899        computeScroll();
14900        final int restoreCount = canvas.save();
14901        canvas.scale(scale, scale);
14902        canvas.translate(-mScrollX, -mScrollY);
14903
14904        // Temporarily remove the dirty mask
14905        int flags = mPrivateFlags;
14906        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14907
14908        // Fast path for layouts with no backgrounds
14909        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14910            dispatchDraw(canvas);
14911            if (mOverlay != null && !mOverlay.isEmpty()) {
14912                mOverlay.getOverlayView().draw(canvas);
14913            }
14914        } else {
14915            draw(canvas);
14916        }
14917
14918        mPrivateFlags = flags;
14919
14920        canvas.restoreToCount(restoreCount);
14921        canvas.setBitmap(null);
14922
14923        if (attachInfo != null) {
14924            // Restore the cached Canvas for our siblings
14925            attachInfo.mCanvas = canvas;
14926        }
14927
14928        return bitmap;
14929    }
14930
14931    /**
14932     * Indicates whether this View is currently in edit mode. A View is usually
14933     * in edit mode when displayed within a developer tool. For instance, if
14934     * this View is being drawn by a visual user interface builder, this method
14935     * should return true.
14936     *
14937     * Subclasses should check the return value of this method to provide
14938     * different behaviors if their normal behavior might interfere with the
14939     * host environment. For instance: the class spawns a thread in its
14940     * constructor, the drawing code relies on device-specific features, etc.
14941     *
14942     * This method is usually checked in the drawing code of custom widgets.
14943     *
14944     * @return True if this View is in edit mode, false otherwise.
14945     */
14946    public boolean isInEditMode() {
14947        return false;
14948    }
14949
14950    /**
14951     * If the View draws content inside its padding and enables fading edges,
14952     * it needs to support padding offsets. Padding offsets are added to the
14953     * fading edges to extend the length of the fade so that it covers pixels
14954     * drawn inside the padding.
14955     *
14956     * Subclasses of this class should override this method if they need
14957     * to draw content inside the padding.
14958     *
14959     * @return True if padding offset must be applied, false otherwise.
14960     *
14961     * @see #getLeftPaddingOffset()
14962     * @see #getRightPaddingOffset()
14963     * @see #getTopPaddingOffset()
14964     * @see #getBottomPaddingOffset()
14965     *
14966     * @since CURRENT
14967     */
14968    protected boolean isPaddingOffsetRequired() {
14969        return false;
14970    }
14971
14972    /**
14973     * Amount by which to extend the left fading region. Called only when
14974     * {@link #isPaddingOffsetRequired()} returns true.
14975     *
14976     * @return The left padding offset in pixels.
14977     *
14978     * @see #isPaddingOffsetRequired()
14979     *
14980     * @since CURRENT
14981     */
14982    protected int getLeftPaddingOffset() {
14983        return 0;
14984    }
14985
14986    /**
14987     * Amount by which to extend the right fading region. Called only when
14988     * {@link #isPaddingOffsetRequired()} returns true.
14989     *
14990     * @return The right padding offset in pixels.
14991     *
14992     * @see #isPaddingOffsetRequired()
14993     *
14994     * @since CURRENT
14995     */
14996    protected int getRightPaddingOffset() {
14997        return 0;
14998    }
14999
15000    /**
15001     * Amount by which to extend the top fading region. Called only when
15002     * {@link #isPaddingOffsetRequired()} returns true.
15003     *
15004     * @return The top padding offset in pixels.
15005     *
15006     * @see #isPaddingOffsetRequired()
15007     *
15008     * @since CURRENT
15009     */
15010    protected int getTopPaddingOffset() {
15011        return 0;
15012    }
15013
15014    /**
15015     * Amount by which to extend the bottom fading region. Called only when
15016     * {@link #isPaddingOffsetRequired()} returns true.
15017     *
15018     * @return The bottom padding offset in pixels.
15019     *
15020     * @see #isPaddingOffsetRequired()
15021     *
15022     * @since CURRENT
15023     */
15024    protected int getBottomPaddingOffset() {
15025        return 0;
15026    }
15027
15028    /**
15029     * @hide
15030     * @param offsetRequired
15031     */
15032    protected int getFadeTop(boolean offsetRequired) {
15033        int top = mPaddingTop;
15034        if (offsetRequired) top += getTopPaddingOffset();
15035        return top;
15036    }
15037
15038    /**
15039     * @hide
15040     * @param offsetRequired
15041     */
15042    protected int getFadeHeight(boolean offsetRequired) {
15043        int padding = mPaddingTop;
15044        if (offsetRequired) padding += getTopPaddingOffset();
15045        return mBottom - mTop - mPaddingBottom - padding;
15046    }
15047
15048    /**
15049     * <p>Indicates whether this view is attached to a hardware accelerated
15050     * window or not.</p>
15051     *
15052     * <p>Even if this method returns true, it does not mean that every call
15053     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15054     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15055     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15056     * window is hardware accelerated,
15057     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15058     * return false, and this method will return true.</p>
15059     *
15060     * @return True if the view is attached to a window and the window is
15061     *         hardware accelerated; false in any other case.
15062     */
15063    @ViewDebug.ExportedProperty(category = "drawing")
15064    public boolean isHardwareAccelerated() {
15065        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15066    }
15067
15068    /**
15069     * Sets a rectangular area on this view to which the view will be clipped
15070     * when it is drawn. Setting the value to null will remove the clip bounds
15071     * and the view will draw normally, using its full bounds.
15072     *
15073     * @param clipBounds The rectangular area, in the local coordinates of
15074     * this view, to which future drawing operations will be clipped.
15075     */
15076    public void setClipBounds(Rect clipBounds) {
15077        if (clipBounds == mClipBounds
15078                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15079            return;
15080        }
15081        if (clipBounds != null) {
15082            if (mClipBounds == null) {
15083                mClipBounds = new Rect(clipBounds);
15084            } else {
15085                mClipBounds.set(clipBounds);
15086            }
15087        } else {
15088            mClipBounds = null;
15089        }
15090        mRenderNode.setClipBounds(mClipBounds);
15091        invalidateViewProperty(false, false);
15092    }
15093
15094    /**
15095     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15096     *
15097     * @return A copy of the current clip bounds if clip bounds are set,
15098     * otherwise null.
15099     */
15100    public Rect getClipBounds() {
15101        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15102    }
15103
15104    /**
15105     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15106     * case of an active Animation being run on the view.
15107     */
15108    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15109            Animation a, boolean scalingRequired) {
15110        Transformation invalidationTransform;
15111        final int flags = parent.mGroupFlags;
15112        final boolean initialized = a.isInitialized();
15113        if (!initialized) {
15114            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15115            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15116            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15117            onAnimationStart();
15118        }
15119
15120        final Transformation t = parent.getChildTransformation();
15121        boolean more = a.getTransformation(drawingTime, t, 1f);
15122        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15123            if (parent.mInvalidationTransformation == null) {
15124                parent.mInvalidationTransformation = new Transformation();
15125            }
15126            invalidationTransform = parent.mInvalidationTransformation;
15127            a.getTransformation(drawingTime, invalidationTransform, 1f);
15128        } else {
15129            invalidationTransform = t;
15130        }
15131
15132        if (more) {
15133            if (!a.willChangeBounds()) {
15134                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15135                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15136                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15137                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15138                    // The child need to draw an animation, potentially offscreen, so
15139                    // make sure we do not cancel invalidate requests
15140                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15141                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15142                }
15143            } else {
15144                if (parent.mInvalidateRegion == null) {
15145                    parent.mInvalidateRegion = new RectF();
15146                }
15147                final RectF region = parent.mInvalidateRegion;
15148                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15149                        invalidationTransform);
15150
15151                // The child need to draw an animation, potentially offscreen, so
15152                // make sure we do not cancel invalidate requests
15153                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15154
15155                final int left = mLeft + (int) region.left;
15156                final int top = mTop + (int) region.top;
15157                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15158                        top + (int) (region.height() + .5f));
15159            }
15160        }
15161        return more;
15162    }
15163
15164    /**
15165     * This method is called by getDisplayList() when a display list is recorded for a View.
15166     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15167     */
15168    void setDisplayListProperties(RenderNode renderNode) {
15169        if (renderNode != null) {
15170            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15171            renderNode.setClipToBounds(mParent instanceof ViewGroup
15172                    && ((ViewGroup) mParent).getClipChildren());
15173
15174            float alpha = 1;
15175            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15176                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15177                ViewGroup parentVG = (ViewGroup) mParent;
15178                final Transformation t = parentVG.getChildTransformation();
15179                if (parentVG.getChildStaticTransformation(this, t)) {
15180                    final int transformType = t.getTransformationType();
15181                    if (transformType != Transformation.TYPE_IDENTITY) {
15182                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15183                            alpha = t.getAlpha();
15184                        }
15185                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15186                            renderNode.setStaticMatrix(t.getMatrix());
15187                        }
15188                    }
15189                }
15190            }
15191            if (mTransformationInfo != null) {
15192                alpha *= getFinalAlpha();
15193                if (alpha < 1) {
15194                    final int multipliedAlpha = (int) (255 * alpha);
15195                    if (onSetAlpha(multipliedAlpha)) {
15196                        alpha = 1;
15197                    }
15198                }
15199                renderNode.setAlpha(alpha);
15200            } else if (alpha < 1) {
15201                renderNode.setAlpha(alpha);
15202            }
15203        }
15204    }
15205
15206    /**
15207     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15208     *
15209     * This is where the View specializes rendering behavior based on layer type,
15210     * and hardware acceleration.
15211     */
15212    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15213        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15214        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15215         *
15216         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15217         * HW accelerated, it can't handle drawing RenderNodes.
15218         */
15219        boolean drawingWithRenderNode = mAttachInfo != null
15220                && mAttachInfo.mHardwareAccelerated
15221                && hardwareAcceleratedCanvas;
15222
15223        boolean more = false;
15224        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15225        final int parentFlags = parent.mGroupFlags;
15226
15227        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15228            parent.getChildTransformation().clear();
15229            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15230        }
15231
15232        Transformation transformToApply = null;
15233        boolean concatMatrix = false;
15234        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15235        final Animation a = getAnimation();
15236        if (a != null) {
15237            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15238            concatMatrix = a.willChangeTransformationMatrix();
15239            if (concatMatrix) {
15240                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15241            }
15242            transformToApply = parent.getChildTransformation();
15243        } else {
15244            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15245                // No longer animating: clear out old animation matrix
15246                mRenderNode.setAnimationMatrix(null);
15247                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15248            }
15249            if (!drawingWithRenderNode
15250                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15251                final Transformation t = parent.getChildTransformation();
15252                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15253                if (hasTransform) {
15254                    final int transformType = t.getTransformationType();
15255                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15256                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15257                }
15258            }
15259        }
15260
15261        concatMatrix |= !childHasIdentityMatrix;
15262
15263        // Sets the flag as early as possible to allow draw() implementations
15264        // to call invalidate() successfully when doing animations
15265        mPrivateFlags |= PFLAG_DRAWN;
15266
15267        if (!concatMatrix &&
15268                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15269                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15270                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15271                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15272            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15273            return more;
15274        }
15275        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15276
15277        if (hardwareAcceleratedCanvas) {
15278            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15279            // retain the flag's value temporarily in the mRecreateDisplayList flag
15280            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15281            mPrivateFlags &= ~PFLAG_INVALIDATED;
15282        }
15283
15284        RenderNode renderNode = null;
15285        Bitmap cache = null;
15286        int layerType = getLayerType();
15287        if (layerType == LAYER_TYPE_SOFTWARE
15288                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15289            layerType = LAYER_TYPE_SOFTWARE;
15290            buildDrawingCache(true);
15291            cache = getDrawingCache(true);
15292        }
15293
15294        if (drawingWithRenderNode) {
15295            // Delay getting the display list until animation-driven alpha values are
15296            // set up and possibly passed on to the view
15297            renderNode = getDisplayList();
15298            if (!renderNode.isValid()) {
15299                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15300                // to getDisplayList(), the display list will be marked invalid and we should not
15301                // try to use it again.
15302                renderNode = null;
15303                drawingWithRenderNode = false;
15304            }
15305        }
15306
15307        int sx = 0;
15308        int sy = 0;
15309        if (!drawingWithRenderNode) {
15310            computeScroll();
15311            sx = mScrollX;
15312            sy = mScrollY;
15313        }
15314
15315        final boolean hasNoCache = cache == null || drawingWithRenderNode;
15316        final boolean offsetForScroll = cache == null
15317                && !drawingWithRenderNode
15318                && layerType != LAYER_TYPE_HARDWARE;
15319
15320        int restoreTo = -1;
15321        if (!drawingWithRenderNode || transformToApply != null) {
15322            restoreTo = canvas.save();
15323        }
15324        if (offsetForScroll) {
15325            canvas.translate(mLeft - sx, mTop - sy);
15326        } else {
15327            if (!drawingWithRenderNode) {
15328                canvas.translate(mLeft, mTop);
15329            }
15330            if (scalingRequired) {
15331                if (drawingWithRenderNode) {
15332                    // TODO: Might not need this if we put everything inside the DL
15333                    restoreTo = canvas.save();
15334                }
15335                // mAttachInfo cannot be null, otherwise scalingRequired == false
15336                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15337                canvas.scale(scale, scale);
15338            }
15339        }
15340
15341        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15342        if (transformToApply != null
15343                || alpha < 1
15344                || !hasIdentityMatrix()
15345                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15346            if (transformToApply != null || !childHasIdentityMatrix) {
15347                int transX = 0;
15348                int transY = 0;
15349
15350                if (offsetForScroll) {
15351                    transX = -sx;
15352                    transY = -sy;
15353                }
15354
15355                if (transformToApply != null) {
15356                    if (concatMatrix) {
15357                        if (drawingWithRenderNode) {
15358                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15359                        } else {
15360                            // Undo the scroll translation, apply the transformation matrix,
15361                            // then redo the scroll translate to get the correct result.
15362                            canvas.translate(-transX, -transY);
15363                            canvas.concat(transformToApply.getMatrix());
15364                            canvas.translate(transX, transY);
15365                        }
15366                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15367                    }
15368
15369                    float transformAlpha = transformToApply.getAlpha();
15370                    if (transformAlpha < 1) {
15371                        alpha *= transformAlpha;
15372                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15373                    }
15374                }
15375
15376                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
15377                    canvas.translate(-transX, -transY);
15378                    canvas.concat(getMatrix());
15379                    canvas.translate(transX, transY);
15380                }
15381            }
15382
15383            // Deal with alpha if it is or used to be <1
15384            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15385                if (alpha < 1) {
15386                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15387                } else {
15388                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15389                }
15390                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15391                if (hasNoCache) {
15392                    final int multipliedAlpha = (int) (255 * alpha);
15393                    if (!onSetAlpha(multipliedAlpha)) {
15394                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15395                        if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0
15396                                || layerType != LAYER_TYPE_NONE) {
15397                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15398                        }
15399                        if (drawingWithRenderNode) {
15400                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15401                        } else if (layerType == LAYER_TYPE_NONE) {
15402                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
15403                                    multipliedAlpha, layerFlags);
15404                        }
15405                    } else {
15406                        // Alpha is handled by the child directly, clobber the layer's alpha
15407                        mPrivateFlags |= PFLAG_ALPHA_SET;
15408                    }
15409                }
15410            }
15411        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15412            onSetAlpha(255);
15413            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15414        }
15415
15416        if (!drawingWithRenderNode) {
15417            // apply clips directly, since RenderNode won't do it for this draw
15418            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
15419                if (offsetForScroll) {
15420                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
15421                } else {
15422                    if (!scalingRequired || cache == null) {
15423                        canvas.clipRect(0, 0, getWidth(), getHeight());
15424                    } else {
15425                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15426                    }
15427                }
15428            }
15429
15430            if (mClipBounds != null) {
15431                // clip bounds ignore scroll
15432                canvas.clipRect(mClipBounds);
15433            }
15434        }
15435
15436        if (hasNoCache) {
15437            boolean layerRendered = false;
15438            if (layerType == LAYER_TYPE_HARDWARE && !drawingWithRenderNode) {
15439                final HardwareLayer layer = getHardwareLayer();
15440                if (layer != null && layer.isValid()) {
15441                    int restoreAlpha = mLayerPaint.getAlpha();
15442                    mLayerPaint.setAlpha((int) (alpha * 255));
15443                    ((DisplayListCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15444                    mLayerPaint.setAlpha(restoreAlpha);
15445                    layerRendered = true;
15446                } else {
15447                    canvas.saveLayer(sx, sy, sx + getWidth(), sy + getHeight(), mLayerPaint);
15448                }
15449            }
15450
15451            if (!layerRendered) {
15452                if (!drawingWithRenderNode) {
15453                    // Fast path for layouts with no backgrounds
15454                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15455                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15456                        dispatchDraw(canvas);
15457                    } else {
15458                        draw(canvas);
15459                    }
15460                } else {
15461                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15462                    ((DisplayListCanvas) canvas).drawRenderNode(renderNode, parentFlags);
15463                }
15464            }
15465        } else if (cache != null) {
15466            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15467            Paint cachePaint;
15468            int restoreAlpha = 0;
15469
15470            if (layerType == LAYER_TYPE_NONE) {
15471                cachePaint = parent.mCachePaint;
15472                if (cachePaint == null) {
15473                    cachePaint = new Paint();
15474                    cachePaint.setDither(false);
15475                    parent.mCachePaint = cachePaint;
15476                }
15477            } else {
15478                cachePaint = mLayerPaint;
15479                restoreAlpha = mLayerPaint.getAlpha();
15480            }
15481            cachePaint.setAlpha((int) (alpha * 255));
15482            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15483            cachePaint.setAlpha(restoreAlpha);
15484        }
15485
15486        if (restoreTo >= 0) {
15487            canvas.restoreToCount(restoreTo);
15488        }
15489
15490        if (a != null && !more) {
15491            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
15492                onSetAlpha(255);
15493            }
15494            parent.finishAnimatingView(this, a);
15495        }
15496
15497        if (more && hardwareAcceleratedCanvas) {
15498            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15499                // alpha animations should cause the child to recreate its display list
15500                invalidate(true);
15501            }
15502        }
15503
15504        mRecreateDisplayList = false;
15505
15506        return more;
15507    }
15508
15509    /**
15510     * Manually render this view (and all of its children) to the given Canvas.
15511     * The view must have already done a full layout before this function is
15512     * called.  When implementing a view, implement
15513     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15514     * If you do need to override this method, call the superclass version.
15515     *
15516     * @param canvas The Canvas to which the View is rendered.
15517     */
15518    @CallSuper
15519    public void draw(Canvas canvas) {
15520        final int privateFlags = mPrivateFlags;
15521        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15522                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15523        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15524
15525        /*
15526         * Draw traversal performs several drawing steps which must be executed
15527         * in the appropriate order:
15528         *
15529         *      1. Draw the background
15530         *      2. If necessary, save the canvas' layers to prepare for fading
15531         *      3. Draw view's content
15532         *      4. Draw children
15533         *      5. If necessary, draw the fading edges and restore layers
15534         *      6. Draw decorations (scrollbars for instance)
15535         */
15536
15537        // Step 1, draw the background, if needed
15538        int saveCount;
15539
15540        if (!dirtyOpaque) {
15541            drawBackground(canvas);
15542        }
15543
15544        // skip step 2 & 5 if possible (common case)
15545        final int viewFlags = mViewFlags;
15546        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15547        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15548        if (!verticalEdges && !horizontalEdges) {
15549            // Step 3, draw the content
15550            if (!dirtyOpaque) onDraw(canvas);
15551
15552            // Step 4, draw the children
15553            dispatchDraw(canvas);
15554
15555            // Overlay is part of the content and draws beneath Foreground
15556            if (mOverlay != null && !mOverlay.isEmpty()) {
15557                mOverlay.getOverlayView().dispatchDraw(canvas);
15558            }
15559
15560            // Step 6, draw decorations (foreground, scrollbars)
15561            onDrawForeground(canvas);
15562
15563            // we're done...
15564            return;
15565        }
15566
15567        /*
15568         * Here we do the full fledged routine...
15569         * (this is an uncommon case where speed matters less,
15570         * this is why we repeat some of the tests that have been
15571         * done above)
15572         */
15573
15574        boolean drawTop = false;
15575        boolean drawBottom = false;
15576        boolean drawLeft = false;
15577        boolean drawRight = false;
15578
15579        float topFadeStrength = 0.0f;
15580        float bottomFadeStrength = 0.0f;
15581        float leftFadeStrength = 0.0f;
15582        float rightFadeStrength = 0.0f;
15583
15584        // Step 2, save the canvas' layers
15585        int paddingLeft = mPaddingLeft;
15586
15587        final boolean offsetRequired = isPaddingOffsetRequired();
15588        if (offsetRequired) {
15589            paddingLeft += getLeftPaddingOffset();
15590        }
15591
15592        int left = mScrollX + paddingLeft;
15593        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15594        int top = mScrollY + getFadeTop(offsetRequired);
15595        int bottom = top + getFadeHeight(offsetRequired);
15596
15597        if (offsetRequired) {
15598            right += getRightPaddingOffset();
15599            bottom += getBottomPaddingOffset();
15600        }
15601
15602        final ScrollabilityCache scrollabilityCache = mScrollCache;
15603        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15604        int length = (int) fadeHeight;
15605
15606        // clip the fade length if top and bottom fades overlap
15607        // overlapping fades produce odd-looking artifacts
15608        if (verticalEdges && (top + length > bottom - length)) {
15609            length = (bottom - top) / 2;
15610        }
15611
15612        // also clip horizontal fades if necessary
15613        if (horizontalEdges && (left + length > right - length)) {
15614            length = (right - left) / 2;
15615        }
15616
15617        if (verticalEdges) {
15618            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15619            drawTop = topFadeStrength * fadeHeight > 1.0f;
15620            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15621            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15622        }
15623
15624        if (horizontalEdges) {
15625            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15626            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15627            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15628            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15629        }
15630
15631        saveCount = canvas.getSaveCount();
15632
15633        int solidColor = getSolidColor();
15634        if (solidColor == 0) {
15635            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15636
15637            if (drawTop) {
15638                canvas.saveLayer(left, top, right, top + length, null, flags);
15639            }
15640
15641            if (drawBottom) {
15642                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15643            }
15644
15645            if (drawLeft) {
15646                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15647            }
15648
15649            if (drawRight) {
15650                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15651            }
15652        } else {
15653            scrollabilityCache.setFadeColor(solidColor);
15654        }
15655
15656        // Step 3, draw the content
15657        if (!dirtyOpaque) onDraw(canvas);
15658
15659        // Step 4, draw the children
15660        dispatchDraw(canvas);
15661
15662        // Step 5, draw the fade effect and restore layers
15663        final Paint p = scrollabilityCache.paint;
15664        final Matrix matrix = scrollabilityCache.matrix;
15665        final Shader fade = scrollabilityCache.shader;
15666
15667        if (drawTop) {
15668            matrix.setScale(1, fadeHeight * topFadeStrength);
15669            matrix.postTranslate(left, top);
15670            fade.setLocalMatrix(matrix);
15671            p.setShader(fade);
15672            canvas.drawRect(left, top, right, top + length, p);
15673        }
15674
15675        if (drawBottom) {
15676            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15677            matrix.postRotate(180);
15678            matrix.postTranslate(left, bottom);
15679            fade.setLocalMatrix(matrix);
15680            p.setShader(fade);
15681            canvas.drawRect(left, bottom - length, right, bottom, p);
15682        }
15683
15684        if (drawLeft) {
15685            matrix.setScale(1, fadeHeight * leftFadeStrength);
15686            matrix.postRotate(-90);
15687            matrix.postTranslate(left, top);
15688            fade.setLocalMatrix(matrix);
15689            p.setShader(fade);
15690            canvas.drawRect(left, top, left + length, bottom, p);
15691        }
15692
15693        if (drawRight) {
15694            matrix.setScale(1, fadeHeight * rightFadeStrength);
15695            matrix.postRotate(90);
15696            matrix.postTranslate(right, top);
15697            fade.setLocalMatrix(matrix);
15698            p.setShader(fade);
15699            canvas.drawRect(right - length, top, right, bottom, p);
15700        }
15701
15702        canvas.restoreToCount(saveCount);
15703
15704        // Overlay is part of the content and draws beneath Foreground
15705        if (mOverlay != null && !mOverlay.isEmpty()) {
15706            mOverlay.getOverlayView().dispatchDraw(canvas);
15707        }
15708
15709        // Step 6, draw decorations (foreground, scrollbars)
15710        onDrawForeground(canvas);
15711    }
15712
15713    /**
15714     * Draws the background onto the specified canvas.
15715     *
15716     * @param canvas Canvas on which to draw the background
15717     */
15718    private void drawBackground(Canvas canvas) {
15719        final Drawable background = mBackground;
15720        if (background == null) {
15721            return;
15722        }
15723
15724        if (mBackgroundSizeChanged) {
15725            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15726            mBackgroundSizeChanged = false;
15727            rebuildOutline();
15728        }
15729
15730        // Attempt to use a display list if requested.
15731        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15732                && mAttachInfo.mHardwareRenderer != null) {
15733            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15734
15735            final RenderNode renderNode = mBackgroundRenderNode;
15736            if (renderNode != null && renderNode.isValid()) {
15737                setBackgroundRenderNodeProperties(renderNode);
15738                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15739                return;
15740            }
15741        }
15742
15743        final int scrollX = mScrollX;
15744        final int scrollY = mScrollY;
15745        if ((scrollX | scrollY) == 0) {
15746            background.draw(canvas);
15747        } else {
15748            canvas.translate(scrollX, scrollY);
15749            background.draw(canvas);
15750            canvas.translate(-scrollX, -scrollY);
15751        }
15752    }
15753
15754    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15755        renderNode.setTranslationX(mScrollX);
15756        renderNode.setTranslationY(mScrollY);
15757    }
15758
15759    /**
15760     * Creates a new display list or updates the existing display list for the
15761     * specified Drawable.
15762     *
15763     * @param drawable Drawable for which to create a display list
15764     * @param renderNode Existing RenderNode, or {@code null}
15765     * @return A valid display list for the specified drawable
15766     */
15767    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15768        if (renderNode == null) {
15769            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15770        }
15771
15772        final Rect bounds = drawable.getBounds();
15773        final int width = bounds.width();
15774        final int height = bounds.height();
15775        final DisplayListCanvas canvas = renderNode.start(width, height);
15776
15777        // Reverse left/top translation done by drawable canvas, which will
15778        // instead be applied by rendernode's LTRB bounds below. This way, the
15779        // drawable's bounds match with its rendernode bounds and its content
15780        // will lie within those bounds in the rendernode tree.
15781        canvas.translate(-bounds.left, -bounds.top);
15782
15783        try {
15784            drawable.draw(canvas);
15785        } finally {
15786            renderNode.end(canvas);
15787        }
15788
15789        // Set up drawable properties that are view-independent.
15790        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15791        renderNode.setProjectBackwards(drawable.isProjected());
15792        renderNode.setProjectionReceiver(true);
15793        renderNode.setClipToBounds(false);
15794        return renderNode;
15795    }
15796
15797    /**
15798     * Returns the overlay for this view, creating it if it does not yet exist.
15799     * Adding drawables to the overlay will cause them to be displayed whenever
15800     * the view itself is redrawn. Objects in the overlay should be actively
15801     * managed: remove them when they should not be displayed anymore. The
15802     * overlay will always have the same size as its host view.
15803     *
15804     * <p>Note: Overlays do not currently work correctly with {@link
15805     * SurfaceView} or {@link TextureView}; contents in overlays for these
15806     * types of views may not display correctly.</p>
15807     *
15808     * @return The ViewOverlay object for this view.
15809     * @see ViewOverlay
15810     */
15811    public ViewOverlay getOverlay() {
15812        if (mOverlay == null) {
15813            mOverlay = new ViewOverlay(mContext, this);
15814        }
15815        return mOverlay;
15816    }
15817
15818    /**
15819     * Override this if your view is known to always be drawn on top of a solid color background,
15820     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15821     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15822     * should be set to 0xFF.
15823     *
15824     * @see #setVerticalFadingEdgeEnabled(boolean)
15825     * @see #setHorizontalFadingEdgeEnabled(boolean)
15826     *
15827     * @return The known solid color background for this view, or 0 if the color may vary
15828     */
15829    @ViewDebug.ExportedProperty(category = "drawing")
15830    @ColorInt
15831    public int getSolidColor() {
15832        return 0;
15833    }
15834
15835    /**
15836     * Build a human readable string representation of the specified view flags.
15837     *
15838     * @param flags the view flags to convert to a string
15839     * @return a String representing the supplied flags
15840     */
15841    private static String printFlags(int flags) {
15842        String output = "";
15843        int numFlags = 0;
15844        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15845            output += "TAKES_FOCUS";
15846            numFlags++;
15847        }
15848
15849        switch (flags & VISIBILITY_MASK) {
15850        case INVISIBLE:
15851            if (numFlags > 0) {
15852                output += " ";
15853            }
15854            output += "INVISIBLE";
15855            // USELESS HERE numFlags++;
15856            break;
15857        case GONE:
15858            if (numFlags > 0) {
15859                output += " ";
15860            }
15861            output += "GONE";
15862            // USELESS HERE numFlags++;
15863            break;
15864        default:
15865            break;
15866        }
15867        return output;
15868    }
15869
15870    /**
15871     * Build a human readable string representation of the specified private
15872     * view flags.
15873     *
15874     * @param privateFlags the private view flags to convert to a string
15875     * @return a String representing the supplied flags
15876     */
15877    private static String printPrivateFlags(int privateFlags) {
15878        String output = "";
15879        int numFlags = 0;
15880
15881        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15882            output += "WANTS_FOCUS";
15883            numFlags++;
15884        }
15885
15886        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15887            if (numFlags > 0) {
15888                output += " ";
15889            }
15890            output += "FOCUSED";
15891            numFlags++;
15892        }
15893
15894        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15895            if (numFlags > 0) {
15896                output += " ";
15897            }
15898            output += "SELECTED";
15899            numFlags++;
15900        }
15901
15902        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15903            if (numFlags > 0) {
15904                output += " ";
15905            }
15906            output += "IS_ROOT_NAMESPACE";
15907            numFlags++;
15908        }
15909
15910        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15911            if (numFlags > 0) {
15912                output += " ";
15913            }
15914            output += "HAS_BOUNDS";
15915            numFlags++;
15916        }
15917
15918        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15919            if (numFlags > 0) {
15920                output += " ";
15921            }
15922            output += "DRAWN";
15923            // USELESS HERE numFlags++;
15924        }
15925        return output;
15926    }
15927
15928    /**
15929     * <p>Indicates whether or not this view's layout will be requested during
15930     * the next hierarchy layout pass.</p>
15931     *
15932     * @return true if the layout will be forced during next layout pass
15933     */
15934    public boolean isLayoutRequested() {
15935        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15936    }
15937
15938    /**
15939     * Return true if o is a ViewGroup that is laying out using optical bounds.
15940     * @hide
15941     */
15942    public static boolean isLayoutModeOptical(Object o) {
15943        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15944    }
15945
15946    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15947        Insets parentInsets = mParent instanceof View ?
15948                ((View) mParent).getOpticalInsets() : Insets.NONE;
15949        Insets childInsets = getOpticalInsets();
15950        return setFrame(
15951                left   + parentInsets.left - childInsets.left,
15952                top    + parentInsets.top  - childInsets.top,
15953                right  + parentInsets.left + childInsets.right,
15954                bottom + parentInsets.top  + childInsets.bottom);
15955    }
15956
15957    /**
15958     * Assign a size and position to a view and all of its
15959     * descendants
15960     *
15961     * <p>This is the second phase of the layout mechanism.
15962     * (The first is measuring). In this phase, each parent calls
15963     * layout on all of its children to position them.
15964     * This is typically done using the child measurements
15965     * that were stored in the measure pass().</p>
15966     *
15967     * <p>Derived classes should not override this method.
15968     * Derived classes with children should override
15969     * onLayout. In that method, they should
15970     * call layout on each of their children.</p>
15971     *
15972     * @param l Left position, relative to parent
15973     * @param t Top position, relative to parent
15974     * @param r Right position, relative to parent
15975     * @param b Bottom position, relative to parent
15976     */
15977    @SuppressWarnings({"unchecked"})
15978    public void layout(int l, int t, int r, int b) {
15979        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15980            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15981            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15982        }
15983
15984        int oldL = mLeft;
15985        int oldT = mTop;
15986        int oldB = mBottom;
15987        int oldR = mRight;
15988
15989        boolean changed = isLayoutModeOptical(mParent) ?
15990                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15991
15992        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15993            onLayout(changed, l, t, r, b);
15994            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15995
15996            ListenerInfo li = mListenerInfo;
15997            if (li != null && li.mOnLayoutChangeListeners != null) {
15998                ArrayList<OnLayoutChangeListener> listenersCopy =
15999                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16000                int numListeners = listenersCopy.size();
16001                for (int i = 0; i < numListeners; ++i) {
16002                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16003                }
16004            }
16005        }
16006
16007        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16008        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16009    }
16010
16011    /**
16012     * Called from layout when this view should
16013     * assign a size and position to each of its children.
16014     *
16015     * Derived classes with children should override
16016     * this method and call layout on each of
16017     * their children.
16018     * @param changed This is a new size or position for this view
16019     * @param left Left position, relative to parent
16020     * @param top Top position, relative to parent
16021     * @param right Right position, relative to parent
16022     * @param bottom Bottom position, relative to parent
16023     */
16024    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16025    }
16026
16027    /**
16028     * Assign a size and position to this view.
16029     *
16030     * This is called from layout.
16031     *
16032     * @param left Left position, relative to parent
16033     * @param top Top position, relative to parent
16034     * @param right Right position, relative to parent
16035     * @param bottom Bottom position, relative to parent
16036     * @return true if the new size and position are different than the
16037     *         previous ones
16038     * {@hide}
16039     */
16040    protected boolean setFrame(int left, int top, int right, int bottom) {
16041        boolean changed = false;
16042
16043        if (DBG) {
16044            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16045                    + right + "," + bottom + ")");
16046        }
16047
16048        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16049            changed = true;
16050
16051            // Remember our drawn bit
16052            int drawn = mPrivateFlags & PFLAG_DRAWN;
16053
16054            int oldWidth = mRight - mLeft;
16055            int oldHeight = mBottom - mTop;
16056            int newWidth = right - left;
16057            int newHeight = bottom - top;
16058            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16059
16060            // Invalidate our old position
16061            invalidate(sizeChanged);
16062
16063            mLeft = left;
16064            mTop = top;
16065            mRight = right;
16066            mBottom = bottom;
16067            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16068
16069            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16070
16071
16072            if (sizeChanged) {
16073                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16074            }
16075
16076            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16077                // If we are visible, force the DRAWN bit to on so that
16078                // this invalidate will go through (at least to our parent).
16079                // This is because someone may have invalidated this view
16080                // before this call to setFrame came in, thereby clearing
16081                // the DRAWN bit.
16082                mPrivateFlags |= PFLAG_DRAWN;
16083                invalidate(sizeChanged);
16084                // parent display list may need to be recreated based on a change in the bounds
16085                // of any child
16086                invalidateParentCaches();
16087            }
16088
16089            // Reset drawn bit to original value (invalidate turns it off)
16090            mPrivateFlags |= drawn;
16091
16092            mBackgroundSizeChanged = true;
16093            if (mForegroundInfo != null) {
16094                mForegroundInfo.mBoundsChanged = true;
16095            }
16096
16097            notifySubtreeAccessibilityStateChangedIfNeeded();
16098        }
16099        return changed;
16100    }
16101
16102    /**
16103     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16104     * @hide
16105     */
16106    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16107        setFrame(left, top, right, bottom);
16108    }
16109
16110    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16111        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16112        if (mOverlay != null) {
16113            mOverlay.getOverlayView().setRight(newWidth);
16114            mOverlay.getOverlayView().setBottom(newHeight);
16115        }
16116        rebuildOutline();
16117    }
16118
16119    /**
16120     * Finalize inflating a view from XML.  This is called as the last phase
16121     * of inflation, after all child views have been added.
16122     *
16123     * <p>Even if the subclass overrides onFinishInflate, they should always be
16124     * sure to call the super method, so that we get called.
16125     */
16126    @CallSuper
16127    protected void onFinishInflate() {
16128    }
16129
16130    /**
16131     * Returns the resources associated with this view.
16132     *
16133     * @return Resources object.
16134     */
16135    public Resources getResources() {
16136        return mResources;
16137    }
16138
16139    /**
16140     * Invalidates the specified Drawable.
16141     *
16142     * @param drawable the drawable to invalidate
16143     */
16144    @Override
16145    public void invalidateDrawable(@NonNull Drawable drawable) {
16146        if (verifyDrawable(drawable)) {
16147            final Rect dirty = drawable.getDirtyBounds();
16148            final int scrollX = mScrollX;
16149            final int scrollY = mScrollY;
16150
16151            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16152                    dirty.right + scrollX, dirty.bottom + scrollY);
16153            rebuildOutline();
16154        }
16155    }
16156
16157    /**
16158     * Schedules an action on a drawable to occur at a specified time.
16159     *
16160     * @param who the recipient of the action
16161     * @param what the action to run on the drawable
16162     * @param when the time at which the action must occur. Uses the
16163     *        {@link SystemClock#uptimeMillis} timebase.
16164     */
16165    @Override
16166    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16167        if (verifyDrawable(who) && what != null) {
16168            final long delay = when - SystemClock.uptimeMillis();
16169            if (mAttachInfo != null) {
16170                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16171                        Choreographer.CALLBACK_ANIMATION, what, who,
16172                        Choreographer.subtractFrameDelay(delay));
16173            } else {
16174                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16175            }
16176        }
16177    }
16178
16179    /**
16180     * Cancels a scheduled action on a drawable.
16181     *
16182     * @param who the recipient of the action
16183     * @param what the action to cancel
16184     */
16185    @Override
16186    public void unscheduleDrawable(Drawable who, Runnable what) {
16187        if (verifyDrawable(who) && what != null) {
16188            if (mAttachInfo != null) {
16189                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16190                        Choreographer.CALLBACK_ANIMATION, what, who);
16191            }
16192            ViewRootImpl.getRunQueue().removeCallbacks(what);
16193        }
16194    }
16195
16196    /**
16197     * Unschedule any events associated with the given Drawable.  This can be
16198     * used when selecting a new Drawable into a view, so that the previous
16199     * one is completely unscheduled.
16200     *
16201     * @param who The Drawable to unschedule.
16202     *
16203     * @see #drawableStateChanged
16204     */
16205    public void unscheduleDrawable(Drawable who) {
16206        if (mAttachInfo != null && who != null) {
16207            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16208                    Choreographer.CALLBACK_ANIMATION, null, who);
16209        }
16210    }
16211
16212    /**
16213     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16214     * that the View directionality can and will be resolved before its Drawables.
16215     *
16216     * Will call {@link View#onResolveDrawables} when resolution is done.
16217     *
16218     * @hide
16219     */
16220    protected void resolveDrawables() {
16221        // Drawables resolution may need to happen before resolving the layout direction (which is
16222        // done only during the measure() call).
16223        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16224        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16225        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16226        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16227        // direction to be resolved as its resolved value will be the same as its raw value.
16228        if (!isLayoutDirectionResolved() &&
16229                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16230            return;
16231        }
16232
16233        final int layoutDirection = isLayoutDirectionResolved() ?
16234                getLayoutDirection() : getRawLayoutDirection();
16235
16236        if (mBackground != null) {
16237            mBackground.setLayoutDirection(layoutDirection);
16238        }
16239        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16240            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16241        }
16242        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16243        onResolveDrawables(layoutDirection);
16244    }
16245
16246    boolean areDrawablesResolved() {
16247        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16248    }
16249
16250    /**
16251     * Called when layout direction has been resolved.
16252     *
16253     * The default implementation does nothing.
16254     *
16255     * @param layoutDirection The resolved layout direction.
16256     *
16257     * @see #LAYOUT_DIRECTION_LTR
16258     * @see #LAYOUT_DIRECTION_RTL
16259     *
16260     * @hide
16261     */
16262    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16263    }
16264
16265    /**
16266     * @hide
16267     */
16268    protected void resetResolvedDrawables() {
16269        resetResolvedDrawablesInternal();
16270    }
16271
16272    void resetResolvedDrawablesInternal() {
16273        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16274    }
16275
16276    /**
16277     * If your view subclass is displaying its own Drawable objects, it should
16278     * override this function and return true for any Drawable it is
16279     * displaying.  This allows animations for those drawables to be
16280     * scheduled.
16281     *
16282     * <p>Be sure to call through to the super class when overriding this
16283     * function.
16284     *
16285     * @param who The Drawable to verify.  Return true if it is one you are
16286     *            displaying, else return the result of calling through to the
16287     *            super class.
16288     *
16289     * @return boolean If true than the Drawable is being displayed in the
16290     *         view; else false and it is not allowed to animate.
16291     *
16292     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16293     * @see #drawableStateChanged()
16294     */
16295    @CallSuper
16296    protected boolean verifyDrawable(Drawable who) {
16297        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16298                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16299    }
16300
16301    /**
16302     * This function is called whenever the state of the view changes in such
16303     * a way that it impacts the state of drawables being shown.
16304     * <p>
16305     * If the View has a StateListAnimator, it will also be called to run necessary state
16306     * change animations.
16307     * <p>
16308     * Be sure to call through to the superclass when overriding this function.
16309     *
16310     * @see Drawable#setState(int[])
16311     */
16312    @CallSuper
16313    protected void drawableStateChanged() {
16314        final int[] state = getDrawableState();
16315
16316        final Drawable bg = mBackground;
16317        if (bg != null && bg.isStateful()) {
16318            bg.setState(state);
16319        }
16320
16321        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16322        if (fg != null && fg.isStateful()) {
16323            fg.setState(state);
16324        }
16325
16326        if (mScrollCache != null) {
16327            final Drawable scrollBar = mScrollCache.scrollBar;
16328            if (scrollBar != null && scrollBar.isStateful()) {
16329                scrollBar.setState(state);
16330            }
16331        }
16332
16333        if (mStateListAnimator != null) {
16334            mStateListAnimator.setState(state);
16335        }
16336    }
16337
16338    /**
16339     * This function is called whenever the view hotspot changes and needs to
16340     * be propagated to drawables or child views managed by the view.
16341     * <p>
16342     * Dispatching to child views is handled by
16343     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16344     * <p>
16345     * Be sure to call through to the superclass when overriding this function.
16346     *
16347     * @param x hotspot x coordinate
16348     * @param y hotspot y coordinate
16349     */
16350    @CallSuper
16351    public void drawableHotspotChanged(float x, float y) {
16352        if (mBackground != null) {
16353            mBackground.setHotspot(x, y);
16354        }
16355        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16356            mForegroundInfo.mDrawable.setHotspot(x, y);
16357        }
16358
16359        dispatchDrawableHotspotChanged(x, y);
16360    }
16361
16362    /**
16363     * Dispatches drawableHotspotChanged to all of this View's children.
16364     *
16365     * @param x hotspot x coordinate
16366     * @param y hotspot y coordinate
16367     * @see #drawableHotspotChanged(float, float)
16368     */
16369    public void dispatchDrawableHotspotChanged(float x, float y) {
16370    }
16371
16372    /**
16373     * Call this to force a view to update its drawable state. This will cause
16374     * drawableStateChanged to be called on this view. Views that are interested
16375     * in the new state should call getDrawableState.
16376     *
16377     * @see #drawableStateChanged
16378     * @see #getDrawableState
16379     */
16380    public void refreshDrawableState() {
16381        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16382        drawableStateChanged();
16383
16384        ViewParent parent = mParent;
16385        if (parent != null) {
16386            parent.childDrawableStateChanged(this);
16387        }
16388    }
16389
16390    /**
16391     * Return an array of resource IDs of the drawable states representing the
16392     * current state of the view.
16393     *
16394     * @return The current drawable state
16395     *
16396     * @see Drawable#setState(int[])
16397     * @see #drawableStateChanged()
16398     * @see #onCreateDrawableState(int)
16399     */
16400    public final int[] getDrawableState() {
16401        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16402            return mDrawableState;
16403        } else {
16404            mDrawableState = onCreateDrawableState(0);
16405            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16406            return mDrawableState;
16407        }
16408    }
16409
16410    /**
16411     * Generate the new {@link android.graphics.drawable.Drawable} state for
16412     * this view. This is called by the view
16413     * system when the cached Drawable state is determined to be invalid.  To
16414     * retrieve the current state, you should use {@link #getDrawableState}.
16415     *
16416     * @param extraSpace if non-zero, this is the number of extra entries you
16417     * would like in the returned array in which you can place your own
16418     * states.
16419     *
16420     * @return Returns an array holding the current {@link Drawable} state of
16421     * the view.
16422     *
16423     * @see #mergeDrawableStates(int[], int[])
16424     */
16425    protected int[] onCreateDrawableState(int extraSpace) {
16426        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16427                mParent instanceof View) {
16428            return ((View) mParent).onCreateDrawableState(extraSpace);
16429        }
16430
16431        int[] drawableState;
16432
16433        int privateFlags = mPrivateFlags;
16434
16435        int viewStateIndex = 0;
16436        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16437        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16438        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16439        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16440        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16441        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16442        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16443                HardwareRenderer.isAvailable()) {
16444            // This is set if HW acceleration is requested, even if the current
16445            // process doesn't allow it.  This is just to allow app preview
16446            // windows to better match their app.
16447            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16448        }
16449        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16450
16451        final int privateFlags2 = mPrivateFlags2;
16452        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16453            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16454        }
16455        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16456            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16457        }
16458
16459        drawableState = StateSet.get(viewStateIndex);
16460
16461        //noinspection ConstantIfStatement
16462        if (false) {
16463            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16464            Log.i("View", toString()
16465                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16466                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16467                    + " fo=" + hasFocus()
16468                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16469                    + " wf=" + hasWindowFocus()
16470                    + ": " + Arrays.toString(drawableState));
16471        }
16472
16473        if (extraSpace == 0) {
16474            return drawableState;
16475        }
16476
16477        final int[] fullState;
16478        if (drawableState != null) {
16479            fullState = new int[drawableState.length + extraSpace];
16480            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16481        } else {
16482            fullState = new int[extraSpace];
16483        }
16484
16485        return fullState;
16486    }
16487
16488    /**
16489     * Merge your own state values in <var>additionalState</var> into the base
16490     * state values <var>baseState</var> that were returned by
16491     * {@link #onCreateDrawableState(int)}.
16492     *
16493     * @param baseState The base state values returned by
16494     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16495     * own additional state values.
16496     *
16497     * @param additionalState The additional state values you would like
16498     * added to <var>baseState</var>; this array is not modified.
16499     *
16500     * @return As a convenience, the <var>baseState</var> array you originally
16501     * passed into the function is returned.
16502     *
16503     * @see #onCreateDrawableState(int)
16504     */
16505    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16506        final int N = baseState.length;
16507        int i = N - 1;
16508        while (i >= 0 && baseState[i] == 0) {
16509            i--;
16510        }
16511        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16512        return baseState;
16513    }
16514
16515    /**
16516     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16517     * on all Drawable objects associated with this view.
16518     * <p>
16519     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16520     * attached to this view.
16521     */
16522    public void jumpDrawablesToCurrentState() {
16523        if (mBackground != null) {
16524            mBackground.jumpToCurrentState();
16525        }
16526        if (mStateListAnimator != null) {
16527            mStateListAnimator.jumpToCurrentState();
16528        }
16529        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16530            mForegroundInfo.mDrawable.jumpToCurrentState();
16531        }
16532    }
16533
16534    /**
16535     * Sets the background color for this view.
16536     * @param color the color of the background
16537     */
16538    @RemotableViewMethod
16539    public void setBackgroundColor(@ColorInt int color) {
16540        if (mBackground instanceof ColorDrawable) {
16541            ((ColorDrawable) mBackground.mutate()).setColor(color);
16542            computeOpaqueFlags();
16543            mBackgroundResource = 0;
16544        } else {
16545            setBackground(new ColorDrawable(color));
16546        }
16547    }
16548
16549    /**
16550     * If the view has a ColorDrawable background, returns the color of that
16551     * drawable.
16552     *
16553     * @return The color of the ColorDrawable background, if set, otherwise 0.
16554     */
16555    @ColorInt
16556    public int getBackgroundColor() {
16557        if (mBackground instanceof ColorDrawable) {
16558            return ((ColorDrawable) mBackground).getColor();
16559        }
16560        return 0;
16561    }
16562
16563    /**
16564     * Set the background to a given resource. The resource should refer to
16565     * a Drawable object or 0 to remove the background.
16566     * @param resid The identifier of the resource.
16567     *
16568     * @attr ref android.R.styleable#View_background
16569     */
16570    @RemotableViewMethod
16571    public void setBackgroundResource(@DrawableRes int resid) {
16572        if (resid != 0 && resid == mBackgroundResource) {
16573            return;
16574        }
16575
16576        Drawable d = null;
16577        if (resid != 0) {
16578            d = mContext.getDrawable(resid);
16579        }
16580        setBackground(d);
16581
16582        mBackgroundResource = resid;
16583    }
16584
16585    /**
16586     * Set the background to a given Drawable, or remove the background. If the
16587     * background has padding, this View's padding is set to the background's
16588     * padding. However, when a background is removed, this View's padding isn't
16589     * touched. If setting the padding is desired, please use
16590     * {@link #setPadding(int, int, int, int)}.
16591     *
16592     * @param background The Drawable to use as the background, or null to remove the
16593     *        background
16594     */
16595    public void setBackground(Drawable background) {
16596        //noinspection deprecation
16597        setBackgroundDrawable(background);
16598    }
16599
16600    /**
16601     * @deprecated use {@link #setBackground(Drawable)} instead
16602     */
16603    @Deprecated
16604    public void setBackgroundDrawable(Drawable background) {
16605        computeOpaqueFlags();
16606
16607        if (background == mBackground) {
16608            return;
16609        }
16610
16611        boolean requestLayout = false;
16612
16613        mBackgroundResource = 0;
16614
16615        /*
16616         * Regardless of whether we're setting a new background or not, we want
16617         * to clear the previous drawable.
16618         */
16619        if (mBackground != null) {
16620            mBackground.setCallback(null);
16621            unscheduleDrawable(mBackground);
16622        }
16623
16624        if (background != null) {
16625            Rect padding = sThreadLocal.get();
16626            if (padding == null) {
16627                padding = new Rect();
16628                sThreadLocal.set(padding);
16629            }
16630            resetResolvedDrawablesInternal();
16631            background.setLayoutDirection(getLayoutDirection());
16632            if (background.getPadding(padding)) {
16633                resetResolvedPaddingInternal();
16634                switch (background.getLayoutDirection()) {
16635                    case LAYOUT_DIRECTION_RTL:
16636                        mUserPaddingLeftInitial = padding.right;
16637                        mUserPaddingRightInitial = padding.left;
16638                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16639                        break;
16640                    case LAYOUT_DIRECTION_LTR:
16641                    default:
16642                        mUserPaddingLeftInitial = padding.left;
16643                        mUserPaddingRightInitial = padding.right;
16644                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16645                }
16646                mLeftPaddingDefined = false;
16647                mRightPaddingDefined = false;
16648            }
16649
16650            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16651            // if it has a different minimum size, we should layout again
16652            if (mBackground == null
16653                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16654                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16655                requestLayout = true;
16656            }
16657
16658            background.setCallback(this);
16659            if (background.isStateful()) {
16660                background.setState(getDrawableState());
16661            }
16662            background.setVisible(getVisibility() == VISIBLE, false);
16663            mBackground = background;
16664
16665            applyBackgroundTint();
16666
16667            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16668                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16669                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16670                requestLayout = true;
16671            }
16672        } else {
16673            /* Remove the background */
16674            mBackground = null;
16675
16676            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16677                /*
16678                 * This view ONLY drew the background before and we're removing
16679                 * the background, so now it won't draw anything
16680                 * (hence we SKIP_DRAW)
16681                 */
16682                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16683                mPrivateFlags |= PFLAG_SKIP_DRAW;
16684            }
16685
16686            /*
16687             * When the background is set, we try to apply its padding to this
16688             * View. When the background is removed, we don't touch this View's
16689             * padding. This is noted in the Javadocs. Hence, we don't need to
16690             * requestLayout(), the invalidate() below is sufficient.
16691             */
16692
16693            // The old background's minimum size could have affected this
16694            // View's layout, so let's requestLayout
16695            requestLayout = true;
16696        }
16697
16698        computeOpaqueFlags();
16699
16700        if (requestLayout) {
16701            requestLayout();
16702        }
16703
16704        mBackgroundSizeChanged = true;
16705        invalidate(true);
16706    }
16707
16708    /**
16709     * Gets the background drawable
16710     *
16711     * @return The drawable used as the background for this view, if any.
16712     *
16713     * @see #setBackground(Drawable)
16714     *
16715     * @attr ref android.R.styleable#View_background
16716     */
16717    public Drawable getBackground() {
16718        return mBackground;
16719    }
16720
16721    /**
16722     * Applies a tint to the background drawable. Does not modify the current tint
16723     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16724     * <p>
16725     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16726     * mutate the drawable and apply the specified tint and tint mode using
16727     * {@link Drawable#setTintList(ColorStateList)}.
16728     *
16729     * @param tint the tint to apply, may be {@code null} to clear tint
16730     *
16731     * @attr ref android.R.styleable#View_backgroundTint
16732     * @see #getBackgroundTintList()
16733     * @see Drawable#setTintList(ColorStateList)
16734     */
16735    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16736        if (mBackgroundTint == null) {
16737            mBackgroundTint = new TintInfo();
16738        }
16739        mBackgroundTint.mTintList = tint;
16740        mBackgroundTint.mHasTintList = true;
16741
16742        applyBackgroundTint();
16743    }
16744
16745    /**
16746     * Return the tint applied to the background drawable, if specified.
16747     *
16748     * @return the tint applied to the background drawable
16749     * @attr ref android.R.styleable#View_backgroundTint
16750     * @see #setBackgroundTintList(ColorStateList)
16751     */
16752    @Nullable
16753    public ColorStateList getBackgroundTintList() {
16754        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16755    }
16756
16757    /**
16758     * Specifies the blending mode used to apply the tint specified by
16759     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16760     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16761     *
16762     * @param tintMode the blending mode used to apply the tint, may be
16763     *                 {@code null} to clear tint
16764     * @attr ref android.R.styleable#View_backgroundTintMode
16765     * @see #getBackgroundTintMode()
16766     * @see Drawable#setTintMode(PorterDuff.Mode)
16767     */
16768    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16769        if (mBackgroundTint == null) {
16770            mBackgroundTint = new TintInfo();
16771        }
16772        mBackgroundTint.mTintMode = tintMode;
16773        mBackgroundTint.mHasTintMode = true;
16774
16775        applyBackgroundTint();
16776    }
16777
16778    /**
16779     * Return the blending mode used to apply the tint to the background
16780     * drawable, if specified.
16781     *
16782     * @return the blending mode used to apply the tint to the background
16783     *         drawable
16784     * @attr ref android.R.styleable#View_backgroundTintMode
16785     * @see #setBackgroundTintMode(PorterDuff.Mode)
16786     */
16787    @Nullable
16788    public PorterDuff.Mode getBackgroundTintMode() {
16789        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16790    }
16791
16792    private void applyBackgroundTint() {
16793        if (mBackground != null && mBackgroundTint != null) {
16794            final TintInfo tintInfo = mBackgroundTint;
16795            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16796                mBackground = mBackground.mutate();
16797
16798                if (tintInfo.mHasTintList) {
16799                    mBackground.setTintList(tintInfo.mTintList);
16800                }
16801
16802                if (tintInfo.mHasTintMode) {
16803                    mBackground.setTintMode(tintInfo.mTintMode);
16804                }
16805
16806                // The drawable (or one of its children) may not have been
16807                // stateful before applying the tint, so let's try again.
16808                if (mBackground.isStateful()) {
16809                    mBackground.setState(getDrawableState());
16810                }
16811            }
16812        }
16813    }
16814
16815    /**
16816     * Returns the drawable used as the foreground of this View. The
16817     * foreground drawable, if non-null, is always drawn on top of the view's content.
16818     *
16819     * @return a Drawable or null if no foreground was set
16820     *
16821     * @see #onDrawForeground(Canvas)
16822     */
16823    public Drawable getForeground() {
16824        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16825    }
16826
16827    /**
16828     * Supply a Drawable that is to be rendered on top of all of the content in the view.
16829     *
16830     * @param foreground the Drawable to be drawn on top of the children
16831     *
16832     * @attr ref android.R.styleable#View_foreground
16833     */
16834    public void setForeground(Drawable foreground) {
16835        if (mForegroundInfo == null) {
16836            if (foreground == null) {
16837                // Nothing to do.
16838                return;
16839            }
16840            mForegroundInfo = new ForegroundInfo();
16841        }
16842
16843        if (foreground == mForegroundInfo.mDrawable) {
16844            // Nothing to do
16845            return;
16846        }
16847
16848        if (mForegroundInfo.mDrawable != null) {
16849            mForegroundInfo.mDrawable.setCallback(null);
16850            unscheduleDrawable(mForegroundInfo.mDrawable);
16851        }
16852
16853        mForegroundInfo.mDrawable = foreground;
16854        mForegroundInfo.mBoundsChanged = true;
16855        if (foreground != null) {
16856            setWillNotDraw(false);
16857            foreground.setCallback(this);
16858            foreground.setLayoutDirection(getLayoutDirection());
16859            if (foreground.isStateful()) {
16860                foreground.setState(getDrawableState());
16861            }
16862            applyForegroundTint();
16863        }
16864        requestLayout();
16865        invalidate();
16866    }
16867
16868    /**
16869     * Magic bit used to support features of framework-internal window decor implementation details.
16870     * This used to live exclusively in FrameLayout.
16871     *
16872     * @return true if the foreground should draw inside the padding region or false
16873     *         if it should draw inset by the view's padding
16874     * @hide internal use only; only used by FrameLayout and internal screen layouts.
16875     */
16876    public boolean isForegroundInsidePadding() {
16877        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
16878    }
16879
16880    /**
16881     * Describes how the foreground is positioned.
16882     *
16883     * @return foreground gravity.
16884     *
16885     * @see #setForegroundGravity(int)
16886     *
16887     * @attr ref android.R.styleable#View_foregroundGravity
16888     */
16889    public int getForegroundGravity() {
16890        return mForegroundInfo != null ? mForegroundInfo.mGravity
16891                : Gravity.START | Gravity.TOP;
16892    }
16893
16894    /**
16895     * Describes how the foreground is positioned. Defaults to START and TOP.
16896     *
16897     * @param gravity see {@link android.view.Gravity}
16898     *
16899     * @see #getForegroundGravity()
16900     *
16901     * @attr ref android.R.styleable#View_foregroundGravity
16902     */
16903    public void setForegroundGravity(int gravity) {
16904        if (mForegroundInfo == null) {
16905            mForegroundInfo = new ForegroundInfo();
16906        }
16907
16908        if (mForegroundInfo.mGravity != gravity) {
16909            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
16910                gravity |= Gravity.START;
16911            }
16912
16913            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
16914                gravity |= Gravity.TOP;
16915            }
16916
16917            mForegroundInfo.mGravity = gravity;
16918            requestLayout();
16919        }
16920    }
16921
16922    /**
16923     * Applies a tint to the foreground drawable. Does not modify the current tint
16924     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16925     * <p>
16926     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
16927     * mutate the drawable and apply the specified tint and tint mode using
16928     * {@link Drawable#setTintList(ColorStateList)}.
16929     *
16930     * @param tint the tint to apply, may be {@code null} to clear tint
16931     *
16932     * @attr ref android.R.styleable#View_foregroundTint
16933     * @see #getForegroundTintList()
16934     * @see Drawable#setTintList(ColorStateList)
16935     */
16936    public void setForegroundTintList(@Nullable ColorStateList tint) {
16937        if (mForegroundInfo == null) {
16938            mForegroundInfo = new ForegroundInfo();
16939        }
16940        if (mForegroundInfo.mTintInfo == null) {
16941            mForegroundInfo.mTintInfo = new TintInfo();
16942        }
16943        mForegroundInfo.mTintInfo.mTintList = tint;
16944        mForegroundInfo.mTintInfo.mHasTintList = true;
16945
16946        applyForegroundTint();
16947    }
16948
16949    /**
16950     * Return the tint applied to the foreground drawable, if specified.
16951     *
16952     * @return the tint applied to the foreground drawable
16953     * @attr ref android.R.styleable#View_foregroundTint
16954     * @see #setForegroundTintList(ColorStateList)
16955     */
16956    @Nullable
16957    public ColorStateList getForegroundTintList() {
16958        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
16959                ? mForegroundInfo.mTintInfo.mTintList : null;
16960    }
16961
16962    /**
16963     * Specifies the blending mode used to apply the tint specified by
16964     * {@link #setForegroundTintList(ColorStateList)}} to the background
16965     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16966     *
16967     * @param tintMode the blending mode used to apply the tint, may be
16968     *                 {@code null} to clear tint
16969     * @attr ref android.R.styleable#View_foregroundTintMode
16970     * @see #getForegroundTintMode()
16971     * @see Drawable#setTintMode(PorterDuff.Mode)
16972     */
16973    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16974        if (mBackgroundTint == null) {
16975            mBackgroundTint = new TintInfo();
16976        }
16977        mBackgroundTint.mTintMode = tintMode;
16978        mBackgroundTint.mHasTintMode = true;
16979
16980        applyBackgroundTint();
16981    }
16982
16983    /**
16984     * Return the blending mode used to apply the tint to the foreground
16985     * drawable, if specified.
16986     *
16987     * @return the blending mode used to apply the tint to the foreground
16988     *         drawable
16989     * @attr ref android.R.styleable#View_foregroundTintMode
16990     * @see #setBackgroundTintMode(PorterDuff.Mode)
16991     */
16992    @Nullable
16993    public PorterDuff.Mode getForegroundTintMode() {
16994        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
16995                ? mForegroundInfo.mTintInfo.mTintMode : null;
16996    }
16997
16998    private void applyForegroundTint() {
16999        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17000                && mForegroundInfo.mTintInfo != null) {
17001            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17002            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17003                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17004
17005                if (tintInfo.mHasTintList) {
17006                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17007                }
17008
17009                if (tintInfo.mHasTintMode) {
17010                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17011                }
17012
17013                // The drawable (or one of its children) may not have been
17014                // stateful before applying the tint, so let's try again.
17015                if (mForegroundInfo.mDrawable.isStateful()) {
17016                    mForegroundInfo.mDrawable.setState(getDrawableState());
17017                }
17018            }
17019        }
17020    }
17021
17022    /**
17023     * Draw any foreground content for this view.
17024     *
17025     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17026     * drawable or other view-specific decorations. The foreground is drawn on top of the
17027     * primary view content.</p>
17028     *
17029     * @param canvas canvas to draw into
17030     */
17031    public void onDrawForeground(Canvas canvas) {
17032        onDrawScrollBars(canvas);
17033
17034        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17035        if (foreground != null) {
17036            if (mForegroundInfo.mBoundsChanged) {
17037                mForegroundInfo.mBoundsChanged = false;
17038                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17039                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17040
17041                if (mForegroundInfo.mInsidePadding) {
17042                    selfBounds.set(0, 0, getWidth(), getHeight());
17043                } else {
17044                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17045                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17046                }
17047
17048                final int ld = getLayoutDirection();
17049                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17050                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17051                foreground.setBounds(overlayBounds);
17052            }
17053
17054            foreground.draw(canvas);
17055        }
17056    }
17057
17058    /**
17059     * Sets the padding. The view may add on the space required to display
17060     * the scrollbars, depending on the style and visibility of the scrollbars.
17061     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17062     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17063     * from the values set in this call.
17064     *
17065     * @attr ref android.R.styleable#View_padding
17066     * @attr ref android.R.styleable#View_paddingBottom
17067     * @attr ref android.R.styleable#View_paddingLeft
17068     * @attr ref android.R.styleable#View_paddingRight
17069     * @attr ref android.R.styleable#View_paddingTop
17070     * @param left the left padding in pixels
17071     * @param top the top padding in pixels
17072     * @param right the right padding in pixels
17073     * @param bottom the bottom padding in pixels
17074     */
17075    public void setPadding(int left, int top, int right, int bottom) {
17076        resetResolvedPaddingInternal();
17077
17078        mUserPaddingStart = UNDEFINED_PADDING;
17079        mUserPaddingEnd = UNDEFINED_PADDING;
17080
17081        mUserPaddingLeftInitial = left;
17082        mUserPaddingRightInitial = right;
17083
17084        mLeftPaddingDefined = true;
17085        mRightPaddingDefined = true;
17086
17087        internalSetPadding(left, top, right, bottom);
17088    }
17089
17090    /**
17091     * @hide
17092     */
17093    protected void internalSetPadding(int left, int top, int right, int bottom) {
17094        mUserPaddingLeft = left;
17095        mUserPaddingRight = right;
17096        mUserPaddingBottom = bottom;
17097
17098        final int viewFlags = mViewFlags;
17099        boolean changed = false;
17100
17101        // Common case is there are no scroll bars.
17102        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17103            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17104                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17105                        ? 0 : getVerticalScrollbarWidth();
17106                switch (mVerticalScrollbarPosition) {
17107                    case SCROLLBAR_POSITION_DEFAULT:
17108                        if (isLayoutRtl()) {
17109                            left += offset;
17110                        } else {
17111                            right += offset;
17112                        }
17113                        break;
17114                    case SCROLLBAR_POSITION_RIGHT:
17115                        right += offset;
17116                        break;
17117                    case SCROLLBAR_POSITION_LEFT:
17118                        left += offset;
17119                        break;
17120                }
17121            }
17122            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17123                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17124                        ? 0 : getHorizontalScrollbarHeight();
17125            }
17126        }
17127
17128        if (mPaddingLeft != left) {
17129            changed = true;
17130            mPaddingLeft = left;
17131        }
17132        if (mPaddingTop != top) {
17133            changed = true;
17134            mPaddingTop = top;
17135        }
17136        if (mPaddingRight != right) {
17137            changed = true;
17138            mPaddingRight = right;
17139        }
17140        if (mPaddingBottom != bottom) {
17141            changed = true;
17142            mPaddingBottom = bottom;
17143        }
17144
17145        if (changed) {
17146            requestLayout();
17147            invalidateOutline();
17148        }
17149    }
17150
17151    /**
17152     * Sets the relative padding. The view may add on the space required to display
17153     * the scrollbars, depending on the style and visibility of the scrollbars.
17154     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17155     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17156     * from the values set in this call.
17157     *
17158     * @attr ref android.R.styleable#View_padding
17159     * @attr ref android.R.styleable#View_paddingBottom
17160     * @attr ref android.R.styleable#View_paddingStart
17161     * @attr ref android.R.styleable#View_paddingEnd
17162     * @attr ref android.R.styleable#View_paddingTop
17163     * @param start the start padding in pixels
17164     * @param top the top padding in pixels
17165     * @param end the end padding in pixels
17166     * @param bottom the bottom padding in pixels
17167     */
17168    public void setPaddingRelative(int start, int top, int end, int bottom) {
17169        resetResolvedPaddingInternal();
17170
17171        mUserPaddingStart = start;
17172        mUserPaddingEnd = end;
17173        mLeftPaddingDefined = true;
17174        mRightPaddingDefined = true;
17175
17176        switch(getLayoutDirection()) {
17177            case LAYOUT_DIRECTION_RTL:
17178                mUserPaddingLeftInitial = end;
17179                mUserPaddingRightInitial = start;
17180                internalSetPadding(end, top, start, bottom);
17181                break;
17182            case LAYOUT_DIRECTION_LTR:
17183            default:
17184                mUserPaddingLeftInitial = start;
17185                mUserPaddingRightInitial = end;
17186                internalSetPadding(start, top, end, bottom);
17187        }
17188    }
17189
17190    /**
17191     * Returns the top padding of this view.
17192     *
17193     * @return the top padding in pixels
17194     */
17195    public int getPaddingTop() {
17196        return mPaddingTop;
17197    }
17198
17199    /**
17200     * Returns the bottom padding of this view. If there are inset and enabled
17201     * scrollbars, this value may include the space required to display the
17202     * scrollbars as well.
17203     *
17204     * @return the bottom padding in pixels
17205     */
17206    public int getPaddingBottom() {
17207        return mPaddingBottom;
17208    }
17209
17210    /**
17211     * Returns the left padding of this view. If there are inset and enabled
17212     * scrollbars, this value may include the space required to display the
17213     * scrollbars as well.
17214     *
17215     * @return the left padding in pixels
17216     */
17217    public int getPaddingLeft() {
17218        if (!isPaddingResolved()) {
17219            resolvePadding();
17220        }
17221        return mPaddingLeft;
17222    }
17223
17224    /**
17225     * Returns the start padding of this view depending on its resolved layout direction.
17226     * If there are inset and enabled scrollbars, this value may include the space
17227     * required to display the scrollbars as well.
17228     *
17229     * @return the start padding in pixels
17230     */
17231    public int getPaddingStart() {
17232        if (!isPaddingResolved()) {
17233            resolvePadding();
17234        }
17235        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17236                mPaddingRight : mPaddingLeft;
17237    }
17238
17239    /**
17240     * Returns the right padding of this view. If there are inset and enabled
17241     * scrollbars, this value may include the space required to display the
17242     * scrollbars as well.
17243     *
17244     * @return the right padding in pixels
17245     */
17246    public int getPaddingRight() {
17247        if (!isPaddingResolved()) {
17248            resolvePadding();
17249        }
17250        return mPaddingRight;
17251    }
17252
17253    /**
17254     * Returns the end padding of this view depending on its resolved layout direction.
17255     * If there are inset and enabled scrollbars, this value may include the space
17256     * required to display the scrollbars as well.
17257     *
17258     * @return the end padding in pixels
17259     */
17260    public int getPaddingEnd() {
17261        if (!isPaddingResolved()) {
17262            resolvePadding();
17263        }
17264        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17265                mPaddingLeft : mPaddingRight;
17266    }
17267
17268    /**
17269     * Return if the padding has been set through relative values
17270     * {@link #setPaddingRelative(int, int, int, int)} or through
17271     * @attr ref android.R.styleable#View_paddingStart or
17272     * @attr ref android.R.styleable#View_paddingEnd
17273     *
17274     * @return true if the padding is relative or false if it is not.
17275     */
17276    public boolean isPaddingRelative() {
17277        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17278    }
17279
17280    Insets computeOpticalInsets() {
17281        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17282    }
17283
17284    /**
17285     * @hide
17286     */
17287    public void resetPaddingToInitialValues() {
17288        if (isRtlCompatibilityMode()) {
17289            mPaddingLeft = mUserPaddingLeftInitial;
17290            mPaddingRight = mUserPaddingRightInitial;
17291            return;
17292        }
17293        if (isLayoutRtl()) {
17294            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17295            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17296        } else {
17297            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17298            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17299        }
17300    }
17301
17302    /**
17303     * @hide
17304     */
17305    public Insets getOpticalInsets() {
17306        if (mLayoutInsets == null) {
17307            mLayoutInsets = computeOpticalInsets();
17308        }
17309        return mLayoutInsets;
17310    }
17311
17312    /**
17313     * Set this view's optical insets.
17314     *
17315     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17316     * property. Views that compute their own optical insets should call it as part of measurement.
17317     * This method does not request layout. If you are setting optical insets outside of
17318     * measure/layout itself you will want to call requestLayout() yourself.
17319     * </p>
17320     * @hide
17321     */
17322    public void setOpticalInsets(Insets insets) {
17323        mLayoutInsets = insets;
17324    }
17325
17326    /**
17327     * Changes the selection state of this view. A view can be selected or not.
17328     * Note that selection is not the same as focus. Views are typically
17329     * selected in the context of an AdapterView like ListView or GridView;
17330     * the selected view is the view that is highlighted.
17331     *
17332     * @param selected true if the view must be selected, false otherwise
17333     */
17334    public void setSelected(boolean selected) {
17335        //noinspection DoubleNegation
17336        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17337            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17338            if (!selected) resetPressedState();
17339            invalidate(true);
17340            refreshDrawableState();
17341            dispatchSetSelected(selected);
17342            if (selected) {
17343                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17344            } else {
17345                notifyViewAccessibilityStateChangedIfNeeded(
17346                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17347            }
17348        }
17349    }
17350
17351    /**
17352     * Dispatch setSelected to all of this View's children.
17353     *
17354     * @see #setSelected(boolean)
17355     *
17356     * @param selected The new selected state
17357     */
17358    protected void dispatchSetSelected(boolean selected) {
17359    }
17360
17361    /**
17362     * Indicates the selection state of this view.
17363     *
17364     * @return true if the view is selected, false otherwise
17365     */
17366    @ViewDebug.ExportedProperty
17367    public boolean isSelected() {
17368        return (mPrivateFlags & PFLAG_SELECTED) != 0;
17369    }
17370
17371    /**
17372     * Changes the activated state of this view. A view can be activated or not.
17373     * Note that activation is not the same as selection.  Selection is
17374     * a transient property, representing the view (hierarchy) the user is
17375     * currently interacting with.  Activation is a longer-term state that the
17376     * user can move views in and out of.  For example, in a list view with
17377     * single or multiple selection enabled, the views in the current selection
17378     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
17379     * here.)  The activated state is propagated down to children of the view it
17380     * is set on.
17381     *
17382     * @param activated true if the view must be activated, false otherwise
17383     */
17384    public void setActivated(boolean activated) {
17385        //noinspection DoubleNegation
17386        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
17387            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
17388            invalidate(true);
17389            refreshDrawableState();
17390            dispatchSetActivated(activated);
17391        }
17392    }
17393
17394    /**
17395     * Dispatch setActivated to all of this View's children.
17396     *
17397     * @see #setActivated(boolean)
17398     *
17399     * @param activated The new activated state
17400     */
17401    protected void dispatchSetActivated(boolean activated) {
17402    }
17403
17404    /**
17405     * Indicates the activation state of this view.
17406     *
17407     * @return true if the view is activated, false otherwise
17408     */
17409    @ViewDebug.ExportedProperty
17410    public boolean isActivated() {
17411        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
17412    }
17413
17414    /**
17415     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
17416     * observer can be used to get notifications when global events, like
17417     * layout, happen.
17418     *
17419     * The returned ViewTreeObserver observer is not guaranteed to remain
17420     * valid for the lifetime of this View. If the caller of this method keeps
17421     * a long-lived reference to ViewTreeObserver, it should always check for
17422     * the return value of {@link ViewTreeObserver#isAlive()}.
17423     *
17424     * @return The ViewTreeObserver for this view's hierarchy.
17425     */
17426    public ViewTreeObserver getViewTreeObserver() {
17427        if (mAttachInfo != null) {
17428            return mAttachInfo.mTreeObserver;
17429        }
17430        if (mFloatingTreeObserver == null) {
17431            mFloatingTreeObserver = new ViewTreeObserver();
17432        }
17433        return mFloatingTreeObserver;
17434    }
17435
17436    /**
17437     * <p>Finds the topmost view in the current view hierarchy.</p>
17438     *
17439     * @return the topmost view containing this view
17440     */
17441    public View getRootView() {
17442        if (mAttachInfo != null) {
17443            final View v = mAttachInfo.mRootView;
17444            if (v != null) {
17445                return v;
17446            }
17447        }
17448
17449        View parent = this;
17450
17451        while (parent.mParent != null && parent.mParent instanceof View) {
17452            parent = (View) parent.mParent;
17453        }
17454
17455        return parent;
17456    }
17457
17458    /**
17459     * Transforms a motion event from view-local coordinates to on-screen
17460     * coordinates.
17461     *
17462     * @param ev the view-local motion event
17463     * @return false if the transformation could not be applied
17464     * @hide
17465     */
17466    public boolean toGlobalMotionEvent(MotionEvent ev) {
17467        final AttachInfo info = mAttachInfo;
17468        if (info == null) {
17469            return false;
17470        }
17471
17472        final Matrix m = info.mTmpMatrix;
17473        m.set(Matrix.IDENTITY_MATRIX);
17474        transformMatrixToGlobal(m);
17475        ev.transform(m);
17476        return true;
17477    }
17478
17479    /**
17480     * Transforms a motion event from on-screen coordinates to view-local
17481     * coordinates.
17482     *
17483     * @param ev the on-screen motion event
17484     * @return false if the transformation could not be applied
17485     * @hide
17486     */
17487    public boolean toLocalMotionEvent(MotionEvent ev) {
17488        final AttachInfo info = mAttachInfo;
17489        if (info == null) {
17490            return false;
17491        }
17492
17493        final Matrix m = info.mTmpMatrix;
17494        m.set(Matrix.IDENTITY_MATRIX);
17495        transformMatrixToLocal(m);
17496        ev.transform(m);
17497        return true;
17498    }
17499
17500    /**
17501     * Modifies the input matrix such that it maps view-local coordinates to
17502     * on-screen coordinates.
17503     *
17504     * @param m input matrix to modify
17505     * @hide
17506     */
17507    public void transformMatrixToGlobal(Matrix m) {
17508        final ViewParent parent = mParent;
17509        if (parent instanceof View) {
17510            final View vp = (View) parent;
17511            vp.transformMatrixToGlobal(m);
17512            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
17513        } else if (parent instanceof ViewRootImpl) {
17514            final ViewRootImpl vr = (ViewRootImpl) parent;
17515            vr.transformMatrixToGlobal(m);
17516            m.preTranslate(0, -vr.mCurScrollY);
17517        }
17518
17519        m.preTranslate(mLeft, mTop);
17520
17521        if (!hasIdentityMatrix()) {
17522            m.preConcat(getMatrix());
17523        }
17524    }
17525
17526    /**
17527     * Modifies the input matrix such that it maps on-screen coordinates to
17528     * view-local coordinates.
17529     *
17530     * @param m input matrix to modify
17531     * @hide
17532     */
17533    public void transformMatrixToLocal(Matrix m) {
17534        final ViewParent parent = mParent;
17535        if (parent instanceof View) {
17536            final View vp = (View) parent;
17537            vp.transformMatrixToLocal(m);
17538            m.postTranslate(vp.mScrollX, vp.mScrollY);
17539        } else if (parent instanceof ViewRootImpl) {
17540            final ViewRootImpl vr = (ViewRootImpl) parent;
17541            vr.transformMatrixToLocal(m);
17542            m.postTranslate(0, vr.mCurScrollY);
17543        }
17544
17545        m.postTranslate(-mLeft, -mTop);
17546
17547        if (!hasIdentityMatrix()) {
17548            m.postConcat(getInverseMatrix());
17549        }
17550    }
17551
17552    /**
17553     * @hide
17554     */
17555    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17556            @ViewDebug.IntToString(from = 0, to = "x"),
17557            @ViewDebug.IntToString(from = 1, to = "y")
17558    })
17559    public int[] getLocationOnScreen() {
17560        int[] location = new int[2];
17561        getLocationOnScreen(location);
17562        return location;
17563    }
17564
17565    /**
17566     * <p>Computes the coordinates of this view on the screen. The argument
17567     * must be an array of two integers. After the method returns, the array
17568     * contains the x and y location in that order.</p>
17569     *
17570     * @param location an array of two integers in which to hold the coordinates
17571     */
17572    public void getLocationOnScreen(@Size(2) int[] location) {
17573        getLocationInWindow(location);
17574
17575        final AttachInfo info = mAttachInfo;
17576        if (info != null) {
17577            location[0] += info.mWindowLeft;
17578            location[1] += info.mWindowTop;
17579        }
17580    }
17581
17582    /**
17583     * <p>Computes the coordinates of this view in its window. The argument
17584     * must be an array of two integers. After the method returns, the array
17585     * contains the x and y location in that order.</p>
17586     *
17587     * @param location an array of two integers in which to hold the coordinates
17588     */
17589    public void getLocationInWindow(@Size(2) int[] location) {
17590        if (location == null || location.length < 2) {
17591            throw new IllegalArgumentException("location must be an array of two integers");
17592        }
17593
17594        if (mAttachInfo == null) {
17595            // When the view is not attached to a window, this method does not make sense
17596            location[0] = location[1] = 0;
17597            return;
17598        }
17599
17600        float[] position = mAttachInfo.mTmpTransformLocation;
17601        position[0] = position[1] = 0.0f;
17602
17603        if (!hasIdentityMatrix()) {
17604            getMatrix().mapPoints(position);
17605        }
17606
17607        position[0] += mLeft;
17608        position[1] += mTop;
17609
17610        ViewParent viewParent = mParent;
17611        while (viewParent instanceof View) {
17612            final View view = (View) viewParent;
17613
17614            position[0] -= view.mScrollX;
17615            position[1] -= view.mScrollY;
17616
17617            if (!view.hasIdentityMatrix()) {
17618                view.getMatrix().mapPoints(position);
17619            }
17620
17621            position[0] += view.mLeft;
17622            position[1] += view.mTop;
17623
17624            viewParent = view.mParent;
17625         }
17626
17627        if (viewParent instanceof ViewRootImpl) {
17628            // *cough*
17629            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17630            position[1] -= vr.mCurScrollY;
17631        }
17632
17633        location[0] = (int) (position[0] + 0.5f);
17634        location[1] = (int) (position[1] + 0.5f);
17635    }
17636
17637    /**
17638     * {@hide}
17639     * @param id the id of the view to be found
17640     * @return the view of the specified id, null if cannot be found
17641     */
17642    protected View findViewTraversal(@IdRes int id) {
17643        if (id == mID) {
17644            return this;
17645        }
17646        return null;
17647    }
17648
17649    /**
17650     * {@hide}
17651     * @param tag the tag of the view to be found
17652     * @return the view of specified tag, null if cannot be found
17653     */
17654    protected View findViewWithTagTraversal(Object tag) {
17655        if (tag != null && tag.equals(mTag)) {
17656            return this;
17657        }
17658        return null;
17659    }
17660
17661    /**
17662     * {@hide}
17663     * @param predicate The predicate to evaluate.
17664     * @param childToSkip If not null, ignores this child during the recursive traversal.
17665     * @return The first view that matches the predicate or null.
17666     */
17667    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17668        if (predicate.apply(this)) {
17669            return this;
17670        }
17671        return null;
17672    }
17673
17674    /**
17675     * Look for a child view with the given id.  If this view has the given
17676     * id, return this view.
17677     *
17678     * @param id The id to search for.
17679     * @return The view that has the given id in the hierarchy or null
17680     */
17681    @Nullable
17682    public final View findViewById(@IdRes int id) {
17683        if (id < 0) {
17684            return null;
17685        }
17686        return findViewTraversal(id);
17687    }
17688
17689    /**
17690     * Finds a view by its unuque and stable accessibility id.
17691     *
17692     * @param accessibilityId The searched accessibility id.
17693     * @return The found view.
17694     */
17695    final View findViewByAccessibilityId(int accessibilityId) {
17696        if (accessibilityId < 0) {
17697            return null;
17698        }
17699        return findViewByAccessibilityIdTraversal(accessibilityId);
17700    }
17701
17702    /**
17703     * Performs the traversal to find a view by its unuque and stable accessibility id.
17704     *
17705     * <strong>Note:</strong>This method does not stop at the root namespace
17706     * boundary since the user can touch the screen at an arbitrary location
17707     * potentially crossing the root namespace bounday which will send an
17708     * accessibility event to accessibility services and they should be able
17709     * to obtain the event source. Also accessibility ids are guaranteed to be
17710     * unique in the window.
17711     *
17712     * @param accessibilityId The accessibility id.
17713     * @return The found view.
17714     *
17715     * @hide
17716     */
17717    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17718        if (getAccessibilityViewId() == accessibilityId) {
17719            return this;
17720        }
17721        return null;
17722    }
17723
17724    /**
17725     * Look for a child view with the given tag.  If this view has the given
17726     * tag, return this view.
17727     *
17728     * @param tag The tag to search for, using "tag.equals(getTag())".
17729     * @return The View that has the given tag in the hierarchy or null
17730     */
17731    public final View findViewWithTag(Object tag) {
17732        if (tag == null) {
17733            return null;
17734        }
17735        return findViewWithTagTraversal(tag);
17736    }
17737
17738    /**
17739     * {@hide}
17740     * Look for a child view that matches the specified predicate.
17741     * If this view matches the predicate, return this view.
17742     *
17743     * @param predicate The predicate to evaluate.
17744     * @return The first view that matches the predicate or null.
17745     */
17746    public final View findViewByPredicate(Predicate<View> predicate) {
17747        return findViewByPredicateTraversal(predicate, null);
17748    }
17749
17750    /**
17751     * {@hide}
17752     * Look for a child view that matches the specified predicate,
17753     * starting with the specified view and its descendents and then
17754     * recusively searching the ancestors and siblings of that view
17755     * until this view is reached.
17756     *
17757     * This method is useful in cases where the predicate does not match
17758     * a single unique view (perhaps multiple views use the same id)
17759     * and we are trying to find the view that is "closest" in scope to the
17760     * starting view.
17761     *
17762     * @param start The view to start from.
17763     * @param predicate The predicate to evaluate.
17764     * @return The first view that matches the predicate or null.
17765     */
17766    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17767        View childToSkip = null;
17768        for (;;) {
17769            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17770            if (view != null || start == this) {
17771                return view;
17772            }
17773
17774            ViewParent parent = start.getParent();
17775            if (parent == null || !(parent instanceof View)) {
17776                return null;
17777            }
17778
17779            childToSkip = start;
17780            start = (View) parent;
17781        }
17782    }
17783
17784    /**
17785     * Sets the identifier for this view. The identifier does not have to be
17786     * unique in this view's hierarchy. The identifier should be a positive
17787     * number.
17788     *
17789     * @see #NO_ID
17790     * @see #getId()
17791     * @see #findViewById(int)
17792     *
17793     * @param id a number used to identify the view
17794     *
17795     * @attr ref android.R.styleable#View_id
17796     */
17797    public void setId(@IdRes int id) {
17798        mID = id;
17799        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17800            mID = generateViewId();
17801        }
17802    }
17803
17804    /**
17805     * {@hide}
17806     *
17807     * @param isRoot true if the view belongs to the root namespace, false
17808     *        otherwise
17809     */
17810    public void setIsRootNamespace(boolean isRoot) {
17811        if (isRoot) {
17812            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17813        } else {
17814            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17815        }
17816    }
17817
17818    /**
17819     * {@hide}
17820     *
17821     * @return true if the view belongs to the root namespace, false otherwise
17822     */
17823    public boolean isRootNamespace() {
17824        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17825    }
17826
17827    /**
17828     * Returns this view's identifier.
17829     *
17830     * @return a positive integer used to identify the view or {@link #NO_ID}
17831     *         if the view has no ID
17832     *
17833     * @see #setId(int)
17834     * @see #findViewById(int)
17835     * @attr ref android.R.styleable#View_id
17836     */
17837    @IdRes
17838    @ViewDebug.CapturedViewProperty
17839    public int getId() {
17840        return mID;
17841    }
17842
17843    /**
17844     * Returns this view's tag.
17845     *
17846     * @return the Object stored in this view as a tag, or {@code null} if not
17847     *         set
17848     *
17849     * @see #setTag(Object)
17850     * @see #getTag(int)
17851     */
17852    @ViewDebug.ExportedProperty
17853    public Object getTag() {
17854        return mTag;
17855    }
17856
17857    /**
17858     * Sets the tag associated with this view. A tag can be used to mark
17859     * a view in its hierarchy and does not have to be unique within the
17860     * hierarchy. Tags can also be used to store data within a view without
17861     * resorting to another data structure.
17862     *
17863     * @param tag an Object to tag the view with
17864     *
17865     * @see #getTag()
17866     * @see #setTag(int, Object)
17867     */
17868    public void setTag(final Object tag) {
17869        mTag = tag;
17870    }
17871
17872    /**
17873     * Returns the tag associated with this view and the specified key.
17874     *
17875     * @param key The key identifying the tag
17876     *
17877     * @return the Object stored in this view as a tag, or {@code null} if not
17878     *         set
17879     *
17880     * @see #setTag(int, Object)
17881     * @see #getTag()
17882     */
17883    public Object getTag(int key) {
17884        if (mKeyedTags != null) return mKeyedTags.get(key);
17885        return null;
17886    }
17887
17888    /**
17889     * Sets a tag associated with this view and a key. A tag can be used
17890     * to mark a view in its hierarchy and does not have to be unique within
17891     * the hierarchy. Tags can also be used to store data within a view
17892     * without resorting to another data structure.
17893     *
17894     * The specified key should be an id declared in the resources of the
17895     * application to ensure it is unique (see the <a
17896     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17897     * Keys identified as belonging to
17898     * the Android framework or not associated with any package will cause
17899     * an {@link IllegalArgumentException} to be thrown.
17900     *
17901     * @param key The key identifying the tag
17902     * @param tag An Object to tag the view with
17903     *
17904     * @throws IllegalArgumentException If they specified key is not valid
17905     *
17906     * @see #setTag(Object)
17907     * @see #getTag(int)
17908     */
17909    public void setTag(int key, final Object tag) {
17910        // If the package id is 0x00 or 0x01, it's either an undefined package
17911        // or a framework id
17912        if ((key >>> 24) < 2) {
17913            throw new IllegalArgumentException("The key must be an application-specific "
17914                    + "resource id.");
17915        }
17916
17917        setKeyedTag(key, tag);
17918    }
17919
17920    /**
17921     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17922     * framework id.
17923     *
17924     * @hide
17925     */
17926    public void setTagInternal(int key, Object tag) {
17927        if ((key >>> 24) != 0x1) {
17928            throw new IllegalArgumentException("The key must be a framework-specific "
17929                    + "resource id.");
17930        }
17931
17932        setKeyedTag(key, tag);
17933    }
17934
17935    private void setKeyedTag(int key, Object tag) {
17936        if (mKeyedTags == null) {
17937            mKeyedTags = new SparseArray<Object>(2);
17938        }
17939
17940        mKeyedTags.put(key, tag);
17941    }
17942
17943    /**
17944     * Prints information about this view in the log output, with the tag
17945     * {@link #VIEW_LOG_TAG}.
17946     *
17947     * @hide
17948     */
17949    public void debug() {
17950        debug(0);
17951    }
17952
17953    /**
17954     * Prints information about this view in the log output, with the tag
17955     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17956     * indentation defined by the <code>depth</code>.
17957     *
17958     * @param depth the indentation level
17959     *
17960     * @hide
17961     */
17962    protected void debug(int depth) {
17963        String output = debugIndent(depth - 1);
17964
17965        output += "+ " + this;
17966        int id = getId();
17967        if (id != -1) {
17968            output += " (id=" + id + ")";
17969        }
17970        Object tag = getTag();
17971        if (tag != null) {
17972            output += " (tag=" + tag + ")";
17973        }
17974        Log.d(VIEW_LOG_TAG, output);
17975
17976        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17977            output = debugIndent(depth) + " FOCUSED";
17978            Log.d(VIEW_LOG_TAG, output);
17979        }
17980
17981        output = debugIndent(depth);
17982        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17983                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17984                + "} ";
17985        Log.d(VIEW_LOG_TAG, output);
17986
17987        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17988                || mPaddingBottom != 0) {
17989            output = debugIndent(depth);
17990            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17991                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17992            Log.d(VIEW_LOG_TAG, output);
17993        }
17994
17995        output = debugIndent(depth);
17996        output += "mMeasureWidth=" + mMeasuredWidth +
17997                " mMeasureHeight=" + mMeasuredHeight;
17998        Log.d(VIEW_LOG_TAG, output);
17999
18000        output = debugIndent(depth);
18001        if (mLayoutParams == null) {
18002            output += "BAD! no layout params";
18003        } else {
18004            output = mLayoutParams.debug(output);
18005        }
18006        Log.d(VIEW_LOG_TAG, output);
18007
18008        output = debugIndent(depth);
18009        output += "flags={";
18010        output += View.printFlags(mViewFlags);
18011        output += "}";
18012        Log.d(VIEW_LOG_TAG, output);
18013
18014        output = debugIndent(depth);
18015        output += "privateFlags={";
18016        output += View.printPrivateFlags(mPrivateFlags);
18017        output += "}";
18018        Log.d(VIEW_LOG_TAG, output);
18019    }
18020
18021    /**
18022     * Creates a string of whitespaces used for indentation.
18023     *
18024     * @param depth the indentation level
18025     * @return a String containing (depth * 2 + 3) * 2 white spaces
18026     *
18027     * @hide
18028     */
18029    protected static String debugIndent(int depth) {
18030        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18031        for (int i = 0; i < (depth * 2) + 3; i++) {
18032            spaces.append(' ').append(' ');
18033        }
18034        return spaces.toString();
18035    }
18036
18037    /**
18038     * <p>Return the offset of the widget's text baseline from the widget's top
18039     * boundary. If this widget does not support baseline alignment, this
18040     * method returns -1. </p>
18041     *
18042     * @return the offset of the baseline within the widget's bounds or -1
18043     *         if baseline alignment is not supported
18044     */
18045    @ViewDebug.ExportedProperty(category = "layout")
18046    public int getBaseline() {
18047        return -1;
18048    }
18049
18050    /**
18051     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18052     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18053     * a layout pass.
18054     *
18055     * @return whether the view hierarchy is currently undergoing a layout pass
18056     */
18057    public boolean isInLayout() {
18058        ViewRootImpl viewRoot = getViewRootImpl();
18059        return (viewRoot != null && viewRoot.isInLayout());
18060    }
18061
18062    /**
18063     * Call this when something has changed which has invalidated the
18064     * layout of this view. This will schedule a layout pass of the view
18065     * tree. This should not be called while the view hierarchy is currently in a layout
18066     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18067     * end of the current layout pass (and then layout will run again) or after the current
18068     * frame is drawn and the next layout occurs.
18069     *
18070     * <p>Subclasses which override this method should call the superclass method to
18071     * handle possible request-during-layout errors correctly.</p>
18072     */
18073    @CallSuper
18074    public void requestLayout() {
18075        if (mMeasureCache != null) mMeasureCache.clear();
18076
18077        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18078            // Only trigger request-during-layout logic if this is the view requesting it,
18079            // not the views in its parent hierarchy
18080            ViewRootImpl viewRoot = getViewRootImpl();
18081            if (viewRoot != null && viewRoot.isInLayout()) {
18082                if (!viewRoot.requestLayoutDuringLayout(this)) {
18083                    return;
18084                }
18085            }
18086            mAttachInfo.mViewRequestingLayout = this;
18087        }
18088
18089        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18090        mPrivateFlags |= PFLAG_INVALIDATED;
18091
18092        if (mParent != null && !mParent.isLayoutRequested()) {
18093            mParent.requestLayout();
18094        }
18095        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18096            mAttachInfo.mViewRequestingLayout = null;
18097        }
18098    }
18099
18100    /**
18101     * Forces this view to be laid out during the next layout pass.
18102     * This method does not call requestLayout() or forceLayout()
18103     * on the parent.
18104     */
18105    public void forceLayout() {
18106        if (mMeasureCache != null) mMeasureCache.clear();
18107
18108        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18109        mPrivateFlags |= PFLAG_INVALIDATED;
18110    }
18111
18112    /**
18113     * <p>
18114     * This is called to find out how big a view should be. The parent
18115     * supplies constraint information in the width and height parameters.
18116     * </p>
18117     *
18118     * <p>
18119     * The actual measurement work of a view is performed in
18120     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18121     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18122     * </p>
18123     *
18124     *
18125     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18126     *        parent
18127     * @param heightMeasureSpec Vertical space requirements as imposed by the
18128     *        parent
18129     *
18130     * @see #onMeasure(int, int)
18131     */
18132    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18133        boolean optical = isLayoutModeOptical(this);
18134        if (optical != isLayoutModeOptical(mParent)) {
18135            Insets insets = getOpticalInsets();
18136            int oWidth  = insets.left + insets.right;
18137            int oHeight = insets.top  + insets.bottom;
18138            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18139            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18140        }
18141
18142        // Suppress sign extension for the low bytes
18143        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18144        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18145
18146        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18147        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18148                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18149        final boolean matchingSize = isExactly &&
18150                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18151                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18152        if (forceLayout || !matchingSize &&
18153                (widthMeasureSpec != mOldWidthMeasureSpec ||
18154                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18155
18156            // first clears the measured dimension flag
18157            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18158
18159            resolveRtlPropertiesIfNeeded();
18160
18161            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18162            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18163                // measure ourselves, this should set the measured dimension flag back
18164                onMeasure(widthMeasureSpec, heightMeasureSpec);
18165                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18166            } else {
18167                long value = mMeasureCache.valueAt(cacheIndex);
18168                // Casting a long to int drops the high 32 bits, no mask needed
18169                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18170                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18171            }
18172
18173            // flag not set, setMeasuredDimension() was not invoked, we raise
18174            // an exception to warn the developer
18175            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18176                throw new IllegalStateException("View with id " + getId() + ": "
18177                        + getClass().getName() + "#onMeasure() did not set the"
18178                        + " measured dimension by calling"
18179                        + " setMeasuredDimension()");
18180            }
18181
18182            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18183        }
18184
18185        mOldWidthMeasureSpec = widthMeasureSpec;
18186        mOldHeightMeasureSpec = heightMeasureSpec;
18187
18188        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18189                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18190    }
18191
18192    /**
18193     * <p>
18194     * Measure the view and its content to determine the measured width and the
18195     * measured height. This method is invoked by {@link #measure(int, int)} and
18196     * should be overridden by subclasses to provide accurate and efficient
18197     * measurement of their contents.
18198     * </p>
18199     *
18200     * <p>
18201     * <strong>CONTRACT:</strong> When overriding this method, you
18202     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18203     * measured width and height of this view. Failure to do so will trigger an
18204     * <code>IllegalStateException</code>, thrown by
18205     * {@link #measure(int, int)}. Calling the superclass'
18206     * {@link #onMeasure(int, int)} is a valid use.
18207     * </p>
18208     *
18209     * <p>
18210     * The base class implementation of measure defaults to the background size,
18211     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18212     * override {@link #onMeasure(int, int)} to provide better measurements of
18213     * their content.
18214     * </p>
18215     *
18216     * <p>
18217     * If this method is overridden, it is the subclass's responsibility to make
18218     * sure the measured height and width are at least the view's minimum height
18219     * and width ({@link #getSuggestedMinimumHeight()} and
18220     * {@link #getSuggestedMinimumWidth()}).
18221     * </p>
18222     *
18223     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18224     *                         The requirements are encoded with
18225     *                         {@link android.view.View.MeasureSpec}.
18226     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18227     *                         The requirements are encoded with
18228     *                         {@link android.view.View.MeasureSpec}.
18229     *
18230     * @see #getMeasuredWidth()
18231     * @see #getMeasuredHeight()
18232     * @see #setMeasuredDimension(int, int)
18233     * @see #getSuggestedMinimumHeight()
18234     * @see #getSuggestedMinimumWidth()
18235     * @see android.view.View.MeasureSpec#getMode(int)
18236     * @see android.view.View.MeasureSpec#getSize(int)
18237     */
18238    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18239        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18240                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18241    }
18242
18243    /**
18244     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18245     * measured width and measured height. Failing to do so will trigger an
18246     * exception at measurement time.</p>
18247     *
18248     * @param measuredWidth The measured width of this view.  May be a complex
18249     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18250     * {@link #MEASURED_STATE_TOO_SMALL}.
18251     * @param measuredHeight The measured height of this view.  May be a complex
18252     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18253     * {@link #MEASURED_STATE_TOO_SMALL}.
18254     */
18255    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18256        boolean optical = isLayoutModeOptical(this);
18257        if (optical != isLayoutModeOptical(mParent)) {
18258            Insets insets = getOpticalInsets();
18259            int opticalWidth  = insets.left + insets.right;
18260            int opticalHeight = insets.top  + insets.bottom;
18261
18262            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18263            measuredHeight += optical ? opticalHeight : -opticalHeight;
18264        }
18265        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18266    }
18267
18268    /**
18269     * Sets the measured dimension without extra processing for things like optical bounds.
18270     * Useful for reapplying consistent values that have already been cooked with adjustments
18271     * for optical bounds, etc. such as those from the measurement cache.
18272     *
18273     * @param measuredWidth The measured width of this view.  May be a complex
18274     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18275     * {@link #MEASURED_STATE_TOO_SMALL}.
18276     * @param measuredHeight The measured height of this view.  May be a complex
18277     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18278     * {@link #MEASURED_STATE_TOO_SMALL}.
18279     */
18280    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18281        mMeasuredWidth = measuredWidth;
18282        mMeasuredHeight = measuredHeight;
18283
18284        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18285    }
18286
18287    /**
18288     * Merge two states as returned by {@link #getMeasuredState()}.
18289     * @param curState The current state as returned from a view or the result
18290     * of combining multiple views.
18291     * @param newState The new view state to combine.
18292     * @return Returns a new integer reflecting the combination of the two
18293     * states.
18294     */
18295    public static int combineMeasuredStates(int curState, int newState) {
18296        return curState | newState;
18297    }
18298
18299    /**
18300     * Version of {@link #resolveSizeAndState(int, int, int)}
18301     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18302     */
18303    public static int resolveSize(int size, int measureSpec) {
18304        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18305    }
18306
18307    /**
18308     * Utility to reconcile a desired size and state, with constraints imposed
18309     * by a MeasureSpec. Will take the desired size, unless a different size
18310     * is imposed by the constraints. The returned value is a compound integer,
18311     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18312     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18313     * resulting size is smaller than the size the view wants to be.
18314     *
18315     * @param size How big the view wants to be.
18316     * @param measureSpec Constraints imposed by the parent.
18317     * @param childMeasuredState Size information bit mask for the view's
18318     *                           children.
18319     * @return Size information bit mask as defined by
18320     *         {@link #MEASURED_SIZE_MASK} and
18321     *         {@link #MEASURED_STATE_TOO_SMALL}.
18322     */
18323    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18324        final int specMode = MeasureSpec.getMode(measureSpec);
18325        final int specSize = MeasureSpec.getSize(measureSpec);
18326        final int result;
18327        switch (specMode) {
18328            case MeasureSpec.AT_MOST:
18329                if (specSize < size) {
18330                    result = specSize | MEASURED_STATE_TOO_SMALL;
18331                } else {
18332                    result = size;
18333                }
18334                break;
18335            case MeasureSpec.EXACTLY:
18336                result = specSize;
18337                break;
18338            case MeasureSpec.UNSPECIFIED:
18339            default:
18340                result = size;
18341        }
18342        return result | (childMeasuredState & MEASURED_STATE_MASK);
18343    }
18344
18345    /**
18346     * Utility to return a default size. Uses the supplied size if the
18347     * MeasureSpec imposed no constraints. Will get larger if allowed
18348     * by the MeasureSpec.
18349     *
18350     * @param size Default size for this view
18351     * @param measureSpec Constraints imposed by the parent
18352     * @return The size this view should be.
18353     */
18354    public static int getDefaultSize(int size, int measureSpec) {
18355        int result = size;
18356        int specMode = MeasureSpec.getMode(measureSpec);
18357        int specSize = MeasureSpec.getSize(measureSpec);
18358
18359        switch (specMode) {
18360        case MeasureSpec.UNSPECIFIED:
18361            result = size;
18362            break;
18363        case MeasureSpec.AT_MOST:
18364        case MeasureSpec.EXACTLY:
18365            result = specSize;
18366            break;
18367        }
18368        return result;
18369    }
18370
18371    /**
18372     * Returns the suggested minimum height that the view should use. This
18373     * returns the maximum of the view's minimum height
18374     * and the background's minimum height
18375     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
18376     * <p>
18377     * When being used in {@link #onMeasure(int, int)}, the caller should still
18378     * ensure the returned height is within the requirements of the parent.
18379     *
18380     * @return The suggested minimum height of the view.
18381     */
18382    protected int getSuggestedMinimumHeight() {
18383        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
18384
18385    }
18386
18387    /**
18388     * Returns the suggested minimum width that the view should use. This
18389     * returns the maximum of the view's minimum width)
18390     * and the background's minimum width
18391     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
18392     * <p>
18393     * When being used in {@link #onMeasure(int, int)}, the caller should still
18394     * ensure the returned width is within the requirements of the parent.
18395     *
18396     * @return The suggested minimum width of the view.
18397     */
18398    protected int getSuggestedMinimumWidth() {
18399        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
18400    }
18401
18402    /**
18403     * Returns the minimum height of the view.
18404     *
18405     * @return the minimum height the view will try to be.
18406     *
18407     * @see #setMinimumHeight(int)
18408     *
18409     * @attr ref android.R.styleable#View_minHeight
18410     */
18411    public int getMinimumHeight() {
18412        return mMinHeight;
18413    }
18414
18415    /**
18416     * Sets the minimum height of the view. It is not guaranteed the view will
18417     * be able to achieve this minimum height (for example, if its parent layout
18418     * constrains it with less available height).
18419     *
18420     * @param minHeight The minimum height the view will try to be.
18421     *
18422     * @see #getMinimumHeight()
18423     *
18424     * @attr ref android.R.styleable#View_minHeight
18425     */
18426    public void setMinimumHeight(int minHeight) {
18427        mMinHeight = minHeight;
18428        requestLayout();
18429    }
18430
18431    /**
18432     * Returns the minimum width of the view.
18433     *
18434     * @return the minimum width the view will try to be.
18435     *
18436     * @see #setMinimumWidth(int)
18437     *
18438     * @attr ref android.R.styleable#View_minWidth
18439     */
18440    public int getMinimumWidth() {
18441        return mMinWidth;
18442    }
18443
18444    /**
18445     * Sets the minimum width of the view. It is not guaranteed the view will
18446     * be able to achieve this minimum width (for example, if its parent layout
18447     * constrains it with less available width).
18448     *
18449     * @param minWidth The minimum width the view will try to be.
18450     *
18451     * @see #getMinimumWidth()
18452     *
18453     * @attr ref android.R.styleable#View_minWidth
18454     */
18455    public void setMinimumWidth(int minWidth) {
18456        mMinWidth = minWidth;
18457        requestLayout();
18458
18459    }
18460
18461    /**
18462     * Get the animation currently associated with this view.
18463     *
18464     * @return The animation that is currently playing or
18465     *         scheduled to play for this view.
18466     */
18467    public Animation getAnimation() {
18468        return mCurrentAnimation;
18469    }
18470
18471    /**
18472     * Start the specified animation now.
18473     *
18474     * @param animation the animation to start now
18475     */
18476    public void startAnimation(Animation animation) {
18477        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
18478        setAnimation(animation);
18479        invalidateParentCaches();
18480        invalidate(true);
18481    }
18482
18483    /**
18484     * Cancels any animations for this view.
18485     */
18486    public void clearAnimation() {
18487        if (mCurrentAnimation != null) {
18488            mCurrentAnimation.detach();
18489        }
18490        mCurrentAnimation = null;
18491        invalidateParentIfNeeded();
18492    }
18493
18494    /**
18495     * Sets the next animation to play for this view.
18496     * If you want the animation to play immediately, use
18497     * {@link #startAnimation(android.view.animation.Animation)} instead.
18498     * This method provides allows fine-grained
18499     * control over the start time and invalidation, but you
18500     * must make sure that 1) the animation has a start time set, and
18501     * 2) the view's parent (which controls animations on its children)
18502     * will be invalidated when the animation is supposed to
18503     * start.
18504     *
18505     * @param animation The next animation, or null.
18506     */
18507    public void setAnimation(Animation animation) {
18508        mCurrentAnimation = animation;
18509
18510        if (animation != null) {
18511            // If the screen is off assume the animation start time is now instead of
18512            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
18513            // would cause the animation to start when the screen turns back on
18514            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
18515                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
18516                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
18517            }
18518            animation.reset();
18519        }
18520    }
18521
18522    /**
18523     * Invoked by a parent ViewGroup to notify the start of the animation
18524     * currently associated with this view. If you override this method,
18525     * always call super.onAnimationStart();
18526     *
18527     * @see #setAnimation(android.view.animation.Animation)
18528     * @see #getAnimation()
18529     */
18530    @CallSuper
18531    protected void onAnimationStart() {
18532        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18533    }
18534
18535    /**
18536     * Invoked by a parent ViewGroup to notify the end of the animation
18537     * currently associated with this view. If you override this method,
18538     * always call super.onAnimationEnd();
18539     *
18540     * @see #setAnimation(android.view.animation.Animation)
18541     * @see #getAnimation()
18542     */
18543    @CallSuper
18544    protected void onAnimationEnd() {
18545        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18546    }
18547
18548    /**
18549     * Invoked if there is a Transform that involves alpha. Subclass that can
18550     * draw themselves with the specified alpha should return true, and then
18551     * respect that alpha when their onDraw() is called. If this returns false
18552     * then the view may be redirected to draw into an offscreen buffer to
18553     * fulfill the request, which will look fine, but may be slower than if the
18554     * subclass handles it internally. The default implementation returns false.
18555     *
18556     * @param alpha The alpha (0..255) to apply to the view's drawing
18557     * @return true if the view can draw with the specified alpha.
18558     */
18559    protected boolean onSetAlpha(int alpha) {
18560        return false;
18561    }
18562
18563    /**
18564     * This is used by the RootView to perform an optimization when
18565     * the view hierarchy contains one or several SurfaceView.
18566     * SurfaceView is always considered transparent, but its children are not,
18567     * therefore all View objects remove themselves from the global transparent
18568     * region (passed as a parameter to this function).
18569     *
18570     * @param region The transparent region for this ViewAncestor (window).
18571     *
18572     * @return Returns true if the effective visibility of the view at this
18573     * point is opaque, regardless of the transparent region; returns false
18574     * if it is possible for underlying windows to be seen behind the view.
18575     *
18576     * {@hide}
18577     */
18578    public boolean gatherTransparentRegion(Region region) {
18579        final AttachInfo attachInfo = mAttachInfo;
18580        if (region != null && attachInfo != null) {
18581            final int pflags = mPrivateFlags;
18582            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18583                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18584                // remove it from the transparent region.
18585                final int[] location = attachInfo.mTransparentLocation;
18586                getLocationInWindow(location);
18587                region.op(location[0], location[1], location[0] + mRight - mLeft,
18588                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18589            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18590                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18591                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18592                // exists, so we remove the background drawable's non-transparent
18593                // parts from this transparent region.
18594                applyDrawableToTransparentRegion(mBackground, region);
18595            }
18596            final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18597            if (foreground != null) {
18598                applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
18599            }
18600        }
18601        return true;
18602    }
18603
18604    /**
18605     * Play a sound effect for this view.
18606     *
18607     * <p>The framework will play sound effects for some built in actions, such as
18608     * clicking, but you may wish to play these effects in your widget,
18609     * for instance, for internal navigation.
18610     *
18611     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18612     * {@link #isSoundEffectsEnabled()} is true.
18613     *
18614     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18615     */
18616    public void playSoundEffect(int soundConstant) {
18617        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18618            return;
18619        }
18620        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18621    }
18622
18623    /**
18624     * BZZZTT!!1!
18625     *
18626     * <p>Provide haptic feedback to the user for this view.
18627     *
18628     * <p>The framework will provide haptic feedback for some built in actions,
18629     * such as long presses, but you may wish to provide feedback for your
18630     * own widget.
18631     *
18632     * <p>The feedback will only be performed if
18633     * {@link #isHapticFeedbackEnabled()} is true.
18634     *
18635     * @param feedbackConstant One of the constants defined in
18636     * {@link HapticFeedbackConstants}
18637     */
18638    public boolean performHapticFeedback(int feedbackConstant) {
18639        return performHapticFeedback(feedbackConstant, 0);
18640    }
18641
18642    /**
18643     * BZZZTT!!1!
18644     *
18645     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18646     *
18647     * @param feedbackConstant One of the constants defined in
18648     * {@link HapticFeedbackConstants}
18649     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18650     */
18651    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18652        if (mAttachInfo == null) {
18653            return false;
18654        }
18655        //noinspection SimplifiableIfStatement
18656        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18657                && !isHapticFeedbackEnabled()) {
18658            return false;
18659        }
18660        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18661                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18662    }
18663
18664    /**
18665     * Request that the visibility of the status bar or other screen/window
18666     * decorations be changed.
18667     *
18668     * <p>This method is used to put the over device UI into temporary modes
18669     * where the user's attention is focused more on the application content,
18670     * by dimming or hiding surrounding system affordances.  This is typically
18671     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18672     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18673     * to be placed behind the action bar (and with these flags other system
18674     * affordances) so that smooth transitions between hiding and showing them
18675     * can be done.
18676     *
18677     * <p>Two representative examples of the use of system UI visibility is
18678     * implementing a content browsing application (like a magazine reader)
18679     * and a video playing application.
18680     *
18681     * <p>The first code shows a typical implementation of a View in a content
18682     * browsing application.  In this implementation, the application goes
18683     * into a content-oriented mode by hiding the status bar and action bar,
18684     * and putting the navigation elements into lights out mode.  The user can
18685     * then interact with content while in this mode.  Such an application should
18686     * provide an easy way for the user to toggle out of the mode (such as to
18687     * check information in the status bar or access notifications).  In the
18688     * implementation here, this is done simply by tapping on the content.
18689     *
18690     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18691     *      content}
18692     *
18693     * <p>This second code sample shows a typical implementation of a View
18694     * in a video playing application.  In this situation, while the video is
18695     * playing the application would like to go into a complete full-screen mode,
18696     * to use as much of the display as possible for the video.  When in this state
18697     * the user can not interact with the application; the system intercepts
18698     * touching on the screen to pop the UI out of full screen mode.  See
18699     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18700     *
18701     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18702     *      content}
18703     *
18704     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18705     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18706     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18707     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18708     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18709     */
18710    public void setSystemUiVisibility(int visibility) {
18711        if (visibility != mSystemUiVisibility) {
18712            mSystemUiVisibility = visibility;
18713            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18714                mParent.recomputeViewAttributes(this);
18715            }
18716        }
18717    }
18718
18719    /**
18720     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18721     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18722     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18723     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18724     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18725     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18726     */
18727    public int getSystemUiVisibility() {
18728        return mSystemUiVisibility;
18729    }
18730
18731    /**
18732     * Returns the current system UI visibility that is currently set for
18733     * the entire window.  This is the combination of the
18734     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18735     * views in the window.
18736     */
18737    public int getWindowSystemUiVisibility() {
18738        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18739    }
18740
18741    /**
18742     * Override to find out when the window's requested system UI visibility
18743     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18744     * This is different from the callbacks received through
18745     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18746     * in that this is only telling you about the local request of the window,
18747     * not the actual values applied by the system.
18748     */
18749    public void onWindowSystemUiVisibilityChanged(int visible) {
18750    }
18751
18752    /**
18753     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18754     * the view hierarchy.
18755     */
18756    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18757        onWindowSystemUiVisibilityChanged(visible);
18758    }
18759
18760    /**
18761     * Set a listener to receive callbacks when the visibility of the system bar changes.
18762     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18763     */
18764    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18765        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18766        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18767            mParent.recomputeViewAttributes(this);
18768        }
18769    }
18770
18771    /**
18772     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18773     * the view hierarchy.
18774     */
18775    public void dispatchSystemUiVisibilityChanged(int visibility) {
18776        ListenerInfo li = mListenerInfo;
18777        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18778            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18779                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18780        }
18781    }
18782
18783    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18784        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18785        if (val != mSystemUiVisibility) {
18786            setSystemUiVisibility(val);
18787            return true;
18788        }
18789        return false;
18790    }
18791
18792    /** @hide */
18793    public void setDisabledSystemUiVisibility(int flags) {
18794        if (mAttachInfo != null) {
18795            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18796                mAttachInfo.mDisabledSystemUiVisibility = flags;
18797                if (mParent != null) {
18798                    mParent.recomputeViewAttributes(this);
18799                }
18800            }
18801        }
18802    }
18803
18804    /**
18805     * Creates an image that the system displays during the drag and drop
18806     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18807     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18808     * appearance as the given View. The default also positions the center of the drag shadow
18809     * directly under the touch point. If no View is provided (the constructor with no parameters
18810     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18811     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
18812     * default is an invisible drag shadow.
18813     * <p>
18814     * You are not required to use the View you provide to the constructor as the basis of the
18815     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18816     * anything you want as the drag shadow.
18817     * </p>
18818     * <p>
18819     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18820     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18821     *  size and position of the drag shadow. It uses this data to construct a
18822     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18823     *  so that your application can draw the shadow image in the Canvas.
18824     * </p>
18825     *
18826     * <div class="special reference">
18827     * <h3>Developer Guides</h3>
18828     * <p>For a guide to implementing drag and drop features, read the
18829     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18830     * </div>
18831     */
18832    public static class DragShadowBuilder {
18833        private final WeakReference<View> mView;
18834
18835        /**
18836         * Constructs a shadow image builder based on a View. By default, the resulting drag
18837         * shadow will have the same appearance and dimensions as the View, with the touch point
18838         * over the center of the View.
18839         * @param view A View. Any View in scope can be used.
18840         */
18841        public DragShadowBuilder(View view) {
18842            mView = new WeakReference<View>(view);
18843        }
18844
18845        /**
18846         * Construct a shadow builder object with no associated View.  This
18847         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18848         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18849         * to supply the drag shadow's dimensions and appearance without
18850         * reference to any View object. If they are not overridden, then the result is an
18851         * invisible drag shadow.
18852         */
18853        public DragShadowBuilder() {
18854            mView = new WeakReference<View>(null);
18855        }
18856
18857        /**
18858         * Returns the View object that had been passed to the
18859         * {@link #View.DragShadowBuilder(View)}
18860         * constructor.  If that View parameter was {@code null} or if the
18861         * {@link #View.DragShadowBuilder()}
18862         * constructor was used to instantiate the builder object, this method will return
18863         * null.
18864         *
18865         * @return The View object associate with this builder object.
18866         */
18867        @SuppressWarnings({"JavadocReference"})
18868        final public View getView() {
18869            return mView.get();
18870        }
18871
18872        /**
18873         * Provides the metrics for the shadow image. These include the dimensions of
18874         * the shadow image, and the point within that shadow that should
18875         * be centered under the touch location while dragging.
18876         * <p>
18877         * The default implementation sets the dimensions of the shadow to be the
18878         * same as the dimensions of the View itself and centers the shadow under
18879         * the touch point.
18880         * </p>
18881         *
18882         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18883         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18884         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18885         * image.
18886         *
18887         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18888         * shadow image that should be underneath the touch point during the drag and drop
18889         * operation. Your application must set {@link android.graphics.Point#x} to the
18890         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18891         */
18892        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18893            final View view = mView.get();
18894            if (view != null) {
18895                shadowSize.set(view.getWidth(), view.getHeight());
18896                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18897            } else {
18898                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18899            }
18900        }
18901
18902        /**
18903         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18904         * based on the dimensions it received from the
18905         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18906         *
18907         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18908         */
18909        public void onDrawShadow(Canvas canvas) {
18910            final View view = mView.get();
18911            if (view != null) {
18912                view.draw(canvas);
18913            } else {
18914                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18915            }
18916        }
18917    }
18918
18919    /**
18920     * Starts a drag and drop operation. When your application calls this method, it passes a
18921     * {@link android.view.View.DragShadowBuilder} object to the system. The
18922     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18923     * to get metrics for the drag shadow, and then calls the object's
18924     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18925     * <p>
18926     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18927     *  drag events to all the View objects in your application that are currently visible. It does
18928     *  this either by calling the View object's drag listener (an implementation of
18929     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18930     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18931     *  Both are passed a {@link android.view.DragEvent} object that has a
18932     *  {@link android.view.DragEvent#getAction()} value of
18933     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18934     * </p>
18935     * <p>
18936     * Your application can invoke startDrag() on any attached View object. The View object does not
18937     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18938     * be related to the View the user selected for dragging.
18939     * </p>
18940     * @param data A {@link android.content.ClipData} object pointing to the data to be
18941     * transferred by the drag and drop operation.
18942     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18943     * drag shadow.
18944     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18945     * drop operation. This Object is put into every DragEvent object sent by the system during the
18946     * current drag.
18947     * <p>
18948     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18949     * to the target Views. For example, it can contain flags that differentiate between a
18950     * a copy operation and a move operation.
18951     * </p>
18952     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18953     * so the parameter should be set to 0.
18954     * @return {@code true} if the method completes successfully, or
18955     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18956     * do a drag, and so no drag operation is in progress.
18957     */
18958    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18959            Object myLocalState, int flags) {
18960        if (ViewDebug.DEBUG_DRAG) {
18961            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18962        }
18963        boolean okay = false;
18964
18965        Point shadowSize = new Point();
18966        Point shadowTouchPoint = new Point();
18967        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18968
18969        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18970                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18971            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18972        }
18973
18974        if (ViewDebug.DEBUG_DRAG) {
18975            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18976                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18977        }
18978        Surface surface = new Surface();
18979        try {
18980            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18981                    flags, shadowSize.x, shadowSize.y, surface);
18982            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18983                    + " surface=" + surface);
18984            if (token != null) {
18985                Canvas canvas = surface.lockCanvas(null);
18986                try {
18987                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18988                    shadowBuilder.onDrawShadow(canvas);
18989                } finally {
18990                    surface.unlockCanvasAndPost(canvas);
18991                }
18992
18993                final ViewRootImpl root = getViewRootImpl();
18994
18995                // Cache the local state object for delivery with DragEvents
18996                root.setLocalDragState(myLocalState);
18997
18998                // repurpose 'shadowSize' for the last touch point
18999                root.getLastTouchPoint(shadowSize);
19000
19001                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19002                        shadowSize.x, shadowSize.y,
19003                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19004                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19005
19006                // Off and running!  Release our local surface instance; the drag
19007                // shadow surface is now managed by the system process.
19008                surface.release();
19009            }
19010        } catch (Exception e) {
19011            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19012            surface.destroy();
19013        }
19014
19015        return okay;
19016    }
19017
19018    /**
19019     * Handles drag events sent by the system following a call to
19020     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19021     *<p>
19022     * When the system calls this method, it passes a
19023     * {@link android.view.DragEvent} object. A call to
19024     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19025     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19026     * operation.
19027     * @param event The {@link android.view.DragEvent} sent by the system.
19028     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19029     * in DragEvent, indicating the type of drag event represented by this object.
19030     * @return {@code true} if the method was successful, otherwise {@code false}.
19031     * <p>
19032     *  The method should return {@code true} in response to an action type of
19033     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19034     *  operation.
19035     * </p>
19036     * <p>
19037     *  The method should also return {@code true} in response to an action type of
19038     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19039     *  {@code false} if it didn't.
19040     * </p>
19041     */
19042    public boolean onDragEvent(DragEvent event) {
19043        return false;
19044    }
19045
19046    /**
19047     * Detects if this View is enabled and has a drag event listener.
19048     * If both are true, then it calls the drag event listener with the
19049     * {@link android.view.DragEvent} it received. If the drag event listener returns
19050     * {@code true}, then dispatchDragEvent() returns {@code true}.
19051     * <p>
19052     * For all other cases, the method calls the
19053     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19054     * method and returns its result.
19055     * </p>
19056     * <p>
19057     * This ensures that a drag event is always consumed, even if the View does not have a drag
19058     * event listener. However, if the View has a listener and the listener returns true, then
19059     * onDragEvent() is not called.
19060     * </p>
19061     */
19062    public boolean dispatchDragEvent(DragEvent event) {
19063        ListenerInfo li = mListenerInfo;
19064        //noinspection SimplifiableIfStatement
19065        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19066                && li.mOnDragListener.onDrag(this, event)) {
19067            return true;
19068        }
19069        return onDragEvent(event);
19070    }
19071
19072    boolean canAcceptDrag() {
19073        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19074    }
19075
19076    /**
19077     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19078     * it is ever exposed at all.
19079     * @hide
19080     */
19081    public void onCloseSystemDialogs(String reason) {
19082    }
19083
19084    /**
19085     * Given a Drawable whose bounds have been set to draw into this view,
19086     * update a Region being computed for
19087     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19088     * that any non-transparent parts of the Drawable are removed from the
19089     * given transparent region.
19090     *
19091     * @param dr The Drawable whose transparency is to be applied to the region.
19092     * @param region A Region holding the current transparency information,
19093     * where any parts of the region that are set are considered to be
19094     * transparent.  On return, this region will be modified to have the
19095     * transparency information reduced by the corresponding parts of the
19096     * Drawable that are not transparent.
19097     * {@hide}
19098     */
19099    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19100        if (DBG) {
19101            Log.i("View", "Getting transparent region for: " + this);
19102        }
19103        final Region r = dr.getTransparentRegion();
19104        final Rect db = dr.getBounds();
19105        final AttachInfo attachInfo = mAttachInfo;
19106        if (r != null && attachInfo != null) {
19107            final int w = getRight()-getLeft();
19108            final int h = getBottom()-getTop();
19109            if (db.left > 0) {
19110                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19111                r.op(0, 0, db.left, h, Region.Op.UNION);
19112            }
19113            if (db.right < w) {
19114                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19115                r.op(db.right, 0, w, h, Region.Op.UNION);
19116            }
19117            if (db.top > 0) {
19118                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19119                r.op(0, 0, w, db.top, Region.Op.UNION);
19120            }
19121            if (db.bottom < h) {
19122                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19123                r.op(0, db.bottom, w, h, Region.Op.UNION);
19124            }
19125            final int[] location = attachInfo.mTransparentLocation;
19126            getLocationInWindow(location);
19127            r.translate(location[0], location[1]);
19128            region.op(r, Region.Op.INTERSECT);
19129        } else {
19130            region.op(db, Region.Op.DIFFERENCE);
19131        }
19132    }
19133
19134    private void checkForLongClick(int delayOffset) {
19135        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19136            mHasPerformedLongPress = false;
19137
19138            if (mPendingCheckForLongPress == null) {
19139                mPendingCheckForLongPress = new CheckForLongPress();
19140            }
19141            mPendingCheckForLongPress.rememberWindowAttachCount();
19142            postDelayed(mPendingCheckForLongPress,
19143                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19144        }
19145    }
19146
19147    /**
19148     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19149     * LayoutInflater} class, which provides a full range of options for view inflation.
19150     *
19151     * @param context The Context object for your activity or application.
19152     * @param resource The resource ID to inflate
19153     * @param root A view group that will be the parent.  Used to properly inflate the
19154     * layout_* parameters.
19155     * @see LayoutInflater
19156     */
19157    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19158        LayoutInflater factory = LayoutInflater.from(context);
19159        return factory.inflate(resource, root);
19160    }
19161
19162    /**
19163     * Scroll the view with standard behavior for scrolling beyond the normal
19164     * content boundaries. Views that call this method should override
19165     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19166     * results of an over-scroll operation.
19167     *
19168     * Views can use this method to handle any touch or fling-based scrolling.
19169     *
19170     * @param deltaX Change in X in pixels
19171     * @param deltaY Change in Y in pixels
19172     * @param scrollX Current X scroll value in pixels before applying deltaX
19173     * @param scrollY Current Y scroll value in pixels before applying deltaY
19174     * @param scrollRangeX Maximum content scroll range along the X axis
19175     * @param scrollRangeY Maximum content scroll range along the Y axis
19176     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19177     *          along the X axis.
19178     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19179     *          along the Y axis.
19180     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19181     * @return true if scrolling was clamped to an over-scroll boundary along either
19182     *          axis, false otherwise.
19183     */
19184    @SuppressWarnings({"UnusedParameters"})
19185    protected boolean overScrollBy(int deltaX, int deltaY,
19186            int scrollX, int scrollY,
19187            int scrollRangeX, int scrollRangeY,
19188            int maxOverScrollX, int maxOverScrollY,
19189            boolean isTouchEvent) {
19190        final int overScrollMode = mOverScrollMode;
19191        final boolean canScrollHorizontal =
19192                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19193        final boolean canScrollVertical =
19194                computeVerticalScrollRange() > computeVerticalScrollExtent();
19195        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19196                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19197        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19198                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19199
19200        int newScrollX = scrollX + deltaX;
19201        if (!overScrollHorizontal) {
19202            maxOverScrollX = 0;
19203        }
19204
19205        int newScrollY = scrollY + deltaY;
19206        if (!overScrollVertical) {
19207            maxOverScrollY = 0;
19208        }
19209
19210        // Clamp values if at the limits and record
19211        final int left = -maxOverScrollX;
19212        final int right = maxOverScrollX + scrollRangeX;
19213        final int top = -maxOverScrollY;
19214        final int bottom = maxOverScrollY + scrollRangeY;
19215
19216        boolean clampedX = false;
19217        if (newScrollX > right) {
19218            newScrollX = right;
19219            clampedX = true;
19220        } else if (newScrollX < left) {
19221            newScrollX = left;
19222            clampedX = true;
19223        }
19224
19225        boolean clampedY = false;
19226        if (newScrollY > bottom) {
19227            newScrollY = bottom;
19228            clampedY = true;
19229        } else if (newScrollY < top) {
19230            newScrollY = top;
19231            clampedY = true;
19232        }
19233
19234        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19235
19236        return clampedX || clampedY;
19237    }
19238
19239    /**
19240     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19241     * respond to the results of an over-scroll operation.
19242     *
19243     * @param scrollX New X scroll value in pixels
19244     * @param scrollY New Y scroll value in pixels
19245     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19246     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19247     */
19248    protected void onOverScrolled(int scrollX, int scrollY,
19249            boolean clampedX, boolean clampedY) {
19250        // Intentionally empty.
19251    }
19252
19253    /**
19254     * Returns the over-scroll mode for this view. The result will be
19255     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19256     * (allow over-scrolling only if the view content is larger than the container),
19257     * or {@link #OVER_SCROLL_NEVER}.
19258     *
19259     * @return This view's over-scroll mode.
19260     */
19261    public int getOverScrollMode() {
19262        return mOverScrollMode;
19263    }
19264
19265    /**
19266     * Set the over-scroll mode for this view. Valid over-scroll modes are
19267     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19268     * (allow over-scrolling only if the view content is larger than the container),
19269     * or {@link #OVER_SCROLL_NEVER}.
19270     *
19271     * Setting the over-scroll mode of a view will have an effect only if the
19272     * view is capable of scrolling.
19273     *
19274     * @param overScrollMode The new over-scroll mode for this view.
19275     */
19276    public void setOverScrollMode(int overScrollMode) {
19277        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19278                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19279                overScrollMode != OVER_SCROLL_NEVER) {
19280            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19281        }
19282        mOverScrollMode = overScrollMode;
19283    }
19284
19285    /**
19286     * Enable or disable nested scrolling for this view.
19287     *
19288     * <p>If this property is set to true the view will be permitted to initiate nested
19289     * scrolling operations with a compatible parent view in the current hierarchy. If this
19290     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19291     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19292     * the nested scroll.</p>
19293     *
19294     * @param enabled true to enable nested scrolling, false to disable
19295     *
19296     * @see #isNestedScrollingEnabled()
19297     */
19298    public void setNestedScrollingEnabled(boolean enabled) {
19299        if (enabled) {
19300            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19301        } else {
19302            stopNestedScroll();
19303            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19304        }
19305    }
19306
19307    /**
19308     * Returns true if nested scrolling is enabled for this view.
19309     *
19310     * <p>If nested scrolling is enabled and this View class implementation supports it,
19311     * this view will act as a nested scrolling child view when applicable, forwarding data
19312     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19313     * parent.</p>
19314     *
19315     * @return true if nested scrolling is enabled
19316     *
19317     * @see #setNestedScrollingEnabled(boolean)
19318     */
19319    public boolean isNestedScrollingEnabled() {
19320        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19321                PFLAG3_NESTED_SCROLLING_ENABLED;
19322    }
19323
19324    /**
19325     * Begin a nestable scroll operation along the given axes.
19326     *
19327     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19328     *
19329     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19330     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19331     * In the case of touch scrolling the nested scroll will be terminated automatically in
19332     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19333     * In the event of programmatic scrolling the caller must explicitly call
19334     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19335     *
19336     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19337     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19338     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19339     *
19340     * <p>At each incremental step of the scroll the caller should invoke
19341     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19342     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19343     * parent at least partially consumed the scroll and the caller should adjust the amount it
19344     * scrolls by.</p>
19345     *
19346     * <p>After applying the remainder of the scroll delta the caller should invoke
19347     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19348     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19349     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19350     * </p>
19351     *
19352     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19353     *             {@link #SCROLL_AXIS_VERTICAL}.
19354     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19355     *         the current gesture.
19356     *
19357     * @see #stopNestedScroll()
19358     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19359     * @see #dispatchNestedScroll(int, int, int, int, int[])
19360     */
19361    public boolean startNestedScroll(int axes) {
19362        if (hasNestedScrollingParent()) {
19363            // Already in progress
19364            return true;
19365        }
19366        if (isNestedScrollingEnabled()) {
19367            ViewParent p = getParent();
19368            View child = this;
19369            while (p != null) {
19370                try {
19371                    if (p.onStartNestedScroll(child, this, axes)) {
19372                        mNestedScrollingParent = p;
19373                        p.onNestedScrollAccepted(child, this, axes);
19374                        return true;
19375                    }
19376                } catch (AbstractMethodError e) {
19377                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
19378                            "method onStartNestedScroll", e);
19379                    // Allow the search upward to continue
19380                }
19381                if (p instanceof View) {
19382                    child = (View) p;
19383                }
19384                p = p.getParent();
19385            }
19386        }
19387        return false;
19388    }
19389
19390    /**
19391     * Stop a nested scroll in progress.
19392     *
19393     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
19394     *
19395     * @see #startNestedScroll(int)
19396     */
19397    public void stopNestedScroll() {
19398        if (mNestedScrollingParent != null) {
19399            mNestedScrollingParent.onStopNestedScroll(this);
19400            mNestedScrollingParent = null;
19401        }
19402    }
19403
19404    /**
19405     * Returns true if this view has a nested scrolling parent.
19406     *
19407     * <p>The presence of a nested scrolling parent indicates that this view has initiated
19408     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
19409     *
19410     * @return whether this view has a nested scrolling parent
19411     */
19412    public boolean hasNestedScrollingParent() {
19413        return mNestedScrollingParent != null;
19414    }
19415
19416    /**
19417     * Dispatch one step of a nested scroll in progress.
19418     *
19419     * <p>Implementations of views that support nested scrolling should call this to report
19420     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
19421     * is not currently in progress or nested scrolling is not
19422     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
19423     *
19424     * <p>Compatible View implementations should also call
19425     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
19426     * consuming a component of the scroll event themselves.</p>
19427     *
19428     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
19429     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
19430     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
19431     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
19432     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19433     *                       in local view coordinates of this view from before this operation
19434     *                       to after it completes. View implementations may use this to adjust
19435     *                       expected input coordinate tracking.
19436     * @return true if the event was dispatched, false if it could not be dispatched.
19437     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19438     */
19439    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
19440            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
19441        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19442            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
19443                int startX = 0;
19444                int startY = 0;
19445                if (offsetInWindow != null) {
19446                    getLocationInWindow(offsetInWindow);
19447                    startX = offsetInWindow[0];
19448                    startY = offsetInWindow[1];
19449                }
19450
19451                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
19452                        dxUnconsumed, dyUnconsumed);
19453
19454                if (offsetInWindow != null) {
19455                    getLocationInWindow(offsetInWindow);
19456                    offsetInWindow[0] -= startX;
19457                    offsetInWindow[1] -= startY;
19458                }
19459                return true;
19460            } else if (offsetInWindow != null) {
19461                // No motion, no dispatch. Keep offsetInWindow up to date.
19462                offsetInWindow[0] = 0;
19463                offsetInWindow[1] = 0;
19464            }
19465        }
19466        return false;
19467    }
19468
19469    /**
19470     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
19471     *
19472     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
19473     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
19474     * scrolling operation to consume some or all of the scroll operation before the child view
19475     * consumes it.</p>
19476     *
19477     * @param dx Horizontal scroll distance in pixels
19478     * @param dy Vertical scroll distance in pixels
19479     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
19480     *                 and consumed[1] the consumed dy.
19481     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19482     *                       in local view coordinates of this view from before this operation
19483     *                       to after it completes. View implementations may use this to adjust
19484     *                       expected input coordinate tracking.
19485     * @return true if the parent consumed some or all of the scroll delta
19486     * @see #dispatchNestedScroll(int, int, int, int, int[])
19487     */
19488    public boolean dispatchNestedPreScroll(int dx, int dy,
19489            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
19490        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19491            if (dx != 0 || dy != 0) {
19492                int startX = 0;
19493                int startY = 0;
19494                if (offsetInWindow != null) {
19495                    getLocationInWindow(offsetInWindow);
19496                    startX = offsetInWindow[0];
19497                    startY = offsetInWindow[1];
19498                }
19499
19500                if (consumed == null) {
19501                    if (mTempNestedScrollConsumed == null) {
19502                        mTempNestedScrollConsumed = new int[2];
19503                    }
19504                    consumed = mTempNestedScrollConsumed;
19505                }
19506                consumed[0] = 0;
19507                consumed[1] = 0;
19508                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
19509
19510                if (offsetInWindow != null) {
19511                    getLocationInWindow(offsetInWindow);
19512                    offsetInWindow[0] -= startX;
19513                    offsetInWindow[1] -= startY;
19514                }
19515                return consumed[0] != 0 || consumed[1] != 0;
19516            } else if (offsetInWindow != null) {
19517                offsetInWindow[0] = 0;
19518                offsetInWindow[1] = 0;
19519            }
19520        }
19521        return false;
19522    }
19523
19524    /**
19525     * Dispatch a fling to a nested scrolling parent.
19526     *
19527     * <p>This method should be used to indicate that a nested scrolling child has detected
19528     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
19529     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19530     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19531     * along a scrollable axis.</p>
19532     *
19533     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19534     * its own content, it can use this method to delegate the fling to its nested scrolling
19535     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19536     *
19537     * @param velocityX Horizontal fling velocity in pixels per second
19538     * @param velocityY Vertical fling velocity in pixels per second
19539     * @param consumed true if the child consumed the fling, false otherwise
19540     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19541     */
19542    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19543        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19544            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19545        }
19546        return false;
19547    }
19548
19549    /**
19550     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19551     *
19552     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19553     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19554     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19555     * before the child view consumes it. If this method returns <code>true</code>, a nested
19556     * parent view consumed the fling and this view should not scroll as a result.</p>
19557     *
19558     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19559     * the fling at a time. If a parent view consumed the fling this method will return false.
19560     * Custom view implementations should account for this in two ways:</p>
19561     *
19562     * <ul>
19563     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19564     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19565     *     position regardless.</li>
19566     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19567     *     even to settle back to a valid idle position.</li>
19568     * </ul>
19569     *
19570     * <p>Views should also not offer fling velocities to nested parent views along an axis
19571     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19572     * should not offer a horizontal fling velocity to its parents since scrolling along that
19573     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19574     *
19575     * @param velocityX Horizontal fling velocity in pixels per second
19576     * @param velocityY Vertical fling velocity in pixels per second
19577     * @return true if a nested scrolling parent consumed the fling
19578     */
19579    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19580        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19581            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19582        }
19583        return false;
19584    }
19585
19586    /**
19587     * Gets a scale factor that determines the distance the view should scroll
19588     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19589     * @return The vertical scroll scale factor.
19590     * @hide
19591     */
19592    protected float getVerticalScrollFactor() {
19593        if (mVerticalScrollFactor == 0) {
19594            TypedValue outValue = new TypedValue();
19595            if (!mContext.getTheme().resolveAttribute(
19596                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19597                throw new IllegalStateException(
19598                        "Expected theme to define listPreferredItemHeight.");
19599            }
19600            mVerticalScrollFactor = outValue.getDimension(
19601                    mContext.getResources().getDisplayMetrics());
19602        }
19603        return mVerticalScrollFactor;
19604    }
19605
19606    /**
19607     * Gets a scale factor that determines the distance the view should scroll
19608     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19609     * @return The horizontal scroll scale factor.
19610     * @hide
19611     */
19612    protected float getHorizontalScrollFactor() {
19613        // TODO: Should use something else.
19614        return getVerticalScrollFactor();
19615    }
19616
19617    /**
19618     * Return the value specifying the text direction or policy that was set with
19619     * {@link #setTextDirection(int)}.
19620     *
19621     * @return the defined text direction. It can be one of:
19622     *
19623     * {@link #TEXT_DIRECTION_INHERIT},
19624     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19625     * {@link #TEXT_DIRECTION_ANY_RTL},
19626     * {@link #TEXT_DIRECTION_LTR},
19627     * {@link #TEXT_DIRECTION_RTL},
19628     * {@link #TEXT_DIRECTION_LOCALE},
19629     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19630     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19631     *
19632     * @attr ref android.R.styleable#View_textDirection
19633     *
19634     * @hide
19635     */
19636    @ViewDebug.ExportedProperty(category = "text", mapping = {
19637            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19638            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19639            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19640            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19641            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19642            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19643            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19644            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19645    })
19646    public int getRawTextDirection() {
19647        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19648    }
19649
19650    /**
19651     * Set the text direction.
19652     *
19653     * @param textDirection the direction to set. Should be one of:
19654     *
19655     * {@link #TEXT_DIRECTION_INHERIT},
19656     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19657     * {@link #TEXT_DIRECTION_ANY_RTL},
19658     * {@link #TEXT_DIRECTION_LTR},
19659     * {@link #TEXT_DIRECTION_RTL},
19660     * {@link #TEXT_DIRECTION_LOCALE}
19661     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19662     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
19663     *
19664     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19665     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19666     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19667     *
19668     * @attr ref android.R.styleable#View_textDirection
19669     */
19670    public void setTextDirection(int textDirection) {
19671        if (getRawTextDirection() != textDirection) {
19672            // Reset the current text direction and the resolved one
19673            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19674            resetResolvedTextDirection();
19675            // Set the new text direction
19676            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19677            // Do resolution
19678            resolveTextDirection();
19679            // Notify change
19680            onRtlPropertiesChanged(getLayoutDirection());
19681            // Refresh
19682            requestLayout();
19683            invalidate(true);
19684        }
19685    }
19686
19687    /**
19688     * Return the resolved text direction.
19689     *
19690     * @return the resolved text direction. Returns one of:
19691     *
19692     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19693     * {@link #TEXT_DIRECTION_ANY_RTL},
19694     * {@link #TEXT_DIRECTION_LTR},
19695     * {@link #TEXT_DIRECTION_RTL},
19696     * {@link #TEXT_DIRECTION_LOCALE},
19697     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19698     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19699     *
19700     * @attr ref android.R.styleable#View_textDirection
19701     */
19702    @ViewDebug.ExportedProperty(category = "text", mapping = {
19703            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19704            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19705            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19706            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19707            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19708            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19709            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19710            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19711    })
19712    public int getTextDirection() {
19713        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19714    }
19715
19716    /**
19717     * Resolve the text direction.
19718     *
19719     * @return true if resolution has been done, false otherwise.
19720     *
19721     * @hide
19722     */
19723    public boolean resolveTextDirection() {
19724        // Reset any previous text direction resolution
19725        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19726
19727        if (hasRtlSupport()) {
19728            // Set resolved text direction flag depending on text direction flag
19729            final int textDirection = getRawTextDirection();
19730            switch(textDirection) {
19731                case TEXT_DIRECTION_INHERIT:
19732                    if (!canResolveTextDirection()) {
19733                        // We cannot do the resolution if there is no parent, so use the default one
19734                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19735                        // Resolution will need to happen again later
19736                        return false;
19737                    }
19738
19739                    // Parent has not yet resolved, so we still return the default
19740                    try {
19741                        if (!mParent.isTextDirectionResolved()) {
19742                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19743                            // Resolution will need to happen again later
19744                            return false;
19745                        }
19746                    } catch (AbstractMethodError e) {
19747                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19748                                " does not fully implement ViewParent", e);
19749                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19750                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19751                        return true;
19752                    }
19753
19754                    // Set current resolved direction to the same value as the parent's one
19755                    int parentResolvedDirection;
19756                    try {
19757                        parentResolvedDirection = mParent.getTextDirection();
19758                    } catch (AbstractMethodError e) {
19759                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19760                                " does not fully implement ViewParent", e);
19761                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19762                    }
19763                    switch (parentResolvedDirection) {
19764                        case TEXT_DIRECTION_FIRST_STRONG:
19765                        case TEXT_DIRECTION_ANY_RTL:
19766                        case TEXT_DIRECTION_LTR:
19767                        case TEXT_DIRECTION_RTL:
19768                        case TEXT_DIRECTION_LOCALE:
19769                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
19770                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
19771                            mPrivateFlags2 |=
19772                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19773                            break;
19774                        default:
19775                            // Default resolved direction is "first strong" heuristic
19776                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19777                    }
19778                    break;
19779                case TEXT_DIRECTION_FIRST_STRONG:
19780                case TEXT_DIRECTION_ANY_RTL:
19781                case TEXT_DIRECTION_LTR:
19782                case TEXT_DIRECTION_RTL:
19783                case TEXT_DIRECTION_LOCALE:
19784                case TEXT_DIRECTION_FIRST_STRONG_LTR:
19785                case TEXT_DIRECTION_FIRST_STRONG_RTL:
19786                    // Resolved direction is the same as text direction
19787                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19788                    break;
19789                default:
19790                    // Default resolved direction is "first strong" heuristic
19791                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19792            }
19793        } else {
19794            // Default resolved direction is "first strong" heuristic
19795            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19796        }
19797
19798        // Set to resolved
19799        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19800        return true;
19801    }
19802
19803    /**
19804     * Check if text direction resolution can be done.
19805     *
19806     * @return true if text direction resolution can be done otherwise return false.
19807     */
19808    public boolean canResolveTextDirection() {
19809        switch (getRawTextDirection()) {
19810            case TEXT_DIRECTION_INHERIT:
19811                if (mParent != null) {
19812                    try {
19813                        return mParent.canResolveTextDirection();
19814                    } catch (AbstractMethodError e) {
19815                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19816                                " does not fully implement ViewParent", e);
19817                    }
19818                }
19819                return false;
19820
19821            default:
19822                return true;
19823        }
19824    }
19825
19826    /**
19827     * Reset resolved text direction. Text direction will be resolved during a call to
19828     * {@link #onMeasure(int, int)}.
19829     *
19830     * @hide
19831     */
19832    public void resetResolvedTextDirection() {
19833        // Reset any previous text direction resolution
19834        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19835        // Set to default value
19836        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19837    }
19838
19839    /**
19840     * @return true if text direction is inherited.
19841     *
19842     * @hide
19843     */
19844    public boolean isTextDirectionInherited() {
19845        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19846    }
19847
19848    /**
19849     * @return true if text direction is resolved.
19850     */
19851    public boolean isTextDirectionResolved() {
19852        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19853    }
19854
19855    /**
19856     * Return the value specifying the text alignment or policy that was set with
19857     * {@link #setTextAlignment(int)}.
19858     *
19859     * @return the defined text alignment. It can be one of:
19860     *
19861     * {@link #TEXT_ALIGNMENT_INHERIT},
19862     * {@link #TEXT_ALIGNMENT_GRAVITY},
19863     * {@link #TEXT_ALIGNMENT_CENTER},
19864     * {@link #TEXT_ALIGNMENT_TEXT_START},
19865     * {@link #TEXT_ALIGNMENT_TEXT_END},
19866     * {@link #TEXT_ALIGNMENT_VIEW_START},
19867     * {@link #TEXT_ALIGNMENT_VIEW_END}
19868     *
19869     * @attr ref android.R.styleable#View_textAlignment
19870     *
19871     * @hide
19872     */
19873    @ViewDebug.ExportedProperty(category = "text", mapping = {
19874            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19875            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19876            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19877            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19878            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19879            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19880            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19881    })
19882    @TextAlignment
19883    public int getRawTextAlignment() {
19884        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19885    }
19886
19887    /**
19888     * Set the text alignment.
19889     *
19890     * @param textAlignment The text alignment to set. Should be one of
19891     *
19892     * {@link #TEXT_ALIGNMENT_INHERIT},
19893     * {@link #TEXT_ALIGNMENT_GRAVITY},
19894     * {@link #TEXT_ALIGNMENT_CENTER},
19895     * {@link #TEXT_ALIGNMENT_TEXT_START},
19896     * {@link #TEXT_ALIGNMENT_TEXT_END},
19897     * {@link #TEXT_ALIGNMENT_VIEW_START},
19898     * {@link #TEXT_ALIGNMENT_VIEW_END}
19899     *
19900     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19901     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19902     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19903     *
19904     * @attr ref android.R.styleable#View_textAlignment
19905     */
19906    public void setTextAlignment(@TextAlignment int textAlignment) {
19907        if (textAlignment != getRawTextAlignment()) {
19908            // Reset the current and resolved text alignment
19909            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19910            resetResolvedTextAlignment();
19911            // Set the new text alignment
19912            mPrivateFlags2 |=
19913                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19914            // Do resolution
19915            resolveTextAlignment();
19916            // Notify change
19917            onRtlPropertiesChanged(getLayoutDirection());
19918            // Refresh
19919            requestLayout();
19920            invalidate(true);
19921        }
19922    }
19923
19924    /**
19925     * Return the resolved text alignment.
19926     *
19927     * @return the resolved text alignment. Returns one of:
19928     *
19929     * {@link #TEXT_ALIGNMENT_GRAVITY},
19930     * {@link #TEXT_ALIGNMENT_CENTER},
19931     * {@link #TEXT_ALIGNMENT_TEXT_START},
19932     * {@link #TEXT_ALIGNMENT_TEXT_END},
19933     * {@link #TEXT_ALIGNMENT_VIEW_START},
19934     * {@link #TEXT_ALIGNMENT_VIEW_END}
19935     *
19936     * @attr ref android.R.styleable#View_textAlignment
19937     */
19938    @ViewDebug.ExportedProperty(category = "text", mapping = {
19939            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19940            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19941            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19942            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19943            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19944            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19945            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19946    })
19947    @TextAlignment
19948    public int getTextAlignment() {
19949        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19950                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19951    }
19952
19953    /**
19954     * Resolve the text alignment.
19955     *
19956     * @return true if resolution has been done, false otherwise.
19957     *
19958     * @hide
19959     */
19960    public boolean resolveTextAlignment() {
19961        // Reset any previous text alignment resolution
19962        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19963
19964        if (hasRtlSupport()) {
19965            // Set resolved text alignment flag depending on text alignment flag
19966            final int textAlignment = getRawTextAlignment();
19967            switch (textAlignment) {
19968                case TEXT_ALIGNMENT_INHERIT:
19969                    // Check if we can resolve the text alignment
19970                    if (!canResolveTextAlignment()) {
19971                        // We cannot do the resolution if there is no parent so use the default
19972                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19973                        // Resolution will need to happen again later
19974                        return false;
19975                    }
19976
19977                    // Parent has not yet resolved, so we still return the default
19978                    try {
19979                        if (!mParent.isTextAlignmentResolved()) {
19980                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19981                            // Resolution will need to happen again later
19982                            return false;
19983                        }
19984                    } catch (AbstractMethodError e) {
19985                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19986                                " does not fully implement ViewParent", e);
19987                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19988                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19989                        return true;
19990                    }
19991
19992                    int parentResolvedTextAlignment;
19993                    try {
19994                        parentResolvedTextAlignment = mParent.getTextAlignment();
19995                    } catch (AbstractMethodError e) {
19996                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19997                                " does not fully implement ViewParent", e);
19998                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19999                    }
20000                    switch (parentResolvedTextAlignment) {
20001                        case TEXT_ALIGNMENT_GRAVITY:
20002                        case TEXT_ALIGNMENT_TEXT_START:
20003                        case TEXT_ALIGNMENT_TEXT_END:
20004                        case TEXT_ALIGNMENT_CENTER:
20005                        case TEXT_ALIGNMENT_VIEW_START:
20006                        case TEXT_ALIGNMENT_VIEW_END:
20007                            // Resolved text alignment is the same as the parent resolved
20008                            // text alignment
20009                            mPrivateFlags2 |=
20010                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20011                            break;
20012                        default:
20013                            // Use default resolved text alignment
20014                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20015                    }
20016                    break;
20017                case TEXT_ALIGNMENT_GRAVITY:
20018                case TEXT_ALIGNMENT_TEXT_START:
20019                case TEXT_ALIGNMENT_TEXT_END:
20020                case TEXT_ALIGNMENT_CENTER:
20021                case TEXT_ALIGNMENT_VIEW_START:
20022                case TEXT_ALIGNMENT_VIEW_END:
20023                    // Resolved text alignment is the same as text alignment
20024                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20025                    break;
20026                default:
20027                    // Use default resolved text alignment
20028                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20029            }
20030        } else {
20031            // Use default resolved text alignment
20032            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20033        }
20034
20035        // Set the resolved
20036        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20037        return true;
20038    }
20039
20040    /**
20041     * Check if text alignment resolution can be done.
20042     *
20043     * @return true if text alignment resolution can be done otherwise return false.
20044     */
20045    public boolean canResolveTextAlignment() {
20046        switch (getRawTextAlignment()) {
20047            case TEXT_DIRECTION_INHERIT:
20048                if (mParent != null) {
20049                    try {
20050                        return mParent.canResolveTextAlignment();
20051                    } catch (AbstractMethodError e) {
20052                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20053                                " does not fully implement ViewParent", e);
20054                    }
20055                }
20056                return false;
20057
20058            default:
20059                return true;
20060        }
20061    }
20062
20063    /**
20064     * Reset resolved text alignment. Text alignment will be resolved during a call to
20065     * {@link #onMeasure(int, int)}.
20066     *
20067     * @hide
20068     */
20069    public void resetResolvedTextAlignment() {
20070        // Reset any previous text alignment resolution
20071        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20072        // Set to default
20073        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20074    }
20075
20076    /**
20077     * @return true if text alignment is inherited.
20078     *
20079     * @hide
20080     */
20081    public boolean isTextAlignmentInherited() {
20082        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20083    }
20084
20085    /**
20086     * @return true if text alignment is resolved.
20087     */
20088    public boolean isTextAlignmentResolved() {
20089        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20090    }
20091
20092    /**
20093     * Generate a value suitable for use in {@link #setId(int)}.
20094     * This value will not collide with ID values generated at build time by aapt for R.id.
20095     *
20096     * @return a generated ID value
20097     */
20098    public static int generateViewId() {
20099        for (;;) {
20100            final int result = sNextGeneratedId.get();
20101            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20102            int newValue = result + 1;
20103            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20104            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20105                return result;
20106            }
20107        }
20108    }
20109
20110    /**
20111     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20112     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20113     *                           a normal View or a ViewGroup with
20114     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20115     * @hide
20116     */
20117    public void captureTransitioningViews(List<View> transitioningViews) {
20118        if (getVisibility() == View.VISIBLE) {
20119            transitioningViews.add(this);
20120        }
20121    }
20122
20123    /**
20124     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20125     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20126     * @hide
20127     */
20128    public void findNamedViews(Map<String, View> namedElements) {
20129        if (getVisibility() == VISIBLE || mGhostView != null) {
20130            String transitionName = getTransitionName();
20131            if (transitionName != null) {
20132                namedElements.put(transitionName, this);
20133            }
20134        }
20135    }
20136
20137    //
20138    // Properties
20139    //
20140    /**
20141     * A Property wrapper around the <code>alpha</code> functionality handled by the
20142     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20143     */
20144    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20145        @Override
20146        public void setValue(View object, float value) {
20147            object.setAlpha(value);
20148        }
20149
20150        @Override
20151        public Float get(View object) {
20152            return object.getAlpha();
20153        }
20154    };
20155
20156    /**
20157     * A Property wrapper around the <code>translationX</code> functionality handled by the
20158     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20159     */
20160    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20161        @Override
20162        public void setValue(View object, float value) {
20163            object.setTranslationX(value);
20164        }
20165
20166                @Override
20167        public Float get(View object) {
20168            return object.getTranslationX();
20169        }
20170    };
20171
20172    /**
20173     * A Property wrapper around the <code>translationY</code> functionality handled by the
20174     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20175     */
20176    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20177        @Override
20178        public void setValue(View object, float value) {
20179            object.setTranslationY(value);
20180        }
20181
20182        @Override
20183        public Float get(View object) {
20184            return object.getTranslationY();
20185        }
20186    };
20187
20188    /**
20189     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20190     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20191     */
20192    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20193        @Override
20194        public void setValue(View object, float value) {
20195            object.setTranslationZ(value);
20196        }
20197
20198        @Override
20199        public Float get(View object) {
20200            return object.getTranslationZ();
20201        }
20202    };
20203
20204    /**
20205     * A Property wrapper around the <code>x</code> functionality handled by the
20206     * {@link View#setX(float)} and {@link View#getX()} methods.
20207     */
20208    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20209        @Override
20210        public void setValue(View object, float value) {
20211            object.setX(value);
20212        }
20213
20214        @Override
20215        public Float get(View object) {
20216            return object.getX();
20217        }
20218    };
20219
20220    /**
20221     * A Property wrapper around the <code>y</code> functionality handled by the
20222     * {@link View#setY(float)} and {@link View#getY()} methods.
20223     */
20224    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20225        @Override
20226        public void setValue(View object, float value) {
20227            object.setY(value);
20228        }
20229
20230        @Override
20231        public Float get(View object) {
20232            return object.getY();
20233        }
20234    };
20235
20236    /**
20237     * A Property wrapper around the <code>z</code> functionality handled by the
20238     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20239     */
20240    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20241        @Override
20242        public void setValue(View object, float value) {
20243            object.setZ(value);
20244        }
20245
20246        @Override
20247        public Float get(View object) {
20248            return object.getZ();
20249        }
20250    };
20251
20252    /**
20253     * A Property wrapper around the <code>rotation</code> functionality handled by the
20254     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20255     */
20256    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20257        @Override
20258        public void setValue(View object, float value) {
20259            object.setRotation(value);
20260        }
20261
20262        @Override
20263        public Float get(View object) {
20264            return object.getRotation();
20265        }
20266    };
20267
20268    /**
20269     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20270     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20271     */
20272    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20273        @Override
20274        public void setValue(View object, float value) {
20275            object.setRotationX(value);
20276        }
20277
20278        @Override
20279        public Float get(View object) {
20280            return object.getRotationX();
20281        }
20282    };
20283
20284    /**
20285     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20286     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20287     */
20288    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20289        @Override
20290        public void setValue(View object, float value) {
20291            object.setRotationY(value);
20292        }
20293
20294        @Override
20295        public Float get(View object) {
20296            return object.getRotationY();
20297        }
20298    };
20299
20300    /**
20301     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20302     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20303     */
20304    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20305        @Override
20306        public void setValue(View object, float value) {
20307            object.setScaleX(value);
20308        }
20309
20310        @Override
20311        public Float get(View object) {
20312            return object.getScaleX();
20313        }
20314    };
20315
20316    /**
20317     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20318     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20319     */
20320    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20321        @Override
20322        public void setValue(View object, float value) {
20323            object.setScaleY(value);
20324        }
20325
20326        @Override
20327        public Float get(View object) {
20328            return object.getScaleY();
20329        }
20330    };
20331
20332    /**
20333     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20334     * Each MeasureSpec represents a requirement for either the width or the height.
20335     * A MeasureSpec is comprised of a size and a mode. There are three possible
20336     * modes:
20337     * <dl>
20338     * <dt>UNSPECIFIED</dt>
20339     * <dd>
20340     * The parent has not imposed any constraint on the child. It can be whatever size
20341     * it wants.
20342     * </dd>
20343     *
20344     * <dt>EXACTLY</dt>
20345     * <dd>
20346     * The parent has determined an exact size for the child. The child is going to be
20347     * given those bounds regardless of how big it wants to be.
20348     * </dd>
20349     *
20350     * <dt>AT_MOST</dt>
20351     * <dd>
20352     * The child can be as large as it wants up to the specified size.
20353     * </dd>
20354     * </dl>
20355     *
20356     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20357     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20358     */
20359    public static class MeasureSpec {
20360        private static final int MODE_SHIFT = 30;
20361        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20362
20363        /**
20364         * Measure specification mode: The parent has not imposed any constraint
20365         * on the child. It can be whatever size it wants.
20366         */
20367        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
20368
20369        /**
20370         * Measure specification mode: The parent has determined an exact size
20371         * for the child. The child is going to be given those bounds regardless
20372         * of how big it wants to be.
20373         */
20374        public static final int EXACTLY     = 1 << MODE_SHIFT;
20375
20376        /**
20377         * Measure specification mode: The child can be as large as it wants up
20378         * to the specified size.
20379         */
20380        public static final int AT_MOST     = 2 << MODE_SHIFT;
20381
20382        /**
20383         * Creates a measure specification based on the supplied size and mode.
20384         *
20385         * The mode must always be one of the following:
20386         * <ul>
20387         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
20388         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
20389         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
20390         * </ul>
20391         *
20392         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
20393         * implementation was such that the order of arguments did not matter
20394         * and overflow in either value could impact the resulting MeasureSpec.
20395         * {@link android.widget.RelativeLayout} was affected by this bug.
20396         * Apps targeting API levels greater than 17 will get the fixed, more strict
20397         * behavior.</p>
20398         *
20399         * @param size the size of the measure specification
20400         * @param mode the mode of the measure specification
20401         * @return the measure specification based on size and mode
20402         */
20403        public static int makeMeasureSpec(int size, int mode) {
20404            if (sUseBrokenMakeMeasureSpec) {
20405                return size + mode;
20406            } else {
20407                return (size & ~MODE_MASK) | (mode & MODE_MASK);
20408            }
20409        }
20410
20411        /**
20412         * Extracts the mode from the supplied measure specification.
20413         *
20414         * @param measureSpec the measure specification to extract the mode from
20415         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
20416         *         {@link android.view.View.MeasureSpec#AT_MOST} or
20417         *         {@link android.view.View.MeasureSpec#EXACTLY}
20418         */
20419        public static int getMode(int measureSpec) {
20420            return (measureSpec & MODE_MASK);
20421        }
20422
20423        /**
20424         * Extracts the size from the supplied measure specification.
20425         *
20426         * @param measureSpec the measure specification to extract the size from
20427         * @return the size in pixels defined in the supplied measure specification
20428         */
20429        public static int getSize(int measureSpec) {
20430            return (measureSpec & ~MODE_MASK);
20431        }
20432
20433        static int adjust(int measureSpec, int delta) {
20434            final int mode = getMode(measureSpec);
20435            if (mode == UNSPECIFIED) {
20436                // No need to adjust size for UNSPECIFIED mode.
20437                return makeMeasureSpec(0, UNSPECIFIED);
20438            }
20439            int size = getSize(measureSpec) + delta;
20440            if (size < 0) {
20441                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
20442                        ") spec: " + toString(measureSpec) + " delta: " + delta);
20443                size = 0;
20444            }
20445            return makeMeasureSpec(size, mode);
20446        }
20447
20448        /**
20449         * Returns a String representation of the specified measure
20450         * specification.
20451         *
20452         * @param measureSpec the measure specification to convert to a String
20453         * @return a String with the following format: "MeasureSpec: MODE SIZE"
20454         */
20455        public static String toString(int measureSpec) {
20456            int mode = getMode(measureSpec);
20457            int size = getSize(measureSpec);
20458
20459            StringBuilder sb = new StringBuilder("MeasureSpec: ");
20460
20461            if (mode == UNSPECIFIED)
20462                sb.append("UNSPECIFIED ");
20463            else if (mode == EXACTLY)
20464                sb.append("EXACTLY ");
20465            else if (mode == AT_MOST)
20466                sb.append("AT_MOST ");
20467            else
20468                sb.append(mode).append(" ");
20469
20470            sb.append(size);
20471            return sb.toString();
20472        }
20473    }
20474
20475    private final class CheckForLongPress implements Runnable {
20476        private int mOriginalWindowAttachCount;
20477
20478        @Override
20479        public void run() {
20480            if (isPressed() && (mParent != null)
20481                    && mOriginalWindowAttachCount == mWindowAttachCount) {
20482                if (performLongClick()) {
20483                    mHasPerformedLongPress = true;
20484                }
20485            }
20486        }
20487
20488        public void rememberWindowAttachCount() {
20489            mOriginalWindowAttachCount = mWindowAttachCount;
20490        }
20491    }
20492
20493    private final class CheckForTap implements Runnable {
20494        public float x;
20495        public float y;
20496
20497        @Override
20498        public void run() {
20499            mPrivateFlags &= ~PFLAG_PREPRESSED;
20500            setPressed(true, x, y);
20501            checkForLongClick(ViewConfiguration.getTapTimeout());
20502        }
20503    }
20504
20505    private final class PerformClick implements Runnable {
20506        @Override
20507        public void run() {
20508            performClick();
20509        }
20510    }
20511
20512    /** @hide */
20513    public void hackTurnOffWindowResizeAnim(boolean off) {
20514        mAttachInfo.mTurnOffWindowResizeAnim = off;
20515    }
20516
20517    /**
20518     * This method returns a ViewPropertyAnimator object, which can be used to animate
20519     * specific properties on this View.
20520     *
20521     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
20522     */
20523    public ViewPropertyAnimator animate() {
20524        if (mAnimator == null) {
20525            mAnimator = new ViewPropertyAnimator(this);
20526        }
20527        return mAnimator;
20528    }
20529
20530    /**
20531     * Sets the name of the View to be used to identify Views in Transitions.
20532     * Names should be unique in the View hierarchy.
20533     *
20534     * @param transitionName The name of the View to uniquely identify it for Transitions.
20535     */
20536    public final void setTransitionName(String transitionName) {
20537        mTransitionName = transitionName;
20538    }
20539
20540    /**
20541     * Returns the name of the View to be used to identify Views in Transitions.
20542     * Names should be unique in the View hierarchy.
20543     *
20544     * <p>This returns null if the View has not been given a name.</p>
20545     *
20546     * @return The name used of the View to be used to identify Views in Transitions or null
20547     * if no name has been given.
20548     */
20549    @ViewDebug.ExportedProperty
20550    public String getTransitionName() {
20551        return mTransitionName;
20552    }
20553
20554    /**
20555     * Interface definition for a callback to be invoked when a hardware key event is
20556     * dispatched to this view. The callback will be invoked before the key event is
20557     * given to the view. This is only useful for hardware keyboards; a software input
20558     * method has no obligation to trigger this listener.
20559     */
20560    public interface OnKeyListener {
20561        /**
20562         * Called when a hardware key is dispatched to a view. This allows listeners to
20563         * get a chance to respond before the target view.
20564         * <p>Key presses in software keyboards will generally NOT trigger this method,
20565         * although some may elect to do so in some situations. Do not assume a
20566         * software input method has to be key-based; even if it is, it may use key presses
20567         * in a different way than you expect, so there is no way to reliably catch soft
20568         * input key presses.
20569         *
20570         * @param v The view the key has been dispatched to.
20571         * @param keyCode The code for the physical key that was pressed
20572         * @param event The KeyEvent object containing full information about
20573         *        the event.
20574         * @return True if the listener has consumed the event, false otherwise.
20575         */
20576        boolean onKey(View v, int keyCode, KeyEvent event);
20577    }
20578
20579    /**
20580     * Interface definition for a callback to be invoked when a touch event is
20581     * dispatched to this view. The callback will be invoked before the touch
20582     * event is given to the view.
20583     */
20584    public interface OnTouchListener {
20585        /**
20586         * Called when a touch event is dispatched to a view. This allows listeners to
20587         * get a chance to respond before the target view.
20588         *
20589         * @param v The view the touch event has been dispatched to.
20590         * @param event The MotionEvent object containing full information about
20591         *        the event.
20592         * @return True if the listener has consumed the event, false otherwise.
20593         */
20594        boolean onTouch(View v, MotionEvent event);
20595    }
20596
20597    /**
20598     * Interface definition for a callback to be invoked when a hover event is
20599     * dispatched to this view. The callback will be invoked before the hover
20600     * event is given to the view.
20601     */
20602    public interface OnHoverListener {
20603        /**
20604         * Called when a hover event is dispatched to a view. This allows listeners to
20605         * get a chance to respond before the target view.
20606         *
20607         * @param v The view the hover event has been dispatched to.
20608         * @param event The MotionEvent object containing full information about
20609         *        the event.
20610         * @return True if the listener has consumed the event, false otherwise.
20611         */
20612        boolean onHover(View v, MotionEvent event);
20613    }
20614
20615    /**
20616     * Interface definition for a callback to be invoked when a generic motion event is
20617     * dispatched to this view. The callback will be invoked before the generic motion
20618     * event is given to the view.
20619     */
20620    public interface OnGenericMotionListener {
20621        /**
20622         * Called when a generic motion event is dispatched to a view. This allows listeners to
20623         * get a chance to respond before the target view.
20624         *
20625         * @param v The view the generic motion event has been dispatched to.
20626         * @param event The MotionEvent object containing full information about
20627         *        the event.
20628         * @return True if the listener has consumed the event, false otherwise.
20629         */
20630        boolean onGenericMotion(View v, MotionEvent event);
20631    }
20632
20633    /**
20634     * Interface definition for a callback to be invoked when a view has been clicked and held.
20635     */
20636    public interface OnLongClickListener {
20637        /**
20638         * Called when a view has been clicked and held.
20639         *
20640         * @param v The view that was clicked and held.
20641         *
20642         * @return true if the callback consumed the long click, false otherwise.
20643         */
20644        boolean onLongClick(View v);
20645    }
20646
20647    /**
20648     * Interface definition for a callback to be invoked when a drag is being dispatched
20649     * to this view.  The callback will be invoked before the hosting view's own
20650     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20651     * onDrag(event) behavior, it should return 'false' from this callback.
20652     *
20653     * <div class="special reference">
20654     * <h3>Developer Guides</h3>
20655     * <p>For a guide to implementing drag and drop features, read the
20656     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20657     * </div>
20658     */
20659    public interface OnDragListener {
20660        /**
20661         * Called when a drag event is dispatched to a view. This allows listeners
20662         * to get a chance to override base View behavior.
20663         *
20664         * @param v The View that received the drag event.
20665         * @param event The {@link android.view.DragEvent} object for the drag event.
20666         * @return {@code true} if the drag event was handled successfully, or {@code false}
20667         * if the drag event was not handled. Note that {@code false} will trigger the View
20668         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20669         */
20670        boolean onDrag(View v, DragEvent event);
20671    }
20672
20673    /**
20674     * Interface definition for a callback to be invoked when the focus state of
20675     * a view changed.
20676     */
20677    public interface OnFocusChangeListener {
20678        /**
20679         * Called when the focus state of a view has changed.
20680         *
20681         * @param v The view whose state has changed.
20682         * @param hasFocus The new focus state of v.
20683         */
20684        void onFocusChange(View v, boolean hasFocus);
20685    }
20686
20687    /**
20688     * Interface definition for a callback to be invoked when a view is clicked.
20689     */
20690    public interface OnClickListener {
20691        /**
20692         * Called when a view has been clicked.
20693         *
20694         * @param v The view that was clicked.
20695         */
20696        void onClick(View v);
20697    }
20698
20699    /**
20700     * Interface definition for a callback to be invoked when the context menu
20701     * for this view is being built.
20702     */
20703    public interface OnCreateContextMenuListener {
20704        /**
20705         * Called when the context menu for this view is being built. It is not
20706         * safe to hold onto the menu after this method returns.
20707         *
20708         * @param menu The context menu that is being built
20709         * @param v The view for which the context menu is being built
20710         * @param menuInfo Extra information about the item for which the
20711         *            context menu should be shown. This information will vary
20712         *            depending on the class of v.
20713         */
20714        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20715    }
20716
20717    /**
20718     * Interface definition for a callback to be invoked when the status bar changes
20719     * visibility.  This reports <strong>global</strong> changes to the system UI
20720     * state, not what the application is requesting.
20721     *
20722     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20723     */
20724    public interface OnSystemUiVisibilityChangeListener {
20725        /**
20726         * Called when the status bar changes visibility because of a call to
20727         * {@link View#setSystemUiVisibility(int)}.
20728         *
20729         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20730         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20731         * This tells you the <strong>global</strong> state of these UI visibility
20732         * flags, not what your app is currently applying.
20733         */
20734        public void onSystemUiVisibilityChange(int visibility);
20735    }
20736
20737    /**
20738     * Interface definition for a callback to be invoked when this view is attached
20739     * or detached from its window.
20740     */
20741    public interface OnAttachStateChangeListener {
20742        /**
20743         * Called when the view is attached to a window.
20744         * @param v The view that was attached
20745         */
20746        public void onViewAttachedToWindow(View v);
20747        /**
20748         * Called when the view is detached from a window.
20749         * @param v The view that was detached
20750         */
20751        public void onViewDetachedFromWindow(View v);
20752    }
20753
20754    /**
20755     * Listener for applying window insets on a view in a custom way.
20756     *
20757     * <p>Apps may choose to implement this interface if they want to apply custom policy
20758     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20759     * is set, its
20760     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20761     * method will be called instead of the View's own
20762     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20763     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20764     * the View's normal behavior as part of its own.</p>
20765     */
20766    public interface OnApplyWindowInsetsListener {
20767        /**
20768         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20769         * on a View, this listener method will be called instead of the view's own
20770         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20771         *
20772         * @param v The view applying window insets
20773         * @param insets The insets to apply
20774         * @return The insets supplied, minus any insets that were consumed
20775         */
20776        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20777    }
20778
20779    private final class UnsetPressedState implements Runnable {
20780        @Override
20781        public void run() {
20782            setPressed(false);
20783        }
20784    }
20785
20786    /**
20787     * Base class for derived classes that want to save and restore their own
20788     * state in {@link android.view.View#onSaveInstanceState()}.
20789     */
20790    public static class BaseSavedState extends AbsSavedState {
20791        String mStartActivityRequestWhoSaved;
20792
20793        /**
20794         * Constructor used when reading from a parcel. Reads the state of the superclass.
20795         *
20796         * @param source
20797         */
20798        public BaseSavedState(Parcel source) {
20799            super(source);
20800            mStartActivityRequestWhoSaved = source.readString();
20801        }
20802
20803        /**
20804         * Constructor called by derived classes when creating their SavedState objects
20805         *
20806         * @param superState The state of the superclass of this view
20807         */
20808        public BaseSavedState(Parcelable superState) {
20809            super(superState);
20810        }
20811
20812        @Override
20813        public void writeToParcel(Parcel out, int flags) {
20814            super.writeToParcel(out, flags);
20815            out.writeString(mStartActivityRequestWhoSaved);
20816        }
20817
20818        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20819                new Parcelable.Creator<BaseSavedState>() {
20820            public BaseSavedState createFromParcel(Parcel in) {
20821                return new BaseSavedState(in);
20822            }
20823
20824            public BaseSavedState[] newArray(int size) {
20825                return new BaseSavedState[size];
20826            }
20827        };
20828    }
20829
20830    /**
20831     * A set of information given to a view when it is attached to its parent
20832     * window.
20833     */
20834    final static class AttachInfo {
20835        interface Callbacks {
20836            void playSoundEffect(int effectId);
20837            boolean performHapticFeedback(int effectId, boolean always);
20838        }
20839
20840        /**
20841         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20842         * to a Handler. This class contains the target (View) to invalidate and
20843         * the coordinates of the dirty rectangle.
20844         *
20845         * For performance purposes, this class also implements a pool of up to
20846         * POOL_LIMIT objects that get reused. This reduces memory allocations
20847         * whenever possible.
20848         */
20849        static class InvalidateInfo {
20850            private static final int POOL_LIMIT = 10;
20851
20852            private static final SynchronizedPool<InvalidateInfo> sPool =
20853                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20854
20855            View target;
20856
20857            int left;
20858            int top;
20859            int right;
20860            int bottom;
20861
20862            public static InvalidateInfo obtain() {
20863                InvalidateInfo instance = sPool.acquire();
20864                return (instance != null) ? instance : new InvalidateInfo();
20865            }
20866
20867            public void recycle() {
20868                target = null;
20869                sPool.release(this);
20870            }
20871        }
20872
20873        final IWindowSession mSession;
20874
20875        final IWindow mWindow;
20876
20877        final IBinder mWindowToken;
20878
20879        final Display mDisplay;
20880
20881        final Callbacks mRootCallbacks;
20882
20883        IWindowId mIWindowId;
20884        WindowId mWindowId;
20885
20886        /**
20887         * The top view of the hierarchy.
20888         */
20889        View mRootView;
20890
20891        IBinder mPanelParentWindowToken;
20892
20893        boolean mHardwareAccelerated;
20894        boolean mHardwareAccelerationRequested;
20895        HardwareRenderer mHardwareRenderer;
20896        List<RenderNode> mPendingAnimatingRenderNodes;
20897
20898        /**
20899         * The state of the display to which the window is attached, as reported
20900         * by {@link Display#getState()}.  Note that the display state constants
20901         * declared by {@link Display} do not exactly line up with the screen state
20902         * constants declared by {@link View} (there are more display states than
20903         * screen states).
20904         */
20905        int mDisplayState = Display.STATE_UNKNOWN;
20906
20907        /**
20908         * Scale factor used by the compatibility mode
20909         */
20910        float mApplicationScale;
20911
20912        /**
20913         * Indicates whether the application is in compatibility mode
20914         */
20915        boolean mScalingRequired;
20916
20917        /**
20918         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20919         */
20920        boolean mTurnOffWindowResizeAnim;
20921
20922        /**
20923         * Left position of this view's window
20924         */
20925        int mWindowLeft;
20926
20927        /**
20928         * Top position of this view's window
20929         */
20930        int mWindowTop;
20931
20932        /**
20933         * Indicates whether views need to use 32-bit drawing caches
20934         */
20935        boolean mUse32BitDrawingCache;
20936
20937        /**
20938         * For windows that are full-screen but using insets to layout inside
20939         * of the screen areas, these are the current insets to appear inside
20940         * the overscan area of the display.
20941         */
20942        final Rect mOverscanInsets = new Rect();
20943
20944        /**
20945         * For windows that are full-screen but using insets to layout inside
20946         * of the screen decorations, these are the current insets for the
20947         * content of the window.
20948         */
20949        final Rect mContentInsets = new Rect();
20950
20951        /**
20952         * For windows that are full-screen but using insets to layout inside
20953         * of the screen decorations, these are the current insets for the
20954         * actual visible parts of the window.
20955         */
20956        final Rect mVisibleInsets = new Rect();
20957
20958        /**
20959         * For windows that are full-screen but using insets to layout inside
20960         * of the screen decorations, these are the current insets for the
20961         * stable system windows.
20962         */
20963        final Rect mStableInsets = new Rect();
20964
20965        /**
20966         * The internal insets given by this window.  This value is
20967         * supplied by the client (through
20968         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20969         * be given to the window manager when changed to be used in laying
20970         * out windows behind it.
20971         */
20972        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20973                = new ViewTreeObserver.InternalInsetsInfo();
20974
20975        /**
20976         * Set to true when mGivenInternalInsets is non-empty.
20977         */
20978        boolean mHasNonEmptyGivenInternalInsets;
20979
20980        /**
20981         * All views in the window's hierarchy that serve as scroll containers,
20982         * used to determine if the window can be resized or must be panned
20983         * to adjust for a soft input area.
20984         */
20985        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20986
20987        final KeyEvent.DispatcherState mKeyDispatchState
20988                = new KeyEvent.DispatcherState();
20989
20990        /**
20991         * Indicates whether the view's window currently has the focus.
20992         */
20993        boolean mHasWindowFocus;
20994
20995        /**
20996         * The current visibility of the window.
20997         */
20998        int mWindowVisibility;
20999
21000        /**
21001         * Indicates the time at which drawing started to occur.
21002         */
21003        long mDrawingTime;
21004
21005        /**
21006         * Indicates whether or not ignoring the DIRTY_MASK flags.
21007         */
21008        boolean mIgnoreDirtyState;
21009
21010        /**
21011         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21012         * to avoid clearing that flag prematurely.
21013         */
21014        boolean mSetIgnoreDirtyState = false;
21015
21016        /**
21017         * Indicates whether the view's window is currently in touch mode.
21018         */
21019        boolean mInTouchMode;
21020
21021        /**
21022         * Indicates whether the view has requested unbuffered input dispatching for the current
21023         * event stream.
21024         */
21025        boolean mUnbufferedDispatchRequested;
21026
21027        /**
21028         * Indicates that ViewAncestor should trigger a global layout change
21029         * the next time it performs a traversal
21030         */
21031        boolean mRecomputeGlobalAttributes;
21032
21033        /**
21034         * Always report new attributes at next traversal.
21035         */
21036        boolean mForceReportNewAttributes;
21037
21038        /**
21039         * Set during a traveral if any views want to keep the screen on.
21040         */
21041        boolean mKeepScreenOn;
21042
21043        /**
21044         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21045         */
21046        int mSystemUiVisibility;
21047
21048        /**
21049         * Hack to force certain system UI visibility flags to be cleared.
21050         */
21051        int mDisabledSystemUiVisibility;
21052
21053        /**
21054         * Last global system UI visibility reported by the window manager.
21055         */
21056        int mGlobalSystemUiVisibility;
21057
21058        /**
21059         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21060         * attached.
21061         */
21062        boolean mHasSystemUiListeners;
21063
21064        /**
21065         * Set if the window has requested to extend into the overscan region
21066         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21067         */
21068        boolean mOverscanRequested;
21069
21070        /**
21071         * Set if the visibility of any views has changed.
21072         */
21073        boolean mViewVisibilityChanged;
21074
21075        /**
21076         * Set to true if a view has been scrolled.
21077         */
21078        boolean mViewScrollChanged;
21079
21080        /**
21081         * Set to true if high contrast mode enabled
21082         */
21083        boolean mHighContrastText;
21084
21085        /**
21086         * Global to the view hierarchy used as a temporary for dealing with
21087         * x/y points in the transparent region computations.
21088         */
21089        final int[] mTransparentLocation = new int[2];
21090
21091        /**
21092         * Global to the view hierarchy used as a temporary for dealing with
21093         * x/y points in the ViewGroup.invalidateChild implementation.
21094         */
21095        final int[] mInvalidateChildLocation = new int[2];
21096
21097        /**
21098         * Global to the view hierarchy used as a temporary for dealng with
21099         * computing absolute on-screen location.
21100         */
21101        final int[] mTmpLocation = new int[2];
21102
21103        /**
21104         * Global to the view hierarchy used as a temporary for dealing with
21105         * x/y location when view is transformed.
21106         */
21107        final float[] mTmpTransformLocation = new float[2];
21108
21109        /**
21110         * The view tree observer used to dispatch global events like
21111         * layout, pre-draw, touch mode change, etc.
21112         */
21113        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21114
21115        /**
21116         * A Canvas used by the view hierarchy to perform bitmap caching.
21117         */
21118        Canvas mCanvas;
21119
21120        /**
21121         * The view root impl.
21122         */
21123        final ViewRootImpl mViewRootImpl;
21124
21125        /**
21126         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21127         * handler can be used to pump events in the UI events queue.
21128         */
21129        final Handler mHandler;
21130
21131        /**
21132         * Temporary for use in computing invalidate rectangles while
21133         * calling up the hierarchy.
21134         */
21135        final Rect mTmpInvalRect = new Rect();
21136
21137        /**
21138         * Temporary for use in computing hit areas with transformed views
21139         */
21140        final RectF mTmpTransformRect = new RectF();
21141
21142        /**
21143         * Temporary for use in computing hit areas with transformed views
21144         */
21145        final RectF mTmpTransformRect1 = new RectF();
21146
21147        /**
21148         * Temporary list of rectanges.
21149         */
21150        final List<RectF> mTmpRectList = new ArrayList<>();
21151
21152        /**
21153         * Temporary for use in transforming invalidation rect
21154         */
21155        final Matrix mTmpMatrix = new Matrix();
21156
21157        /**
21158         * Temporary for use in transforming invalidation rect
21159         */
21160        final Transformation mTmpTransformation = new Transformation();
21161
21162        /**
21163         * Temporary for use in querying outlines from OutlineProviders
21164         */
21165        final Outline mTmpOutline = new Outline();
21166
21167        /**
21168         * Temporary list for use in collecting focusable descendents of a view.
21169         */
21170        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21171
21172        /**
21173         * The id of the window for accessibility purposes.
21174         */
21175        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21176
21177        /**
21178         * Flags related to accessibility processing.
21179         *
21180         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21181         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21182         */
21183        int mAccessibilityFetchFlags;
21184
21185        /**
21186         * The drawable for highlighting accessibility focus.
21187         */
21188        Drawable mAccessibilityFocusDrawable;
21189
21190        /**
21191         * Show where the margins, bounds and layout bounds are for each view.
21192         */
21193        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21194
21195        /**
21196         * Point used to compute visible regions.
21197         */
21198        final Point mPoint = new Point();
21199
21200        /**
21201         * Used to track which View originated a requestLayout() call, used when
21202         * requestLayout() is called during layout.
21203         */
21204        View mViewRequestingLayout;
21205
21206        /**
21207         * Creates a new set of attachment information with the specified
21208         * events handler and thread.
21209         *
21210         * @param handler the events handler the view must use
21211         */
21212        AttachInfo(IWindowSession session, IWindow window, Display display,
21213                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21214            mSession = session;
21215            mWindow = window;
21216            mWindowToken = window.asBinder();
21217            mDisplay = display;
21218            mViewRootImpl = viewRootImpl;
21219            mHandler = handler;
21220            mRootCallbacks = effectPlayer;
21221        }
21222    }
21223
21224    /**
21225     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21226     * is supported. This avoids keeping too many unused fields in most
21227     * instances of View.</p>
21228     */
21229    private static class ScrollabilityCache implements Runnable {
21230
21231        /**
21232         * Scrollbars are not visible
21233         */
21234        public static final int OFF = 0;
21235
21236        /**
21237         * Scrollbars are visible
21238         */
21239        public static final int ON = 1;
21240
21241        /**
21242         * Scrollbars are fading away
21243         */
21244        public static final int FADING = 2;
21245
21246        public boolean fadeScrollBars;
21247
21248        public int fadingEdgeLength;
21249        public int scrollBarDefaultDelayBeforeFade;
21250        public int scrollBarFadeDuration;
21251
21252        public int scrollBarSize;
21253        public ScrollBarDrawable scrollBar;
21254        public float[] interpolatorValues;
21255        public View host;
21256
21257        public final Paint paint;
21258        public final Matrix matrix;
21259        public Shader shader;
21260
21261        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21262
21263        private static final float[] OPAQUE = { 255 };
21264        private static final float[] TRANSPARENT = { 0.0f };
21265
21266        /**
21267         * When fading should start. This time moves into the future every time
21268         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21269         */
21270        public long fadeStartTime;
21271
21272
21273        /**
21274         * The current state of the scrollbars: ON, OFF, or FADING
21275         */
21276        public int state = OFF;
21277
21278        private int mLastColor;
21279
21280        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21281            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21282            scrollBarSize = configuration.getScaledScrollBarSize();
21283            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21284            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21285
21286            paint = new Paint();
21287            matrix = new Matrix();
21288            // use use a height of 1, and then wack the matrix each time we
21289            // actually use it.
21290            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21291            paint.setShader(shader);
21292            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21293
21294            this.host = host;
21295        }
21296
21297        public void setFadeColor(int color) {
21298            if (color != mLastColor) {
21299                mLastColor = color;
21300
21301                if (color != 0) {
21302                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21303                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21304                    paint.setShader(shader);
21305                    // Restore the default transfer mode (src_over)
21306                    paint.setXfermode(null);
21307                } else {
21308                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21309                    paint.setShader(shader);
21310                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21311                }
21312            }
21313        }
21314
21315        public void run() {
21316            long now = AnimationUtils.currentAnimationTimeMillis();
21317            if (now >= fadeStartTime) {
21318
21319                // the animation fades the scrollbars out by changing
21320                // the opacity (alpha) from fully opaque to fully
21321                // transparent
21322                int nextFrame = (int) now;
21323                int framesCount = 0;
21324
21325                Interpolator interpolator = scrollBarInterpolator;
21326
21327                // Start opaque
21328                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21329
21330                // End transparent
21331                nextFrame += scrollBarFadeDuration;
21332                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21333
21334                state = FADING;
21335
21336                // Kick off the fade animation
21337                host.invalidate(true);
21338            }
21339        }
21340    }
21341
21342    /**
21343     * Resuable callback for sending
21344     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
21345     */
21346    private class SendViewScrolledAccessibilityEvent implements Runnable {
21347        public volatile boolean mIsPending;
21348
21349        public void run() {
21350            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
21351            mIsPending = false;
21352        }
21353    }
21354
21355    /**
21356     * <p>
21357     * This class represents a delegate that can be registered in a {@link View}
21358     * to enhance accessibility support via composition rather via inheritance.
21359     * It is specifically targeted to widget developers that extend basic View
21360     * classes i.e. classes in package android.view, that would like their
21361     * applications to be backwards compatible.
21362     * </p>
21363     * <div class="special reference">
21364     * <h3>Developer Guides</h3>
21365     * <p>For more information about making applications accessible, read the
21366     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
21367     * developer guide.</p>
21368     * </div>
21369     * <p>
21370     * A scenario in which a developer would like to use an accessibility delegate
21371     * is overriding a method introduced in a later API version then the minimal API
21372     * version supported by the application. For example, the method
21373     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
21374     * in API version 4 when the accessibility APIs were first introduced. If a
21375     * developer would like his application to run on API version 4 devices (assuming
21376     * all other APIs used by the application are version 4 or lower) and take advantage
21377     * of this method, instead of overriding the method which would break the application's
21378     * backwards compatibility, he can override the corresponding method in this
21379     * delegate and register the delegate in the target View if the API version of
21380     * the system is high enough i.e. the API version is same or higher to the API
21381     * version that introduced
21382     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
21383     * </p>
21384     * <p>
21385     * Here is an example implementation:
21386     * </p>
21387     * <code><pre><p>
21388     * if (Build.VERSION.SDK_INT >= 14) {
21389     *     // If the API version is equal of higher than the version in
21390     *     // which onInitializeAccessibilityNodeInfo was introduced we
21391     *     // register a delegate with a customized implementation.
21392     *     View view = findViewById(R.id.view_id);
21393     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
21394     *         public void onInitializeAccessibilityNodeInfo(View host,
21395     *                 AccessibilityNodeInfo info) {
21396     *             // Let the default implementation populate the info.
21397     *             super.onInitializeAccessibilityNodeInfo(host, info);
21398     *             // Set some other information.
21399     *             info.setEnabled(host.isEnabled());
21400     *         }
21401     *     });
21402     * }
21403     * </code></pre></p>
21404     * <p>
21405     * This delegate contains methods that correspond to the accessibility methods
21406     * in View. If a delegate has been specified the implementation in View hands
21407     * off handling to the corresponding method in this delegate. The default
21408     * implementation the delegate methods behaves exactly as the corresponding
21409     * method in View for the case of no accessibility delegate been set. Hence,
21410     * to customize the behavior of a View method, clients can override only the
21411     * corresponding delegate method without altering the behavior of the rest
21412     * accessibility related methods of the host view.
21413     * </p>
21414     */
21415    public static class AccessibilityDelegate {
21416
21417        /**
21418         * Sends an accessibility event of the given type. If accessibility is not
21419         * enabled this method has no effect.
21420         * <p>
21421         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
21422         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
21423         * been set.
21424         * </p>
21425         *
21426         * @param host The View hosting the delegate.
21427         * @param eventType The type of the event to send.
21428         *
21429         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
21430         */
21431        public void sendAccessibilityEvent(View host, int eventType) {
21432            host.sendAccessibilityEventInternal(eventType);
21433        }
21434
21435        /**
21436         * Performs the specified accessibility action on the view. For
21437         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
21438         * <p>
21439         * The default implementation behaves as
21440         * {@link View#performAccessibilityAction(int, Bundle)
21441         *  View#performAccessibilityAction(int, Bundle)} for the case of
21442         *  no accessibility delegate been set.
21443         * </p>
21444         *
21445         * @param action The action to perform.
21446         * @return Whether the action was performed.
21447         *
21448         * @see View#performAccessibilityAction(int, Bundle)
21449         *      View#performAccessibilityAction(int, Bundle)
21450         */
21451        public boolean performAccessibilityAction(View host, int action, Bundle args) {
21452            return host.performAccessibilityActionInternal(action, args);
21453        }
21454
21455        /**
21456         * Sends an accessibility event. This method behaves exactly as
21457         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
21458         * empty {@link AccessibilityEvent} and does not perform a check whether
21459         * accessibility is enabled.
21460         * <p>
21461         * The default implementation behaves as
21462         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21463         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
21464         * the case of no accessibility delegate been set.
21465         * </p>
21466         *
21467         * @param host The View hosting the delegate.
21468         * @param event The event to send.
21469         *
21470         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21471         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21472         */
21473        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
21474            host.sendAccessibilityEventUncheckedInternal(event);
21475        }
21476
21477        /**
21478         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
21479         * to its children for adding their text content to the event.
21480         * <p>
21481         * The default implementation behaves as
21482         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21483         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
21484         * the case of no accessibility delegate been set.
21485         * </p>
21486         *
21487         * @param host The View hosting the delegate.
21488         * @param event The event.
21489         * @return True if the event population was completed.
21490         *
21491         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21492         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21493         */
21494        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21495            return host.dispatchPopulateAccessibilityEventInternal(event);
21496        }
21497
21498        /**
21499         * Gives a chance to the host View to populate the accessibility event with its
21500         * text content.
21501         * <p>
21502         * The default implementation behaves as
21503         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
21504         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
21505         * the case of no accessibility delegate been set.
21506         * </p>
21507         *
21508         * @param host The View hosting the delegate.
21509         * @param event The accessibility event which to populate.
21510         *
21511         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
21512         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
21513         */
21514        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21515            host.onPopulateAccessibilityEventInternal(event);
21516        }
21517
21518        /**
21519         * Initializes an {@link AccessibilityEvent} with information about the
21520         * the host View which is the event source.
21521         * <p>
21522         * The default implementation behaves as
21523         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
21524         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
21525         * the case of no accessibility delegate been set.
21526         * </p>
21527         *
21528         * @param host The View hosting the delegate.
21529         * @param event The event to initialize.
21530         *
21531         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
21532         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
21533         */
21534        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
21535            host.onInitializeAccessibilityEventInternal(event);
21536        }
21537
21538        /**
21539         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
21540         * <p>
21541         * The default implementation behaves as
21542         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21543         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
21544         * the case of no accessibility delegate been set.
21545         * </p>
21546         *
21547         * @param host The View hosting the delegate.
21548         * @param info The instance to initialize.
21549         *
21550         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21551         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21552         */
21553        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21554            host.onInitializeAccessibilityNodeInfoInternal(info);
21555        }
21556
21557        /**
21558         * Called when a child of the host View has requested sending an
21559         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21560         * to augment the event.
21561         * <p>
21562         * The default implementation behaves as
21563         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21564         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21565         * the case of no accessibility delegate been set.
21566         * </p>
21567         *
21568         * @param host The View hosting the delegate.
21569         * @param child The child which requests sending the event.
21570         * @param event The event to be sent.
21571         * @return True if the event should be sent
21572         *
21573         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21574         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21575         */
21576        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21577                AccessibilityEvent event) {
21578            return host.onRequestSendAccessibilityEventInternal(child, event);
21579        }
21580
21581        /**
21582         * Gets the provider for managing a virtual view hierarchy rooted at this View
21583         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21584         * that explore the window content.
21585         * <p>
21586         * The default implementation behaves as
21587         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21588         * the case of no accessibility delegate been set.
21589         * </p>
21590         *
21591         * @return The provider.
21592         *
21593         * @see AccessibilityNodeProvider
21594         */
21595        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21596            return null;
21597        }
21598
21599        /**
21600         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21601         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21602         * This method is responsible for obtaining an accessibility node info from a
21603         * pool of reusable instances and calling
21604         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21605         * view to initialize the former.
21606         * <p>
21607         * <strong>Note:</strong> The client is responsible for recycling the obtained
21608         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21609         * creation.
21610         * </p>
21611         * <p>
21612         * The default implementation behaves as
21613         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21614         * the case of no accessibility delegate been set.
21615         * </p>
21616         * @return A populated {@link AccessibilityNodeInfo}.
21617         *
21618         * @see AccessibilityNodeInfo
21619         *
21620         * @hide
21621         */
21622        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21623            return host.createAccessibilityNodeInfoInternal();
21624        }
21625    }
21626
21627    private class MatchIdPredicate implements Predicate<View> {
21628        public int mId;
21629
21630        @Override
21631        public boolean apply(View view) {
21632            return (view.mID == mId);
21633        }
21634    }
21635
21636    private class MatchLabelForPredicate implements Predicate<View> {
21637        private int mLabeledId;
21638
21639        @Override
21640        public boolean apply(View view) {
21641            return (view.mLabelForId == mLabeledId);
21642        }
21643    }
21644
21645    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21646        private int mChangeTypes = 0;
21647        private boolean mPosted;
21648        private boolean mPostedWithDelay;
21649        private long mLastEventTimeMillis;
21650
21651        @Override
21652        public void run() {
21653            mPosted = false;
21654            mPostedWithDelay = false;
21655            mLastEventTimeMillis = SystemClock.uptimeMillis();
21656            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21657                final AccessibilityEvent event = AccessibilityEvent.obtain();
21658                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21659                event.setContentChangeTypes(mChangeTypes);
21660                sendAccessibilityEventUnchecked(event);
21661            }
21662            mChangeTypes = 0;
21663        }
21664
21665        public void runOrPost(int changeType) {
21666            mChangeTypes |= changeType;
21667
21668            // If this is a live region or the child of a live region, collect
21669            // all events from this frame and send them on the next frame.
21670            if (inLiveRegion()) {
21671                // If we're already posted with a delay, remove that.
21672                if (mPostedWithDelay) {
21673                    removeCallbacks(this);
21674                    mPostedWithDelay = false;
21675                }
21676                // Only post if we're not already posted.
21677                if (!mPosted) {
21678                    post(this);
21679                    mPosted = true;
21680                }
21681                return;
21682            }
21683
21684            if (mPosted) {
21685                return;
21686            }
21687
21688            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21689            final long minEventIntevalMillis =
21690                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21691            if (timeSinceLastMillis >= minEventIntevalMillis) {
21692                removeCallbacks(this);
21693                run();
21694            } else {
21695                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21696                mPostedWithDelay = true;
21697            }
21698        }
21699    }
21700
21701    private boolean inLiveRegion() {
21702        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21703            return true;
21704        }
21705
21706        ViewParent parent = getParent();
21707        while (parent instanceof View) {
21708            if (((View) parent).getAccessibilityLiveRegion()
21709                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21710                return true;
21711            }
21712            parent = parent.getParent();
21713        }
21714
21715        return false;
21716    }
21717
21718    /**
21719     * Dump all private flags in readable format, useful for documentation and
21720     * sanity checking.
21721     */
21722    private static void dumpFlags() {
21723        final HashMap<String, String> found = Maps.newHashMap();
21724        try {
21725            for (Field field : View.class.getDeclaredFields()) {
21726                final int modifiers = field.getModifiers();
21727                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21728                    if (field.getType().equals(int.class)) {
21729                        final int value = field.getInt(null);
21730                        dumpFlag(found, field.getName(), value);
21731                    } else if (field.getType().equals(int[].class)) {
21732                        final int[] values = (int[]) field.get(null);
21733                        for (int i = 0; i < values.length; i++) {
21734                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21735                        }
21736                    }
21737                }
21738            }
21739        } catch (IllegalAccessException e) {
21740            throw new RuntimeException(e);
21741        }
21742
21743        final ArrayList<String> keys = Lists.newArrayList();
21744        keys.addAll(found.keySet());
21745        Collections.sort(keys);
21746        for (String key : keys) {
21747            Log.d(VIEW_LOG_TAG, found.get(key));
21748        }
21749    }
21750
21751    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21752        // Sort flags by prefix, then by bits, always keeping unique keys
21753        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21754        final int prefix = name.indexOf('_');
21755        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21756        final String output = bits + " " + name;
21757        found.put(key, output);
21758    }
21759}
21760