View.java revision 632af849240f54f91b2b4fde77d3a51c4d045f74
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.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.Path;
39import android.graphics.PathMeasure;
40import android.graphics.PixelFormat;
41import android.graphics.Point;
42import android.graphics.PorterDuff;
43import android.graphics.PorterDuffXfermode;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.ColorDrawable;
49import android.graphics.drawable.Drawable;
50import android.hardware.display.DisplayManagerGlobal;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.IBinder;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.RemoteException;
57import android.os.SystemClock;
58import android.os.SystemProperties;
59import android.text.TextUtils;
60import android.util.AttributeSet;
61import android.util.FloatProperty;
62import android.util.LayoutDirection;
63import android.util.Log;
64import android.util.LongSparseLongArray;
65import android.util.Pools.SynchronizedPool;
66import android.util.Property;
67import android.util.SparseArray;
68import android.util.SuperNotCalledException;
69import android.util.TypedValue;
70import android.view.ContextMenu.ContextMenuInfo;
71import android.view.AccessibilityIterators.TextSegmentIterator;
72import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
73import android.view.AccessibilityIterators.WordTextSegmentIterator;
74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
75import android.view.accessibility.AccessibilityEvent;
76import android.view.accessibility.AccessibilityEventSource;
77import android.view.accessibility.AccessibilityManager;
78import android.view.accessibility.AccessibilityNodeInfo;
79import android.view.accessibility.AccessibilityNodeProvider;
80import android.view.animation.Animation;
81import android.view.animation.AnimationUtils;
82import android.view.animation.Transformation;
83import android.view.inputmethod.EditorInfo;
84import android.view.inputmethod.InputConnection;
85import android.view.inputmethod.InputMethodManager;
86import android.widget.ScrollBarDrawable;
87
88import static android.os.Build.VERSION_CODES.*;
89import static java.lang.Math.max;
90
91import com.android.internal.R;
92import com.android.internal.util.Predicate;
93import com.android.internal.view.menu.MenuBuilder;
94import com.google.android.collect.Lists;
95import com.google.android.collect.Maps;
96
97import java.lang.annotation.Retention;
98import java.lang.annotation.RetentionPolicy;
99import java.lang.ref.WeakReference;
100import java.lang.reflect.Field;
101import java.lang.reflect.InvocationTargetException;
102import java.lang.reflect.Method;
103import java.lang.reflect.Modifier;
104import java.util.ArrayList;
105import java.util.Arrays;
106import java.util.Collections;
107import java.util.HashMap;
108import java.util.List;
109import java.util.Locale;
110import java.util.Map;
111import java.util.concurrent.CopyOnWriteArrayList;
112import java.util.concurrent.atomic.AtomicInteger;
113
114/**
115 * <p>
116 * This class represents the basic building block for user interface components. A View
117 * occupies a rectangular area on the screen and is responsible for drawing and
118 * event handling. View is the base class for <em>widgets</em>, which are
119 * used to create interactive UI components (buttons, text fields, etc.). The
120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
121 * are invisible containers that hold other Views (or other ViewGroups) and define
122 * their layout properties.
123 * </p>
124 *
125 * <div class="special reference">
126 * <h3>Developer Guides</h3>
127 * <p>For information about using this class to develop your application's user interface,
128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
129 * </div>
130 *
131 * <a name="Using"></a>
132 * <h3>Using Views</h3>
133 * <p>
134 * All of the views in a window are arranged in a single tree. You can add views
135 * either from code or by specifying a tree of views in one or more XML layout
136 * files. There are many specialized subclasses of views that act as controls or
137 * are capable of displaying text, images, or other content.
138 * </p>
139 * <p>
140 * Once you have created a tree of views, there are typically a few types of
141 * common operations you may wish to perform:
142 * <ul>
143 * <li><strong>Set properties:</strong> for example setting the text of a
144 * {@link android.widget.TextView}. The available properties and the methods
145 * that set them will vary among the different subclasses of views. Note that
146 * properties that are known at build time can be set in the XML layout
147 * files.</li>
148 * <li><strong>Set focus:</strong> The framework will handled moving focus in
149 * response to user input. To force focus to a specific view, call
150 * {@link #requestFocus}.</li>
151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
152 * that will be notified when something interesting happens to the view. For
153 * example, all views will let you set a listener to be notified when the view
154 * gains or loses focus. You can register such a listener using
155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
156 * Other view subclasses offer more specialized listeners. For example, a Button
157 * exposes a listener to notify clients when the button is clicked.</li>
158 * <li><strong>Set visibility:</strong> You can hide or show views using
159 * {@link #setVisibility(int)}.</li>
160 * </ul>
161 * </p>
162 * <p><em>
163 * Note: The Android framework is responsible for measuring, laying out and
164 * drawing views. You should not call methods that perform these actions on
165 * views yourself unless you are actually implementing a
166 * {@link android.view.ViewGroup}.
167 * </em></p>
168 *
169 * <a name="Lifecycle"></a>
170 * <h3>Implementing a Custom View</h3>
171 *
172 * <p>
173 * To implement a custom view, you will usually begin by providing overrides for
174 * some of the standard methods that the framework calls on all views. You do
175 * not need to override all of these methods. In fact, you can start by just
176 * overriding {@link #onDraw(android.graphics.Canvas)}.
177 * <table border="2" width="85%" align="center" cellpadding="5">
178 *     <thead>
179 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
180 *     </thead>
181 *
182 *     <tbody>
183 *     <tr>
184 *         <td rowspan="2">Creation</td>
185 *         <td>Constructors</td>
186 *         <td>There is a form of the constructor that are called when the view
187 *         is created from code and a form that is called when the view is
188 *         inflated from a layout file. The second form should parse and apply
189 *         any attributes defined in the layout file.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onFinishInflate()}</code></td>
194 *         <td>Called after a view and all of its children has been inflated
195 *         from XML.</td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="3">Layout</td>
200 *         <td><code>{@link #onMeasure(int, int)}</code></td>
201 *         <td>Called to determine the size requirements for this view and all
202 *         of its children.
203 *         </td>
204 *     </tr>
205 *     <tr>
206 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
207 *         <td>Called when this view should assign a size and position to all
208 *         of its children.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
213 *         <td>Called when the size of this view has changed.
214 *         </td>
215 *     </tr>
216 *
217 *     <tr>
218 *         <td>Drawing</td>
219 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
220 *         <td>Called when the view should render its content.
221 *         </td>
222 *     </tr>
223 *
224 *     <tr>
225 *         <td rowspan="4">Event processing</td>
226 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
227 *         <td>Called when a new hardware key event occurs.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
232 *         <td>Called when a hardware key up event occurs.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
237 *         <td>Called when a trackball motion event occurs.
238 *         </td>
239 *     </tr>
240 *     <tr>
241 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
242 *         <td>Called when a touch screen motion event occurs.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td rowspan="2">Focus</td>
248 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
249 *         <td>Called when the view gains or loses focus.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
255 *         <td>Called when the window containing the view gains or loses focus.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td rowspan="3">Attaching</td>
261 *         <td><code>{@link #onAttachedToWindow()}</code></td>
262 *         <td>Called when the view is attached to a window.
263 *         </td>
264 *     </tr>
265 *
266 *     <tr>
267 *         <td><code>{@link #onDetachedFromWindow}</code></td>
268 *         <td>Called when the view is detached from its window.
269 *         </td>
270 *     </tr>
271 *
272 *     <tr>
273 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
274 *         <td>Called when the visibility of the window containing the view
275 *         has changed.
276 *         </td>
277 *     </tr>
278 *     </tbody>
279 *
280 * </table>
281 * </p>
282 *
283 * <a name="IDs"></a>
284 * <h3>IDs</h3>
285 * Views may have an integer id associated with them. These ids are typically
286 * assigned in the layout XML files, and are used to find specific views within
287 * the view tree. A common pattern is to:
288 * <ul>
289 * <li>Define a Button in the layout file and assign it a unique ID.
290 * <pre>
291 * &lt;Button
292 *     android:id="@+id/my_button"
293 *     android:layout_width="wrap_content"
294 *     android:layout_height="wrap_content"
295 *     android:text="@string/my_button_text"/&gt;
296 * </pre></li>
297 * <li>From the onCreate method of an Activity, find the Button
298 * <pre class="prettyprint">
299 *      Button myButton = (Button) findViewById(R.id.my_button);
300 * </pre></li>
301 * </ul>
302 * <p>
303 * View IDs need not be unique throughout the tree, but it is good practice to
304 * ensure that they are at least unique within the part of the tree you are
305 * searching.
306 * </p>
307 *
308 * <a name="Position"></a>
309 * <h3>Position</h3>
310 * <p>
311 * The geometry of a view is that of a rectangle. A view has a location,
312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
313 * two dimensions, expressed as a width and a height. The unit for location
314 * and dimensions is the pixel.
315 * </p>
316 *
317 * <p>
318 * It is possible to retrieve the location of a view by invoking the methods
319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
320 * coordinate of the rectangle representing the view. The latter returns the
321 * top, or Y, coordinate of the rectangle representing the view. These methods
322 * both return the location of the view relative to its parent. For instance,
323 * when getLeft() returns 20, that means the view is located 20 pixels to the
324 * right of the left edge of its direct parent.
325 * </p>
326 *
327 * <p>
328 * In addition, several convenience methods are offered to avoid unnecessary
329 * computations, namely {@link #getRight()} and {@link #getBottom()}.
330 * These methods return the coordinates of the right and bottom edges of the
331 * rectangle representing the view. For instance, calling {@link #getRight()}
332 * is similar to the following computation: <code>getLeft() + getWidth()</code>
333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
334 * </p>
335 *
336 * <a name="SizePaddingMargins"></a>
337 * <h3>Size, padding and margins</h3>
338 * <p>
339 * The size of a view is expressed with a width and a height. A view actually
340 * possess two pairs of width and height values.
341 * </p>
342 *
343 * <p>
344 * The first pair is known as <em>measured width</em> and
345 * <em>measured height</em>. These dimensions define how big a view wants to be
346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
348 * and {@link #getMeasuredHeight()}.
349 * </p>
350 *
351 * <p>
352 * The second pair is simply known as <em>width</em> and <em>height</em>, or
353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
354 * dimensions define the actual size of the view on screen, at drawing time and
355 * after layout. These values may, but do not have to, be different from the
356 * measured width and height. The width and height can be obtained by calling
357 * {@link #getWidth()} and {@link #getHeight()}.
358 * </p>
359 *
360 * <p>
361 * To measure its dimensions, a view takes into account its padding. The padding
362 * is expressed in pixels for the left, top, right and bottom parts of the view.
363 * Padding can be used to offset the content of the view by a specific amount of
364 * pixels. For instance, a left padding of 2 will push the view's content by
365 * 2 pixels to the right of the left edge. Padding can be set using the
366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
369 * {@link #getPaddingEnd()}.
370 * </p>
371 *
372 * <p>
373 * Even though a view can define a padding, it does not provide any support for
374 * margins. However, view groups provide such a support. Refer to
375 * {@link android.view.ViewGroup} and
376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
377 * </p>
378 *
379 * <a name="Layout"></a>
380 * <h3>Layout</h3>
381 * <p>
382 * Layout is a two pass process: a measure pass and a layout pass. The measuring
383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
384 * of the view tree. Each view pushes dimension specifications down the tree
385 * during the recursion. At the end of the measure pass, every view has stored
386 * its measurements. The second pass happens in
387 * {@link #layout(int,int,int,int)} and is also top-down. During
388 * this pass each parent is responsible for positioning all of its children
389 * using the sizes computed in the measure pass.
390 * </p>
391 *
392 * <p>
393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
394 * {@link #getMeasuredHeight()} values must be set, along with those for all of
395 * that view's descendants. A view's measured width and measured height values
396 * must respect the constraints imposed by the view's parents. This guarantees
397 * that at the end of the measure pass, all parents accept all of their
398 * children's measurements. A parent view may call measure() more than once on
399 * its children. For example, the parent may measure each child once with
400 * unspecified dimensions to find out how big they want to be, then call
401 * measure() on them again with actual numbers if the sum of all the children's
402 * unconstrained sizes is too big or too small.
403 * </p>
404 *
405 * <p>
406 * The measure pass uses two classes to communicate dimensions. The
407 * {@link MeasureSpec} class is used by views to tell their parents how they
408 * want to be measured and positioned. The base LayoutParams class just
409 * describes how big the view wants to be for both width and height. For each
410 * dimension, it can specify one of:
411 * <ul>
412 * <li> an exact number
413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
414 * (minus padding)
415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
416 * enclose its content (plus padding).
417 * </ul>
418 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
420 * an X and Y value.
421 * </p>
422 *
423 * <p>
424 * MeasureSpecs are used to push requirements down the tree from parent to
425 * child. A MeasureSpec can be in one of three modes:
426 * <ul>
427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
428 * of a child view. For example, a LinearLayout may call measure() on its child
429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
430 * tall the child view wants to be given a width of 240 pixels.
431 * <li>EXACTLY: This is used by the parent to impose an exact size on the
432 * child. The child must use this size, and guarantee that all of its
433 * descendants will fit within this size.
434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
435 * child. The child must guarantee that it and all of its descendants will fit
436 * within this size.
437 * </ul>
438 * </p>
439 *
440 * <p>
441 * To intiate a layout, call {@link #requestLayout}. This method is typically
442 * called by a view on itself when it believes that is can no longer fit within
443 * its current bounds.
444 * </p>
445 *
446 * <a name="Drawing"></a>
447 * <h3>Drawing</h3>
448 * <p>
449 * Drawing is handled by walking the tree and recording the drawing commands of
450 * any View that needs to update. After this, the drawing commands of the
451 * entire tree are issued to screen, clipped to the newly damaged area.
452 * </p>
453 *
454 * <p>
455 * The tree is largely recorded and drawn in order, with parents drawn before
456 * (i.e., behind) their children, with siblings drawn in the order they appear
457 * in the tree. If you set a background drawable for a View, then the View will
458 * draw it before calling back to its <code>onDraw()</code> method. The child
459 * drawing order can be overridden with
460 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
461 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
462 * </p>
463 *
464 * <p>
465 * To force a view to draw, call {@link #invalidate()}.
466 * </p>
467 *
468 * <a name="EventHandlingThreading"></a>
469 * <h3>Event Handling and Threading</h3>
470 * <p>
471 * The basic cycle of a view is as follows:
472 * <ol>
473 * <li>An event comes in and is dispatched to the appropriate view. The view
474 * handles the event and notifies any listeners.</li>
475 * <li>If in the course of processing the event, the view's bounds may need
476 * to be changed, the view will call {@link #requestLayout()}.</li>
477 * <li>Similarly, if in the course of processing the event the view's appearance
478 * may need to be changed, the view will call {@link #invalidate()}.</li>
479 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
480 * the framework will take care of measuring, laying out, and drawing the tree
481 * as appropriate.</li>
482 * </ol>
483 * </p>
484 *
485 * <p><em>Note: The entire view tree is single threaded. You must always be on
486 * the UI thread when calling any method on any view.</em>
487 * If you are doing work on other threads and want to update the state of a view
488 * from that thread, you should use a {@link Handler}.
489 * </p>
490 *
491 * <a name="FocusHandling"></a>
492 * <h3>Focus Handling</h3>
493 * <p>
494 * The framework will handle routine focus movement in response to user input.
495 * This includes changing the focus as views are removed or hidden, or as new
496 * views become available. Views indicate their willingness to take focus
497 * through the {@link #isFocusable} method. To change whether a view can take
498 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
499 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
500 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
501 * </p>
502 * <p>
503 * Focus movement is based on an algorithm which finds the nearest neighbor in a
504 * given direction. In rare cases, the default algorithm may not match the
505 * intended behavior of the developer. In these situations, you can provide
506 * explicit overrides by using these XML attributes in the layout file:
507 * <pre>
508 * nextFocusDown
509 * nextFocusLeft
510 * nextFocusRight
511 * nextFocusUp
512 * </pre>
513 * </p>
514 *
515 *
516 * <p>
517 * To get a particular view to take focus, call {@link #requestFocus()}.
518 * </p>
519 *
520 * <a name="TouchMode"></a>
521 * <h3>Touch Mode</h3>
522 * <p>
523 * When a user is navigating a user interface via directional keys such as a D-pad, it is
524 * necessary to give focus to actionable items such as buttons so the user can see
525 * what will take input.  If the device has touch capabilities, however, and the user
526 * begins interacting with the interface by touching it, it is no longer necessary to
527 * always highlight, or give focus to, a particular view.  This motivates a mode
528 * for interaction named 'touch mode'.
529 * </p>
530 * <p>
531 * For a touch capable device, once the user touches the screen, the device
532 * will enter touch mode.  From this point onward, only views for which
533 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
534 * Other views that are touchable, like buttons, will not take focus when touched; they will
535 * only fire the on click listeners.
536 * </p>
537 * <p>
538 * Any time a user hits a directional key, such as a D-pad direction, the view device will
539 * exit touch mode, and find a view to take focus, so that the user may resume interacting
540 * with the user interface without touching the screen again.
541 * </p>
542 * <p>
543 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
544 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
545 * </p>
546 *
547 * <a name="Scrolling"></a>
548 * <h3>Scrolling</h3>
549 * <p>
550 * The framework provides basic support for views that wish to internally
551 * scroll their content. This includes keeping track of the X and Y scroll
552 * offset as well as mechanisms for drawing scrollbars. See
553 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
554 * {@link #awakenScrollBars()} for more details.
555 * </p>
556 *
557 * <a name="Tags"></a>
558 * <h3>Tags</h3>
559 * <p>
560 * Unlike IDs, tags are not used to identify views. Tags are essentially an
561 * extra piece of information that can be associated with a view. They are most
562 * often used as a convenience to store data related to views in the views
563 * themselves rather than by putting them in a separate structure.
564 * </p>
565 *
566 * <a name="Properties"></a>
567 * <h3>Properties</h3>
568 * <p>
569 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
570 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
571 * available both in the {@link Property} form as well as in similarly-named setter/getter
572 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
573 * be used to set persistent state associated with these rendering-related properties on the view.
574 * The properties and methods can also be used in conjunction with
575 * {@link android.animation.Animator Animator}-based animations, described more in the
576 * <a href="#Animation">Animation</a> section.
577 * </p>
578 *
579 * <a name="Animation"></a>
580 * <h3>Animation</h3>
581 * <p>
582 * Starting with Android 3.0, the preferred way of animating views is to use the
583 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
584 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
585 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
586 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
587 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
588 * makes animating these View properties particularly easy and efficient.
589 * </p>
590 * <p>
591 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
592 * You can attach an {@link Animation} object to a view using
593 * {@link #setAnimation(Animation)} or
594 * {@link #startAnimation(Animation)}. The animation can alter the scale,
595 * rotation, translation and alpha of a view over time. If the animation is
596 * attached to a view that has children, the animation will affect the entire
597 * subtree rooted by that node. When an animation is started, the framework will
598 * take care of redrawing the appropriate views until the animation completes.
599 * </p>
600 *
601 * <a name="Security"></a>
602 * <h3>Security</h3>
603 * <p>
604 * Sometimes it is essential that an application be able to verify that an action
605 * is being performed with the full knowledge and consent of the user, such as
606 * granting a permission request, making a purchase or clicking on an advertisement.
607 * Unfortunately, a malicious application could try to spoof the user into
608 * performing these actions, unaware, by concealing the intended purpose of the view.
609 * As a remedy, the framework offers a touch filtering mechanism that can be used to
610 * improve the security of views that provide access to sensitive functionality.
611 * </p><p>
612 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
613 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
614 * will discard touches that are received whenever the view's window is obscured by
615 * another visible window.  As a result, the view will not receive touches whenever a
616 * toast, dialog or other window appears above the view's window.
617 * </p><p>
618 * For more fine-grained control over security, consider overriding the
619 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
620 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
621 * </p>
622 *
623 * @attr ref android.R.styleable#View_alpha
624 * @attr ref android.R.styleable#View_background
625 * @attr ref android.R.styleable#View_clickable
626 * @attr ref android.R.styleable#View_contentDescription
627 * @attr ref android.R.styleable#View_drawingCacheQuality
628 * @attr ref android.R.styleable#View_duplicateParentState
629 * @attr ref android.R.styleable#View_id
630 * @attr ref android.R.styleable#View_requiresFadingEdge
631 * @attr ref android.R.styleable#View_fadeScrollbars
632 * @attr ref android.R.styleable#View_fadingEdgeLength
633 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
634 * @attr ref android.R.styleable#View_fitsSystemWindows
635 * @attr ref android.R.styleable#View_isScrollContainer
636 * @attr ref android.R.styleable#View_focusable
637 * @attr ref android.R.styleable#View_focusableInTouchMode
638 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
639 * @attr ref android.R.styleable#View_keepScreenOn
640 * @attr ref android.R.styleable#View_layerType
641 * @attr ref android.R.styleable#View_layoutDirection
642 * @attr ref android.R.styleable#View_longClickable
643 * @attr ref android.R.styleable#View_minHeight
644 * @attr ref android.R.styleable#View_minWidth
645 * @attr ref android.R.styleable#View_nextFocusDown
646 * @attr ref android.R.styleable#View_nextFocusLeft
647 * @attr ref android.R.styleable#View_nextFocusRight
648 * @attr ref android.R.styleable#View_nextFocusUp
649 * @attr ref android.R.styleable#View_onClick
650 * @attr ref android.R.styleable#View_padding
651 * @attr ref android.R.styleable#View_paddingBottom
652 * @attr ref android.R.styleable#View_paddingLeft
653 * @attr ref android.R.styleable#View_paddingRight
654 * @attr ref android.R.styleable#View_paddingTop
655 * @attr ref android.R.styleable#View_paddingStart
656 * @attr ref android.R.styleable#View_paddingEnd
657 * @attr ref android.R.styleable#View_saveEnabled
658 * @attr ref android.R.styleable#View_rotation
659 * @attr ref android.R.styleable#View_rotationX
660 * @attr ref android.R.styleable#View_rotationY
661 * @attr ref android.R.styleable#View_scaleX
662 * @attr ref android.R.styleable#View_scaleY
663 * @attr ref android.R.styleable#View_scrollX
664 * @attr ref android.R.styleable#View_scrollY
665 * @attr ref android.R.styleable#View_scrollbarSize
666 * @attr ref android.R.styleable#View_scrollbarStyle
667 * @attr ref android.R.styleable#View_scrollbars
668 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
669 * @attr ref android.R.styleable#View_scrollbarFadeDuration
670 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
671 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
672 * @attr ref android.R.styleable#View_scrollbarThumbVertical
673 * @attr ref android.R.styleable#View_scrollbarTrackVertical
674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
676 * @attr ref android.R.styleable#View_stateListAnimator
677 * @attr ref android.R.styleable#View_transitionName
678 * @attr ref android.R.styleable#View_soundEffectsEnabled
679 * @attr ref android.R.styleable#View_tag
680 * @attr ref android.R.styleable#View_textAlignment
681 * @attr ref android.R.styleable#View_textDirection
682 * @attr ref android.R.styleable#View_transformPivotX
683 * @attr ref android.R.styleable#View_transformPivotY
684 * @attr ref android.R.styleable#View_translationX
685 * @attr ref android.R.styleable#View_translationY
686 * @attr ref android.R.styleable#View_translationZ
687 * @attr ref android.R.styleable#View_visibility
688 *
689 * @see android.view.ViewGroup
690 */
691public class View implements Drawable.Callback, KeyEvent.Callback,
692        AccessibilityEventSource {
693    private static final boolean DBG = false;
694
695    /**
696     * The logging tag used by this class with android.util.Log.
697     */
698    protected static final String VIEW_LOG_TAG = "View";
699
700    /**
701     * When set to true, apps will draw debugging information about their layouts.
702     *
703     * @hide
704     */
705    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
706
707    /**
708     * When set to true, this view will save its attribute data.
709     *
710     * @hide
711     */
712    public static boolean mDebugViewAttributes = false;
713
714    /**
715     * Used to mark a View that has no ID.
716     */
717    public static final int NO_ID = -1;
718
719    /**
720     * Signals that compatibility booleans have been initialized according to
721     * target SDK versions.
722     */
723    private static boolean sCompatibilityDone = false;
724
725    /**
726     * Use the old (broken) way of building MeasureSpecs.
727     */
728    private static boolean sUseBrokenMakeMeasureSpec = false;
729
730    /**
731     * Ignore any optimizations using the measure cache.
732     */
733    private static boolean sIgnoreMeasureCache = false;
734
735    /**
736     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
737     * calling setFlags.
738     */
739    private static final int NOT_FOCUSABLE = 0x00000000;
740
741    /**
742     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
743     * setFlags.
744     */
745    private static final int FOCUSABLE = 0x00000001;
746
747    /**
748     * Mask for use with setFlags indicating bits used for focus.
749     */
750    private static final int FOCUSABLE_MASK = 0x00000001;
751
752    /**
753     * This view will adjust its padding to fit sytem windows (e.g. status bar)
754     */
755    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
756
757    /** @hide */
758    @IntDef({VISIBLE, INVISIBLE, GONE})
759    @Retention(RetentionPolicy.SOURCE)
760    public @interface Visibility {}
761
762    /**
763     * This view is visible.
764     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
765     * android:visibility}.
766     */
767    public static final int VISIBLE = 0x00000000;
768
769    /**
770     * This view is invisible, but it still takes up space for layout purposes.
771     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
772     * android:visibility}.
773     */
774    public static final int INVISIBLE = 0x00000004;
775
776    /**
777     * This view is invisible, and it doesn't take any space for layout
778     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
779     * android:visibility}.
780     */
781    public static final int GONE = 0x00000008;
782
783    /**
784     * Mask for use with setFlags indicating bits used for visibility.
785     * {@hide}
786     */
787    static final int VISIBILITY_MASK = 0x0000000C;
788
789    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
790
791    /**
792     * This view is enabled. Interpretation varies by subclass.
793     * Use with ENABLED_MASK when calling setFlags.
794     * {@hide}
795     */
796    static final int ENABLED = 0x00000000;
797
798    /**
799     * This view is disabled. Interpretation varies by subclass.
800     * Use with ENABLED_MASK when calling setFlags.
801     * {@hide}
802     */
803    static final int DISABLED = 0x00000020;
804
805   /**
806    * Mask for use with setFlags indicating bits used for indicating whether
807    * this view is enabled
808    * {@hide}
809    */
810    static final int ENABLED_MASK = 0x00000020;
811
812    /**
813     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
814     * called and further optimizations will be performed. It is okay to have
815     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
816     * {@hide}
817     */
818    static final int WILL_NOT_DRAW = 0x00000080;
819
820    /**
821     * Mask for use with setFlags indicating bits used for indicating whether
822     * this view is will draw
823     * {@hide}
824     */
825    static final int DRAW_MASK = 0x00000080;
826
827    /**
828     * <p>This view doesn't show scrollbars.</p>
829     * {@hide}
830     */
831    static final int SCROLLBARS_NONE = 0x00000000;
832
833    /**
834     * <p>This view shows horizontal scrollbars.</p>
835     * {@hide}
836     */
837    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
838
839    /**
840     * <p>This view shows vertical scrollbars.</p>
841     * {@hide}
842     */
843    static final int SCROLLBARS_VERTICAL = 0x00000200;
844
845    /**
846     * <p>Mask for use with setFlags indicating bits used for indicating which
847     * scrollbars are enabled.</p>
848     * {@hide}
849     */
850    static final int SCROLLBARS_MASK = 0x00000300;
851
852    /**
853     * Indicates that the view should filter touches when its window is obscured.
854     * Refer to the class comments for more information about this security feature.
855     * {@hide}
856     */
857    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
858
859    /**
860     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
861     * that they are optional and should be skipped if the window has
862     * requested system UI flags that ignore those insets for layout.
863     */
864    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
865
866    /**
867     * <p>This view doesn't show fading edges.</p>
868     * {@hide}
869     */
870    static final int FADING_EDGE_NONE = 0x00000000;
871
872    /**
873     * <p>This view shows horizontal fading edges.</p>
874     * {@hide}
875     */
876    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
877
878    /**
879     * <p>This view shows vertical fading edges.</p>
880     * {@hide}
881     */
882    static final int FADING_EDGE_VERTICAL = 0x00002000;
883
884    /**
885     * <p>Mask for use with setFlags indicating bits used for indicating which
886     * fading edges are enabled.</p>
887     * {@hide}
888     */
889    static final int FADING_EDGE_MASK = 0x00003000;
890
891    /**
892     * <p>Indicates this view can be clicked. When clickable, a View reacts
893     * to clicks by notifying the OnClickListener.<p>
894     * {@hide}
895     */
896    static final int CLICKABLE = 0x00004000;
897
898    /**
899     * <p>Indicates this view is caching its drawing into a bitmap.</p>
900     * {@hide}
901     */
902    static final int DRAWING_CACHE_ENABLED = 0x00008000;
903
904    /**
905     * <p>Indicates that no icicle should be saved for this view.<p>
906     * {@hide}
907     */
908    static final int SAVE_DISABLED = 0x000010000;
909
910    /**
911     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
912     * property.</p>
913     * {@hide}
914     */
915    static final int SAVE_DISABLED_MASK = 0x000010000;
916
917    /**
918     * <p>Indicates that no drawing cache should ever be created for this view.<p>
919     * {@hide}
920     */
921    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
922
923    /**
924     * <p>Indicates this view can take / keep focus when int touch mode.</p>
925     * {@hide}
926     */
927    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
928
929    /** @hide */
930    @Retention(RetentionPolicy.SOURCE)
931    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
932    public @interface DrawingCacheQuality {}
933
934    /**
935     * <p>Enables low quality mode for the drawing cache.</p>
936     */
937    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
938
939    /**
940     * <p>Enables high quality mode for the drawing cache.</p>
941     */
942    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
943
944    /**
945     * <p>Enables automatic quality mode for the drawing cache.</p>
946     */
947    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
948
949    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
950            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
951    };
952
953    /**
954     * <p>Mask for use with setFlags indicating bits used for the cache
955     * quality property.</p>
956     * {@hide}
957     */
958    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
959
960    /**
961     * <p>
962     * Indicates this view can be long clicked. When long clickable, a View
963     * reacts to long clicks by notifying the OnLongClickListener or showing a
964     * context menu.
965     * </p>
966     * {@hide}
967     */
968    static final int LONG_CLICKABLE = 0x00200000;
969
970    /**
971     * <p>Indicates that this view gets its drawable states from its direct parent
972     * and ignores its original internal states.</p>
973     *
974     * @hide
975     */
976    static final int DUPLICATE_PARENT_STATE = 0x00400000;
977
978    /** @hide */
979    @IntDef({
980        SCROLLBARS_INSIDE_OVERLAY,
981        SCROLLBARS_INSIDE_INSET,
982        SCROLLBARS_OUTSIDE_OVERLAY,
983        SCROLLBARS_OUTSIDE_INSET
984    })
985    @Retention(RetentionPolicy.SOURCE)
986    public @interface ScrollBarStyle {}
987
988    /**
989     * The scrollbar style to display the scrollbars inside the content area,
990     * without increasing the padding. The scrollbars will be overlaid with
991     * translucency on the view's content.
992     */
993    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
994
995    /**
996     * The scrollbar style to display the scrollbars inside the padded area,
997     * increasing the padding of the view. The scrollbars will not overlap the
998     * content area of the view.
999     */
1000    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1001
1002    /**
1003     * The scrollbar style to display the scrollbars at the edge of the view,
1004     * without increasing the padding. The scrollbars will be overlaid with
1005     * translucency.
1006     */
1007    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1008
1009    /**
1010     * The scrollbar style to display the scrollbars at the edge of the view,
1011     * increasing the padding of the view. The scrollbars will only overlap the
1012     * background, if any.
1013     */
1014    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1015
1016    /**
1017     * Mask to check if the scrollbar style is overlay or inset.
1018     * {@hide}
1019     */
1020    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1021
1022    /**
1023     * Mask to check if the scrollbar style is inside or outside.
1024     * {@hide}
1025     */
1026    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1027
1028    /**
1029     * Mask for scrollbar style.
1030     * {@hide}
1031     */
1032    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1033
1034    /**
1035     * View flag indicating that the screen should remain on while the
1036     * window containing this view is visible to the user.  This effectively
1037     * takes care of automatically setting the WindowManager's
1038     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1039     */
1040    public static final int KEEP_SCREEN_ON = 0x04000000;
1041
1042    /**
1043     * View flag indicating whether this view should have sound effects enabled
1044     * for events such as clicking and touching.
1045     */
1046    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1047
1048    /**
1049     * View flag indicating whether this view should have haptic feedback
1050     * enabled for events such as long presses.
1051     */
1052    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1053
1054    /**
1055     * <p>Indicates that the view hierarchy should stop saving state when
1056     * it reaches this view.  If state saving is initiated immediately at
1057     * the view, it will be allowed.
1058     * {@hide}
1059     */
1060    static final int PARENT_SAVE_DISABLED = 0x20000000;
1061
1062    /**
1063     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1064     * {@hide}
1065     */
1066    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1067
1068    /** @hide */
1069    @IntDef(flag = true,
1070            value = {
1071                FOCUSABLES_ALL,
1072                FOCUSABLES_TOUCH_MODE
1073            })
1074    @Retention(RetentionPolicy.SOURCE)
1075    public @interface FocusableMode {}
1076
1077    /**
1078     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1079     * should add all focusable Views regardless if they are focusable in touch mode.
1080     */
1081    public static final int FOCUSABLES_ALL = 0x00000000;
1082
1083    /**
1084     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1085     * should add only Views focusable in touch mode.
1086     */
1087    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1088
1089    /** @hide */
1090    @IntDef({
1091            FOCUS_BACKWARD,
1092            FOCUS_FORWARD,
1093            FOCUS_LEFT,
1094            FOCUS_UP,
1095            FOCUS_RIGHT,
1096            FOCUS_DOWN
1097    })
1098    @Retention(RetentionPolicy.SOURCE)
1099    public @interface FocusDirection {}
1100
1101    /** @hide */
1102    @IntDef({
1103            FOCUS_LEFT,
1104            FOCUS_UP,
1105            FOCUS_RIGHT,
1106            FOCUS_DOWN
1107    })
1108    @Retention(RetentionPolicy.SOURCE)
1109    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1110
1111    /**
1112     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1113     * item.
1114     */
1115    public static final int FOCUS_BACKWARD = 0x00000001;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1119     * item.
1120     */
1121    public static final int FOCUS_FORWARD = 0x00000002;
1122
1123    /**
1124     * Use with {@link #focusSearch(int)}. Move focus to the left.
1125     */
1126    public static final int FOCUS_LEFT = 0x00000011;
1127
1128    /**
1129     * Use with {@link #focusSearch(int)}. Move focus up.
1130     */
1131    public static final int FOCUS_UP = 0x00000021;
1132
1133    /**
1134     * Use with {@link #focusSearch(int)}. Move focus to the right.
1135     */
1136    public static final int FOCUS_RIGHT = 0x00000042;
1137
1138    /**
1139     * Use with {@link #focusSearch(int)}. Move focus down.
1140     */
1141    public static final int FOCUS_DOWN = 0x00000082;
1142
1143    /**
1144     * Bits of {@link #getMeasuredWidthAndState()} and
1145     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1146     */
1147    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1148
1149    /**
1150     * Bits of {@link #getMeasuredWidthAndState()} and
1151     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1152     */
1153    public static final int MEASURED_STATE_MASK = 0xff000000;
1154
1155    /**
1156     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1157     * for functions that combine both width and height into a single int,
1158     * such as {@link #getMeasuredState()} and the childState argument of
1159     * {@link #resolveSizeAndState(int, int, int)}.
1160     */
1161    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1162
1163    /**
1164     * Bit of {@link #getMeasuredWidthAndState()} and
1165     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1166     * is smaller that the space the view would like to have.
1167     */
1168    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1169
1170    /**
1171     * Base View state sets
1172     */
1173    // Singles
1174    /**
1175     * Indicates the view has no states set. States are used with
1176     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1177     * view depending on its state.
1178     *
1179     * @see android.graphics.drawable.Drawable
1180     * @see #getDrawableState()
1181     */
1182    protected static final int[] EMPTY_STATE_SET;
1183    /**
1184     * Indicates the view is enabled. States are used with
1185     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1186     * view depending on its state.
1187     *
1188     * @see android.graphics.drawable.Drawable
1189     * @see #getDrawableState()
1190     */
1191    protected static final int[] ENABLED_STATE_SET;
1192    /**
1193     * Indicates the view is focused. States are used with
1194     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1195     * view depending on its state.
1196     *
1197     * @see android.graphics.drawable.Drawable
1198     * @see #getDrawableState()
1199     */
1200    protected static final int[] FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is selected. States are used with
1203     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1204     * view depending on its state.
1205     *
1206     * @see android.graphics.drawable.Drawable
1207     * @see #getDrawableState()
1208     */
1209    protected static final int[] SELECTED_STATE_SET;
1210    /**
1211     * Indicates the view is pressed. States are used with
1212     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1213     * view depending on its state.
1214     *
1215     * @see android.graphics.drawable.Drawable
1216     * @see #getDrawableState()
1217     */
1218    protected static final int[] PRESSED_STATE_SET;
1219    /**
1220     * Indicates the view's window has focus. States are used with
1221     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1222     * view depending on its state.
1223     *
1224     * @see android.graphics.drawable.Drawable
1225     * @see #getDrawableState()
1226     */
1227    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1228    // Doubles
1229    /**
1230     * Indicates the view is enabled and has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #FOCUSED_STATE_SET
1234     */
1235    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1236    /**
1237     * Indicates the view is enabled and selected.
1238     *
1239     * @see #ENABLED_STATE_SET
1240     * @see #SELECTED_STATE_SET
1241     */
1242    protected static final int[] ENABLED_SELECTED_STATE_SET;
1243    /**
1244     * Indicates the view is enabled and that its window has focus.
1245     *
1246     * @see #ENABLED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is focused and selected.
1252     *
1253     * @see #FOCUSED_STATE_SET
1254     * @see #SELECTED_STATE_SET
1255     */
1256    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1257    /**
1258     * Indicates the view has the focus and that its window has the focus.
1259     *
1260     * @see #FOCUSED_STATE_SET
1261     * @see #WINDOW_FOCUSED_STATE_SET
1262     */
1263    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is selected and that its window has the focus.
1266     *
1267     * @see #SELECTED_STATE_SET
1268     * @see #WINDOW_FOCUSED_STATE_SET
1269     */
1270    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1271    // Triples
1272    /**
1273     * Indicates the view is enabled, focused and selected.
1274     *
1275     * @see #ENABLED_STATE_SET
1276     * @see #FOCUSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     */
1279    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1280    /**
1281     * Indicates the view is enabled, focused and its window has the focus.
1282     *
1283     * @see #ENABLED_STATE_SET
1284     * @see #FOCUSED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is enabled, selected and its window has the focus.
1290     *
1291     * @see #ENABLED_STATE_SET
1292     * @see #SELECTED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is focused, selected and its window has the focus.
1298     *
1299     * @see #FOCUSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is enabled, focused, selected and its window
1306     * has the focus.
1307     *
1308     * @see #ENABLED_STATE_SET
1309     * @see #FOCUSED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #WINDOW_FOCUSED_STATE_SET
1312     */
1313    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed and its window has the focus.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed and selected.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #SELECTED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_SELECTED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, selected and its window has the focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #SELECTED_STATE_SET
1333     * @see #WINDOW_FOCUSED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed and focused.
1338     *
1339     * @see #PRESSED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1343    /**
1344     * Indicates the view is pressed, focused and its window has the focus.
1345     *
1346     * @see #PRESSED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     * @see #WINDOW_FOCUSED_STATE_SET
1349     */
1350    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1351    /**
1352     * Indicates the view is pressed, focused and selected.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #SELECTED_STATE_SET
1356     * @see #FOCUSED_STATE_SET
1357     */
1358    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1359    /**
1360     * Indicates the view is pressed, focused, selected and its window has the focus.
1361     *
1362     * @see #PRESSED_STATE_SET
1363     * @see #FOCUSED_STATE_SET
1364     * @see #SELECTED_STATE_SET
1365     * @see #WINDOW_FOCUSED_STATE_SET
1366     */
1367    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1368    /**
1369     * Indicates the view is pressed and enabled.
1370     *
1371     * @see #PRESSED_STATE_SET
1372     * @see #ENABLED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_ENABLED_STATE_SET;
1375    /**
1376     * Indicates the view is pressed, enabled and its window has the focus.
1377     *
1378     * @see #PRESSED_STATE_SET
1379     * @see #ENABLED_STATE_SET
1380     * @see #WINDOW_FOCUSED_STATE_SET
1381     */
1382    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1383    /**
1384     * Indicates the view is pressed, enabled and selected.
1385     *
1386     * @see #PRESSED_STATE_SET
1387     * @see #ENABLED_STATE_SET
1388     * @see #SELECTED_STATE_SET
1389     */
1390    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1391    /**
1392     * Indicates the view is pressed, enabled, selected and its window has the
1393     * focus.
1394     *
1395     * @see #PRESSED_STATE_SET
1396     * @see #ENABLED_STATE_SET
1397     * @see #SELECTED_STATE_SET
1398     * @see #WINDOW_FOCUSED_STATE_SET
1399     */
1400    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1401    /**
1402     * Indicates the view is pressed, enabled and focused.
1403     *
1404     * @see #PRESSED_STATE_SET
1405     * @see #ENABLED_STATE_SET
1406     * @see #FOCUSED_STATE_SET
1407     */
1408    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1409    /**
1410     * Indicates the view is pressed, enabled, focused and its window has the
1411     * focus.
1412     *
1413     * @see #PRESSED_STATE_SET
1414     * @see #ENABLED_STATE_SET
1415     * @see #FOCUSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed, enabled, focused and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #ENABLED_STATE_SET
1424     * @see #SELECTED_STATE_SET
1425     * @see #FOCUSED_STATE_SET
1426     */
1427    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1428    /**
1429     * Indicates the view is pressed, enabled, focused, selected and its window
1430     * has the focus.
1431     *
1432     * @see #PRESSED_STATE_SET
1433     * @see #ENABLED_STATE_SET
1434     * @see #SELECTED_STATE_SET
1435     * @see #FOCUSED_STATE_SET
1436     * @see #WINDOW_FOCUSED_STATE_SET
1437     */
1438    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1439
1440    /**
1441     * The order here is very important to {@link #getDrawableState()}
1442     */
1443    private static final int[][] VIEW_STATE_SETS;
1444
1445    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1446    static final int VIEW_STATE_SELECTED = 1 << 1;
1447    static final int VIEW_STATE_FOCUSED = 1 << 2;
1448    static final int VIEW_STATE_ENABLED = 1 << 3;
1449    static final int VIEW_STATE_PRESSED = 1 << 4;
1450    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1451    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1452    static final int VIEW_STATE_HOVERED = 1 << 7;
1453    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1454    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1455
1456    static final int[] VIEW_STATE_IDS = new int[] {
1457        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1458        R.attr.state_selected,          VIEW_STATE_SELECTED,
1459        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1460        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1461        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1462        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1463        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1464        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1465        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1466        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1467    };
1468
1469    static {
1470        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1471            throw new IllegalStateException(
1472                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1473        }
1474        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1475        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1476            int viewState = R.styleable.ViewDrawableStates[i];
1477            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1478                if (VIEW_STATE_IDS[j] == viewState) {
1479                    orderedIds[i * 2] = viewState;
1480                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1481                }
1482            }
1483        }
1484        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1485        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1486        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1487            int numBits = Integer.bitCount(i);
1488            int[] set = new int[numBits];
1489            int pos = 0;
1490            for (int j = 0; j < orderedIds.length; j += 2) {
1491                if ((i & orderedIds[j+1]) != 0) {
1492                    set[pos++] = orderedIds[j];
1493                }
1494            }
1495            VIEW_STATE_SETS[i] = set;
1496        }
1497
1498        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1499        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1500        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1501        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1503        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1504        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1506        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1508        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1510                | VIEW_STATE_FOCUSED];
1511        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1512        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1514        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1515                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1516        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_ENABLED];
1519        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1521        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1523                | VIEW_STATE_ENABLED];
1524        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1526                | VIEW_STATE_ENABLED];
1527        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1529                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1530
1531        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1532        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1534        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1535                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1536        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_PRESSED];
1539        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1541        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1549                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1552        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1553                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1554                | VIEW_STATE_PRESSED];
1555        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1556                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1557                | VIEW_STATE_PRESSED];
1558        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1559                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1560                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1561        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1562                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1563                | VIEW_STATE_PRESSED];
1564        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1565                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1566                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1567        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1568                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1569                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1570        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1571                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1572                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1573                | VIEW_STATE_PRESSED];
1574    }
1575
1576    /**
1577     * Accessibility event types that are dispatched for text population.
1578     */
1579    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1580            AccessibilityEvent.TYPE_VIEW_CLICKED
1581            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1582            | AccessibilityEvent.TYPE_VIEW_SELECTED
1583            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1584            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1585            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1586            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1587            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1588            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1589            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1590            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1591
1592    /**
1593     * Temporary Rect currently for use in setBackground().  This will probably
1594     * be extended in the future to hold our own class with more than just
1595     * a Rect. :)
1596     */
1597    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1598
1599    /**
1600     * Map used to store views' tags.
1601     */
1602    private SparseArray<Object> mKeyedTags;
1603
1604    /**
1605     * The next available accessibility id.
1606     */
1607    private static int sNextAccessibilityViewId;
1608
1609    /**
1610     * The animation currently associated with this view.
1611     * @hide
1612     */
1613    protected Animation mCurrentAnimation = null;
1614
1615    /**
1616     * Width as measured during measure pass.
1617     * {@hide}
1618     */
1619    @ViewDebug.ExportedProperty(category = "measurement")
1620    int mMeasuredWidth;
1621
1622    /**
1623     * Height as measured during measure pass.
1624     * {@hide}
1625     */
1626    @ViewDebug.ExportedProperty(category = "measurement")
1627    int mMeasuredHeight;
1628
1629    /**
1630     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1631     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1632     * its display list. This flag, used only when hw accelerated, allows us to clear the
1633     * flag while retaining this information until it's needed (at getDisplayList() time and
1634     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1635     *
1636     * {@hide}
1637     */
1638    boolean mRecreateDisplayList = false;
1639
1640    /**
1641     * The view's identifier.
1642     * {@hide}
1643     *
1644     * @see #setId(int)
1645     * @see #getId()
1646     */
1647    @ViewDebug.ExportedProperty(resolveId = true)
1648    int mID = NO_ID;
1649
1650    /**
1651     * The stable ID of this view for accessibility purposes.
1652     */
1653    int mAccessibilityViewId = NO_ID;
1654
1655    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1656
1657    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1658
1659    /**
1660     * The view's tag.
1661     * {@hide}
1662     *
1663     * @see #setTag(Object)
1664     * @see #getTag()
1665     */
1666    protected Object mTag = null;
1667
1668    // for mPrivateFlags:
1669    /** {@hide} */
1670    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1671    /** {@hide} */
1672    static final int PFLAG_FOCUSED                     = 0x00000002;
1673    /** {@hide} */
1674    static final int PFLAG_SELECTED                    = 0x00000004;
1675    /** {@hide} */
1676    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1677    /** {@hide} */
1678    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1679    /** {@hide} */
1680    static final int PFLAG_DRAWN                       = 0x00000020;
1681    /**
1682     * When this flag is set, this view is running an animation on behalf of its
1683     * children and should therefore not cancel invalidate requests, even if they
1684     * lie outside of this view's bounds.
1685     *
1686     * {@hide}
1687     */
1688    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1689    /** {@hide} */
1690    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1691    /** {@hide} */
1692    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1693    /** {@hide} */
1694    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1695    /** {@hide} */
1696    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1697    /** {@hide} */
1698    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1699    /** {@hide} */
1700    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1701    /** {@hide} */
1702    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1703
1704    private static final int PFLAG_PRESSED             = 0x00004000;
1705
1706    /** {@hide} */
1707    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1708    /**
1709     * Flag used to indicate that this view should be drawn once more (and only once
1710     * more) after its animation has completed.
1711     * {@hide}
1712     */
1713    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1714
1715    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1716
1717    /**
1718     * Indicates that the View returned true when onSetAlpha() was called and that
1719     * the alpha must be restored.
1720     * {@hide}
1721     */
1722    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1723
1724    /**
1725     * Set by {@link #setScrollContainer(boolean)}.
1726     */
1727    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1728
1729    /**
1730     * Set by {@link #setScrollContainer(boolean)}.
1731     */
1732    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1733
1734    /**
1735     * View flag indicating whether this view was invalidated (fully or partially.)
1736     *
1737     * @hide
1738     */
1739    static final int PFLAG_DIRTY                       = 0x00200000;
1740
1741    /**
1742     * View flag indicating whether this view was invalidated by an opaque
1743     * invalidate request.
1744     *
1745     * @hide
1746     */
1747    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1748
1749    /**
1750     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1751     *
1752     * @hide
1753     */
1754    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1755
1756    /**
1757     * Indicates whether the background is opaque.
1758     *
1759     * @hide
1760     */
1761    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1762
1763    /**
1764     * Indicates whether the scrollbars are opaque.
1765     *
1766     * @hide
1767     */
1768    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1769
1770    /**
1771     * Indicates whether the view is opaque.
1772     *
1773     * @hide
1774     */
1775    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1776
1777    /**
1778     * Indicates a prepressed state;
1779     * the short time between ACTION_DOWN and recognizing
1780     * a 'real' press. Prepressed is used to recognize quick taps
1781     * even when they are shorter than ViewConfiguration.getTapTimeout().
1782     *
1783     * @hide
1784     */
1785    private static final int PFLAG_PREPRESSED          = 0x02000000;
1786
1787    /**
1788     * Indicates whether the view is temporarily detached.
1789     *
1790     * @hide
1791     */
1792    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1793
1794    /**
1795     * Indicates that we should awaken scroll bars once attached
1796     *
1797     * @hide
1798     */
1799    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1800
1801    /**
1802     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1803     * @hide
1804     */
1805    private static final int PFLAG_HOVERED             = 0x10000000;
1806
1807    /**
1808     * no longer needed, should be reused
1809     */
1810    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1811
1812    /** {@hide} */
1813    static final int PFLAG_ACTIVATED                   = 0x40000000;
1814
1815    /**
1816     * Indicates that this view was specifically invalidated, not just dirtied because some
1817     * child view was invalidated. The flag is used to determine when we need to recreate
1818     * a view's display list (as opposed to just returning a reference to its existing
1819     * display list).
1820     *
1821     * @hide
1822     */
1823    static final int PFLAG_INVALIDATED                 = 0x80000000;
1824
1825    /**
1826     * Masks for mPrivateFlags2, as generated by dumpFlags():
1827     *
1828     * |-------|-------|-------|-------|
1829     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1830     *                                1  PFLAG2_DRAG_HOVERED
1831     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1832     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1833     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1834     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1835     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1836     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1837     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1838     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1839     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1840     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1841     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1842     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1843     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1844     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1845     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1846     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1847     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1848     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1849     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1850     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1851     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1852     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1853     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1854     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1855     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1856     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1857     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1858     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1859     *    1                              PFLAG2_PADDING_RESOLVED
1860     *   1                               PFLAG2_DRAWABLE_RESOLVED
1861     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1862     * |-------|-------|-------|-------|
1863     */
1864
1865    /**
1866     * Indicates that this view has reported that it can accept the current drag's content.
1867     * Cleared when the drag operation concludes.
1868     * @hide
1869     */
1870    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1871
1872    /**
1873     * Indicates that this view is currently directly under the drag location in a
1874     * drag-and-drop operation involving content that it can accept.  Cleared when
1875     * the drag exits the view, or when the drag operation concludes.
1876     * @hide
1877     */
1878    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL,
1884        LAYOUT_DIRECTION_INHERIT,
1885        LAYOUT_DIRECTION_LOCALE
1886    })
1887    @Retention(RetentionPolicy.SOURCE)
1888    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1889    public @interface LayoutDir {}
1890
1891    /** @hide */
1892    @IntDef({
1893        LAYOUT_DIRECTION_LTR,
1894        LAYOUT_DIRECTION_RTL
1895    })
1896    @Retention(RetentionPolicy.SOURCE)
1897    public @interface ResolvedLayoutDir {}
1898
1899    /**
1900     * Horizontal layout direction of this view is from Left to Right.
1901     * Use with {@link #setLayoutDirection}.
1902     */
1903    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1904
1905    /**
1906     * Horizontal layout direction of this view is from Right to Left.
1907     * Use with {@link #setLayoutDirection}.
1908     */
1909    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1910
1911    /**
1912     * Horizontal layout direction of this view is inherited from its parent.
1913     * Use with {@link #setLayoutDirection}.
1914     */
1915    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1916
1917    /**
1918     * Horizontal layout direction of this view is from deduced from the default language
1919     * script for the locale. Use with {@link #setLayoutDirection}.
1920     */
1921    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1922
1923    /**
1924     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1928
1929    /**
1930     * Mask for use with private flags indicating bits used for horizontal layout direction.
1931     * @hide
1932     */
1933    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1934
1935    /**
1936     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1937     * right-to-left direction.
1938     * @hide
1939     */
1940    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Indicates whether the view horizontal layout direction has been resolved.
1944     * @hide
1945     */
1946    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1947
1948    /**
1949     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1950     * @hide
1951     */
1952    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1953            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1954
1955    /*
1956     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1957     * flag value.
1958     * @hide
1959     */
1960    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1961            LAYOUT_DIRECTION_LTR,
1962            LAYOUT_DIRECTION_RTL,
1963            LAYOUT_DIRECTION_INHERIT,
1964            LAYOUT_DIRECTION_LOCALE
1965    };
1966
1967    /**
1968     * Default horizontal layout direction.
1969     */
1970    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1971
1972    /**
1973     * Default horizontal layout direction.
1974     * @hide
1975     */
1976    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1977
1978    /**
1979     * Text direction is inherited thru {@link ViewGroup}
1980     */
1981    public static final int TEXT_DIRECTION_INHERIT = 0;
1982
1983    /**
1984     * Text direction is using "first strong algorithm". The first strong directional character
1985     * determines the paragraph direction. If there is no strong directional character, the
1986     * paragraph direction is the view's resolved layout direction.
1987     */
1988    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1989
1990    /**
1991     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1992     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1993     * If there are neither, the paragraph direction is the view's resolved layout direction.
1994     */
1995    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1996
1997    /**
1998     * Text direction is forced to LTR.
1999     */
2000    public static final int TEXT_DIRECTION_LTR = 3;
2001
2002    /**
2003     * Text direction is forced to RTL.
2004     */
2005    public static final int TEXT_DIRECTION_RTL = 4;
2006
2007    /**
2008     * Text direction is coming from the system Locale.
2009     */
2010    public static final int TEXT_DIRECTION_LOCALE = 5;
2011
2012    /**
2013     * Default text direction is inherited
2014     */
2015    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2016
2017    /**
2018     * Default resolved text direction
2019     * @hide
2020     */
2021    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2022
2023    /**
2024     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2025     * @hide
2026     */
2027    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2028
2029    /**
2030     * Mask for use with private flags indicating bits used for text direction.
2031     * @hide
2032     */
2033    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2034            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2035
2036    /**
2037     * Array of text direction flags for mapping attribute "textDirection" to correct
2038     * flag value.
2039     * @hide
2040     */
2041    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2042            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2043            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2044            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2045            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2046            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2047            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2048    };
2049
2050    /**
2051     * Indicates whether the view text direction has been resolved.
2052     * @hide
2053     */
2054    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2055            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2056
2057    /**
2058     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2059     * @hide
2060     */
2061    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2062
2063    /**
2064     * Mask for use with private flags indicating bits used for resolved text direction.
2065     * @hide
2066     */
2067    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2068            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2069
2070    /**
2071     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2072     * @hide
2073     */
2074    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2075            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2076
2077    /** @hide */
2078    @IntDef({
2079        TEXT_ALIGNMENT_INHERIT,
2080        TEXT_ALIGNMENT_GRAVITY,
2081        TEXT_ALIGNMENT_CENTER,
2082        TEXT_ALIGNMENT_TEXT_START,
2083        TEXT_ALIGNMENT_TEXT_END,
2084        TEXT_ALIGNMENT_VIEW_START,
2085        TEXT_ALIGNMENT_VIEW_END
2086    })
2087    @Retention(RetentionPolicy.SOURCE)
2088    public @interface TextAlignment {}
2089
2090    /**
2091     * Default text alignment. The text alignment of this View is inherited from its parent.
2092     * Use with {@link #setTextAlignment(int)}
2093     */
2094    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2095
2096    /**
2097     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2098     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2099     *
2100     * Use with {@link #setTextAlignment(int)}
2101     */
2102    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2103
2104    /**
2105     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2106     *
2107     * Use with {@link #setTextAlignment(int)}
2108     */
2109    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2110
2111    /**
2112     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2113     *
2114     * Use with {@link #setTextAlignment(int)}
2115     */
2116    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2117
2118    /**
2119     * Center the paragraph, e.g. ALIGN_CENTER.
2120     *
2121     * Use with {@link #setTextAlignment(int)}
2122     */
2123    public static final int TEXT_ALIGNMENT_CENTER = 4;
2124
2125    /**
2126     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2127     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2128     *
2129     * Use with {@link #setTextAlignment(int)}
2130     */
2131    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2132
2133    /**
2134     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2135     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2136     *
2137     * Use with {@link #setTextAlignment(int)}
2138     */
2139    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2140
2141    /**
2142     * Default text alignment is inherited
2143     */
2144    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2145
2146    /**
2147     * Default resolved text alignment
2148     * @hide
2149     */
2150    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2151
2152    /**
2153      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2154      * @hide
2155      */
2156    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2157
2158    /**
2159      * Mask for use with private flags indicating bits used for text alignment.
2160      * @hide
2161      */
2162    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2163
2164    /**
2165     * Array of text direction flags for mapping attribute "textAlignment" to correct
2166     * flag value.
2167     * @hide
2168     */
2169    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2170            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2171            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2172            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2173            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2174            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2175            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2176            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2177    };
2178
2179    /**
2180     * Indicates whether the view text alignment has been resolved.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2184
2185    /**
2186     * Bit shift to get the resolved text alignment.
2187     * @hide
2188     */
2189    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2190
2191    /**
2192     * Mask for use with private flags indicating bits used for text alignment.
2193     * @hide
2194     */
2195    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2196            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2197
2198    /**
2199     * Indicates whether if the view text alignment has been resolved to gravity
2200     */
2201    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2202            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2203
2204    // Accessiblity constants for mPrivateFlags2
2205
2206    /**
2207     * Shift for the bits in {@link #mPrivateFlags2} related to the
2208     * "importantForAccessibility" attribute.
2209     */
2210    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2211
2212    /**
2213     * Automatically determine whether a view is important for accessibility.
2214     */
2215    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2216
2217    /**
2218     * The view is important for accessibility.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2221
2222    /**
2223     * The view is not important for accessibility.
2224     */
2225    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2226
2227    /**
2228     * The view is not important for accessibility, nor are any of its
2229     * descendant views.
2230     */
2231    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2232
2233    /**
2234     * The default whether the view is important for accessibility.
2235     */
2236    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2237
2238    /**
2239     * Mask for obtainig the bits which specify how to determine
2240     * whether a view is important for accessibility.
2241     */
2242    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2243        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2244        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2245        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2246
2247    /**
2248     * Shift for the bits in {@link #mPrivateFlags2} related to the
2249     * "accessibilityLiveRegion" attribute.
2250     */
2251    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2252
2253    /**
2254     * Live region mode specifying that accessibility services should not
2255     * automatically announce changes to this view. This is the default live
2256     * region mode for most views.
2257     * <p>
2258     * Use with {@link #setAccessibilityLiveRegion(int)}.
2259     */
2260    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2261
2262    /**
2263     * Live region mode specifying that accessibility services should announce
2264     * changes to this view.
2265     * <p>
2266     * Use with {@link #setAccessibilityLiveRegion(int)}.
2267     */
2268    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2269
2270    /**
2271     * Live region mode specifying that accessibility services should interrupt
2272     * ongoing speech to immediately announce changes to this view.
2273     * <p>
2274     * Use with {@link #setAccessibilityLiveRegion(int)}.
2275     */
2276    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2277
2278    /**
2279     * The default whether the view is important for accessibility.
2280     */
2281    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2282
2283    /**
2284     * Mask for obtaining the bits which specify a view's accessibility live
2285     * region mode.
2286     */
2287    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2288            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2289            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2290
2291    /**
2292     * Flag indicating whether a view has accessibility focus.
2293     */
2294    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2295
2296    /**
2297     * Flag whether the accessibility state of the subtree rooted at this view changed.
2298     */
2299    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2300
2301    /**
2302     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2303     * is used to check whether later changes to the view's transform should invalidate the
2304     * view to force the quickReject test to run again.
2305     */
2306    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2307
2308    /**
2309     * Flag indicating that start/end padding has been resolved into left/right padding
2310     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2311     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2312     * during measurement. In some special cases this is required such as when an adapter-based
2313     * view measures prospective children without attaching them to a window.
2314     */
2315    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2316
2317    /**
2318     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2319     */
2320    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2321
2322    /**
2323     * Indicates that the view is tracking some sort of transient state
2324     * that the app should not need to be aware of, but that the framework
2325     * should take special care to preserve.
2326     */
2327    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2328
2329    /**
2330     * Group of bits indicating that RTL properties resolution is done.
2331     */
2332    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2333            PFLAG2_TEXT_DIRECTION_RESOLVED |
2334            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2335            PFLAG2_PADDING_RESOLVED |
2336            PFLAG2_DRAWABLE_RESOLVED;
2337
2338    // There are a couple of flags left in mPrivateFlags2
2339
2340    /* End of masks for mPrivateFlags2 */
2341
2342    /**
2343     * Masks for mPrivateFlags3, as generated by dumpFlags():
2344     *
2345     * |-------|-------|-------|-------|
2346     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2347     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2348     *                               1   PFLAG3_IS_LAID_OUT
2349     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2350     *                             1     PFLAG3_CALLED_SUPER
2351     * |-------|-------|-------|-------|
2352     */
2353
2354    /**
2355     * Flag indicating that view has a transform animation set on it. This is used to track whether
2356     * an animation is cleared between successive frames, in order to tell the associated
2357     * DisplayList to clear its animation matrix.
2358     */
2359    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2360
2361    /**
2362     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2363     * animation is cleared between successive frames, in order to tell the associated
2364     * DisplayList to restore its alpha value.
2365     */
2366    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2367
2368    /**
2369     * Flag indicating that the view has been through at least one layout since it
2370     * was last attached to a window.
2371     */
2372    static final int PFLAG3_IS_LAID_OUT = 0x4;
2373
2374    /**
2375     * Flag indicating that a call to measure() was skipped and should be done
2376     * instead when layout() is invoked.
2377     */
2378    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2379
2380    /**
2381     * Flag indicating that an overridden method correctly called down to
2382     * the superclass implementation as required by the API spec.
2383     */
2384    static final int PFLAG3_CALLED_SUPER = 0x10;
2385
2386    /**
2387     * Flag indicating that we're in the process of applying window insets.
2388     */
2389    static final int PFLAG3_APPLYING_INSETS = 0x20;
2390
2391    /**
2392     * Flag indicating that we're in the process of fitting system windows using the old method.
2393     */
2394    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2395
2396    /**
2397     * Flag indicating that nested scrolling is enabled for this view.
2398     * The view will optionally cooperate with views up its parent chain to allow for
2399     * integrated nested scrolling along the same axis.
2400     */
2401    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2402
2403    /**
2404     * Flag indicating that outline was invalidated and should be rebuilt the next time
2405     * the DisplayList is updated.
2406     */
2407    static final int PFLAG3_OUTLINE_INVALID = 0x100;
2408
2409    /* End of masks for mPrivateFlags3 */
2410
2411    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2412
2413    /**
2414     * Always allow a user to over-scroll this view, provided it is a
2415     * view that can scroll.
2416     *
2417     * @see #getOverScrollMode()
2418     * @see #setOverScrollMode(int)
2419     */
2420    public static final int OVER_SCROLL_ALWAYS = 0;
2421
2422    /**
2423     * Allow a user to over-scroll this view only if the content is large
2424     * enough to meaningfully scroll, provided it is a view that can scroll.
2425     *
2426     * @see #getOverScrollMode()
2427     * @see #setOverScrollMode(int)
2428     */
2429    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2430
2431    /**
2432     * Never allow a user to over-scroll this view.
2433     *
2434     * @see #getOverScrollMode()
2435     * @see #setOverScrollMode(int)
2436     */
2437    public static final int OVER_SCROLL_NEVER = 2;
2438
2439    /**
2440     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2441     * requested the system UI (status bar) to be visible (the default).
2442     *
2443     * @see #setSystemUiVisibility(int)
2444     */
2445    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2446
2447    /**
2448     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2449     * system UI to enter an unobtrusive "low profile" mode.
2450     *
2451     * <p>This is for use in games, book readers, video players, or any other
2452     * "immersive" application where the usual system chrome is deemed too distracting.
2453     *
2454     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2455     *
2456     * @see #setSystemUiVisibility(int)
2457     */
2458    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2459
2460    /**
2461     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2462     * system navigation be temporarily hidden.
2463     *
2464     * <p>This is an even less obtrusive state than that called for by
2465     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2466     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2467     * those to disappear. This is useful (in conjunction with the
2468     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2469     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2470     * window flags) for displaying content using every last pixel on the display.
2471     *
2472     * <p>There is a limitation: because navigation controls are so important, the least user
2473     * interaction will cause them to reappear immediately.  When this happens, both
2474     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2475     * so that both elements reappear at the same time.
2476     *
2477     * @see #setSystemUiVisibility(int)
2478     */
2479    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2480
2481    /**
2482     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2483     * into the normal fullscreen mode so that its content can take over the screen
2484     * while still allowing the user to interact with the application.
2485     *
2486     * <p>This has the same visual effect as
2487     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2488     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2489     * meaning that non-critical screen decorations (such as the status bar) will be
2490     * hidden while the user is in the View's window, focusing the experience on
2491     * that content.  Unlike the window flag, if you are using ActionBar in
2492     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2493     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2494     * hide the action bar.
2495     *
2496     * <p>This approach to going fullscreen is best used over the window flag when
2497     * it is a transient state -- that is, the application does this at certain
2498     * points in its user interaction where it wants to allow the user to focus
2499     * on content, but not as a continuous state.  For situations where the application
2500     * would like to simply stay full screen the entire time (such as a game that
2501     * wants to take over the screen), the
2502     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2503     * is usually a better approach.  The state set here will be removed by the system
2504     * in various situations (such as the user moving to another application) like
2505     * the other system UI states.
2506     *
2507     * <p>When using this flag, the application should provide some easy facility
2508     * for the user to go out of it.  A common example would be in an e-book
2509     * reader, where tapping on the screen brings back whatever screen and UI
2510     * decorations that had been hidden while the user was immersed in reading
2511     * the book.
2512     *
2513     * @see #setSystemUiVisibility(int)
2514     */
2515    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2516
2517    /**
2518     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2519     * flags, we would like a stable view of the content insets given to
2520     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2521     * will always represent the worst case that the application can expect
2522     * as a continuous state.  In the stock Android UI this is the space for
2523     * the system bar, nav bar, and status bar, but not more transient elements
2524     * such as an input method.
2525     *
2526     * The stable layout your UI sees is based on the system UI modes you can
2527     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2528     * then you will get a stable layout for changes of the
2529     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2530     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2531     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2532     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2533     * with a stable layout.  (Note that you should avoid using
2534     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2535     *
2536     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2537     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2538     * then a hidden status bar will be considered a "stable" state for purposes
2539     * here.  This allows your UI to continually hide the status bar, while still
2540     * using the system UI flags to hide the action bar while still retaining
2541     * a stable layout.  Note that changing the window fullscreen flag will never
2542     * provide a stable layout for a clean transition.
2543     *
2544     * <p>If you are using ActionBar in
2545     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2546     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2547     * insets it adds to those given to the application.
2548     */
2549    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2550
2551    /**
2552     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2553     * to be layed out as if it has requested
2554     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2555     * allows it to avoid artifacts when switching in and out of that mode, at
2556     * the expense that some of its user interface may be covered by screen
2557     * decorations when they are shown.  You can perform layout of your inner
2558     * UI elements to account for the navigation system UI through the
2559     * {@link #fitSystemWindows(Rect)} method.
2560     */
2561    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2562
2563    /**
2564     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2565     * to be layed out as if it has requested
2566     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2567     * allows it to avoid artifacts when switching in and out of that mode, at
2568     * the expense that some of its user interface may be covered by screen
2569     * decorations when they are shown.  You can perform layout of your inner
2570     * UI elements to account for non-fullscreen system UI through the
2571     * {@link #fitSystemWindows(Rect)} method.
2572     */
2573    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2574
2575    /**
2576     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2577     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2578     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2579     * user interaction.
2580     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2581     * has an effect when used in combination with that flag.</p>
2582     */
2583    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2584
2585    /**
2586     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2587     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2588     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2589     * experience while also hiding the system bars.  If this flag is not set,
2590     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2591     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2592     * if the user swipes from the top of the screen.
2593     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2594     * system gestures, such as swiping from the top of the screen.  These transient system bars
2595     * will overlay app’s content, may have some degree of transparency, and will automatically
2596     * hide after a short timeout.
2597     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2598     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2599     * with one or both of those flags.</p>
2600     */
2601    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2602
2603    /**
2604     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2605     */
2606    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2607
2608    /**
2609     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2610     */
2611    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2612
2613    /**
2614     * @hide
2615     *
2616     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2617     * out of the public fields to keep the undefined bits out of the developer's way.
2618     *
2619     * Flag to make the status bar not expandable.  Unless you also
2620     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2621     */
2622    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2623
2624    /**
2625     * @hide
2626     *
2627     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2628     * out of the public fields to keep the undefined bits out of the developer's way.
2629     *
2630     * Flag to hide notification icons and scrolling ticker text.
2631     */
2632    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2633
2634    /**
2635     * @hide
2636     *
2637     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2638     * out of the public fields to keep the undefined bits out of the developer's way.
2639     *
2640     * Flag to disable incoming notification alerts.  This will not block
2641     * icons, but it will block sound, vibrating and other visual or aural notifications.
2642     */
2643    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2644
2645    /**
2646     * @hide
2647     *
2648     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2649     * out of the public fields to keep the undefined bits out of the developer's way.
2650     *
2651     * Flag to hide only the scrolling ticker.  Note that
2652     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2653     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2654     */
2655    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2656
2657    /**
2658     * @hide
2659     *
2660     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2661     * out of the public fields to keep the undefined bits out of the developer's way.
2662     *
2663     * Flag to hide the center system info area.
2664     */
2665    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2666
2667    /**
2668     * @hide
2669     *
2670     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2671     * out of the public fields to keep the undefined bits out of the developer's way.
2672     *
2673     * Flag to hide only the home button.  Don't use this
2674     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2675     */
2676    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2677
2678    /**
2679     * @hide
2680     *
2681     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2682     * out of the public fields to keep the undefined bits out of the developer's way.
2683     *
2684     * Flag to hide only the back button. Don't use this
2685     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2686     */
2687    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2688
2689    /**
2690     * @hide
2691     *
2692     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2693     * out of the public fields to keep the undefined bits out of the developer's way.
2694     *
2695     * Flag to hide only the clock.  You might use this if your activity has
2696     * its own clock making the status bar's clock redundant.
2697     */
2698    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2699
2700    /**
2701     * @hide
2702     *
2703     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2704     * out of the public fields to keep the undefined bits out of the developer's way.
2705     *
2706     * Flag to hide only the recent apps button. Don't use this
2707     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2708     */
2709    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2710
2711    /**
2712     * @hide
2713     *
2714     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2715     * out of the public fields to keep the undefined bits out of the developer's way.
2716     *
2717     * Flag to disable the global search gesture. Don't use this
2718     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2719     */
2720    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2721
2722    /**
2723     * @hide
2724     *
2725     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2726     * out of the public fields to keep the undefined bits out of the developer's way.
2727     *
2728     * Flag to specify that the status bar is displayed in transient mode.
2729     */
2730    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2731
2732    /**
2733     * @hide
2734     *
2735     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2736     * out of the public fields to keep the undefined bits out of the developer's way.
2737     *
2738     * Flag to specify that the navigation bar is displayed in transient mode.
2739     */
2740    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2741
2742    /**
2743     * @hide
2744     *
2745     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2746     * out of the public fields to keep the undefined bits out of the developer's way.
2747     *
2748     * Flag to specify that the hidden status bar would like to be shown.
2749     */
2750    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2751
2752    /**
2753     * @hide
2754     *
2755     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2756     * out of the public fields to keep the undefined bits out of the developer's way.
2757     *
2758     * Flag to specify that the hidden navigation bar would like to be shown.
2759     */
2760    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2761
2762    /**
2763     * @hide
2764     *
2765     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2766     * out of the public fields to keep the undefined bits out of the developer's way.
2767     *
2768     * Flag to specify that the status bar is displayed in translucent mode.
2769     */
2770    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2771
2772    /**
2773     * @hide
2774     *
2775     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2776     * out of the public fields to keep the undefined bits out of the developer's way.
2777     *
2778     * Flag to specify that the navigation bar is displayed in translucent mode.
2779     */
2780    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2781
2782    /**
2783     * @hide
2784     *
2785     * Whether Recents is visible or not.
2786     */
2787    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2788
2789    /**
2790     * @hide
2791     *
2792     * Makes system ui transparent.
2793     */
2794    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2795
2796    /**
2797     * @hide
2798     */
2799    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2800
2801    /**
2802     * These are the system UI flags that can be cleared by events outside
2803     * of an application.  Currently this is just the ability to tap on the
2804     * screen while hiding the navigation bar to have it return.
2805     * @hide
2806     */
2807    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2808            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2809            | SYSTEM_UI_FLAG_FULLSCREEN;
2810
2811    /**
2812     * Flags that can impact the layout in relation to system UI.
2813     */
2814    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2815            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2816            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2817
2818    /** @hide */
2819    @IntDef(flag = true,
2820            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2821    @Retention(RetentionPolicy.SOURCE)
2822    public @interface FindViewFlags {}
2823
2824    /**
2825     * Find views that render the specified text.
2826     *
2827     * @see #findViewsWithText(ArrayList, CharSequence, int)
2828     */
2829    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2830
2831    /**
2832     * Find find views that contain the specified content description.
2833     *
2834     * @see #findViewsWithText(ArrayList, CharSequence, int)
2835     */
2836    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2837
2838    /**
2839     * Find views that contain {@link AccessibilityNodeProvider}. Such
2840     * a View is a root of virtual view hierarchy and may contain the searched
2841     * text. If this flag is set Views with providers are automatically
2842     * added and it is a responsibility of the client to call the APIs of
2843     * the provider to determine whether the virtual tree rooted at this View
2844     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2845     * representing the virtual views with this text.
2846     *
2847     * @see #findViewsWithText(ArrayList, CharSequence, int)
2848     *
2849     * @hide
2850     */
2851    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2852
2853    /**
2854     * The undefined cursor position.
2855     *
2856     * @hide
2857     */
2858    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2859
2860    /**
2861     * Indicates that the screen has changed state and is now off.
2862     *
2863     * @see #onScreenStateChanged(int)
2864     */
2865    public static final int SCREEN_STATE_OFF = 0x0;
2866
2867    /**
2868     * Indicates that the screen has changed state and is now on.
2869     *
2870     * @see #onScreenStateChanged(int)
2871     */
2872    public static final int SCREEN_STATE_ON = 0x1;
2873
2874    /**
2875     * Indicates no axis of view scrolling.
2876     */
2877    public static final int SCROLL_AXIS_NONE = 0;
2878
2879    /**
2880     * Indicates scrolling along the horizontal axis.
2881     */
2882    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2883
2884    /**
2885     * Indicates scrolling along the vertical axis.
2886     */
2887    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2888
2889    /**
2890     * Controls the over-scroll mode for this view.
2891     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2892     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2893     * and {@link #OVER_SCROLL_NEVER}.
2894     */
2895    private int mOverScrollMode;
2896
2897    /**
2898     * The parent this view is attached to.
2899     * {@hide}
2900     *
2901     * @see #getParent()
2902     */
2903    protected ViewParent mParent;
2904
2905    /**
2906     * {@hide}
2907     */
2908    AttachInfo mAttachInfo;
2909
2910    /**
2911     * {@hide}
2912     */
2913    @ViewDebug.ExportedProperty(flagMapping = {
2914        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2915                name = "FORCE_LAYOUT"),
2916        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2917                name = "LAYOUT_REQUIRED"),
2918        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2919            name = "DRAWING_CACHE_INVALID", outputIf = false),
2920        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2921        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2922        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2923        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2924    }, formatToHexString = true)
2925    int mPrivateFlags;
2926    int mPrivateFlags2;
2927    int mPrivateFlags3;
2928
2929    /**
2930     * This view's request for the visibility of the status bar.
2931     * @hide
2932     */
2933    @ViewDebug.ExportedProperty(flagMapping = {
2934        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2935                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2936                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2937        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2938                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2939                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2940        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2941                                equals = SYSTEM_UI_FLAG_VISIBLE,
2942                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2943    }, formatToHexString = true)
2944    int mSystemUiVisibility;
2945
2946    /**
2947     * Reference count for transient state.
2948     * @see #setHasTransientState(boolean)
2949     */
2950    int mTransientStateCount = 0;
2951
2952    /**
2953     * Count of how many windows this view has been attached to.
2954     */
2955    int mWindowAttachCount;
2956
2957    /**
2958     * The layout parameters associated with this view and used by the parent
2959     * {@link android.view.ViewGroup} to determine how this view should be
2960     * laid out.
2961     * {@hide}
2962     */
2963    protected ViewGroup.LayoutParams mLayoutParams;
2964
2965    /**
2966     * The view flags hold various views states.
2967     * {@hide}
2968     */
2969    @ViewDebug.ExportedProperty(formatToHexString = true)
2970    int mViewFlags;
2971
2972    static class TransformationInfo {
2973        /**
2974         * The transform matrix for the View. This transform is calculated internally
2975         * based on the translation, rotation, and scale properties.
2976         *
2977         * Do *not* use this variable directly; instead call getMatrix(), which will
2978         * load the value from the View's RenderNode.
2979         */
2980        private final Matrix mMatrix = new Matrix();
2981
2982        /**
2983         * The inverse transform matrix for the View. This transform is calculated
2984         * internally based on the translation, rotation, and scale properties.
2985         *
2986         * Do *not* use this variable directly; instead call getInverseMatrix(),
2987         * which will load the value from the View's RenderNode.
2988         */
2989        private Matrix mInverseMatrix;
2990
2991        /**
2992         * The opacity of the View. This is a value from 0 to 1, where 0 means
2993         * completely transparent and 1 means completely opaque.
2994         */
2995        @ViewDebug.ExportedProperty
2996        float mAlpha = 1f;
2997
2998        /**
2999         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3000         * property only used by transitions, which is composited with the other alpha
3001         * values to calculate the final visual alpha value.
3002         */
3003        float mTransitionAlpha = 1f;
3004    }
3005
3006    TransformationInfo mTransformationInfo;
3007
3008    /**
3009     * Current clip bounds. to which all drawing of this view are constrained.
3010     */
3011    Rect mClipBounds = null;
3012
3013    private boolean mLastIsOpaque;
3014
3015    /**
3016     * The distance in pixels from the left edge of this view's parent
3017     * to the left edge of this view.
3018     * {@hide}
3019     */
3020    @ViewDebug.ExportedProperty(category = "layout")
3021    protected int mLeft;
3022    /**
3023     * The distance in pixels from the left edge of this view's parent
3024     * to the right edge of this view.
3025     * {@hide}
3026     */
3027    @ViewDebug.ExportedProperty(category = "layout")
3028    protected int mRight;
3029    /**
3030     * The distance in pixels from the top edge of this view's parent
3031     * to the top edge of this view.
3032     * {@hide}
3033     */
3034    @ViewDebug.ExportedProperty(category = "layout")
3035    protected int mTop;
3036    /**
3037     * The distance in pixels from the top edge of this view's parent
3038     * to the bottom edge of this view.
3039     * {@hide}
3040     */
3041    @ViewDebug.ExportedProperty(category = "layout")
3042    protected int mBottom;
3043
3044    /**
3045     * The offset, in pixels, by which the content of this view is scrolled
3046     * horizontally.
3047     * {@hide}
3048     */
3049    @ViewDebug.ExportedProperty(category = "scrolling")
3050    protected int mScrollX;
3051    /**
3052     * The offset, in pixels, by which the content of this view is scrolled
3053     * vertically.
3054     * {@hide}
3055     */
3056    @ViewDebug.ExportedProperty(category = "scrolling")
3057    protected int mScrollY;
3058
3059    /**
3060     * The left padding in pixels, that is the distance in pixels between the
3061     * left edge of this view and the left edge of its content.
3062     * {@hide}
3063     */
3064    @ViewDebug.ExportedProperty(category = "padding")
3065    protected int mPaddingLeft = 0;
3066    /**
3067     * The right padding in pixels, that is the distance in pixels between the
3068     * right edge of this view and the right edge of its content.
3069     * {@hide}
3070     */
3071    @ViewDebug.ExportedProperty(category = "padding")
3072    protected int mPaddingRight = 0;
3073    /**
3074     * The top padding in pixels, that is the distance in pixels between the
3075     * top edge of this view and the top edge of its content.
3076     * {@hide}
3077     */
3078    @ViewDebug.ExportedProperty(category = "padding")
3079    protected int mPaddingTop;
3080    /**
3081     * The bottom padding in pixels, that is the distance in pixels between the
3082     * bottom edge of this view and the bottom edge of its content.
3083     * {@hide}
3084     */
3085    @ViewDebug.ExportedProperty(category = "padding")
3086    protected int mPaddingBottom;
3087
3088    /**
3089     * The layout insets in pixels, that is the distance in pixels between the
3090     * visible edges of this view its bounds.
3091     */
3092    private Insets mLayoutInsets;
3093
3094    /**
3095     * Briefly describes the view and is primarily used for accessibility support.
3096     */
3097    private CharSequence mContentDescription;
3098
3099    /**
3100     * Specifies the id of a view for which this view serves as a label for
3101     * accessibility purposes.
3102     */
3103    private int mLabelForId = View.NO_ID;
3104
3105    /**
3106     * Predicate for matching labeled view id with its label for
3107     * accessibility purposes.
3108     */
3109    private MatchLabelForPredicate mMatchLabelForPredicate;
3110
3111    /**
3112     * Predicate for matching a view by its id.
3113     */
3114    private MatchIdPredicate mMatchIdPredicate;
3115
3116    /**
3117     * Cache the paddingRight set by the user to append to the scrollbar's size.
3118     *
3119     * @hide
3120     */
3121    @ViewDebug.ExportedProperty(category = "padding")
3122    protected int mUserPaddingRight;
3123
3124    /**
3125     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3126     *
3127     * @hide
3128     */
3129    @ViewDebug.ExportedProperty(category = "padding")
3130    protected int mUserPaddingBottom;
3131
3132    /**
3133     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3134     *
3135     * @hide
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    protected int mUserPaddingLeft;
3139
3140    /**
3141     * Cache the paddingStart set by the user to append to the scrollbar's size.
3142     *
3143     */
3144    @ViewDebug.ExportedProperty(category = "padding")
3145    int mUserPaddingStart;
3146
3147    /**
3148     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3149     *
3150     */
3151    @ViewDebug.ExportedProperty(category = "padding")
3152    int mUserPaddingEnd;
3153
3154    /**
3155     * Cache initial left padding.
3156     *
3157     * @hide
3158     */
3159    int mUserPaddingLeftInitial;
3160
3161    /**
3162     * Cache initial right padding.
3163     *
3164     * @hide
3165     */
3166    int mUserPaddingRightInitial;
3167
3168    /**
3169     * Default undefined padding
3170     */
3171    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3172
3173    /**
3174     * Cache if a left padding has been defined
3175     */
3176    private boolean mLeftPaddingDefined = false;
3177
3178    /**
3179     * Cache if a right padding has been defined
3180     */
3181    private boolean mRightPaddingDefined = false;
3182
3183    /**
3184     * @hide
3185     */
3186    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3187    /**
3188     * @hide
3189     */
3190    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3191
3192    private LongSparseLongArray mMeasureCache;
3193
3194    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3195    private Drawable mBackground;
3196    private TintInfo mBackgroundTint;
3197
3198    /**
3199     * RenderNode used for backgrounds.
3200     * <p>
3201     * When non-null and valid, this is expected to contain an up-to-date copy
3202     * of the background drawable. It is cleared on temporary detach, and reset
3203     * on cleanup.
3204     */
3205    private RenderNode mBackgroundRenderNode;
3206
3207    private int mBackgroundResource;
3208    private boolean mBackgroundSizeChanged;
3209
3210    private String mTransitionName;
3211
3212    private static class TintInfo {
3213        ColorStateList mTintList;
3214        PorterDuff.Mode mTintMode;
3215        boolean mHasTintMode;
3216        boolean mHasTintList;
3217    }
3218
3219    static class ListenerInfo {
3220        /**
3221         * Listener used to dispatch focus change events.
3222         * This field should be made private, so it is hidden from the SDK.
3223         * {@hide}
3224         */
3225        protected OnFocusChangeListener mOnFocusChangeListener;
3226
3227        /**
3228         * Listeners for layout change events.
3229         */
3230        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3231
3232        /**
3233         * Listeners for attach events.
3234         */
3235        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3236
3237        /**
3238         * Listener used to dispatch click events.
3239         * This field should be made private, so it is hidden from the SDK.
3240         * {@hide}
3241         */
3242        public OnClickListener mOnClickListener;
3243
3244        /**
3245         * Listener used to dispatch long click events.
3246         * This field should be made private, so it is hidden from the SDK.
3247         * {@hide}
3248         */
3249        protected OnLongClickListener mOnLongClickListener;
3250
3251        /**
3252         * Listener used to build the context menu.
3253         * This field should be made private, so it is hidden from the SDK.
3254         * {@hide}
3255         */
3256        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3257
3258        private OnKeyListener mOnKeyListener;
3259
3260        private OnTouchListener mOnTouchListener;
3261
3262        private OnHoverListener mOnHoverListener;
3263
3264        private OnGenericMotionListener mOnGenericMotionListener;
3265
3266        private OnDragListener mOnDragListener;
3267
3268        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3269
3270        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3271    }
3272
3273    ListenerInfo mListenerInfo;
3274
3275    /**
3276     * The application environment this view lives in.
3277     * This field should be made private, so it is hidden from the SDK.
3278     * {@hide}
3279     */
3280    @ViewDebug.ExportedProperty(deepExport = true)
3281    protected Context mContext;
3282
3283    private final Resources mResources;
3284
3285    private ScrollabilityCache mScrollCache;
3286
3287    private int[] mDrawableState = null;
3288
3289    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3290
3291    /**
3292     * Animator that automatically runs based on state changes.
3293     */
3294    private StateListAnimator mStateListAnimator;
3295
3296    /**
3297     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3298     * the user may specify which view to go to next.
3299     */
3300    private int mNextFocusLeftId = View.NO_ID;
3301
3302    /**
3303     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3304     * the user may specify which view to go to next.
3305     */
3306    private int mNextFocusRightId = View.NO_ID;
3307
3308    /**
3309     * When this view has focus and the next focus is {@link #FOCUS_UP},
3310     * the user may specify which view to go to next.
3311     */
3312    private int mNextFocusUpId = View.NO_ID;
3313
3314    /**
3315     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3316     * the user may specify which view to go to next.
3317     */
3318    private int mNextFocusDownId = View.NO_ID;
3319
3320    /**
3321     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3322     * the user may specify which view to go to next.
3323     */
3324    int mNextFocusForwardId = View.NO_ID;
3325
3326    private CheckForLongPress mPendingCheckForLongPress;
3327    private CheckForTap mPendingCheckForTap = null;
3328    private PerformClick mPerformClick;
3329    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3330
3331    private UnsetPressedState mUnsetPressedState;
3332
3333    /**
3334     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3335     * up event while a long press is invoked as soon as the long press duration is reached, so
3336     * a long press could be performed before the tap is checked, in which case the tap's action
3337     * should not be invoked.
3338     */
3339    private boolean mHasPerformedLongPress;
3340
3341    /**
3342     * The minimum height of the view. We'll try our best to have the height
3343     * of this view to at least this amount.
3344     */
3345    @ViewDebug.ExportedProperty(category = "measurement")
3346    private int mMinHeight;
3347
3348    /**
3349     * The minimum width of the view. We'll try our best to have the width
3350     * of this view to at least this amount.
3351     */
3352    @ViewDebug.ExportedProperty(category = "measurement")
3353    private int mMinWidth;
3354
3355    /**
3356     * The delegate to handle touch events that are physically in this view
3357     * but should be handled by another view.
3358     */
3359    private TouchDelegate mTouchDelegate = null;
3360
3361    /**
3362     * Solid color to use as a background when creating the drawing cache. Enables
3363     * the cache to use 16 bit bitmaps instead of 32 bit.
3364     */
3365    private int mDrawingCacheBackgroundColor = 0;
3366
3367    /**
3368     * Special tree observer used when mAttachInfo is null.
3369     */
3370    private ViewTreeObserver mFloatingTreeObserver;
3371
3372    /**
3373     * Cache the touch slop from the context that created the view.
3374     */
3375    private int mTouchSlop;
3376
3377    /**
3378     * Object that handles automatic animation of view properties.
3379     */
3380    private ViewPropertyAnimator mAnimator = null;
3381
3382    /**
3383     * Flag indicating that a drag can cross window boundaries.  When
3384     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3385     * with this flag set, all visible applications will be able to participate
3386     * in the drag operation and receive the dragged content.
3387     *
3388     * @hide
3389     */
3390    public static final int DRAG_FLAG_GLOBAL = 1;
3391
3392    /**
3393     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3394     */
3395    private float mVerticalScrollFactor;
3396
3397    /**
3398     * Position of the vertical scroll bar.
3399     */
3400    private int mVerticalScrollbarPosition;
3401
3402    /**
3403     * Position the scroll bar at the default position as determined by the system.
3404     */
3405    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3406
3407    /**
3408     * Position the scroll bar along the left edge.
3409     */
3410    public static final int SCROLLBAR_POSITION_LEFT = 1;
3411
3412    /**
3413     * Position the scroll bar along the right edge.
3414     */
3415    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3416
3417    /**
3418     * Indicates that the view does not have a layer.
3419     *
3420     * @see #getLayerType()
3421     * @see #setLayerType(int, android.graphics.Paint)
3422     * @see #LAYER_TYPE_SOFTWARE
3423     * @see #LAYER_TYPE_HARDWARE
3424     */
3425    public static final int LAYER_TYPE_NONE = 0;
3426
3427    /**
3428     * <p>Indicates that the view has a software layer. A software layer is backed
3429     * by a bitmap and causes the view to be rendered using Android's software
3430     * rendering pipeline, even if hardware acceleration is enabled.</p>
3431     *
3432     * <p>Software layers have various usages:</p>
3433     * <p>When the application is not using hardware acceleration, a software layer
3434     * is useful to apply a specific color filter and/or blending mode and/or
3435     * translucency to a view and all its children.</p>
3436     * <p>When the application is using hardware acceleration, a software layer
3437     * is useful to render drawing primitives not supported by the hardware
3438     * accelerated pipeline. It can also be used to cache a complex view tree
3439     * into a texture and reduce the complexity of drawing operations. For instance,
3440     * when animating a complex view tree with a translation, a software layer can
3441     * be used to render the view tree only once.</p>
3442     * <p>Software layers should be avoided when the affected view tree updates
3443     * often. Every update will require to re-render the software layer, which can
3444     * potentially be slow (particularly when hardware acceleration is turned on
3445     * since the layer will have to be uploaded into a hardware texture after every
3446     * update.)</p>
3447     *
3448     * @see #getLayerType()
3449     * @see #setLayerType(int, android.graphics.Paint)
3450     * @see #LAYER_TYPE_NONE
3451     * @see #LAYER_TYPE_HARDWARE
3452     */
3453    public static final int LAYER_TYPE_SOFTWARE = 1;
3454
3455    /**
3456     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3457     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3458     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3459     * rendering pipeline, but only if hardware acceleration is turned on for the
3460     * view hierarchy. When hardware acceleration is turned off, hardware layers
3461     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3462     *
3463     * <p>A hardware layer is useful to apply a specific color filter and/or
3464     * blending mode and/or translucency to a view and all its children.</p>
3465     * <p>A hardware layer can be used to cache a complex view tree into a
3466     * texture and reduce the complexity of drawing operations. For instance,
3467     * when animating a complex view tree with a translation, a hardware layer can
3468     * be used to render the view tree only once.</p>
3469     * <p>A hardware layer can also be used to increase the rendering quality when
3470     * rotation transformations are applied on a view. It can also be used to
3471     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3472     *
3473     * @see #getLayerType()
3474     * @see #setLayerType(int, android.graphics.Paint)
3475     * @see #LAYER_TYPE_NONE
3476     * @see #LAYER_TYPE_SOFTWARE
3477     */
3478    public static final int LAYER_TYPE_HARDWARE = 2;
3479
3480    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3481            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3482            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3483            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3484    })
3485    int mLayerType = LAYER_TYPE_NONE;
3486    Paint mLayerPaint;
3487
3488    /**
3489     * Set to true when drawing cache is enabled and cannot be created.
3490     *
3491     * @hide
3492     */
3493    public boolean mCachingFailed;
3494    private Bitmap mDrawingCache;
3495    private Bitmap mUnscaledDrawingCache;
3496
3497    /**
3498     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3499     * <p>
3500     * When non-null and valid, this is expected to contain an up-to-date copy
3501     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3502     * cleanup.
3503     */
3504    final RenderNode mRenderNode;
3505
3506    /**
3507     * Set to true when the view is sending hover accessibility events because it
3508     * is the innermost hovered view.
3509     */
3510    private boolean mSendingHoverAccessibilityEvents;
3511
3512    /**
3513     * Delegate for injecting accessibility functionality.
3514     */
3515    AccessibilityDelegate mAccessibilityDelegate;
3516
3517    /**
3518     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3519     * and add/remove objects to/from the overlay directly through the Overlay methods.
3520     */
3521    ViewOverlay mOverlay;
3522
3523    /**
3524     * The currently active parent view for receiving delegated nested scrolling events.
3525     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3526     * by {@link #stopNestedScroll()} at the same point where we clear
3527     * requestDisallowInterceptTouchEvent.
3528     */
3529    private ViewParent mNestedScrollingParent;
3530
3531    /**
3532     * Consistency verifier for debugging purposes.
3533     * @hide
3534     */
3535    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3536            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3537                    new InputEventConsistencyVerifier(this, 0) : null;
3538
3539    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3540
3541    private int[] mTempNestedScrollConsumed;
3542
3543    /**
3544     * An overlay is going to draw this View instead of being drawn as part of this
3545     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3546     * when this view is invalidated.
3547     */
3548    GhostView mGhostView;
3549
3550    /**
3551     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3552     * @hide
3553     */
3554    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3555    public String[] mAttributes;
3556
3557    /**
3558     * Maps a Resource id to its name.
3559     */
3560    private static SparseArray<String> mAttributeMap;
3561
3562    /**
3563     * Simple constructor to use when creating a view from code.
3564     *
3565     * @param context The Context the view is running in, through which it can
3566     *        access the current theme, resources, etc.
3567     */
3568    public View(Context context) {
3569        mContext = context;
3570        mResources = context != null ? context.getResources() : null;
3571        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3572        // Set some flags defaults
3573        mPrivateFlags2 =
3574                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3575                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3576                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3577                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3578                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3579                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3580        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3581        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3582        mUserPaddingStart = UNDEFINED_PADDING;
3583        mUserPaddingEnd = UNDEFINED_PADDING;
3584        mRenderNode = RenderNode.create(getClass().getName(), this);
3585
3586        if (!sCompatibilityDone && context != null) {
3587            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3588
3589            // Older apps may need this compatibility hack for measurement.
3590            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3591
3592            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3593            // of whether a layout was requested on that View.
3594            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3595
3596            sCompatibilityDone = true;
3597        }
3598    }
3599
3600    /**
3601     * Constructor that is called when inflating a view from XML. This is called
3602     * when a view is being constructed from an XML file, supplying attributes
3603     * that were specified in the XML file. This version uses a default style of
3604     * 0, so the only attribute values applied are those in the Context's Theme
3605     * and the given AttributeSet.
3606     *
3607     * <p>
3608     * The method onFinishInflate() will be called after all children have been
3609     * added.
3610     *
3611     * @param context The Context the view is running in, through which it can
3612     *        access the current theme, resources, etc.
3613     * @param attrs The attributes of the XML tag that is inflating the view.
3614     * @see #View(Context, AttributeSet, int)
3615     */
3616    public View(Context context, AttributeSet attrs) {
3617        this(context, attrs, 0);
3618    }
3619
3620    /**
3621     * Perform inflation from XML and apply a class-specific base style from a
3622     * theme attribute. This constructor of View allows subclasses to use their
3623     * own base style when they are inflating. For example, a Button class's
3624     * constructor would call this version of the super class constructor and
3625     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3626     * allows the theme's button style to modify all of the base view attributes
3627     * (in particular its background) as well as the Button class's attributes.
3628     *
3629     * @param context The Context the view is running in, through which it can
3630     *        access the current theme, resources, etc.
3631     * @param attrs The attributes of the XML tag that is inflating the view.
3632     * @param defStyleAttr An attribute in the current theme that contains a
3633     *        reference to a style resource that supplies default values for
3634     *        the view. Can be 0 to not look for defaults.
3635     * @see #View(Context, AttributeSet)
3636     */
3637    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3638        this(context, attrs, defStyleAttr, 0);
3639    }
3640
3641    /**
3642     * Perform inflation from XML and apply a class-specific base style from a
3643     * theme attribute or style resource. This constructor of View allows
3644     * subclasses to use their own base style when they are inflating.
3645     * <p>
3646     * When determining the final value of a particular attribute, there are
3647     * four inputs that come into play:
3648     * <ol>
3649     * <li>Any attribute values in the given AttributeSet.
3650     * <li>The style resource specified in the AttributeSet (named "style").
3651     * <li>The default style specified by <var>defStyleAttr</var>.
3652     * <li>The default style specified by <var>defStyleRes</var>.
3653     * <li>The base values in this theme.
3654     * </ol>
3655     * <p>
3656     * Each of these inputs is considered in-order, with the first listed taking
3657     * precedence over the following ones. In other words, if in the
3658     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3659     * , then the button's text will <em>always</em> be black, regardless of
3660     * what is specified in any of the styles.
3661     *
3662     * @param context The Context the view is running in, through which it can
3663     *        access the current theme, resources, etc.
3664     * @param attrs The attributes of the XML tag that is inflating the view.
3665     * @param defStyleAttr An attribute in the current theme that contains a
3666     *        reference to a style resource that supplies default values for
3667     *        the view. Can be 0 to not look for defaults.
3668     * @param defStyleRes A resource identifier of a style resource that
3669     *        supplies default values for the view, used only if
3670     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3671     *        to not look for defaults.
3672     * @see #View(Context, AttributeSet, int)
3673     */
3674    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3675        this(context);
3676
3677        final TypedArray a = context.obtainStyledAttributes(
3678                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3679
3680        if (mDebugViewAttributes) {
3681            saveAttributeData(attrs, a);
3682        }
3683
3684        Drawable background = null;
3685
3686        int leftPadding = -1;
3687        int topPadding = -1;
3688        int rightPadding = -1;
3689        int bottomPadding = -1;
3690        int startPadding = UNDEFINED_PADDING;
3691        int endPadding = UNDEFINED_PADDING;
3692
3693        int padding = -1;
3694
3695        int viewFlagValues = 0;
3696        int viewFlagMasks = 0;
3697
3698        boolean setScrollContainer = false;
3699
3700        int x = 0;
3701        int y = 0;
3702
3703        float tx = 0;
3704        float ty = 0;
3705        float tz = 0;
3706        float elevation = 0;
3707        float rotation = 0;
3708        float rotationX = 0;
3709        float rotationY = 0;
3710        float sx = 1f;
3711        float sy = 1f;
3712        boolean transformSet = false;
3713
3714        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3715        int overScrollMode = mOverScrollMode;
3716        boolean initializeScrollbars = false;
3717
3718        boolean startPaddingDefined = false;
3719        boolean endPaddingDefined = false;
3720        boolean leftPaddingDefined = false;
3721        boolean rightPaddingDefined = false;
3722
3723        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3724
3725        final int N = a.getIndexCount();
3726        for (int i = 0; i < N; i++) {
3727            int attr = a.getIndex(i);
3728            switch (attr) {
3729                case com.android.internal.R.styleable.View_background:
3730                    background = a.getDrawable(attr);
3731                    break;
3732                case com.android.internal.R.styleable.View_padding:
3733                    padding = a.getDimensionPixelSize(attr, -1);
3734                    mUserPaddingLeftInitial = padding;
3735                    mUserPaddingRightInitial = padding;
3736                    leftPaddingDefined = true;
3737                    rightPaddingDefined = true;
3738                    break;
3739                 case com.android.internal.R.styleable.View_paddingLeft:
3740                    leftPadding = a.getDimensionPixelSize(attr, -1);
3741                    mUserPaddingLeftInitial = leftPadding;
3742                    leftPaddingDefined = true;
3743                    break;
3744                case com.android.internal.R.styleable.View_paddingTop:
3745                    topPadding = a.getDimensionPixelSize(attr, -1);
3746                    break;
3747                case com.android.internal.R.styleable.View_paddingRight:
3748                    rightPadding = a.getDimensionPixelSize(attr, -1);
3749                    mUserPaddingRightInitial = rightPadding;
3750                    rightPaddingDefined = true;
3751                    break;
3752                case com.android.internal.R.styleable.View_paddingBottom:
3753                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3754                    break;
3755                case com.android.internal.R.styleable.View_paddingStart:
3756                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3757                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3758                    break;
3759                case com.android.internal.R.styleable.View_paddingEnd:
3760                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3761                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3762                    break;
3763                case com.android.internal.R.styleable.View_scrollX:
3764                    x = a.getDimensionPixelOffset(attr, 0);
3765                    break;
3766                case com.android.internal.R.styleable.View_scrollY:
3767                    y = a.getDimensionPixelOffset(attr, 0);
3768                    break;
3769                case com.android.internal.R.styleable.View_alpha:
3770                    setAlpha(a.getFloat(attr, 1f));
3771                    break;
3772                case com.android.internal.R.styleable.View_transformPivotX:
3773                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3774                    break;
3775                case com.android.internal.R.styleable.View_transformPivotY:
3776                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3777                    break;
3778                case com.android.internal.R.styleable.View_translationX:
3779                    tx = a.getDimensionPixelOffset(attr, 0);
3780                    transformSet = true;
3781                    break;
3782                case com.android.internal.R.styleable.View_translationY:
3783                    ty = a.getDimensionPixelOffset(attr, 0);
3784                    transformSet = true;
3785                    break;
3786                case com.android.internal.R.styleable.View_translationZ:
3787                    tz = a.getDimensionPixelOffset(attr, 0);
3788                    transformSet = true;
3789                    break;
3790                case com.android.internal.R.styleable.View_elevation:
3791                    elevation = a.getDimensionPixelOffset(attr, 0);
3792                    transformSet = true;
3793                    break;
3794                case com.android.internal.R.styleable.View_rotation:
3795                    rotation = a.getFloat(attr, 0);
3796                    transformSet = true;
3797                    break;
3798                case com.android.internal.R.styleable.View_rotationX:
3799                    rotationX = a.getFloat(attr, 0);
3800                    transformSet = true;
3801                    break;
3802                case com.android.internal.R.styleable.View_rotationY:
3803                    rotationY = a.getFloat(attr, 0);
3804                    transformSet = true;
3805                    break;
3806                case com.android.internal.R.styleable.View_scaleX:
3807                    sx = a.getFloat(attr, 1f);
3808                    transformSet = true;
3809                    break;
3810                case com.android.internal.R.styleable.View_scaleY:
3811                    sy = a.getFloat(attr, 1f);
3812                    transformSet = true;
3813                    break;
3814                case com.android.internal.R.styleable.View_id:
3815                    mID = a.getResourceId(attr, NO_ID);
3816                    break;
3817                case com.android.internal.R.styleable.View_tag:
3818                    mTag = a.getText(attr);
3819                    break;
3820                case com.android.internal.R.styleable.View_fitsSystemWindows:
3821                    if (a.getBoolean(attr, false)) {
3822                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3823                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3824                    }
3825                    break;
3826                case com.android.internal.R.styleable.View_focusable:
3827                    if (a.getBoolean(attr, false)) {
3828                        viewFlagValues |= FOCUSABLE;
3829                        viewFlagMasks |= FOCUSABLE_MASK;
3830                    }
3831                    break;
3832                case com.android.internal.R.styleable.View_focusableInTouchMode:
3833                    if (a.getBoolean(attr, false)) {
3834                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3835                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3836                    }
3837                    break;
3838                case com.android.internal.R.styleable.View_clickable:
3839                    if (a.getBoolean(attr, false)) {
3840                        viewFlagValues |= CLICKABLE;
3841                        viewFlagMasks |= CLICKABLE;
3842                    }
3843                    break;
3844                case com.android.internal.R.styleable.View_longClickable:
3845                    if (a.getBoolean(attr, false)) {
3846                        viewFlagValues |= LONG_CLICKABLE;
3847                        viewFlagMasks |= LONG_CLICKABLE;
3848                    }
3849                    break;
3850                case com.android.internal.R.styleable.View_saveEnabled:
3851                    if (!a.getBoolean(attr, true)) {
3852                        viewFlagValues |= SAVE_DISABLED;
3853                        viewFlagMasks |= SAVE_DISABLED_MASK;
3854                    }
3855                    break;
3856                case com.android.internal.R.styleable.View_duplicateParentState:
3857                    if (a.getBoolean(attr, false)) {
3858                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3859                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3860                    }
3861                    break;
3862                case com.android.internal.R.styleable.View_visibility:
3863                    final int visibility = a.getInt(attr, 0);
3864                    if (visibility != 0) {
3865                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3866                        viewFlagMasks |= VISIBILITY_MASK;
3867                    }
3868                    break;
3869                case com.android.internal.R.styleable.View_layoutDirection:
3870                    // Clear any layout direction flags (included resolved bits) already set
3871                    mPrivateFlags2 &=
3872                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3873                    // Set the layout direction flags depending on the value of the attribute
3874                    final int layoutDirection = a.getInt(attr, -1);
3875                    final int value = (layoutDirection != -1) ?
3876                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3877                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3878                    break;
3879                case com.android.internal.R.styleable.View_drawingCacheQuality:
3880                    final int cacheQuality = a.getInt(attr, 0);
3881                    if (cacheQuality != 0) {
3882                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3883                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3884                    }
3885                    break;
3886                case com.android.internal.R.styleable.View_contentDescription:
3887                    setContentDescription(a.getString(attr));
3888                    break;
3889                case com.android.internal.R.styleable.View_labelFor:
3890                    setLabelFor(a.getResourceId(attr, NO_ID));
3891                    break;
3892                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3893                    if (!a.getBoolean(attr, true)) {
3894                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3895                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3896                    }
3897                    break;
3898                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3899                    if (!a.getBoolean(attr, true)) {
3900                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3901                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3902                    }
3903                    break;
3904                case R.styleable.View_scrollbars:
3905                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3906                    if (scrollbars != SCROLLBARS_NONE) {
3907                        viewFlagValues |= scrollbars;
3908                        viewFlagMasks |= SCROLLBARS_MASK;
3909                        initializeScrollbars = true;
3910                    }
3911                    break;
3912                //noinspection deprecation
3913                case R.styleable.View_fadingEdge:
3914                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3915                        // Ignore the attribute starting with ICS
3916                        break;
3917                    }
3918                    // With builds < ICS, fall through and apply fading edges
3919                case R.styleable.View_requiresFadingEdge:
3920                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3921                    if (fadingEdge != FADING_EDGE_NONE) {
3922                        viewFlagValues |= fadingEdge;
3923                        viewFlagMasks |= FADING_EDGE_MASK;
3924                        initializeFadingEdgeInternal(a);
3925                    }
3926                    break;
3927                case R.styleable.View_scrollbarStyle:
3928                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3929                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3930                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3931                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3932                    }
3933                    break;
3934                case R.styleable.View_isScrollContainer:
3935                    setScrollContainer = true;
3936                    if (a.getBoolean(attr, false)) {
3937                        setScrollContainer(true);
3938                    }
3939                    break;
3940                case com.android.internal.R.styleable.View_keepScreenOn:
3941                    if (a.getBoolean(attr, false)) {
3942                        viewFlagValues |= KEEP_SCREEN_ON;
3943                        viewFlagMasks |= KEEP_SCREEN_ON;
3944                    }
3945                    break;
3946                case R.styleable.View_filterTouchesWhenObscured:
3947                    if (a.getBoolean(attr, false)) {
3948                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3949                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3950                    }
3951                    break;
3952                case R.styleable.View_nextFocusLeft:
3953                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3954                    break;
3955                case R.styleable.View_nextFocusRight:
3956                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3957                    break;
3958                case R.styleable.View_nextFocusUp:
3959                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3960                    break;
3961                case R.styleable.View_nextFocusDown:
3962                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3963                    break;
3964                case R.styleable.View_nextFocusForward:
3965                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3966                    break;
3967                case R.styleable.View_minWidth:
3968                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3969                    break;
3970                case R.styleable.View_minHeight:
3971                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3972                    break;
3973                case R.styleable.View_onClick:
3974                    if (context.isRestricted()) {
3975                        throw new IllegalStateException("The android:onClick attribute cannot "
3976                                + "be used within a restricted context");
3977                    }
3978
3979                    final String handlerName = a.getString(attr);
3980                    if (handlerName != null) {
3981                        setOnClickListener(new OnClickListener() {
3982                            private Method mHandler;
3983
3984                            public void onClick(View v) {
3985                                if (mHandler == null) {
3986                                    try {
3987                                        mHandler = getContext().getClass().getMethod(handlerName,
3988                                                View.class);
3989                                    } catch (NoSuchMethodException e) {
3990                                        int id = getId();
3991                                        String idText = id == NO_ID ? "" : " with id '"
3992                                                + getContext().getResources().getResourceEntryName(
3993                                                    id) + "'";
3994                                        throw new IllegalStateException("Could not find a method " +
3995                                                handlerName + "(View) in the activity "
3996                                                + getContext().getClass() + " for onClick handler"
3997                                                + " on view " + View.this.getClass() + idText, e);
3998                                    }
3999                                }
4000
4001                                try {
4002                                    mHandler.invoke(getContext(), View.this);
4003                                } catch (IllegalAccessException e) {
4004                                    throw new IllegalStateException("Could not execute non "
4005                                            + "public method of the activity", e);
4006                                } catch (InvocationTargetException e) {
4007                                    throw new IllegalStateException("Could not execute "
4008                                            + "method of the activity", e);
4009                                }
4010                            }
4011                        });
4012                    }
4013                    break;
4014                case R.styleable.View_overScrollMode:
4015                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4016                    break;
4017                case R.styleable.View_verticalScrollbarPosition:
4018                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4019                    break;
4020                case R.styleable.View_layerType:
4021                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4022                    break;
4023                case R.styleable.View_textDirection:
4024                    // Clear any text direction flag already set
4025                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4026                    // Set the text direction flags depending on the value of the attribute
4027                    final int textDirection = a.getInt(attr, -1);
4028                    if (textDirection != -1) {
4029                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4030                    }
4031                    break;
4032                case R.styleable.View_textAlignment:
4033                    // Clear any text alignment flag already set
4034                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4035                    // Set the text alignment flag depending on the value of the attribute
4036                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4037                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4038                    break;
4039                case R.styleable.View_importantForAccessibility:
4040                    setImportantForAccessibility(a.getInt(attr,
4041                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4042                    break;
4043                case R.styleable.View_accessibilityLiveRegion:
4044                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4045                    break;
4046                case R.styleable.View_transitionName:
4047                    setTransitionName(a.getString(attr));
4048                    break;
4049                case R.styleable.View_nestedScrollingEnabled:
4050                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4051                    break;
4052                case R.styleable.View_stateListAnimator:
4053                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4054                            a.getResourceId(attr, 0)));
4055                    break;
4056                case R.styleable.View_backgroundTint:
4057                    // This will get applied later during setBackground().
4058                    if (mBackgroundTint == null) {
4059                        mBackgroundTint = new TintInfo();
4060                    }
4061                    mBackgroundTint.mTintList = a.getColorStateList(
4062                            R.styleable.View_backgroundTint);
4063                    mBackgroundTint.mHasTintList = true;
4064                    break;
4065                case R.styleable.View_backgroundTintMode:
4066                    // This will get applied later during setBackground().
4067                    if (mBackgroundTint == null) {
4068                        mBackgroundTint = new TintInfo();
4069                    }
4070                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4071                            R.styleable.View_backgroundTintMode, -1), null);
4072                    mBackgroundTint.mHasTintMode = true;
4073                    break;
4074                case R.styleable.View_outlineProvider:
4075                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4076                            PROVIDER_BACKGROUND));
4077                    break;
4078            }
4079        }
4080
4081        setOverScrollMode(overScrollMode);
4082
4083        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4084        // the resolved layout direction). Those cached values will be used later during padding
4085        // resolution.
4086        mUserPaddingStart = startPadding;
4087        mUserPaddingEnd = endPadding;
4088
4089        if (background != null) {
4090            setBackground(background);
4091        }
4092
4093        // setBackground above will record that padding is currently provided by the background.
4094        // If we have padding specified via xml, record that here instead and use it.
4095        mLeftPaddingDefined = leftPaddingDefined;
4096        mRightPaddingDefined = rightPaddingDefined;
4097
4098        if (padding >= 0) {
4099            leftPadding = padding;
4100            topPadding = padding;
4101            rightPadding = padding;
4102            bottomPadding = padding;
4103            mUserPaddingLeftInitial = padding;
4104            mUserPaddingRightInitial = padding;
4105        }
4106
4107        if (isRtlCompatibilityMode()) {
4108            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4109            // left / right padding are used if defined (meaning here nothing to do). If they are not
4110            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4111            // start / end and resolve them as left / right (layout direction is not taken into account).
4112            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4113            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4114            // defined.
4115            if (!mLeftPaddingDefined && startPaddingDefined) {
4116                leftPadding = startPadding;
4117            }
4118            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4119            if (!mRightPaddingDefined && endPaddingDefined) {
4120                rightPadding = endPadding;
4121            }
4122            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4123        } else {
4124            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4125            // values defined. Otherwise, left /right values are used.
4126            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4127            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4128            // defined.
4129            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4130
4131            if (mLeftPaddingDefined && !hasRelativePadding) {
4132                mUserPaddingLeftInitial = leftPadding;
4133            }
4134            if (mRightPaddingDefined && !hasRelativePadding) {
4135                mUserPaddingRightInitial = rightPadding;
4136            }
4137        }
4138
4139        internalSetPadding(
4140                mUserPaddingLeftInitial,
4141                topPadding >= 0 ? topPadding : mPaddingTop,
4142                mUserPaddingRightInitial,
4143                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4144
4145        if (viewFlagMasks != 0) {
4146            setFlags(viewFlagValues, viewFlagMasks);
4147        }
4148
4149        if (initializeScrollbars) {
4150            initializeScrollbarsInternal(a);
4151        }
4152
4153        a.recycle();
4154
4155        // Needs to be called after mViewFlags is set
4156        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4157            recomputePadding();
4158        }
4159
4160        if (x != 0 || y != 0) {
4161            scrollTo(x, y);
4162        }
4163
4164        if (transformSet) {
4165            setTranslationX(tx);
4166            setTranslationY(ty);
4167            setTranslationZ(tz);
4168            setElevation(elevation);
4169            setRotation(rotation);
4170            setRotationX(rotationX);
4171            setRotationY(rotationY);
4172            setScaleX(sx);
4173            setScaleY(sy);
4174        }
4175
4176        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4177            setScrollContainer(true);
4178        }
4179
4180        computeOpaqueFlags();
4181    }
4182
4183    /**
4184     * Non-public constructor for use in testing
4185     */
4186    View() {
4187        mResources = null;
4188        mRenderNode = RenderNode.create(getClass().getName(), this);
4189    }
4190
4191    private static SparseArray<String> getAttributeMap() {
4192        if (mAttributeMap == null) {
4193            mAttributeMap = new SparseArray<String>();
4194        }
4195        return mAttributeMap;
4196    }
4197
4198    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4199        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4200        mAttributes = new String[length];
4201
4202        int i = 0;
4203        if (attrs != null) {
4204            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4205                mAttributes[i] = attrs.getAttributeName(i);
4206                mAttributes[i + 1] = attrs.getAttributeValue(i);
4207            }
4208
4209        }
4210
4211        SparseArray<String> attributeMap = getAttributeMap();
4212        for (int j = 0; j < a.length(); ++j) {
4213            if (a.hasValue(j)) {
4214                try {
4215                    int resourceId = a.getResourceId(j, 0);
4216                    if (resourceId == 0) {
4217                        continue;
4218                    }
4219
4220                    String resourceName = attributeMap.get(resourceId);
4221                    if (resourceName == null) {
4222                        resourceName = a.getResources().getResourceName(resourceId);
4223                        attributeMap.put(resourceId, resourceName);
4224                    }
4225
4226                    mAttributes[i] = resourceName;
4227                    mAttributes[i + 1] = a.getText(j).toString();
4228                    i += 2;
4229                } catch (Resources.NotFoundException e) {
4230                    // if we can't get the resource name, we just ignore it
4231                }
4232            }
4233        }
4234    }
4235
4236    public String toString() {
4237        StringBuilder out = new StringBuilder(128);
4238        out.append(getClass().getName());
4239        out.append('{');
4240        out.append(Integer.toHexString(System.identityHashCode(this)));
4241        out.append(' ');
4242        switch (mViewFlags&VISIBILITY_MASK) {
4243            case VISIBLE: out.append('V'); break;
4244            case INVISIBLE: out.append('I'); break;
4245            case GONE: out.append('G'); break;
4246            default: out.append('.'); break;
4247        }
4248        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4249        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4250        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4251        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4252        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4253        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4254        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4255        out.append(' ');
4256        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4257        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4258        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4259        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4260            out.append('p');
4261        } else {
4262            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4263        }
4264        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4265        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4266        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4267        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4268        out.append(' ');
4269        out.append(mLeft);
4270        out.append(',');
4271        out.append(mTop);
4272        out.append('-');
4273        out.append(mRight);
4274        out.append(',');
4275        out.append(mBottom);
4276        final int id = getId();
4277        if (id != NO_ID) {
4278            out.append(" #");
4279            out.append(Integer.toHexString(id));
4280            final Resources r = mResources;
4281            if (Resources.resourceHasPackage(id) && r != null) {
4282                try {
4283                    String pkgname;
4284                    switch (id&0xff000000) {
4285                        case 0x7f000000:
4286                            pkgname="app";
4287                            break;
4288                        case 0x01000000:
4289                            pkgname="android";
4290                            break;
4291                        default:
4292                            pkgname = r.getResourcePackageName(id);
4293                            break;
4294                    }
4295                    String typename = r.getResourceTypeName(id);
4296                    String entryname = r.getResourceEntryName(id);
4297                    out.append(" ");
4298                    out.append(pkgname);
4299                    out.append(":");
4300                    out.append(typename);
4301                    out.append("/");
4302                    out.append(entryname);
4303                } catch (Resources.NotFoundException e) {
4304                }
4305            }
4306        }
4307        out.append("}");
4308        return out.toString();
4309    }
4310
4311    /**
4312     * <p>
4313     * Initializes the fading edges from a given set of styled attributes. This
4314     * method should be called by subclasses that need fading edges and when an
4315     * instance of these subclasses is created programmatically rather than
4316     * being inflated from XML. This method is automatically called when the XML
4317     * is inflated.
4318     * </p>
4319     *
4320     * @param a the styled attributes set to initialize the fading edges from
4321     *
4322     * @removed
4323     */
4324    protected void initializeFadingEdge(TypedArray a) {
4325        // This method probably shouldn't have been included in the SDK to begin with.
4326        // It relies on 'a' having been initialized using an attribute filter array that is
4327        // not publicly available to the SDK. The old method has been renamed
4328        // to initializeFadingEdgeInternal and hidden for framework use only;
4329        // this one initializes using defaults to make it safe to call for apps.
4330
4331        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4332
4333        initializeFadingEdgeInternal(arr);
4334
4335        arr.recycle();
4336    }
4337
4338    /**
4339     * <p>
4340     * Initializes the fading edges from a given set of styled attributes. This
4341     * method should be called by subclasses that need fading edges and when an
4342     * instance of these subclasses is created programmatically rather than
4343     * being inflated from XML. This method is automatically called when the XML
4344     * is inflated.
4345     * </p>
4346     *
4347     * @param a the styled attributes set to initialize the fading edges from
4348     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4349     */
4350    protected void initializeFadingEdgeInternal(TypedArray a) {
4351        initScrollCache();
4352
4353        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4354                R.styleable.View_fadingEdgeLength,
4355                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4356    }
4357
4358    /**
4359     * Returns the size of the vertical faded edges used to indicate that more
4360     * content in this view is visible.
4361     *
4362     * @return The size in pixels of the vertical faded edge or 0 if vertical
4363     *         faded edges are not enabled for this view.
4364     * @attr ref android.R.styleable#View_fadingEdgeLength
4365     */
4366    public int getVerticalFadingEdgeLength() {
4367        if (isVerticalFadingEdgeEnabled()) {
4368            ScrollabilityCache cache = mScrollCache;
4369            if (cache != null) {
4370                return cache.fadingEdgeLength;
4371            }
4372        }
4373        return 0;
4374    }
4375
4376    /**
4377     * Set the size of the faded edge used to indicate that more content in this
4378     * view is available.  Will not change whether the fading edge is enabled; use
4379     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4380     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4381     * for the vertical or horizontal fading edges.
4382     *
4383     * @param length The size in pixels of the faded edge used to indicate that more
4384     *        content in this view is visible.
4385     */
4386    public void setFadingEdgeLength(int length) {
4387        initScrollCache();
4388        mScrollCache.fadingEdgeLength = length;
4389    }
4390
4391    /**
4392     * Returns the size of the horizontal faded edges used to indicate that more
4393     * content in this view is visible.
4394     *
4395     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4396     *         faded edges are not enabled for this view.
4397     * @attr ref android.R.styleable#View_fadingEdgeLength
4398     */
4399    public int getHorizontalFadingEdgeLength() {
4400        if (isHorizontalFadingEdgeEnabled()) {
4401            ScrollabilityCache cache = mScrollCache;
4402            if (cache != null) {
4403                return cache.fadingEdgeLength;
4404            }
4405        }
4406        return 0;
4407    }
4408
4409    /**
4410     * Returns the width of the vertical scrollbar.
4411     *
4412     * @return The width in pixels of the vertical scrollbar or 0 if there
4413     *         is no vertical scrollbar.
4414     */
4415    public int getVerticalScrollbarWidth() {
4416        ScrollabilityCache cache = mScrollCache;
4417        if (cache != null) {
4418            ScrollBarDrawable scrollBar = cache.scrollBar;
4419            if (scrollBar != null) {
4420                int size = scrollBar.getSize(true);
4421                if (size <= 0) {
4422                    size = cache.scrollBarSize;
4423                }
4424                return size;
4425            }
4426            return 0;
4427        }
4428        return 0;
4429    }
4430
4431    /**
4432     * Returns the height of the horizontal scrollbar.
4433     *
4434     * @return The height in pixels of the horizontal scrollbar or 0 if
4435     *         there is no horizontal scrollbar.
4436     */
4437    protected int getHorizontalScrollbarHeight() {
4438        ScrollabilityCache cache = mScrollCache;
4439        if (cache != null) {
4440            ScrollBarDrawable scrollBar = cache.scrollBar;
4441            if (scrollBar != null) {
4442                int size = scrollBar.getSize(false);
4443                if (size <= 0) {
4444                    size = cache.scrollBarSize;
4445                }
4446                return size;
4447            }
4448            return 0;
4449        }
4450        return 0;
4451    }
4452
4453    /**
4454     * <p>
4455     * Initializes the scrollbars from a given set of styled attributes. This
4456     * method should be called by subclasses that need scrollbars and when an
4457     * instance of these subclasses is created programmatically rather than
4458     * being inflated from XML. This method is automatically called when the XML
4459     * is inflated.
4460     * </p>
4461     *
4462     * @param a the styled attributes set to initialize the scrollbars from
4463     *
4464     * @removed
4465     */
4466    protected void initializeScrollbars(TypedArray a) {
4467        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4468        // using the View filter array which is not available to the SDK. As such, internal
4469        // framework usage now uses initializeScrollbarsInternal and we grab a default
4470        // TypedArray with the right filter instead here.
4471        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4472
4473        initializeScrollbarsInternal(arr);
4474
4475        // We ignored the method parameter. Recycle the one we actually did use.
4476        arr.recycle();
4477    }
4478
4479    /**
4480     * <p>
4481     * Initializes the scrollbars from a given set of styled attributes. This
4482     * method should be called by subclasses that need scrollbars and when an
4483     * instance of these subclasses is created programmatically rather than
4484     * being inflated from XML. This method is automatically called when the XML
4485     * is inflated.
4486     * </p>
4487     *
4488     * @param a the styled attributes set to initialize the scrollbars from
4489     * @hide
4490     */
4491    protected void initializeScrollbarsInternal(TypedArray a) {
4492        initScrollCache();
4493
4494        final ScrollabilityCache scrollabilityCache = mScrollCache;
4495
4496        if (scrollabilityCache.scrollBar == null) {
4497            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4498        }
4499
4500        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4501
4502        if (!fadeScrollbars) {
4503            scrollabilityCache.state = ScrollabilityCache.ON;
4504        }
4505        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4506
4507
4508        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4509                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4510                        .getScrollBarFadeDuration());
4511        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4512                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4513                ViewConfiguration.getScrollDefaultDelay());
4514
4515
4516        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4517                com.android.internal.R.styleable.View_scrollbarSize,
4518                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4519
4520        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4521        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4522
4523        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4524        if (thumb != null) {
4525            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4526        }
4527
4528        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4529                false);
4530        if (alwaysDraw) {
4531            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4532        }
4533
4534        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4535        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4536
4537        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4538        if (thumb != null) {
4539            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4540        }
4541
4542        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4543                false);
4544        if (alwaysDraw) {
4545            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4546        }
4547
4548        // Apply layout direction to the new Drawables if needed
4549        final int layoutDirection = getLayoutDirection();
4550        if (track != null) {
4551            track.setLayoutDirection(layoutDirection);
4552        }
4553        if (thumb != null) {
4554            thumb.setLayoutDirection(layoutDirection);
4555        }
4556
4557        // Re-apply user/background padding so that scrollbar(s) get added
4558        resolvePadding();
4559    }
4560
4561    /**
4562     * <p>
4563     * Initalizes the scrollability cache if necessary.
4564     * </p>
4565     */
4566    private void initScrollCache() {
4567        if (mScrollCache == null) {
4568            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4569        }
4570    }
4571
4572    private ScrollabilityCache getScrollCache() {
4573        initScrollCache();
4574        return mScrollCache;
4575    }
4576
4577    /**
4578     * Set the position of the vertical scroll bar. Should be one of
4579     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4580     * {@link #SCROLLBAR_POSITION_RIGHT}.
4581     *
4582     * @param position Where the vertical scroll bar should be positioned.
4583     */
4584    public void setVerticalScrollbarPosition(int position) {
4585        if (mVerticalScrollbarPosition != position) {
4586            mVerticalScrollbarPosition = position;
4587            computeOpaqueFlags();
4588            resolvePadding();
4589        }
4590    }
4591
4592    /**
4593     * @return The position where the vertical scroll bar will show, if applicable.
4594     * @see #setVerticalScrollbarPosition(int)
4595     */
4596    public int getVerticalScrollbarPosition() {
4597        return mVerticalScrollbarPosition;
4598    }
4599
4600    ListenerInfo getListenerInfo() {
4601        if (mListenerInfo != null) {
4602            return mListenerInfo;
4603        }
4604        mListenerInfo = new ListenerInfo();
4605        return mListenerInfo;
4606    }
4607
4608    /**
4609     * Register a callback to be invoked when focus of this view changed.
4610     *
4611     * @param l The callback that will run.
4612     */
4613    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4614        getListenerInfo().mOnFocusChangeListener = l;
4615    }
4616
4617    /**
4618     * Add a listener that will be called when the bounds of the view change due to
4619     * layout processing.
4620     *
4621     * @param listener The listener that will be called when layout bounds change.
4622     */
4623    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4624        ListenerInfo li = getListenerInfo();
4625        if (li.mOnLayoutChangeListeners == null) {
4626            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4627        }
4628        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4629            li.mOnLayoutChangeListeners.add(listener);
4630        }
4631    }
4632
4633    /**
4634     * Remove a listener for layout changes.
4635     *
4636     * @param listener The listener for layout bounds change.
4637     */
4638    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4639        ListenerInfo li = mListenerInfo;
4640        if (li == null || li.mOnLayoutChangeListeners == null) {
4641            return;
4642        }
4643        li.mOnLayoutChangeListeners.remove(listener);
4644    }
4645
4646    /**
4647     * Add a listener for attach state changes.
4648     *
4649     * This listener will be called whenever this view is attached or detached
4650     * from a window. Remove the listener using
4651     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4652     *
4653     * @param listener Listener to attach
4654     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4655     */
4656    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4657        ListenerInfo li = getListenerInfo();
4658        if (li.mOnAttachStateChangeListeners == null) {
4659            li.mOnAttachStateChangeListeners
4660                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4661        }
4662        li.mOnAttachStateChangeListeners.add(listener);
4663    }
4664
4665    /**
4666     * Remove a listener for attach state changes. The listener will receive no further
4667     * notification of window attach/detach events.
4668     *
4669     * @param listener Listener to remove
4670     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4671     */
4672    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4673        ListenerInfo li = mListenerInfo;
4674        if (li == null || li.mOnAttachStateChangeListeners == null) {
4675            return;
4676        }
4677        li.mOnAttachStateChangeListeners.remove(listener);
4678    }
4679
4680    /**
4681     * Returns the focus-change callback registered for this view.
4682     *
4683     * @return The callback, or null if one is not registered.
4684     */
4685    public OnFocusChangeListener getOnFocusChangeListener() {
4686        ListenerInfo li = mListenerInfo;
4687        return li != null ? li.mOnFocusChangeListener : null;
4688    }
4689
4690    /**
4691     * Register a callback to be invoked when this view is clicked. If this view is not
4692     * clickable, it becomes clickable.
4693     *
4694     * @param l The callback that will run
4695     *
4696     * @see #setClickable(boolean)
4697     */
4698    public void setOnClickListener(OnClickListener l) {
4699        if (!isClickable()) {
4700            setClickable(true);
4701        }
4702        getListenerInfo().mOnClickListener = l;
4703    }
4704
4705    /**
4706     * Return whether this view has an attached OnClickListener.  Returns
4707     * true if there is a listener, false if there is none.
4708     */
4709    public boolean hasOnClickListeners() {
4710        ListenerInfo li = mListenerInfo;
4711        return (li != null && li.mOnClickListener != null);
4712    }
4713
4714    /**
4715     * Register a callback to be invoked when this view is clicked and held. If this view is not
4716     * long clickable, it becomes long clickable.
4717     *
4718     * @param l The callback that will run
4719     *
4720     * @see #setLongClickable(boolean)
4721     */
4722    public void setOnLongClickListener(OnLongClickListener l) {
4723        if (!isLongClickable()) {
4724            setLongClickable(true);
4725        }
4726        getListenerInfo().mOnLongClickListener = l;
4727    }
4728
4729    /**
4730     * Register a callback to be invoked when the context menu for this view is
4731     * being built. If this view is not long clickable, it becomes long clickable.
4732     *
4733     * @param l The callback that will run
4734     *
4735     */
4736    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4737        if (!isLongClickable()) {
4738            setLongClickable(true);
4739        }
4740        getListenerInfo().mOnCreateContextMenuListener = l;
4741    }
4742
4743    /**
4744     * Call this view's OnClickListener, if it is defined.  Performs all normal
4745     * actions associated with clicking: reporting accessibility event, playing
4746     * a sound, etc.
4747     *
4748     * @return True there was an assigned OnClickListener that was called, false
4749     *         otherwise is returned.
4750     */
4751    public boolean performClick() {
4752        final boolean result;
4753        final ListenerInfo li = mListenerInfo;
4754        if (li != null && li.mOnClickListener != null) {
4755            playSoundEffect(SoundEffectConstants.CLICK);
4756            li.mOnClickListener.onClick(this);
4757            result = true;
4758        } else {
4759            result = false;
4760        }
4761
4762        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4763        return result;
4764    }
4765
4766    /**
4767     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4768     * this only calls the listener, and does not do any associated clicking
4769     * actions like reporting an accessibility event.
4770     *
4771     * @return True there was an assigned OnClickListener that was called, false
4772     *         otherwise is returned.
4773     */
4774    public boolean callOnClick() {
4775        ListenerInfo li = mListenerInfo;
4776        if (li != null && li.mOnClickListener != null) {
4777            li.mOnClickListener.onClick(this);
4778            return true;
4779        }
4780        return false;
4781    }
4782
4783    /**
4784     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4785     * OnLongClickListener did not consume the event.
4786     *
4787     * @return True if one of the above receivers consumed the event, false otherwise.
4788     */
4789    public boolean performLongClick() {
4790        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4791
4792        boolean handled = false;
4793        ListenerInfo li = mListenerInfo;
4794        if (li != null && li.mOnLongClickListener != null) {
4795            handled = li.mOnLongClickListener.onLongClick(View.this);
4796        }
4797        if (!handled) {
4798            handled = showContextMenu();
4799        }
4800        if (handled) {
4801            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4802        }
4803        return handled;
4804    }
4805
4806    /**
4807     * Performs button-related actions during a touch down event.
4808     *
4809     * @param event The event.
4810     * @return True if the down was consumed.
4811     *
4812     * @hide
4813     */
4814    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4815        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4816            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4817                return true;
4818            }
4819        }
4820        return false;
4821    }
4822
4823    /**
4824     * Bring up the context menu for this view.
4825     *
4826     * @return Whether a context menu was displayed.
4827     */
4828    public boolean showContextMenu() {
4829        return getParent().showContextMenuForChild(this);
4830    }
4831
4832    /**
4833     * Bring up the context menu for this view, referring to the item under the specified point.
4834     *
4835     * @param x The referenced x coordinate.
4836     * @param y The referenced y coordinate.
4837     * @param metaState The keyboard modifiers that were pressed.
4838     * @return Whether a context menu was displayed.
4839     *
4840     * @hide
4841     */
4842    public boolean showContextMenu(float x, float y, int metaState) {
4843        return showContextMenu();
4844    }
4845
4846    /**
4847     * Start an action mode.
4848     *
4849     * @param callback Callback that will control the lifecycle of the action mode
4850     * @return The new action mode if it is started, null otherwise
4851     *
4852     * @see ActionMode
4853     */
4854    public ActionMode startActionMode(ActionMode.Callback callback) {
4855        ViewParent parent = getParent();
4856        if (parent == null) return null;
4857        return parent.startActionModeForChild(this, callback);
4858    }
4859
4860    /**
4861     * Register a callback to be invoked when a hardware key is pressed in this view.
4862     * Key presses in software input methods will generally not trigger the methods of
4863     * this listener.
4864     * @param l the key listener to attach to this view
4865     */
4866    public void setOnKeyListener(OnKeyListener l) {
4867        getListenerInfo().mOnKeyListener = l;
4868    }
4869
4870    /**
4871     * Register a callback to be invoked when a touch event is sent to this view.
4872     * @param l the touch listener to attach to this view
4873     */
4874    public void setOnTouchListener(OnTouchListener l) {
4875        getListenerInfo().mOnTouchListener = l;
4876    }
4877
4878    /**
4879     * Register a callback to be invoked when a generic motion event is sent to this view.
4880     * @param l the generic motion listener to attach to this view
4881     */
4882    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4883        getListenerInfo().mOnGenericMotionListener = l;
4884    }
4885
4886    /**
4887     * Register a callback to be invoked when a hover event is sent to this view.
4888     * @param l the hover listener to attach to this view
4889     */
4890    public void setOnHoverListener(OnHoverListener l) {
4891        getListenerInfo().mOnHoverListener = l;
4892    }
4893
4894    /**
4895     * Register a drag event listener callback object for this View. The parameter is
4896     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4897     * View, the system calls the
4898     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4899     * @param l An implementation of {@link android.view.View.OnDragListener}.
4900     */
4901    public void setOnDragListener(OnDragListener l) {
4902        getListenerInfo().mOnDragListener = l;
4903    }
4904
4905    /**
4906     * Give this view focus. This will cause
4907     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4908     *
4909     * Note: this does not check whether this {@link View} should get focus, it just
4910     * gives it focus no matter what.  It should only be called internally by framework
4911     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4912     *
4913     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4914     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4915     *        focus moved when requestFocus() is called. It may not always
4916     *        apply, in which case use the default View.FOCUS_DOWN.
4917     * @param previouslyFocusedRect The rectangle of the view that had focus
4918     *        prior in this View's coordinate system.
4919     */
4920    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4921        if (DBG) {
4922            System.out.println(this + " requestFocus()");
4923        }
4924
4925        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4926            mPrivateFlags |= PFLAG_FOCUSED;
4927
4928            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4929
4930            if (mParent != null) {
4931                mParent.requestChildFocus(this, this);
4932            }
4933
4934            if (mAttachInfo != null) {
4935                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4936            }
4937
4938            onFocusChanged(true, direction, previouslyFocusedRect);
4939            refreshDrawableState();
4940        }
4941    }
4942
4943    /**
4944     * Populates <code>outRect</code> with the hotspot bounds. By default,
4945     * the hotspot bounds are identical to the screen bounds.
4946     *
4947     * @param outRect rect to populate with hotspot bounds
4948     * @hide Only for internal use by views and widgets.
4949     */
4950    public void getHotspotBounds(Rect outRect) {
4951        final Drawable background = getBackground();
4952        if (background != null) {
4953            background.getHotspotBounds(outRect);
4954        } else {
4955            getBoundsOnScreen(outRect);
4956        }
4957    }
4958
4959    /**
4960     * Request that a rectangle of this view be visible on the screen,
4961     * scrolling if necessary just enough.
4962     *
4963     * <p>A View should call this if it maintains some notion of which part
4964     * of its content is interesting.  For example, a text editing view
4965     * should call this when its cursor moves.
4966     *
4967     * @param rectangle The rectangle.
4968     * @return Whether any parent scrolled.
4969     */
4970    public boolean requestRectangleOnScreen(Rect rectangle) {
4971        return requestRectangleOnScreen(rectangle, false);
4972    }
4973
4974    /**
4975     * Request that a rectangle of this view be visible on the screen,
4976     * scrolling if necessary just enough.
4977     *
4978     * <p>A View should call this if it maintains some notion of which part
4979     * of its content is interesting.  For example, a text editing view
4980     * should call this when its cursor moves.
4981     *
4982     * <p>When <code>immediate</code> is set to true, scrolling will not be
4983     * animated.
4984     *
4985     * @param rectangle The rectangle.
4986     * @param immediate True to forbid animated scrolling, false otherwise
4987     * @return Whether any parent scrolled.
4988     */
4989    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4990        if (mParent == null) {
4991            return false;
4992        }
4993
4994        View child = this;
4995
4996        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4997        position.set(rectangle);
4998
4999        ViewParent parent = mParent;
5000        boolean scrolled = false;
5001        while (parent != null) {
5002            rectangle.set((int) position.left, (int) position.top,
5003                    (int) position.right, (int) position.bottom);
5004
5005            scrolled |= parent.requestChildRectangleOnScreen(child,
5006                    rectangle, immediate);
5007
5008            if (!child.hasIdentityMatrix()) {
5009                child.getMatrix().mapRect(position);
5010            }
5011
5012            position.offset(child.mLeft, child.mTop);
5013
5014            if (!(parent instanceof View)) {
5015                break;
5016            }
5017
5018            View parentView = (View) parent;
5019
5020            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5021
5022            child = parentView;
5023            parent = child.getParent();
5024        }
5025
5026        return scrolled;
5027    }
5028
5029    /**
5030     * Called when this view wants to give up focus. If focus is cleared
5031     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5032     * <p>
5033     * <strong>Note:</strong> When a View clears focus the framework is trying
5034     * to give focus to the first focusable View from the top. Hence, if this
5035     * View is the first from the top that can take focus, then all callbacks
5036     * related to clearing focus will be invoked after which the framework will
5037     * give focus to this view.
5038     * </p>
5039     */
5040    public void clearFocus() {
5041        if (DBG) {
5042            System.out.println(this + " clearFocus()");
5043        }
5044
5045        clearFocusInternal(null, true, true);
5046    }
5047
5048    /**
5049     * Clears focus from the view, optionally propagating the change up through
5050     * the parent hierarchy and requesting that the root view place new focus.
5051     *
5052     * @param propagate whether to propagate the change up through the parent
5053     *            hierarchy
5054     * @param refocus when propagate is true, specifies whether to request the
5055     *            root view place new focus
5056     */
5057    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5058        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5059            mPrivateFlags &= ~PFLAG_FOCUSED;
5060
5061            if (propagate && mParent != null) {
5062                mParent.clearChildFocus(this);
5063            }
5064
5065            onFocusChanged(false, 0, null);
5066            refreshDrawableState();
5067
5068            if (propagate && (!refocus || !rootViewRequestFocus())) {
5069                notifyGlobalFocusCleared(this);
5070            }
5071        }
5072    }
5073
5074    void notifyGlobalFocusCleared(View oldFocus) {
5075        if (oldFocus != null && mAttachInfo != null) {
5076            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5077        }
5078    }
5079
5080    boolean rootViewRequestFocus() {
5081        final View root = getRootView();
5082        return root != null && root.requestFocus();
5083    }
5084
5085    /**
5086     * Called internally by the view system when a new view is getting focus.
5087     * This is what clears the old focus.
5088     * <p>
5089     * <b>NOTE:</b> The parent view's focused child must be updated manually
5090     * after calling this method. Otherwise, the view hierarchy may be left in
5091     * an inconstent state.
5092     */
5093    void unFocus(View focused) {
5094        if (DBG) {
5095            System.out.println(this + " unFocus()");
5096        }
5097
5098        clearFocusInternal(focused, false, false);
5099    }
5100
5101    /**
5102     * Returns true if this view has focus iteself, or is the ancestor of the
5103     * view that has focus.
5104     *
5105     * @return True if this view has or contains focus, false otherwise.
5106     */
5107    @ViewDebug.ExportedProperty(category = "focus")
5108    public boolean hasFocus() {
5109        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5110    }
5111
5112    /**
5113     * Returns true if this view is focusable or if it contains a reachable View
5114     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5115     * is a View whose parents do not block descendants focus.
5116     *
5117     * Only {@link #VISIBLE} views are considered focusable.
5118     *
5119     * @return True if the view is focusable or if the view contains a focusable
5120     *         View, false otherwise.
5121     *
5122     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5123     * @see ViewGroup#getTouchscreenBlocksFocus()
5124     */
5125    public boolean hasFocusable() {
5126        if (!isFocusableInTouchMode()) {
5127            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5128                final ViewGroup g = (ViewGroup) p;
5129                if (g.shouldBlockFocusForTouchscreen()) {
5130                    return false;
5131                }
5132            }
5133        }
5134        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5135    }
5136
5137    /**
5138     * Called by the view system when the focus state of this view changes.
5139     * When the focus change event is caused by directional navigation, direction
5140     * and previouslyFocusedRect provide insight into where the focus is coming from.
5141     * When overriding, be sure to call up through to the super class so that
5142     * the standard focus handling will occur.
5143     *
5144     * @param gainFocus True if the View has focus; false otherwise.
5145     * @param direction The direction focus has moved when requestFocus()
5146     *                  is called to give this view focus. Values are
5147     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5148     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5149     *                  It may not always apply, in which case use the default.
5150     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5151     *        system, of the previously focused view.  If applicable, this will be
5152     *        passed in as finer grained information about where the focus is coming
5153     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5154     */
5155    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5156            @Nullable Rect previouslyFocusedRect) {
5157        if (gainFocus) {
5158            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5159        } else {
5160            notifyViewAccessibilityStateChangedIfNeeded(
5161                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5162        }
5163
5164        InputMethodManager imm = InputMethodManager.peekInstance();
5165        if (!gainFocus) {
5166            if (isPressed()) {
5167                setPressed(false);
5168            }
5169            if (imm != null && mAttachInfo != null
5170                    && mAttachInfo.mHasWindowFocus) {
5171                imm.focusOut(this);
5172            }
5173            onFocusLost();
5174        } else if (imm != null && mAttachInfo != null
5175                && mAttachInfo.mHasWindowFocus) {
5176            imm.focusIn(this);
5177        }
5178
5179        invalidate(true);
5180        ListenerInfo li = mListenerInfo;
5181        if (li != null && li.mOnFocusChangeListener != null) {
5182            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5183        }
5184
5185        if (mAttachInfo != null) {
5186            mAttachInfo.mKeyDispatchState.reset(this);
5187        }
5188    }
5189
5190    /**
5191     * Sends an accessibility event of the given type. If accessibility is
5192     * not enabled this method has no effect. The default implementation calls
5193     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5194     * to populate information about the event source (this View), then calls
5195     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5196     * populate the text content of the event source including its descendants,
5197     * and last calls
5198     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5199     * on its parent to resuest sending of the event to interested parties.
5200     * <p>
5201     * If an {@link AccessibilityDelegate} has been specified via calling
5202     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5203     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5204     * responsible for handling this call.
5205     * </p>
5206     *
5207     * @param eventType The type of the event to send, as defined by several types from
5208     * {@link android.view.accessibility.AccessibilityEvent}, such as
5209     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5210     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5211     *
5212     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5213     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5214     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5215     * @see AccessibilityDelegate
5216     */
5217    public void sendAccessibilityEvent(int eventType) {
5218        if (mAccessibilityDelegate != null) {
5219            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5220        } else {
5221            sendAccessibilityEventInternal(eventType);
5222        }
5223    }
5224
5225    /**
5226     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5227     * {@link AccessibilityEvent} to make an announcement which is related to some
5228     * sort of a context change for which none of the events representing UI transitions
5229     * is a good fit. For example, announcing a new page in a book. If accessibility
5230     * is not enabled this method does nothing.
5231     *
5232     * @param text The announcement text.
5233     */
5234    public void announceForAccessibility(CharSequence text) {
5235        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5236            AccessibilityEvent event = AccessibilityEvent.obtain(
5237                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5238            onInitializeAccessibilityEvent(event);
5239            event.getText().add(text);
5240            event.setContentDescription(null);
5241            mParent.requestSendAccessibilityEvent(this, event);
5242        }
5243    }
5244
5245    /**
5246     * @see #sendAccessibilityEvent(int)
5247     *
5248     * Note: Called from the default {@link AccessibilityDelegate}.
5249     */
5250    void sendAccessibilityEventInternal(int eventType) {
5251        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5252            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5253        }
5254    }
5255
5256    /**
5257     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5258     * takes as an argument an empty {@link AccessibilityEvent} and does not
5259     * perform a check whether accessibility is enabled.
5260     * <p>
5261     * If an {@link AccessibilityDelegate} has been specified via calling
5262     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5263     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5264     * is responsible for handling this call.
5265     * </p>
5266     *
5267     * @param event The event to send.
5268     *
5269     * @see #sendAccessibilityEvent(int)
5270     */
5271    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5272        if (mAccessibilityDelegate != null) {
5273            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5274        } else {
5275            sendAccessibilityEventUncheckedInternal(event);
5276        }
5277    }
5278
5279    /**
5280     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5281     *
5282     * Note: Called from the default {@link AccessibilityDelegate}.
5283     */
5284    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5285        if (!isShown()) {
5286            return;
5287        }
5288        onInitializeAccessibilityEvent(event);
5289        // Only a subset of accessibility events populates text content.
5290        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5291            dispatchPopulateAccessibilityEvent(event);
5292        }
5293        // In the beginning we called #isShown(), so we know that getParent() is not null.
5294        getParent().requestSendAccessibilityEvent(this, event);
5295    }
5296
5297    /**
5298     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5299     * to its children for adding their text content to the event. Note that the
5300     * event text is populated in a separate dispatch path since we add to the
5301     * event not only the text of the source but also the text of all its descendants.
5302     * A typical implementation will call
5303     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5304     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5305     * on each child. Override this method if custom population of the event text
5306     * content is required.
5307     * <p>
5308     * If an {@link AccessibilityDelegate} has been specified via calling
5309     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5310     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5311     * is responsible for handling this call.
5312     * </p>
5313     * <p>
5314     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5315     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5316     * </p>
5317     *
5318     * @param event The event.
5319     *
5320     * @return True if the event population was completed.
5321     */
5322    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5323        if (mAccessibilityDelegate != null) {
5324            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5325        } else {
5326            return dispatchPopulateAccessibilityEventInternal(event);
5327        }
5328    }
5329
5330    /**
5331     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5332     *
5333     * Note: Called from the default {@link AccessibilityDelegate}.
5334     */
5335    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5336        onPopulateAccessibilityEvent(event);
5337        return false;
5338    }
5339
5340    /**
5341     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5342     * giving a chance to this View to populate the accessibility event with its
5343     * text content. While this method is free to modify event
5344     * attributes other than text content, doing so should normally be performed in
5345     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5346     * <p>
5347     * Example: Adding formatted date string to an accessibility event in addition
5348     *          to the text added by the super implementation:
5349     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5350     *     super.onPopulateAccessibilityEvent(event);
5351     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5352     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5353     *         mCurrentDate.getTimeInMillis(), flags);
5354     *     event.getText().add(selectedDateUtterance);
5355     * }</pre>
5356     * <p>
5357     * If an {@link AccessibilityDelegate} has been specified via calling
5358     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5359     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5360     * is responsible for handling this call.
5361     * </p>
5362     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5363     * information to the event, in case the default implementation has basic information to add.
5364     * </p>
5365     *
5366     * @param event The accessibility event which to populate.
5367     *
5368     * @see #sendAccessibilityEvent(int)
5369     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5370     */
5371    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5372        if (mAccessibilityDelegate != null) {
5373            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5374        } else {
5375            onPopulateAccessibilityEventInternal(event);
5376        }
5377    }
5378
5379    /**
5380     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5381     *
5382     * Note: Called from the default {@link AccessibilityDelegate}.
5383     */
5384    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5385    }
5386
5387    /**
5388     * Initializes an {@link AccessibilityEvent} with information about
5389     * this View which is the event source. In other words, the source of
5390     * an accessibility event is the view whose state change triggered firing
5391     * the event.
5392     * <p>
5393     * Example: Setting the password property of an event in addition
5394     *          to properties set by the super implementation:
5395     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5396     *     super.onInitializeAccessibilityEvent(event);
5397     *     event.setPassword(true);
5398     * }</pre>
5399     * <p>
5400     * If an {@link AccessibilityDelegate} has been specified via calling
5401     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5402     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5403     * is responsible for handling this call.
5404     * </p>
5405     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5406     * information to the event, in case the default implementation has basic information to add.
5407     * </p>
5408     * @param event The event to initialize.
5409     *
5410     * @see #sendAccessibilityEvent(int)
5411     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5412     */
5413    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5414        if (mAccessibilityDelegate != null) {
5415            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5416        } else {
5417            onInitializeAccessibilityEventInternal(event);
5418        }
5419    }
5420
5421    /**
5422     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5423     *
5424     * Note: Called from the default {@link AccessibilityDelegate}.
5425     */
5426    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5427        event.setSource(this);
5428        event.setClassName(View.class.getName());
5429        event.setPackageName(getContext().getPackageName());
5430        event.setEnabled(isEnabled());
5431        event.setContentDescription(mContentDescription);
5432
5433        switch (event.getEventType()) {
5434            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5435                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5436                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5437                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5438                event.setItemCount(focusablesTempList.size());
5439                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5440                if (mAttachInfo != null) {
5441                    focusablesTempList.clear();
5442                }
5443            } break;
5444            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5445                CharSequence text = getIterableTextForAccessibility();
5446                if (text != null && text.length() > 0) {
5447                    event.setFromIndex(getAccessibilitySelectionStart());
5448                    event.setToIndex(getAccessibilitySelectionEnd());
5449                    event.setItemCount(text.length());
5450                }
5451            } break;
5452        }
5453    }
5454
5455    /**
5456     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5457     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5458     * This method is responsible for obtaining an accessibility node info from a
5459     * pool of reusable instances and calling
5460     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5461     * initialize the former.
5462     * <p>
5463     * Note: The client is responsible for recycling the obtained instance by calling
5464     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5465     * </p>
5466     *
5467     * @return A populated {@link AccessibilityNodeInfo}.
5468     *
5469     * @see AccessibilityNodeInfo
5470     */
5471    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5472        if (mAccessibilityDelegate != null) {
5473            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5474        } else {
5475            return createAccessibilityNodeInfoInternal();
5476        }
5477    }
5478
5479    /**
5480     * @see #createAccessibilityNodeInfo()
5481     */
5482    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5483        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5484        if (provider != null) {
5485            return provider.createAccessibilityNodeInfo(View.NO_ID);
5486        } else {
5487            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5488            onInitializeAccessibilityNodeInfo(info);
5489            return info;
5490        }
5491    }
5492
5493    /**
5494     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5495     * The base implementation sets:
5496     * <ul>
5497     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5498     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5499     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5500     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5501     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5502     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5503     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5504     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5505     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5506     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5507     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5508     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5509     * </ul>
5510     * <p>
5511     * Subclasses should override this method, call the super implementation,
5512     * and set additional attributes.
5513     * </p>
5514     * <p>
5515     * If an {@link AccessibilityDelegate} has been specified via calling
5516     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5517     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5518     * is responsible for handling this call.
5519     * </p>
5520     *
5521     * @param info The instance to initialize.
5522     */
5523    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5524        if (mAccessibilityDelegate != null) {
5525            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5526        } else {
5527            onInitializeAccessibilityNodeInfoInternal(info);
5528        }
5529    }
5530
5531    /**
5532     * Gets the location of this view in screen coordintates.
5533     *
5534     * @param outRect The output location
5535     * @hide
5536     */
5537    public void getBoundsOnScreen(Rect outRect) {
5538        if (mAttachInfo == null) {
5539            return;
5540        }
5541
5542        RectF position = mAttachInfo.mTmpTransformRect;
5543        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5544
5545        if (!hasIdentityMatrix()) {
5546            getMatrix().mapRect(position);
5547        }
5548
5549        position.offset(mLeft, mTop);
5550
5551        ViewParent parent = mParent;
5552        while (parent instanceof View) {
5553            View parentView = (View) parent;
5554
5555            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5556
5557            if (!parentView.hasIdentityMatrix()) {
5558                parentView.getMatrix().mapRect(position);
5559            }
5560
5561            position.offset(parentView.mLeft, parentView.mTop);
5562
5563            parent = parentView.mParent;
5564        }
5565
5566        if (parent instanceof ViewRootImpl) {
5567            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5568            position.offset(0, -viewRootImpl.mCurScrollY);
5569        }
5570
5571        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5572
5573        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5574                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5575    }
5576
5577    /**
5578     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5579     *
5580     * Note: Called from the default {@link AccessibilityDelegate}.
5581     */
5582    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5583        Rect bounds = mAttachInfo.mTmpInvalRect;
5584
5585        getDrawingRect(bounds);
5586        info.setBoundsInParent(bounds);
5587
5588        getBoundsOnScreen(bounds);
5589        info.setBoundsInScreen(bounds);
5590
5591        ViewParent parent = getParentForAccessibility();
5592        if (parent instanceof View) {
5593            info.setParent((View) parent);
5594        }
5595
5596        if (mID != View.NO_ID) {
5597            View rootView = getRootView();
5598            if (rootView == null) {
5599                rootView = this;
5600            }
5601            View label = rootView.findLabelForView(this, mID);
5602            if (label != null) {
5603                info.setLabeledBy(label);
5604            }
5605
5606            if ((mAttachInfo.mAccessibilityFetchFlags
5607                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5608                    && Resources.resourceHasPackage(mID)) {
5609                try {
5610                    String viewId = getResources().getResourceName(mID);
5611                    info.setViewIdResourceName(viewId);
5612                } catch (Resources.NotFoundException nfe) {
5613                    /* ignore */
5614                }
5615            }
5616        }
5617
5618        if (mLabelForId != View.NO_ID) {
5619            View rootView = getRootView();
5620            if (rootView == null) {
5621                rootView = this;
5622            }
5623            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5624            if (labeled != null) {
5625                info.setLabelFor(labeled);
5626            }
5627        }
5628
5629        info.setVisibleToUser(isVisibleToUser());
5630
5631        info.setPackageName(mContext.getPackageName());
5632        info.setClassName(View.class.getName());
5633        info.setContentDescription(getContentDescription());
5634
5635        info.setEnabled(isEnabled());
5636        info.setClickable(isClickable());
5637        info.setFocusable(isFocusable());
5638        info.setFocused(isFocused());
5639        info.setAccessibilityFocused(isAccessibilityFocused());
5640        info.setSelected(isSelected());
5641        info.setLongClickable(isLongClickable());
5642        info.setLiveRegion(getAccessibilityLiveRegion());
5643
5644        // TODO: These make sense only if we are in an AdapterView but all
5645        // views can be selected. Maybe from accessibility perspective
5646        // we should report as selectable view in an AdapterView.
5647        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5648        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5649
5650        if (isFocusable()) {
5651            if (isFocused()) {
5652                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5653            } else {
5654                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5655            }
5656        }
5657
5658        if (!isAccessibilityFocused()) {
5659            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5660        } else {
5661            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5662        }
5663
5664        if (isClickable() && isEnabled()) {
5665            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5666        }
5667
5668        if (isLongClickable() && isEnabled()) {
5669            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5670        }
5671
5672        CharSequence text = getIterableTextForAccessibility();
5673        if (text != null && text.length() > 0) {
5674            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5675
5676            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5677            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5678            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5679            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5680                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5681                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5682        }
5683    }
5684
5685    private View findLabelForView(View view, int labeledId) {
5686        if (mMatchLabelForPredicate == null) {
5687            mMatchLabelForPredicate = new MatchLabelForPredicate();
5688        }
5689        mMatchLabelForPredicate.mLabeledId = labeledId;
5690        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5691    }
5692
5693    /**
5694     * Computes whether this view is visible to the user. Such a view is
5695     * attached, visible, all its predecessors are visible, it is not clipped
5696     * entirely by its predecessors, and has an alpha greater than zero.
5697     *
5698     * @return Whether the view is visible on the screen.
5699     *
5700     * @hide
5701     */
5702    protected boolean isVisibleToUser() {
5703        return isVisibleToUser(null);
5704    }
5705
5706    /**
5707     * Computes whether the given portion of this view is visible to the user.
5708     * Such a view is attached, visible, all its predecessors are visible,
5709     * has an alpha greater than zero, and the specified portion is not
5710     * clipped entirely by its predecessors.
5711     *
5712     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5713     *                    <code>null</code>, and the entire view will be tested in this case.
5714     *                    When <code>true</code> is returned by the function, the actual visible
5715     *                    region will be stored in this parameter; that is, if boundInView is fully
5716     *                    contained within the view, no modification will be made, otherwise regions
5717     *                    outside of the visible area of the view will be clipped.
5718     *
5719     * @return Whether the specified portion of the view is visible on the screen.
5720     *
5721     * @hide
5722     */
5723    protected boolean isVisibleToUser(Rect boundInView) {
5724        if (mAttachInfo != null) {
5725            // Attached to invisible window means this view is not visible.
5726            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5727                return false;
5728            }
5729            // An invisible predecessor or one with alpha zero means
5730            // that this view is not visible to the user.
5731            Object current = this;
5732            while (current instanceof View) {
5733                View view = (View) current;
5734                // We have attach info so this view is attached and there is no
5735                // need to check whether we reach to ViewRootImpl on the way up.
5736                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5737                        view.getVisibility() != VISIBLE) {
5738                    return false;
5739                }
5740                current = view.mParent;
5741            }
5742            // Check if the view is entirely covered by its predecessors.
5743            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5744            Point offset = mAttachInfo.mPoint;
5745            if (!getGlobalVisibleRect(visibleRect, offset)) {
5746                return false;
5747            }
5748            // Check if the visible portion intersects the rectangle of interest.
5749            if (boundInView != null) {
5750                visibleRect.offset(-offset.x, -offset.y);
5751                return boundInView.intersect(visibleRect);
5752            }
5753            return true;
5754        }
5755        return false;
5756    }
5757
5758    /**
5759     * Computes a point on which a sequence of a down/up event can be sent to
5760     * trigger clicking this view. This method is for the exclusive use by the
5761     * accessibility layer to determine where to send a click event in explore
5762     * by touch mode.
5763     *
5764     * @param interactiveRegion The interactive portion of this window.
5765     * @param outPoint The point to populate.
5766     * @return True of such a point exists.
5767     */
5768    boolean computeClickPointInScreenForAccessibility(Region interactiveRegion,
5769            Point outPoint) {
5770        // Since the interactive portion of the view is a region but as a view
5771        // may have a transformation matrix which cannot be applied to a
5772        // region we compute the view bounds rectangle and all interactive
5773        // predecessor's and sibling's (siblings of predecessors included)
5774        // rectangles that intersect the view bounds. At the
5775        // end if the view was partially covered by another interactive
5776        // view we compute the view's interactive region and pick a point
5777        // on its boundary path as regions do not offer APIs to get inner
5778        // points. Note that the the code is optimized to fail early and
5779        // avoid unnecessary allocations plus computations.
5780
5781        // The current approach has edge cases that may produce false
5782        // positives or false negatives. For example, a portion of the
5783        // view may be covered by an interactive descendant of a
5784        // predecessor, which we do not compute. Also a view may be handling
5785        // raw touch events instead registering click listeners, which
5786        // we cannot compute. Despite these limitations this approach will
5787        // work most of the time and it is a huge improvement over just
5788        // blindly sending the down and up events in the center of the
5789        // view.
5790
5791        // Cannot click on an unattached view.
5792        if (mAttachInfo == null) {
5793            return false;
5794        }
5795
5796        // Attached to an invisible window means this view is not visible.
5797        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5798            return false;
5799        }
5800
5801        RectF bounds = mAttachInfo.mTmpTransformRect;
5802        bounds.set(0, 0, getWidth(), getHeight());
5803        List<RectF> intersections = mAttachInfo.mTmpRectList;
5804        intersections.clear();
5805
5806        if (mParent instanceof ViewGroup) {
5807            ViewGroup parentGroup = (ViewGroup) mParent;
5808            if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates(
5809                    this, bounds, intersections)) {
5810                intersections.clear();
5811                return false;
5812            }
5813        }
5814
5815        // Take into account the window location.
5816        final int dx = mAttachInfo.mWindowLeft;
5817        final int dy = mAttachInfo.mWindowTop;
5818        bounds.offset(dx, dy);
5819        offsetRects(intersections, dx, dy);
5820
5821        if (intersections.isEmpty() && interactiveRegion == null) {
5822            outPoint.set((int) bounds.centerX(), (int) bounds.centerY());
5823        } else {
5824            // This view is partially covered by other views, then compute
5825            // the not covered region and pick a point on its boundary.
5826            Region region = new Region();
5827            region.set((int) bounds.left, (int) bounds.top,
5828                    (int) bounds.right, (int) bounds.bottom);
5829
5830            final int intersectionCount = intersections.size();
5831            for (int i = intersectionCount - 1; i >= 0; i--) {
5832                RectF intersection = intersections.remove(i);
5833                region.op((int) intersection.left, (int) intersection.top,
5834                        (int) intersection.right, (int) intersection.bottom,
5835                        Region.Op.DIFFERENCE);
5836            }
5837
5838            // If the view is completely covered, done.
5839            if (region.isEmpty()) {
5840                return false;
5841            }
5842
5843            // Take into account the interactive portion of the window
5844            // as the rest is covered by other windows. If no such a region
5845            // then the whole window is interactive.
5846            if (interactiveRegion != null) {
5847                region.op(interactiveRegion, Region.Op.INTERSECT);
5848            }
5849
5850            // If the view is completely covered, done.
5851            if (region.isEmpty()) {
5852                return false;
5853            }
5854
5855            // Try a shortcut here.
5856            if (region.isRect()) {
5857                Rect regionBounds = mAttachInfo.mTmpInvalRect;
5858                region.getBounds(regionBounds);
5859                outPoint.set(regionBounds.centerX(), regionBounds.centerY());
5860                return true;
5861            }
5862
5863            // Get the a point on the region boundary path.
5864            Path path = region.getBoundaryPath();
5865            PathMeasure pathMeasure = new PathMeasure(path, false);
5866            final float[] coordinates = mAttachInfo.mTmpTransformLocation;
5867
5868            // Without loss of generality pick a point.
5869            final float point = pathMeasure.getLength() * 0.01f;
5870            if (!pathMeasure.getPosTan(point, coordinates, null)) {
5871                return false;
5872            }
5873
5874            outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1]));
5875        }
5876
5877        return true;
5878    }
5879
5880    /**
5881     * Adds the clickable rectangles withing the bounds of this view. They
5882     * may overlap. This method is intended for use only by the accessibility
5883     * layer.
5884     *
5885     * @param outRects List to which to add clickable areas.
5886     */
5887    void addClickableRectsForAccessibility(List<RectF> outRects) {
5888        if (isClickable() || isLongClickable()) {
5889            RectF bounds = new RectF();
5890            bounds.set(0, 0, getWidth(), getHeight());
5891            outRects.add(bounds);
5892        }
5893    }
5894
5895    static void offsetRects(List<RectF> rects, float offsetX, float offsetY) {
5896        final int rectCount = rects.size();
5897        for (int i = 0; i < rectCount; i++) {
5898            RectF intersection = rects.get(i);
5899            intersection.offset(offsetX, offsetY);
5900        }
5901    }
5902
5903    /**
5904     * Returns the delegate for implementing accessibility support via
5905     * composition. For more details see {@link AccessibilityDelegate}.
5906     *
5907     * @return The delegate, or null if none set.
5908     *
5909     * @hide
5910     */
5911    public AccessibilityDelegate getAccessibilityDelegate() {
5912        return mAccessibilityDelegate;
5913    }
5914
5915    /**
5916     * Sets a delegate for implementing accessibility support via composition as
5917     * opposed to inheritance. The delegate's primary use is for implementing
5918     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5919     *
5920     * @param delegate The delegate instance.
5921     *
5922     * @see AccessibilityDelegate
5923     */
5924    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5925        mAccessibilityDelegate = delegate;
5926    }
5927
5928    /**
5929     * Gets the provider for managing a virtual view hierarchy rooted at this View
5930     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5931     * that explore the window content.
5932     * <p>
5933     * If this method returns an instance, this instance is responsible for managing
5934     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5935     * View including the one representing the View itself. Similarly the returned
5936     * instance is responsible for performing accessibility actions on any virtual
5937     * view or the root view itself.
5938     * </p>
5939     * <p>
5940     * If an {@link AccessibilityDelegate} has been specified via calling
5941     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5942     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5943     * is responsible for handling this call.
5944     * </p>
5945     *
5946     * @return The provider.
5947     *
5948     * @see AccessibilityNodeProvider
5949     */
5950    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5951        if (mAccessibilityDelegate != null) {
5952            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5953        } else {
5954            return null;
5955        }
5956    }
5957
5958    /**
5959     * Gets the unique identifier of this view on the screen for accessibility purposes.
5960     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5961     *
5962     * @return The view accessibility id.
5963     *
5964     * @hide
5965     */
5966    public int getAccessibilityViewId() {
5967        if (mAccessibilityViewId == NO_ID) {
5968            mAccessibilityViewId = sNextAccessibilityViewId++;
5969        }
5970        return mAccessibilityViewId;
5971    }
5972
5973    /**
5974     * Gets the unique identifier of the window in which this View reseides.
5975     *
5976     * @return The window accessibility id.
5977     *
5978     * @hide
5979     */
5980    public int getAccessibilityWindowId() {
5981        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5982                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5983    }
5984
5985    /**
5986     * Gets the {@link View} description. It briefly describes the view and is
5987     * primarily used for accessibility support. Set this property to enable
5988     * better accessibility support for your application. This is especially
5989     * true for views that do not have textual representation (For example,
5990     * ImageButton).
5991     *
5992     * @return The content description.
5993     *
5994     * @attr ref android.R.styleable#View_contentDescription
5995     */
5996    @ViewDebug.ExportedProperty(category = "accessibility")
5997    public CharSequence getContentDescription() {
5998        return mContentDescription;
5999    }
6000
6001    /**
6002     * Sets the {@link View} description. It briefly describes the view and is
6003     * primarily used for accessibility support. Set this property to enable
6004     * better accessibility support for your application. This is especially
6005     * true for views that do not have textual representation (For example,
6006     * ImageButton).
6007     *
6008     * @param contentDescription The content description.
6009     *
6010     * @attr ref android.R.styleable#View_contentDescription
6011     */
6012    @RemotableViewMethod
6013    public void setContentDescription(CharSequence contentDescription) {
6014        if (mContentDescription == null) {
6015            if (contentDescription == null) {
6016                return;
6017            }
6018        } else if (mContentDescription.equals(contentDescription)) {
6019            return;
6020        }
6021        mContentDescription = contentDescription;
6022        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6023        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6024            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6025            notifySubtreeAccessibilityStateChangedIfNeeded();
6026        } else {
6027            notifyViewAccessibilityStateChangedIfNeeded(
6028                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6029        }
6030    }
6031
6032    /**
6033     * Gets the id of a view for which this view serves as a label for
6034     * accessibility purposes.
6035     *
6036     * @return The labeled view id.
6037     */
6038    @ViewDebug.ExportedProperty(category = "accessibility")
6039    public int getLabelFor() {
6040        return mLabelForId;
6041    }
6042
6043    /**
6044     * Sets the id of a view for which this view serves as a label for
6045     * accessibility purposes.
6046     *
6047     * @param id The labeled view id.
6048     */
6049    @RemotableViewMethod
6050    public void setLabelFor(int id) {
6051        mLabelForId = id;
6052        if (mLabelForId != View.NO_ID
6053                && mID == View.NO_ID) {
6054            mID = generateViewId();
6055        }
6056    }
6057
6058    /**
6059     * Invoked whenever this view loses focus, either by losing window focus or by losing
6060     * focus within its window. This method can be used to clear any state tied to the
6061     * focus. For instance, if a button is held pressed with the trackball and the window
6062     * loses focus, this method can be used to cancel the press.
6063     *
6064     * Subclasses of View overriding this method should always call super.onFocusLost().
6065     *
6066     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6067     * @see #onWindowFocusChanged(boolean)
6068     *
6069     * @hide pending API council approval
6070     */
6071    protected void onFocusLost() {
6072        resetPressedState();
6073    }
6074
6075    private void resetPressedState() {
6076        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6077            return;
6078        }
6079
6080        if (isPressed()) {
6081            setPressed(false);
6082
6083            if (!mHasPerformedLongPress) {
6084                removeLongPressCallback();
6085            }
6086        }
6087    }
6088
6089    /**
6090     * Returns true if this view has focus
6091     *
6092     * @return True if this view has focus, false otherwise.
6093     */
6094    @ViewDebug.ExportedProperty(category = "focus")
6095    public boolean isFocused() {
6096        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6097    }
6098
6099    /**
6100     * Find the view in the hierarchy rooted at this view that currently has
6101     * focus.
6102     *
6103     * @return The view that currently has focus, or null if no focused view can
6104     *         be found.
6105     */
6106    public View findFocus() {
6107        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6108    }
6109
6110    /**
6111     * Indicates whether this view is one of the set of scrollable containers in
6112     * its window.
6113     *
6114     * @return whether this view is one of the set of scrollable containers in
6115     * its window
6116     *
6117     * @attr ref android.R.styleable#View_isScrollContainer
6118     */
6119    public boolean isScrollContainer() {
6120        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6121    }
6122
6123    /**
6124     * Change whether this view is one of the set of scrollable containers in
6125     * its window.  This will be used to determine whether the window can
6126     * resize or must pan when a soft input area is open -- scrollable
6127     * containers allow the window to use resize mode since the container
6128     * will appropriately shrink.
6129     *
6130     * @attr ref android.R.styleable#View_isScrollContainer
6131     */
6132    public void setScrollContainer(boolean isScrollContainer) {
6133        if (isScrollContainer) {
6134            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6135                mAttachInfo.mScrollContainers.add(this);
6136                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6137            }
6138            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6139        } else {
6140            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6141                mAttachInfo.mScrollContainers.remove(this);
6142            }
6143            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6144        }
6145    }
6146
6147    /**
6148     * Returns the quality of the drawing cache.
6149     *
6150     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6151     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6152     *
6153     * @see #setDrawingCacheQuality(int)
6154     * @see #setDrawingCacheEnabled(boolean)
6155     * @see #isDrawingCacheEnabled()
6156     *
6157     * @attr ref android.R.styleable#View_drawingCacheQuality
6158     */
6159    @DrawingCacheQuality
6160    public int getDrawingCacheQuality() {
6161        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6162    }
6163
6164    /**
6165     * Set the drawing cache quality of this view. This value is used only when the
6166     * drawing cache is enabled
6167     *
6168     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6169     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6170     *
6171     * @see #getDrawingCacheQuality()
6172     * @see #setDrawingCacheEnabled(boolean)
6173     * @see #isDrawingCacheEnabled()
6174     *
6175     * @attr ref android.R.styleable#View_drawingCacheQuality
6176     */
6177    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6178        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6179    }
6180
6181    /**
6182     * Returns whether the screen should remain on, corresponding to the current
6183     * value of {@link #KEEP_SCREEN_ON}.
6184     *
6185     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6186     *
6187     * @see #setKeepScreenOn(boolean)
6188     *
6189     * @attr ref android.R.styleable#View_keepScreenOn
6190     */
6191    public boolean getKeepScreenOn() {
6192        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6193    }
6194
6195    /**
6196     * Controls whether the screen should remain on, modifying the
6197     * value of {@link #KEEP_SCREEN_ON}.
6198     *
6199     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6200     *
6201     * @see #getKeepScreenOn()
6202     *
6203     * @attr ref android.R.styleable#View_keepScreenOn
6204     */
6205    public void setKeepScreenOn(boolean keepScreenOn) {
6206        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6207    }
6208
6209    /**
6210     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6211     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6212     *
6213     * @attr ref android.R.styleable#View_nextFocusLeft
6214     */
6215    public int getNextFocusLeftId() {
6216        return mNextFocusLeftId;
6217    }
6218
6219    /**
6220     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6221     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6222     * decide automatically.
6223     *
6224     * @attr ref android.R.styleable#View_nextFocusLeft
6225     */
6226    public void setNextFocusLeftId(int nextFocusLeftId) {
6227        mNextFocusLeftId = nextFocusLeftId;
6228    }
6229
6230    /**
6231     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6232     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6233     *
6234     * @attr ref android.R.styleable#View_nextFocusRight
6235     */
6236    public int getNextFocusRightId() {
6237        return mNextFocusRightId;
6238    }
6239
6240    /**
6241     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6242     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6243     * decide automatically.
6244     *
6245     * @attr ref android.R.styleable#View_nextFocusRight
6246     */
6247    public void setNextFocusRightId(int nextFocusRightId) {
6248        mNextFocusRightId = nextFocusRightId;
6249    }
6250
6251    /**
6252     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6253     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6254     *
6255     * @attr ref android.R.styleable#View_nextFocusUp
6256     */
6257    public int getNextFocusUpId() {
6258        return mNextFocusUpId;
6259    }
6260
6261    /**
6262     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6263     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6264     * decide automatically.
6265     *
6266     * @attr ref android.R.styleable#View_nextFocusUp
6267     */
6268    public void setNextFocusUpId(int nextFocusUpId) {
6269        mNextFocusUpId = nextFocusUpId;
6270    }
6271
6272    /**
6273     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6274     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6275     *
6276     * @attr ref android.R.styleable#View_nextFocusDown
6277     */
6278    public int getNextFocusDownId() {
6279        return mNextFocusDownId;
6280    }
6281
6282    /**
6283     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6284     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6285     * decide automatically.
6286     *
6287     * @attr ref android.R.styleable#View_nextFocusDown
6288     */
6289    public void setNextFocusDownId(int nextFocusDownId) {
6290        mNextFocusDownId = nextFocusDownId;
6291    }
6292
6293    /**
6294     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6295     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6296     *
6297     * @attr ref android.R.styleable#View_nextFocusForward
6298     */
6299    public int getNextFocusForwardId() {
6300        return mNextFocusForwardId;
6301    }
6302
6303    /**
6304     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6305     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6306     * decide automatically.
6307     *
6308     * @attr ref android.R.styleable#View_nextFocusForward
6309     */
6310    public void setNextFocusForwardId(int nextFocusForwardId) {
6311        mNextFocusForwardId = nextFocusForwardId;
6312    }
6313
6314    /**
6315     * Returns the visibility of this view and all of its ancestors
6316     *
6317     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6318     */
6319    public boolean isShown() {
6320        View current = this;
6321        //noinspection ConstantConditions
6322        do {
6323            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6324                return false;
6325            }
6326            ViewParent parent = current.mParent;
6327            if (parent == null) {
6328                return false; // We are not attached to the view root
6329            }
6330            if (!(parent instanceof View)) {
6331                return true;
6332            }
6333            current = (View) parent;
6334        } while (current != null);
6335
6336        return false;
6337    }
6338
6339    /**
6340     * Called by the view hierarchy when the content insets for a window have
6341     * changed, to allow it to adjust its content to fit within those windows.
6342     * The content insets tell you the space that the status bar, input method,
6343     * and other system windows infringe on the application's window.
6344     *
6345     * <p>You do not normally need to deal with this function, since the default
6346     * window decoration given to applications takes care of applying it to the
6347     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6348     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6349     * and your content can be placed under those system elements.  You can then
6350     * use this method within your view hierarchy if you have parts of your UI
6351     * which you would like to ensure are not being covered.
6352     *
6353     * <p>The default implementation of this method simply applies the content
6354     * insets to the view's padding, consuming that content (modifying the
6355     * insets to be 0), and returning true.  This behavior is off by default, but can
6356     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6357     *
6358     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6359     * insets object is propagated down the hierarchy, so any changes made to it will
6360     * be seen by all following views (including potentially ones above in
6361     * the hierarchy since this is a depth-first traversal).  The first view
6362     * that returns true will abort the entire traversal.
6363     *
6364     * <p>The default implementation works well for a situation where it is
6365     * used with a container that covers the entire window, allowing it to
6366     * apply the appropriate insets to its content on all edges.  If you need
6367     * a more complicated layout (such as two different views fitting system
6368     * windows, one on the top of the window, and one on the bottom),
6369     * you can override the method and handle the insets however you would like.
6370     * Note that the insets provided by the framework are always relative to the
6371     * far edges of the window, not accounting for the location of the called view
6372     * within that window.  (In fact when this method is called you do not yet know
6373     * where the layout will place the view, as it is done before layout happens.)
6374     *
6375     * <p>Note: unlike many View methods, there is no dispatch phase to this
6376     * call.  If you are overriding it in a ViewGroup and want to allow the
6377     * call to continue to your children, you must be sure to call the super
6378     * implementation.
6379     *
6380     * <p>Here is a sample layout that makes use of fitting system windows
6381     * to have controls for a video view placed inside of the window decorations
6382     * that it hides and shows.  This can be used with code like the second
6383     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6384     *
6385     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6386     *
6387     * @param insets Current content insets of the window.  Prior to
6388     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6389     * the insets or else you and Android will be unhappy.
6390     *
6391     * @return {@code true} if this view applied the insets and it should not
6392     * continue propagating further down the hierarchy, {@code false} otherwise.
6393     * @see #getFitsSystemWindows()
6394     * @see #setFitsSystemWindows(boolean)
6395     * @see #setSystemUiVisibility(int)
6396     *
6397     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6398     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6399     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6400     * to implement handling their own insets.
6401     */
6402    protected boolean fitSystemWindows(Rect insets) {
6403        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6404            if (insets == null) {
6405                // Null insets by definition have already been consumed.
6406                // This call cannot apply insets since there are none to apply,
6407                // so return false.
6408                return false;
6409            }
6410            // If we're not in the process of dispatching the newer apply insets call,
6411            // that means we're not in the compatibility path. Dispatch into the newer
6412            // apply insets path and take things from there.
6413            try {
6414                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6415                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6416            } finally {
6417                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6418            }
6419        } else {
6420            // We're being called from the newer apply insets path.
6421            // Perform the standard fallback behavior.
6422            return fitSystemWindowsInt(insets);
6423        }
6424    }
6425
6426    private boolean fitSystemWindowsInt(Rect insets) {
6427        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6428            mUserPaddingStart = UNDEFINED_PADDING;
6429            mUserPaddingEnd = UNDEFINED_PADDING;
6430            Rect localInsets = sThreadLocal.get();
6431            if (localInsets == null) {
6432                localInsets = new Rect();
6433                sThreadLocal.set(localInsets);
6434            }
6435            boolean res = computeFitSystemWindows(insets, localInsets);
6436            mUserPaddingLeftInitial = localInsets.left;
6437            mUserPaddingRightInitial = localInsets.right;
6438            internalSetPadding(localInsets.left, localInsets.top,
6439                    localInsets.right, localInsets.bottom);
6440            return res;
6441        }
6442        return false;
6443    }
6444
6445    /**
6446     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6447     *
6448     * <p>This method should be overridden by views that wish to apply a policy different from or
6449     * in addition to the default behavior. Clients that wish to force a view subtree
6450     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6451     *
6452     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6453     * it will be called during dispatch instead of this method. The listener may optionally
6454     * call this method from its own implementation if it wishes to apply the view's default
6455     * insets policy in addition to its own.</p>
6456     *
6457     * <p>Implementations of this method should either return the insets parameter unchanged
6458     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6459     * that this view applied itself. This allows new inset types added in future platform
6460     * versions to pass through existing implementations unchanged without being erroneously
6461     * consumed.</p>
6462     *
6463     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6464     * property is set then the view will consume the system window insets and apply them
6465     * as padding for the view.</p>
6466     *
6467     * @param insets Insets to apply
6468     * @return The supplied insets with any applied insets consumed
6469     */
6470    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6471        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6472            // We weren't called from within a direct call to fitSystemWindows,
6473            // call into it as a fallback in case we're in a class that overrides it
6474            // and has logic to perform.
6475            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6476                return insets.consumeSystemWindowInsets();
6477            }
6478        } else {
6479            // We were called from within a direct call to fitSystemWindows.
6480            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6481                return insets.consumeSystemWindowInsets();
6482            }
6483        }
6484        return insets;
6485    }
6486
6487    /**
6488     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6489     * window insets to this view. The listener's
6490     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6491     * method will be called instead of the view's
6492     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6493     *
6494     * @param listener Listener to set
6495     *
6496     * @see #onApplyWindowInsets(WindowInsets)
6497     */
6498    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6499        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6500    }
6501
6502    /**
6503     * Request to apply the given window insets to this view or another view in its subtree.
6504     *
6505     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6506     * obscured by window decorations or overlays. This can include the status and navigation bars,
6507     * action bars, input methods and more. New inset categories may be added in the future.
6508     * The method returns the insets provided minus any that were applied by this view or its
6509     * children.</p>
6510     *
6511     * <p>Clients wishing to provide custom behavior should override the
6512     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6513     * {@link OnApplyWindowInsetsListener} via the
6514     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6515     * method.</p>
6516     *
6517     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6518     * </p>
6519     *
6520     * @param insets Insets to apply
6521     * @return The provided insets minus the insets that were consumed
6522     */
6523    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6524        try {
6525            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6526            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6527                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6528            } else {
6529                return onApplyWindowInsets(insets);
6530            }
6531        } finally {
6532            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6533        }
6534    }
6535
6536    /**
6537     * @hide Compute the insets that should be consumed by this view and the ones
6538     * that should propagate to those under it.
6539     */
6540    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6541        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6542                || mAttachInfo == null
6543                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6544                        && !mAttachInfo.mOverscanRequested)) {
6545            outLocalInsets.set(inoutInsets);
6546            inoutInsets.set(0, 0, 0, 0);
6547            return true;
6548        } else {
6549            // The application wants to take care of fitting system window for
6550            // the content...  however we still need to take care of any overscan here.
6551            final Rect overscan = mAttachInfo.mOverscanInsets;
6552            outLocalInsets.set(overscan);
6553            inoutInsets.left -= overscan.left;
6554            inoutInsets.top -= overscan.top;
6555            inoutInsets.right -= overscan.right;
6556            inoutInsets.bottom -= overscan.bottom;
6557            return false;
6558        }
6559    }
6560
6561    /**
6562     * Compute insets that should be consumed by this view and the ones that should propagate
6563     * to those under it.
6564     *
6565     * @param in Insets currently being processed by this View, likely received as a parameter
6566     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6567     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6568     *                       by this view
6569     * @return Insets that should be passed along to views under this one
6570     */
6571    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6572        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6573                || mAttachInfo == null
6574                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6575            outLocalInsets.set(in.getSystemWindowInsets());
6576            return in.consumeSystemWindowInsets();
6577        } else {
6578            outLocalInsets.set(0, 0, 0, 0);
6579            return in;
6580        }
6581    }
6582
6583    /**
6584     * Sets whether or not this view should account for system screen decorations
6585     * such as the status bar and inset its content; that is, controlling whether
6586     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6587     * executed.  See that method for more details.
6588     *
6589     * <p>Note that if you are providing your own implementation of
6590     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6591     * flag to true -- your implementation will be overriding the default
6592     * implementation that checks this flag.
6593     *
6594     * @param fitSystemWindows If true, then the default implementation of
6595     * {@link #fitSystemWindows(Rect)} will be executed.
6596     *
6597     * @attr ref android.R.styleable#View_fitsSystemWindows
6598     * @see #getFitsSystemWindows()
6599     * @see #fitSystemWindows(Rect)
6600     * @see #setSystemUiVisibility(int)
6601     */
6602    public void setFitsSystemWindows(boolean fitSystemWindows) {
6603        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6604    }
6605
6606    /**
6607     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6608     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6609     * will be executed.
6610     *
6611     * @return {@code true} if the default implementation of
6612     * {@link #fitSystemWindows(Rect)} will be executed.
6613     *
6614     * @attr ref android.R.styleable#View_fitsSystemWindows
6615     * @see #setFitsSystemWindows(boolean)
6616     * @see #fitSystemWindows(Rect)
6617     * @see #setSystemUiVisibility(int)
6618     */
6619    @ViewDebug.ExportedProperty
6620    public boolean getFitsSystemWindows() {
6621        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6622    }
6623
6624    /** @hide */
6625    public boolean fitsSystemWindows() {
6626        return getFitsSystemWindows();
6627    }
6628
6629    /**
6630     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6631     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6632     */
6633    public void requestFitSystemWindows() {
6634        if (mParent != null) {
6635            mParent.requestFitSystemWindows();
6636        }
6637    }
6638
6639    /**
6640     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6641     */
6642    public void requestApplyInsets() {
6643        requestFitSystemWindows();
6644    }
6645
6646    /**
6647     * For use by PhoneWindow to make its own system window fitting optional.
6648     * @hide
6649     */
6650    public void makeOptionalFitsSystemWindows() {
6651        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6652    }
6653
6654    /**
6655     * Returns the visibility status for this view.
6656     *
6657     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6658     * @attr ref android.R.styleable#View_visibility
6659     */
6660    @ViewDebug.ExportedProperty(mapping = {
6661        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6662        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6663        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6664    })
6665    @Visibility
6666    public int getVisibility() {
6667        return mViewFlags & VISIBILITY_MASK;
6668    }
6669
6670    /**
6671     * Set the enabled state of this view.
6672     *
6673     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6674     * @attr ref android.R.styleable#View_visibility
6675     */
6676    @RemotableViewMethod
6677    public void setVisibility(@Visibility int visibility) {
6678        setFlags(visibility, VISIBILITY_MASK);
6679        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6680    }
6681
6682    /**
6683     * Returns the enabled status for this view. The interpretation of the
6684     * enabled state varies by subclass.
6685     *
6686     * @return True if this view is enabled, false otherwise.
6687     */
6688    @ViewDebug.ExportedProperty
6689    public boolean isEnabled() {
6690        return (mViewFlags & ENABLED_MASK) == ENABLED;
6691    }
6692
6693    /**
6694     * Set the enabled state of this view. The interpretation of the enabled
6695     * state varies by subclass.
6696     *
6697     * @param enabled True if this view is enabled, false otherwise.
6698     */
6699    @RemotableViewMethod
6700    public void setEnabled(boolean enabled) {
6701        if (enabled == isEnabled()) return;
6702
6703        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6704
6705        /*
6706         * The View most likely has to change its appearance, so refresh
6707         * the drawable state.
6708         */
6709        refreshDrawableState();
6710
6711        // Invalidate too, since the default behavior for views is to be
6712        // be drawn at 50% alpha rather than to change the drawable.
6713        invalidate(true);
6714
6715        if (!enabled) {
6716            cancelPendingInputEvents();
6717        }
6718    }
6719
6720    /**
6721     * Set whether this view can receive the focus.
6722     *
6723     * Setting this to false will also ensure that this view is not focusable
6724     * in touch mode.
6725     *
6726     * @param focusable If true, this view can receive the focus.
6727     *
6728     * @see #setFocusableInTouchMode(boolean)
6729     * @attr ref android.R.styleable#View_focusable
6730     */
6731    public void setFocusable(boolean focusable) {
6732        if (!focusable) {
6733            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6734        }
6735        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6736    }
6737
6738    /**
6739     * Set whether this view can receive focus while in touch mode.
6740     *
6741     * Setting this to true will also ensure that this view is focusable.
6742     *
6743     * @param focusableInTouchMode If true, this view can receive the focus while
6744     *   in touch mode.
6745     *
6746     * @see #setFocusable(boolean)
6747     * @attr ref android.R.styleable#View_focusableInTouchMode
6748     */
6749    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6750        // Focusable in touch mode should always be set before the focusable flag
6751        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6752        // which, in touch mode, will not successfully request focus on this view
6753        // because the focusable in touch mode flag is not set
6754        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6755        if (focusableInTouchMode) {
6756            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6757        }
6758    }
6759
6760    /**
6761     * Set whether this view should have sound effects enabled for events such as
6762     * clicking and touching.
6763     *
6764     * <p>You may wish to disable sound effects for a view if you already play sounds,
6765     * for instance, a dial key that plays dtmf tones.
6766     *
6767     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6768     * @see #isSoundEffectsEnabled()
6769     * @see #playSoundEffect(int)
6770     * @attr ref android.R.styleable#View_soundEffectsEnabled
6771     */
6772    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6773        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6774    }
6775
6776    /**
6777     * @return whether this view should have sound effects enabled for events such as
6778     *     clicking and touching.
6779     *
6780     * @see #setSoundEffectsEnabled(boolean)
6781     * @see #playSoundEffect(int)
6782     * @attr ref android.R.styleable#View_soundEffectsEnabled
6783     */
6784    @ViewDebug.ExportedProperty
6785    public boolean isSoundEffectsEnabled() {
6786        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6787    }
6788
6789    /**
6790     * Set whether this view should have haptic feedback for events such as
6791     * long presses.
6792     *
6793     * <p>You may wish to disable haptic feedback if your view already controls
6794     * its own haptic feedback.
6795     *
6796     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6797     * @see #isHapticFeedbackEnabled()
6798     * @see #performHapticFeedback(int)
6799     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6800     */
6801    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6802        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6803    }
6804
6805    /**
6806     * @return whether this view should have haptic feedback enabled for events
6807     * long presses.
6808     *
6809     * @see #setHapticFeedbackEnabled(boolean)
6810     * @see #performHapticFeedback(int)
6811     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6812     */
6813    @ViewDebug.ExportedProperty
6814    public boolean isHapticFeedbackEnabled() {
6815        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6816    }
6817
6818    /**
6819     * Returns the layout direction for this view.
6820     *
6821     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6822     *   {@link #LAYOUT_DIRECTION_RTL},
6823     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6824     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6825     *
6826     * @attr ref android.R.styleable#View_layoutDirection
6827     *
6828     * @hide
6829     */
6830    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6831        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6832        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6833        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6834        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6835    })
6836    @LayoutDir
6837    public int getRawLayoutDirection() {
6838        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6839    }
6840
6841    /**
6842     * Set the layout direction for this view. This will propagate a reset of layout direction
6843     * resolution to the view's children and resolve layout direction for this view.
6844     *
6845     * @param layoutDirection the layout direction to set. Should be one of:
6846     *
6847     * {@link #LAYOUT_DIRECTION_LTR},
6848     * {@link #LAYOUT_DIRECTION_RTL},
6849     * {@link #LAYOUT_DIRECTION_INHERIT},
6850     * {@link #LAYOUT_DIRECTION_LOCALE}.
6851     *
6852     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6853     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6854     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6855     *
6856     * @attr ref android.R.styleable#View_layoutDirection
6857     */
6858    @RemotableViewMethod
6859    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6860        if (getRawLayoutDirection() != layoutDirection) {
6861            // Reset the current layout direction and the resolved one
6862            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6863            resetRtlProperties();
6864            // Set the new layout direction (filtered)
6865            mPrivateFlags2 |=
6866                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6867            // We need to resolve all RTL properties as they all depend on layout direction
6868            resolveRtlPropertiesIfNeeded();
6869            requestLayout();
6870            invalidate(true);
6871        }
6872    }
6873
6874    /**
6875     * Returns the resolved layout direction for this view.
6876     *
6877     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6878     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6879     *
6880     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6881     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6882     *
6883     * @attr ref android.R.styleable#View_layoutDirection
6884     */
6885    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6886        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6887        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6888    })
6889    @ResolvedLayoutDir
6890    public int getLayoutDirection() {
6891        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6892        if (targetSdkVersion < JELLY_BEAN_MR1) {
6893            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6894            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6895        }
6896        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6897                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6898    }
6899
6900    /**
6901     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6902     * layout attribute and/or the inherited value from the parent
6903     *
6904     * @return true if the layout is right-to-left.
6905     *
6906     * @hide
6907     */
6908    @ViewDebug.ExportedProperty(category = "layout")
6909    public boolean isLayoutRtl() {
6910        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6911    }
6912
6913    /**
6914     * Indicates whether the view is currently tracking transient state that the
6915     * app should not need to concern itself with saving and restoring, but that
6916     * the framework should take special note to preserve when possible.
6917     *
6918     * <p>A view with transient state cannot be trivially rebound from an external
6919     * data source, such as an adapter binding item views in a list. This may be
6920     * because the view is performing an animation, tracking user selection
6921     * of content, or similar.</p>
6922     *
6923     * @return true if the view has transient state
6924     */
6925    @ViewDebug.ExportedProperty(category = "layout")
6926    public boolean hasTransientState() {
6927        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6928    }
6929
6930    /**
6931     * Set whether this view is currently tracking transient state that the
6932     * framework should attempt to preserve when possible. This flag is reference counted,
6933     * so every call to setHasTransientState(true) should be paired with a later call
6934     * to setHasTransientState(false).
6935     *
6936     * <p>A view with transient state cannot be trivially rebound from an external
6937     * data source, such as an adapter binding item views in a list. This may be
6938     * because the view is performing an animation, tracking user selection
6939     * of content, or similar.</p>
6940     *
6941     * @param hasTransientState true if this view has transient state
6942     */
6943    public void setHasTransientState(boolean hasTransientState) {
6944        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6945                mTransientStateCount - 1;
6946        if (mTransientStateCount < 0) {
6947            mTransientStateCount = 0;
6948            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6949                    "unmatched pair of setHasTransientState calls");
6950        } else if ((hasTransientState && mTransientStateCount == 1) ||
6951                (!hasTransientState && mTransientStateCount == 0)) {
6952            // update flag if we've just incremented up from 0 or decremented down to 0
6953            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6954                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6955            if (mParent != null) {
6956                try {
6957                    mParent.childHasTransientStateChanged(this, hasTransientState);
6958                } catch (AbstractMethodError e) {
6959                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6960                            " does not fully implement ViewParent", e);
6961                }
6962            }
6963        }
6964    }
6965
6966    /**
6967     * Returns true if this view is currently attached to a window.
6968     */
6969    public boolean isAttachedToWindow() {
6970        return mAttachInfo != null;
6971    }
6972
6973    /**
6974     * Returns true if this view has been through at least one layout since it
6975     * was last attached to or detached from a window.
6976     */
6977    public boolean isLaidOut() {
6978        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6979    }
6980
6981    /**
6982     * If this view doesn't do any drawing on its own, set this flag to
6983     * allow further optimizations. By default, this flag is not set on
6984     * View, but could be set on some View subclasses such as ViewGroup.
6985     *
6986     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6987     * you should clear this flag.
6988     *
6989     * @param willNotDraw whether or not this View draw on its own
6990     */
6991    public void setWillNotDraw(boolean willNotDraw) {
6992        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6993    }
6994
6995    /**
6996     * Returns whether or not this View draws on its own.
6997     *
6998     * @return true if this view has nothing to draw, false otherwise
6999     */
7000    @ViewDebug.ExportedProperty(category = "drawing")
7001    public boolean willNotDraw() {
7002        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7003    }
7004
7005    /**
7006     * When a View's drawing cache is enabled, drawing is redirected to an
7007     * offscreen bitmap. Some views, like an ImageView, must be able to
7008     * bypass this mechanism if they already draw a single bitmap, to avoid
7009     * unnecessary usage of the memory.
7010     *
7011     * @param willNotCacheDrawing true if this view does not cache its
7012     *        drawing, false otherwise
7013     */
7014    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7015        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7016    }
7017
7018    /**
7019     * Returns whether or not this View can cache its drawing or not.
7020     *
7021     * @return true if this view does not cache its drawing, false otherwise
7022     */
7023    @ViewDebug.ExportedProperty(category = "drawing")
7024    public boolean willNotCacheDrawing() {
7025        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7026    }
7027
7028    /**
7029     * Indicates whether this view reacts to click events or not.
7030     *
7031     * @return true if the view is clickable, false otherwise
7032     *
7033     * @see #setClickable(boolean)
7034     * @attr ref android.R.styleable#View_clickable
7035     */
7036    @ViewDebug.ExportedProperty
7037    public boolean isClickable() {
7038        return (mViewFlags & CLICKABLE) == CLICKABLE;
7039    }
7040
7041    /**
7042     * Enables or disables click events for this view. When a view
7043     * is clickable it will change its state to "pressed" on every click.
7044     * Subclasses should set the view clickable to visually react to
7045     * user's clicks.
7046     *
7047     * @param clickable true to make the view clickable, false otherwise
7048     *
7049     * @see #isClickable()
7050     * @attr ref android.R.styleable#View_clickable
7051     */
7052    public void setClickable(boolean clickable) {
7053        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7054    }
7055
7056    /**
7057     * Indicates whether this view reacts to long click events or not.
7058     *
7059     * @return true if the view is long clickable, false otherwise
7060     *
7061     * @see #setLongClickable(boolean)
7062     * @attr ref android.R.styleable#View_longClickable
7063     */
7064    public boolean isLongClickable() {
7065        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7066    }
7067
7068    /**
7069     * Enables or disables long click events for this view. When a view is long
7070     * clickable it reacts to the user holding down the button for a longer
7071     * duration than a tap. This event can either launch the listener or a
7072     * context menu.
7073     *
7074     * @param longClickable true to make the view long clickable, false otherwise
7075     * @see #isLongClickable()
7076     * @attr ref android.R.styleable#View_longClickable
7077     */
7078    public void setLongClickable(boolean longClickable) {
7079        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7080    }
7081
7082    /**
7083     * Sets the pressed state for this view and provides a touch coordinate for
7084     * animation hinting.
7085     *
7086     * @param pressed Pass true to set the View's internal state to "pressed",
7087     *            or false to reverts the View's internal state from a
7088     *            previously set "pressed" state.
7089     * @param x The x coordinate of the touch that caused the press
7090     * @param y The y coordinate of the touch that caused the press
7091     */
7092    private void setPressed(boolean pressed, float x, float y) {
7093        if (pressed) {
7094            drawableHotspotChanged(x, y);
7095        }
7096
7097        setPressed(pressed);
7098    }
7099
7100    /**
7101     * Sets the pressed state for this view.
7102     *
7103     * @see #isClickable()
7104     * @see #setClickable(boolean)
7105     *
7106     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7107     *        the View's internal state from a previously set "pressed" state.
7108     */
7109    public void setPressed(boolean pressed) {
7110        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7111
7112        if (pressed) {
7113            mPrivateFlags |= PFLAG_PRESSED;
7114        } else {
7115            mPrivateFlags &= ~PFLAG_PRESSED;
7116        }
7117
7118        if (needsRefresh) {
7119            refreshDrawableState();
7120        }
7121        dispatchSetPressed(pressed);
7122    }
7123
7124    /**
7125     * Dispatch setPressed to all of this View's children.
7126     *
7127     * @see #setPressed(boolean)
7128     *
7129     * @param pressed The new pressed state
7130     */
7131    protected void dispatchSetPressed(boolean pressed) {
7132    }
7133
7134    /**
7135     * Indicates whether the view is currently in pressed state. Unless
7136     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7137     * the pressed state.
7138     *
7139     * @see #setPressed(boolean)
7140     * @see #isClickable()
7141     * @see #setClickable(boolean)
7142     *
7143     * @return true if the view is currently pressed, false otherwise
7144     */
7145    @ViewDebug.ExportedProperty
7146    public boolean isPressed() {
7147        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7148    }
7149
7150    /**
7151     * Indicates whether this view will save its state (that is,
7152     * whether its {@link #onSaveInstanceState} method will be called).
7153     *
7154     * @return Returns true if the view state saving is enabled, else false.
7155     *
7156     * @see #setSaveEnabled(boolean)
7157     * @attr ref android.R.styleable#View_saveEnabled
7158     */
7159    public boolean isSaveEnabled() {
7160        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7161    }
7162
7163    /**
7164     * Controls whether the saving of this view's state is
7165     * enabled (that is, whether its {@link #onSaveInstanceState} method
7166     * will be called).  Note that even if freezing is enabled, the
7167     * view still must have an id assigned to it (via {@link #setId(int)})
7168     * for its state to be saved.  This flag can only disable the
7169     * saving of this view; any child views may still have their state saved.
7170     *
7171     * @param enabled Set to false to <em>disable</em> state saving, or true
7172     * (the default) to allow it.
7173     *
7174     * @see #isSaveEnabled()
7175     * @see #setId(int)
7176     * @see #onSaveInstanceState()
7177     * @attr ref android.R.styleable#View_saveEnabled
7178     */
7179    public void setSaveEnabled(boolean enabled) {
7180        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7181    }
7182
7183    /**
7184     * Gets whether the framework should discard touches when the view's
7185     * window is obscured by another visible window.
7186     * Refer to the {@link View} security documentation for more details.
7187     *
7188     * @return True if touch filtering is enabled.
7189     *
7190     * @see #setFilterTouchesWhenObscured(boolean)
7191     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7192     */
7193    @ViewDebug.ExportedProperty
7194    public boolean getFilterTouchesWhenObscured() {
7195        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7196    }
7197
7198    /**
7199     * Sets whether the framework should discard touches when the view's
7200     * window is obscured by another visible window.
7201     * Refer to the {@link View} security documentation for more details.
7202     *
7203     * @param enabled True if touch filtering should be enabled.
7204     *
7205     * @see #getFilterTouchesWhenObscured
7206     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7207     */
7208    public void setFilterTouchesWhenObscured(boolean enabled) {
7209        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7210                FILTER_TOUCHES_WHEN_OBSCURED);
7211    }
7212
7213    /**
7214     * Indicates whether the entire hierarchy under this view will save its
7215     * state when a state saving traversal occurs from its parent.  The default
7216     * is true; if false, these views will not be saved unless
7217     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7218     *
7219     * @return Returns true if the view state saving from parent is enabled, else false.
7220     *
7221     * @see #setSaveFromParentEnabled(boolean)
7222     */
7223    public boolean isSaveFromParentEnabled() {
7224        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7225    }
7226
7227    /**
7228     * Controls whether the entire hierarchy under this view will save its
7229     * state when a state saving traversal occurs from its parent.  The default
7230     * is true; if false, these views will not be saved unless
7231     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7232     *
7233     * @param enabled Set to false to <em>disable</em> state saving, or true
7234     * (the default) to allow it.
7235     *
7236     * @see #isSaveFromParentEnabled()
7237     * @see #setId(int)
7238     * @see #onSaveInstanceState()
7239     */
7240    public void setSaveFromParentEnabled(boolean enabled) {
7241        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7242    }
7243
7244
7245    /**
7246     * Returns whether this View is able to take focus.
7247     *
7248     * @return True if this view can take focus, or false otherwise.
7249     * @attr ref android.R.styleable#View_focusable
7250     */
7251    @ViewDebug.ExportedProperty(category = "focus")
7252    public final boolean isFocusable() {
7253        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7254    }
7255
7256    /**
7257     * When a view is focusable, it may not want to take focus when in touch mode.
7258     * For example, a button would like focus when the user is navigating via a D-pad
7259     * so that the user can click on it, but once the user starts touching the screen,
7260     * the button shouldn't take focus
7261     * @return Whether the view is focusable in touch mode.
7262     * @attr ref android.R.styleable#View_focusableInTouchMode
7263     */
7264    @ViewDebug.ExportedProperty
7265    public final boolean isFocusableInTouchMode() {
7266        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7267    }
7268
7269    /**
7270     * Find the nearest view in the specified direction that can take focus.
7271     * This does not actually give focus to that view.
7272     *
7273     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7274     *
7275     * @return The nearest focusable in the specified direction, or null if none
7276     *         can be found.
7277     */
7278    public View focusSearch(@FocusRealDirection int direction) {
7279        if (mParent != null) {
7280            return mParent.focusSearch(this, direction);
7281        } else {
7282            return null;
7283        }
7284    }
7285
7286    /**
7287     * This method is the last chance for the focused view and its ancestors to
7288     * respond to an arrow key. This is called when the focused view did not
7289     * consume the key internally, nor could the view system find a new view in
7290     * the requested direction to give focus to.
7291     *
7292     * @param focused The currently focused view.
7293     * @param direction The direction focus wants to move. One of FOCUS_UP,
7294     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7295     * @return True if the this view consumed this unhandled move.
7296     */
7297    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7298        return false;
7299    }
7300
7301    /**
7302     * If a user manually specified the next view id for a particular direction,
7303     * use the root to look up the view.
7304     * @param root The root view of the hierarchy containing this view.
7305     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7306     * or FOCUS_BACKWARD.
7307     * @return The user specified next view, or null if there is none.
7308     */
7309    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7310        switch (direction) {
7311            case FOCUS_LEFT:
7312                if (mNextFocusLeftId == View.NO_ID) return null;
7313                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7314            case FOCUS_RIGHT:
7315                if (mNextFocusRightId == View.NO_ID) return null;
7316                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7317            case FOCUS_UP:
7318                if (mNextFocusUpId == View.NO_ID) return null;
7319                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7320            case FOCUS_DOWN:
7321                if (mNextFocusDownId == View.NO_ID) return null;
7322                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7323            case FOCUS_FORWARD:
7324                if (mNextFocusForwardId == View.NO_ID) return null;
7325                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7326            case FOCUS_BACKWARD: {
7327                if (mID == View.NO_ID) return null;
7328                final int id = mID;
7329                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7330                    @Override
7331                    public boolean apply(View t) {
7332                        return t.mNextFocusForwardId == id;
7333                    }
7334                });
7335            }
7336        }
7337        return null;
7338    }
7339
7340    private View findViewInsideOutShouldExist(View root, int id) {
7341        if (mMatchIdPredicate == null) {
7342            mMatchIdPredicate = new MatchIdPredicate();
7343        }
7344        mMatchIdPredicate.mId = id;
7345        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7346        if (result == null) {
7347            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7348        }
7349        return result;
7350    }
7351
7352    /**
7353     * Find and return all focusable views that are descendants of this view,
7354     * possibly including this view if it is focusable itself.
7355     *
7356     * @param direction The direction of the focus
7357     * @return A list of focusable views
7358     */
7359    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7360        ArrayList<View> result = new ArrayList<View>(24);
7361        addFocusables(result, direction);
7362        return result;
7363    }
7364
7365    /**
7366     * Add any focusable views that are descendants of this view (possibly
7367     * including this view if it is focusable itself) to views.  If we are in touch mode,
7368     * only add views that are also focusable in touch mode.
7369     *
7370     * @param views Focusable views found so far
7371     * @param direction The direction of the focus
7372     */
7373    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7374        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7375    }
7376
7377    /**
7378     * Adds any focusable views that are descendants of this view (possibly
7379     * including this view if it is focusable itself) to views. This method
7380     * adds all focusable views regardless if we are in touch mode or
7381     * only views focusable in touch mode if we are in touch mode or
7382     * only views that can take accessibility focus if accessibility is enabeld
7383     * depending on the focusable mode paramater.
7384     *
7385     * @param views Focusable views found so far or null if all we are interested is
7386     *        the number of focusables.
7387     * @param direction The direction of the focus.
7388     * @param focusableMode The type of focusables to be added.
7389     *
7390     * @see #FOCUSABLES_ALL
7391     * @see #FOCUSABLES_TOUCH_MODE
7392     */
7393    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7394            @FocusableMode int focusableMode) {
7395        if (views == null) {
7396            return;
7397        }
7398        if (!isFocusable()) {
7399            return;
7400        }
7401        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7402                && isInTouchMode() && !isFocusableInTouchMode()) {
7403            return;
7404        }
7405        views.add(this);
7406    }
7407
7408    /**
7409     * Finds the Views that contain given text. The containment is case insensitive.
7410     * The search is performed by either the text that the View renders or the content
7411     * description that describes the view for accessibility purposes and the view does
7412     * not render or both. Clients can specify how the search is to be performed via
7413     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7414     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7415     *
7416     * @param outViews The output list of matching Views.
7417     * @param searched The text to match against.
7418     *
7419     * @see #FIND_VIEWS_WITH_TEXT
7420     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7421     * @see #setContentDescription(CharSequence)
7422     */
7423    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7424            @FindViewFlags int flags) {
7425        if (getAccessibilityNodeProvider() != null) {
7426            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7427                outViews.add(this);
7428            }
7429        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7430                && (searched != null && searched.length() > 0)
7431                && (mContentDescription != null && mContentDescription.length() > 0)) {
7432            String searchedLowerCase = searched.toString().toLowerCase();
7433            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7434            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7435                outViews.add(this);
7436            }
7437        }
7438    }
7439
7440    /**
7441     * Find and return all touchable views that are descendants of this view,
7442     * possibly including this view if it is touchable itself.
7443     *
7444     * @return A list of touchable views
7445     */
7446    public ArrayList<View> getTouchables() {
7447        ArrayList<View> result = new ArrayList<View>();
7448        addTouchables(result);
7449        return result;
7450    }
7451
7452    /**
7453     * Add any touchable views that are descendants of this view (possibly
7454     * including this view if it is touchable itself) to views.
7455     *
7456     * @param views Touchable views found so far
7457     */
7458    public void addTouchables(ArrayList<View> views) {
7459        final int viewFlags = mViewFlags;
7460
7461        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7462                && (viewFlags & ENABLED_MASK) == ENABLED) {
7463            views.add(this);
7464        }
7465    }
7466
7467    /**
7468     * Returns whether this View is accessibility focused.
7469     *
7470     * @return True if this View is accessibility focused.
7471     */
7472    public boolean isAccessibilityFocused() {
7473        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7474    }
7475
7476    /**
7477     * Call this to try to give accessibility focus to this view.
7478     *
7479     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7480     * returns false or the view is no visible or the view already has accessibility
7481     * focus.
7482     *
7483     * See also {@link #focusSearch(int)}, which is what you call to say that you
7484     * have focus, and you want your parent to look for the next one.
7485     *
7486     * @return Whether this view actually took accessibility focus.
7487     *
7488     * @hide
7489     */
7490    public boolean requestAccessibilityFocus() {
7491        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7492        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7493            return false;
7494        }
7495        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7496            return false;
7497        }
7498        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7499            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7500            ViewRootImpl viewRootImpl = getViewRootImpl();
7501            if (viewRootImpl != null) {
7502                viewRootImpl.setAccessibilityFocus(this, null);
7503            }
7504            invalidate();
7505            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7506            return true;
7507        }
7508        return false;
7509    }
7510
7511    /**
7512     * Call this to try to clear accessibility focus of this view.
7513     *
7514     * See also {@link #focusSearch(int)}, which is what you call to say that you
7515     * have focus, and you want your parent to look for the next one.
7516     *
7517     * @hide
7518     */
7519    public void clearAccessibilityFocus() {
7520        clearAccessibilityFocusNoCallbacks();
7521        // Clear the global reference of accessibility focus if this
7522        // view or any of its descendants had accessibility focus.
7523        ViewRootImpl viewRootImpl = getViewRootImpl();
7524        if (viewRootImpl != null) {
7525            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7526            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7527                viewRootImpl.setAccessibilityFocus(null, null);
7528            }
7529        }
7530    }
7531
7532    private void sendAccessibilityHoverEvent(int eventType) {
7533        // Since we are not delivering to a client accessibility events from not
7534        // important views (unless the clinet request that) we need to fire the
7535        // event from the deepest view exposed to the client. As a consequence if
7536        // the user crosses a not exposed view the client will see enter and exit
7537        // of the exposed predecessor followed by and enter and exit of that same
7538        // predecessor when entering and exiting the not exposed descendant. This
7539        // is fine since the client has a clear idea which view is hovered at the
7540        // price of a couple more events being sent. This is a simple and
7541        // working solution.
7542        View source = this;
7543        while (true) {
7544            if (source.includeForAccessibility()) {
7545                source.sendAccessibilityEvent(eventType);
7546                return;
7547            }
7548            ViewParent parent = source.getParent();
7549            if (parent instanceof View) {
7550                source = (View) parent;
7551            } else {
7552                return;
7553            }
7554        }
7555    }
7556
7557    /**
7558     * Clears accessibility focus without calling any callback methods
7559     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7560     * is used for clearing accessibility focus when giving this focus to
7561     * another view.
7562     */
7563    void clearAccessibilityFocusNoCallbacks() {
7564        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7565            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7566            invalidate();
7567            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7568        }
7569    }
7570
7571    /**
7572     * Call this to try to give focus to a specific view or to one of its
7573     * descendants.
7574     *
7575     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7576     * false), or if it is focusable and it is not focusable in touch mode
7577     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7578     *
7579     * See also {@link #focusSearch(int)}, which is what you call to say that you
7580     * have focus, and you want your parent to look for the next one.
7581     *
7582     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7583     * {@link #FOCUS_DOWN} and <code>null</code>.
7584     *
7585     * @return Whether this view or one of its descendants actually took focus.
7586     */
7587    public final boolean requestFocus() {
7588        return requestFocus(View.FOCUS_DOWN);
7589    }
7590
7591    /**
7592     * Call this to try to give focus to a specific view or to one of its
7593     * descendants and give it a hint about what direction focus is heading.
7594     *
7595     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7596     * false), or if it is focusable and it is not focusable in touch mode
7597     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7598     *
7599     * See also {@link #focusSearch(int)}, which is what you call to say that you
7600     * have focus, and you want your parent to look for the next one.
7601     *
7602     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7603     * <code>null</code> set for the previously focused rectangle.
7604     *
7605     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7606     * @return Whether this view or one of its descendants actually took focus.
7607     */
7608    public final boolean requestFocus(int direction) {
7609        return requestFocus(direction, null);
7610    }
7611
7612    /**
7613     * Call this to try to give focus to a specific view or to one of its descendants
7614     * and give it hints about the direction and a specific rectangle that the focus
7615     * is coming from.  The rectangle can help give larger views a finer grained hint
7616     * about where focus is coming from, and therefore, where to show selection, or
7617     * forward focus change internally.
7618     *
7619     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7620     * false), or if it is focusable and it is not focusable in touch mode
7621     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7622     *
7623     * A View will not take focus if it is not visible.
7624     *
7625     * A View will not take focus if one of its parents has
7626     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7627     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7628     *
7629     * See also {@link #focusSearch(int)}, which is what you call to say that you
7630     * have focus, and you want your parent to look for the next one.
7631     *
7632     * You may wish to override this method if your custom {@link View} has an internal
7633     * {@link View} that it wishes to forward the request to.
7634     *
7635     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7636     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7637     *        to give a finer grained hint about where focus is coming from.  May be null
7638     *        if there is no hint.
7639     * @return Whether this view or one of its descendants actually took focus.
7640     */
7641    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7642        return requestFocusNoSearch(direction, previouslyFocusedRect);
7643    }
7644
7645    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7646        // need to be focusable
7647        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7648                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7649            return false;
7650        }
7651
7652        // need to be focusable in touch mode if in touch mode
7653        if (isInTouchMode() &&
7654            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7655               return false;
7656        }
7657
7658        // need to not have any parents blocking us
7659        if (hasAncestorThatBlocksDescendantFocus()) {
7660            return false;
7661        }
7662
7663        handleFocusGainInternal(direction, previouslyFocusedRect);
7664        return true;
7665    }
7666
7667    /**
7668     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7669     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7670     * touch mode to request focus when they are touched.
7671     *
7672     * @return Whether this view or one of its descendants actually took focus.
7673     *
7674     * @see #isInTouchMode()
7675     *
7676     */
7677    public final boolean requestFocusFromTouch() {
7678        // Leave touch mode if we need to
7679        if (isInTouchMode()) {
7680            ViewRootImpl viewRoot = getViewRootImpl();
7681            if (viewRoot != null) {
7682                viewRoot.ensureTouchMode(false);
7683            }
7684        }
7685        return requestFocus(View.FOCUS_DOWN);
7686    }
7687
7688    /**
7689     * @return Whether any ancestor of this view blocks descendant focus.
7690     */
7691    private boolean hasAncestorThatBlocksDescendantFocus() {
7692        final boolean focusableInTouchMode = isFocusableInTouchMode();
7693        ViewParent ancestor = mParent;
7694        while (ancestor instanceof ViewGroup) {
7695            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7696            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7697                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7698                return true;
7699            } else {
7700                ancestor = vgAncestor.getParent();
7701            }
7702        }
7703        return false;
7704    }
7705
7706    /**
7707     * Gets the mode for determining whether this View is important for accessibility
7708     * which is if it fires accessibility events and if it is reported to
7709     * accessibility services that query the screen.
7710     *
7711     * @return The mode for determining whether a View is important for accessibility.
7712     *
7713     * @attr ref android.R.styleable#View_importantForAccessibility
7714     *
7715     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7716     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7717     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7718     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7719     */
7720    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7721            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7722            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7723            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7724            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7725                    to = "noHideDescendants")
7726        })
7727    public int getImportantForAccessibility() {
7728        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7729                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7730    }
7731
7732    /**
7733     * Sets the live region mode for this view. This indicates to accessibility
7734     * services whether they should automatically notify the user about changes
7735     * to the view's content description or text, or to the content descriptions
7736     * or text of the view's children (where applicable).
7737     * <p>
7738     * For example, in a login screen with a TextView that displays an "incorrect
7739     * password" notification, that view should be marked as a live region with
7740     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7741     * <p>
7742     * To disable change notifications for this view, use
7743     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7744     * mode for most views.
7745     * <p>
7746     * To indicate that the user should be notified of changes, use
7747     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7748     * <p>
7749     * If the view's changes should interrupt ongoing speech and notify the user
7750     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7751     *
7752     * @param mode The live region mode for this view, one of:
7753     *        <ul>
7754     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7755     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7756     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7757     *        </ul>
7758     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7759     */
7760    public void setAccessibilityLiveRegion(int mode) {
7761        if (mode != getAccessibilityLiveRegion()) {
7762            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7763            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7764                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7765            notifyViewAccessibilityStateChangedIfNeeded(
7766                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7767        }
7768    }
7769
7770    /**
7771     * Gets the live region mode for this View.
7772     *
7773     * @return The live region mode for the view.
7774     *
7775     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7776     *
7777     * @see #setAccessibilityLiveRegion(int)
7778     */
7779    public int getAccessibilityLiveRegion() {
7780        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7781                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7782    }
7783
7784    /**
7785     * Sets how to determine whether this view is important for accessibility
7786     * which is if it fires accessibility events and if it is reported to
7787     * accessibility services that query the screen.
7788     *
7789     * @param mode How to determine whether this view is important for accessibility.
7790     *
7791     * @attr ref android.R.styleable#View_importantForAccessibility
7792     *
7793     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7794     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7795     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7796     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7797     */
7798    public void setImportantForAccessibility(int mode) {
7799        final int oldMode = getImportantForAccessibility();
7800        if (mode != oldMode) {
7801            // If we're moving between AUTO and another state, we might not need
7802            // to send a subtree changed notification. We'll store the computed
7803            // importance, since we'll need to check it later to make sure.
7804            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7805                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7806            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7807            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7808            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7809                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7810            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7811                notifySubtreeAccessibilityStateChangedIfNeeded();
7812            } else {
7813                notifyViewAccessibilityStateChangedIfNeeded(
7814                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7815            }
7816        }
7817    }
7818
7819    /**
7820     * Computes whether this view should be exposed for accessibility. In
7821     * general, views that are interactive or provide information are exposed
7822     * while views that serve only as containers are hidden.
7823     * <p>
7824     * If an ancestor of this view has importance
7825     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7826     * returns <code>false</code>.
7827     * <p>
7828     * Otherwise, the value is computed according to the view's
7829     * {@link #getImportantForAccessibility()} value:
7830     * <ol>
7831     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7832     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7833     * </code>
7834     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7835     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7836     * view satisfies any of the following:
7837     * <ul>
7838     * <li>Is actionable, e.g. {@link #isClickable()},
7839     * {@link #isLongClickable()}, or {@link #isFocusable()}
7840     * <li>Has an {@link AccessibilityDelegate}
7841     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7842     * {@link OnKeyListener}, etc.
7843     * <li>Is an accessibility live region, e.g.
7844     * {@link #getAccessibilityLiveRegion()} is not
7845     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7846     * </ul>
7847     * </ol>
7848     *
7849     * @return Whether the view is exposed for accessibility.
7850     * @see #setImportantForAccessibility(int)
7851     * @see #getImportantForAccessibility()
7852     */
7853    public boolean isImportantForAccessibility() {
7854        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7855                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7856        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7857                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7858            return false;
7859        }
7860
7861        // Check parent mode to ensure we're not hidden.
7862        ViewParent parent = mParent;
7863        while (parent instanceof View) {
7864            if (((View) parent).getImportantForAccessibility()
7865                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7866                return false;
7867            }
7868            parent = parent.getParent();
7869        }
7870
7871        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7872                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7873                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7874    }
7875
7876    /**
7877     * Gets the parent for accessibility purposes. Note that the parent for
7878     * accessibility is not necessary the immediate parent. It is the first
7879     * predecessor that is important for accessibility.
7880     *
7881     * @return The parent for accessibility purposes.
7882     */
7883    public ViewParent getParentForAccessibility() {
7884        if (mParent instanceof View) {
7885            View parentView = (View) mParent;
7886            if (parentView.includeForAccessibility()) {
7887                return mParent;
7888            } else {
7889                return mParent.getParentForAccessibility();
7890            }
7891        }
7892        return null;
7893    }
7894
7895    /**
7896     * Adds the children of a given View for accessibility. Since some Views are
7897     * not important for accessibility the children for accessibility are not
7898     * necessarily direct children of the view, rather they are the first level of
7899     * descendants important for accessibility.
7900     *
7901     * @param children The list of children for accessibility.
7902     */
7903    public void addChildrenForAccessibility(ArrayList<View> children) {
7904
7905    }
7906
7907    /**
7908     * Whether to regard this view for accessibility. A view is regarded for
7909     * accessibility if it is important for accessibility or the querying
7910     * accessibility service has explicitly requested that view not
7911     * important for accessibility are regarded.
7912     *
7913     * @return Whether to regard the view for accessibility.
7914     *
7915     * @hide
7916     */
7917    public boolean includeForAccessibility() {
7918        if (mAttachInfo != null) {
7919            return (mAttachInfo.mAccessibilityFetchFlags
7920                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7921                    || isImportantForAccessibility();
7922        }
7923        return false;
7924    }
7925
7926    /**
7927     * Returns whether the View is considered actionable from
7928     * accessibility perspective. Such view are important for
7929     * accessibility.
7930     *
7931     * @return True if the view is actionable for accessibility.
7932     *
7933     * @hide
7934     */
7935    public boolean isActionableForAccessibility() {
7936        return (isClickable() || isLongClickable() || isFocusable());
7937    }
7938
7939    /**
7940     * Returns whether the View has registered callbacks which makes it
7941     * important for accessibility.
7942     *
7943     * @return True if the view is actionable for accessibility.
7944     */
7945    private boolean hasListenersForAccessibility() {
7946        ListenerInfo info = getListenerInfo();
7947        return mTouchDelegate != null || info.mOnKeyListener != null
7948                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7949                || info.mOnHoverListener != null || info.mOnDragListener != null;
7950    }
7951
7952    /**
7953     * Notifies that the accessibility state of this view changed. The change
7954     * is local to this view and does not represent structural changes such
7955     * as children and parent. For example, the view became focusable. The
7956     * notification is at at most once every
7957     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7958     * to avoid unnecessary load to the system. Also once a view has a pending
7959     * notification this method is a NOP until the notification has been sent.
7960     *
7961     * @hide
7962     */
7963    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7964        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7965            return;
7966        }
7967        if (mSendViewStateChangedAccessibilityEvent == null) {
7968            mSendViewStateChangedAccessibilityEvent =
7969                    new SendViewStateChangedAccessibilityEvent();
7970        }
7971        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7972    }
7973
7974    /**
7975     * Notifies that the accessibility state of this view changed. The change
7976     * is *not* local to this view and does represent structural changes such
7977     * as children and parent. For example, the view size changed. The
7978     * notification is at at most once every
7979     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7980     * to avoid unnecessary load to the system. Also once a view has a pending
7981     * notification this method is a NOP until the notification has been sent.
7982     *
7983     * @hide
7984     */
7985    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7986        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7987            return;
7988        }
7989        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7990            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7991            if (mParent != null) {
7992                try {
7993                    mParent.notifySubtreeAccessibilityStateChanged(
7994                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7995                } catch (AbstractMethodError e) {
7996                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7997                            " does not fully implement ViewParent", e);
7998                }
7999            }
8000        }
8001    }
8002
8003    /**
8004     * Reset the flag indicating the accessibility state of the subtree rooted
8005     * at this view changed.
8006     */
8007    void resetSubtreeAccessibilityStateChanged() {
8008        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8009    }
8010
8011    /**
8012     * Performs the specified accessibility action on the view. For
8013     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8014     * <p>
8015     * If an {@link AccessibilityDelegate} has been specified via calling
8016     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8017     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8018     * is responsible for handling this call.
8019     * </p>
8020     *
8021     * @param action The action to perform.
8022     * @param arguments Optional action arguments.
8023     * @return Whether the action was performed.
8024     */
8025    public boolean performAccessibilityAction(int action, Bundle arguments) {
8026      if (mAccessibilityDelegate != null) {
8027          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8028      } else {
8029          return performAccessibilityActionInternal(action, arguments);
8030      }
8031    }
8032
8033   /**
8034    * @see #performAccessibilityAction(int, Bundle)
8035    *
8036    * Note: Called from the default {@link AccessibilityDelegate}.
8037    */
8038    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8039        switch (action) {
8040            case AccessibilityNodeInfo.ACTION_CLICK: {
8041                if (isClickable()) {
8042                    performClick();
8043                    return true;
8044                }
8045            } break;
8046            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8047                if (isLongClickable()) {
8048                    performLongClick();
8049                    return true;
8050                }
8051            } break;
8052            case AccessibilityNodeInfo.ACTION_FOCUS: {
8053                if (!hasFocus()) {
8054                    // Get out of touch mode since accessibility
8055                    // wants to move focus around.
8056                    getViewRootImpl().ensureTouchMode(false);
8057                    return requestFocus();
8058                }
8059            } break;
8060            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8061                if (hasFocus()) {
8062                    clearFocus();
8063                    return !isFocused();
8064                }
8065            } break;
8066            case AccessibilityNodeInfo.ACTION_SELECT: {
8067                if (!isSelected()) {
8068                    setSelected(true);
8069                    return isSelected();
8070                }
8071            } break;
8072            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8073                if (isSelected()) {
8074                    setSelected(false);
8075                    return !isSelected();
8076                }
8077            } break;
8078            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8079                if (!isAccessibilityFocused()) {
8080                    return requestAccessibilityFocus();
8081                }
8082            } break;
8083            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8084                if (isAccessibilityFocused()) {
8085                    clearAccessibilityFocus();
8086                    return true;
8087                }
8088            } break;
8089            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8090                if (arguments != null) {
8091                    final int granularity = arguments.getInt(
8092                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8093                    final boolean extendSelection = arguments.getBoolean(
8094                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8095                    return traverseAtGranularity(granularity, true, extendSelection);
8096                }
8097            } break;
8098            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8099                if (arguments != null) {
8100                    final int granularity = arguments.getInt(
8101                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8102                    final boolean extendSelection = arguments.getBoolean(
8103                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8104                    return traverseAtGranularity(granularity, false, extendSelection);
8105                }
8106            } break;
8107            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8108                CharSequence text = getIterableTextForAccessibility();
8109                if (text == null) {
8110                    return false;
8111                }
8112                final int start = (arguments != null) ? arguments.getInt(
8113                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8114                final int end = (arguments != null) ? arguments.getInt(
8115                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8116                // Only cursor position can be specified (selection length == 0)
8117                if ((getAccessibilitySelectionStart() != start
8118                        || getAccessibilitySelectionEnd() != end)
8119                        && (start == end)) {
8120                    setAccessibilitySelection(start, end);
8121                    notifyViewAccessibilityStateChangedIfNeeded(
8122                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8123                    return true;
8124                }
8125            } break;
8126        }
8127        return false;
8128    }
8129
8130    private boolean traverseAtGranularity(int granularity, boolean forward,
8131            boolean extendSelection) {
8132        CharSequence text = getIterableTextForAccessibility();
8133        if (text == null || text.length() == 0) {
8134            return false;
8135        }
8136        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8137        if (iterator == null) {
8138            return false;
8139        }
8140        int current = getAccessibilitySelectionEnd();
8141        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8142            current = forward ? 0 : text.length();
8143        }
8144        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8145        if (range == null) {
8146            return false;
8147        }
8148        final int segmentStart = range[0];
8149        final int segmentEnd = range[1];
8150        int selectionStart;
8151        int selectionEnd;
8152        if (extendSelection && isAccessibilitySelectionExtendable()) {
8153            selectionStart = getAccessibilitySelectionStart();
8154            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8155                selectionStart = forward ? segmentStart : segmentEnd;
8156            }
8157            selectionEnd = forward ? segmentEnd : segmentStart;
8158        } else {
8159            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8160        }
8161        setAccessibilitySelection(selectionStart, selectionEnd);
8162        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8163                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8164        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8165        return true;
8166    }
8167
8168    /**
8169     * Gets the text reported for accessibility purposes.
8170     *
8171     * @return The accessibility text.
8172     *
8173     * @hide
8174     */
8175    public CharSequence getIterableTextForAccessibility() {
8176        return getContentDescription();
8177    }
8178
8179    /**
8180     * Gets whether accessibility selection can be extended.
8181     *
8182     * @return If selection is extensible.
8183     *
8184     * @hide
8185     */
8186    public boolean isAccessibilitySelectionExtendable() {
8187        return false;
8188    }
8189
8190    /**
8191     * @hide
8192     */
8193    public int getAccessibilitySelectionStart() {
8194        return mAccessibilityCursorPosition;
8195    }
8196
8197    /**
8198     * @hide
8199     */
8200    public int getAccessibilitySelectionEnd() {
8201        return getAccessibilitySelectionStart();
8202    }
8203
8204    /**
8205     * @hide
8206     */
8207    public void setAccessibilitySelection(int start, int end) {
8208        if (start ==  end && end == mAccessibilityCursorPosition) {
8209            return;
8210        }
8211        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8212            mAccessibilityCursorPosition = start;
8213        } else {
8214            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8215        }
8216        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8217    }
8218
8219    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8220            int fromIndex, int toIndex) {
8221        if (mParent == null) {
8222            return;
8223        }
8224        AccessibilityEvent event = AccessibilityEvent.obtain(
8225                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8226        onInitializeAccessibilityEvent(event);
8227        onPopulateAccessibilityEvent(event);
8228        event.setFromIndex(fromIndex);
8229        event.setToIndex(toIndex);
8230        event.setAction(action);
8231        event.setMovementGranularity(granularity);
8232        mParent.requestSendAccessibilityEvent(this, event);
8233    }
8234
8235    /**
8236     * @hide
8237     */
8238    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8239        switch (granularity) {
8240            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8241                CharSequence text = getIterableTextForAccessibility();
8242                if (text != null && text.length() > 0) {
8243                    CharacterTextSegmentIterator iterator =
8244                        CharacterTextSegmentIterator.getInstance(
8245                                mContext.getResources().getConfiguration().locale);
8246                    iterator.initialize(text.toString());
8247                    return iterator;
8248                }
8249            } break;
8250            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8251                CharSequence text = getIterableTextForAccessibility();
8252                if (text != null && text.length() > 0) {
8253                    WordTextSegmentIterator iterator =
8254                        WordTextSegmentIterator.getInstance(
8255                                mContext.getResources().getConfiguration().locale);
8256                    iterator.initialize(text.toString());
8257                    return iterator;
8258                }
8259            } break;
8260            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8261                CharSequence text = getIterableTextForAccessibility();
8262                if (text != null && text.length() > 0) {
8263                    ParagraphTextSegmentIterator iterator =
8264                        ParagraphTextSegmentIterator.getInstance();
8265                    iterator.initialize(text.toString());
8266                    return iterator;
8267                }
8268            } break;
8269        }
8270        return null;
8271    }
8272
8273    /**
8274     * @hide
8275     */
8276    public void dispatchStartTemporaryDetach() {
8277        onStartTemporaryDetach();
8278    }
8279
8280    /**
8281     * This is called when a container is going to temporarily detach a child, with
8282     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8283     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8284     * {@link #onDetachedFromWindow()} when the container is done.
8285     */
8286    public void onStartTemporaryDetach() {
8287        removeUnsetPressCallback();
8288        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8289    }
8290
8291    /**
8292     * @hide
8293     */
8294    public void dispatchFinishTemporaryDetach() {
8295        onFinishTemporaryDetach();
8296    }
8297
8298    /**
8299     * Called after {@link #onStartTemporaryDetach} when the container is done
8300     * changing the view.
8301     */
8302    public void onFinishTemporaryDetach() {
8303    }
8304
8305    /**
8306     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8307     * for this view's window.  Returns null if the view is not currently attached
8308     * to the window.  Normally you will not need to use this directly, but
8309     * just use the standard high-level event callbacks like
8310     * {@link #onKeyDown(int, KeyEvent)}.
8311     */
8312    public KeyEvent.DispatcherState getKeyDispatcherState() {
8313        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8314    }
8315
8316    /**
8317     * Dispatch a key event before it is processed by any input method
8318     * associated with the view hierarchy.  This can be used to intercept
8319     * key events in special situations before the IME consumes them; a
8320     * typical example would be handling the BACK key to update the application's
8321     * UI instead of allowing the IME to see it and close itself.
8322     *
8323     * @param event The key event to be dispatched.
8324     * @return True if the event was handled, false otherwise.
8325     */
8326    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8327        return onKeyPreIme(event.getKeyCode(), event);
8328    }
8329
8330    /**
8331     * Dispatch a key event to the next view on the focus path. This path runs
8332     * from the top of the view tree down to the currently focused view. If this
8333     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8334     * the next node down the focus path. This method also fires any key
8335     * listeners.
8336     *
8337     * @param event The key event to be dispatched.
8338     * @return True if the event was handled, false otherwise.
8339     */
8340    public boolean dispatchKeyEvent(KeyEvent event) {
8341        if (mInputEventConsistencyVerifier != null) {
8342            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8343        }
8344
8345        // Give any attached key listener a first crack at the event.
8346        //noinspection SimplifiableIfStatement
8347        ListenerInfo li = mListenerInfo;
8348        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8349                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8350            return true;
8351        }
8352
8353        if (event.dispatch(this, mAttachInfo != null
8354                ? mAttachInfo.mKeyDispatchState : null, this)) {
8355            return true;
8356        }
8357
8358        if (mInputEventConsistencyVerifier != null) {
8359            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8360        }
8361        return false;
8362    }
8363
8364    /**
8365     * Dispatches a key shortcut event.
8366     *
8367     * @param event The key event to be dispatched.
8368     * @return True if the event was handled by the view, false otherwise.
8369     */
8370    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8371        return onKeyShortcut(event.getKeyCode(), event);
8372    }
8373
8374    /**
8375     * Pass the touch screen motion event down to the target view, or this
8376     * view if it is the target.
8377     *
8378     * @param event The motion event to be dispatched.
8379     * @return True if the event was handled by the view, false otherwise.
8380     */
8381    public boolean dispatchTouchEvent(MotionEvent event) {
8382        boolean result = false;
8383
8384        if (mInputEventConsistencyVerifier != null) {
8385            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8386        }
8387
8388        final int actionMasked = event.getActionMasked();
8389        if (actionMasked == MotionEvent.ACTION_DOWN) {
8390            // Defensive cleanup for new gesture
8391            stopNestedScroll();
8392        }
8393
8394        if (onFilterTouchEventForSecurity(event)) {
8395            //noinspection SimplifiableIfStatement
8396            ListenerInfo li = mListenerInfo;
8397            if (li != null && li.mOnTouchListener != null
8398                    && (mViewFlags & ENABLED_MASK) == ENABLED
8399                    && li.mOnTouchListener.onTouch(this, event)) {
8400                result = true;
8401            }
8402
8403            if (!result && onTouchEvent(event)) {
8404                result = true;
8405            }
8406        }
8407
8408        if (!result && mInputEventConsistencyVerifier != null) {
8409            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8410        }
8411
8412        // Clean up after nested scrolls if this is the end of a gesture;
8413        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8414        // of the gesture.
8415        if (actionMasked == MotionEvent.ACTION_UP ||
8416                actionMasked == MotionEvent.ACTION_CANCEL ||
8417                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8418            stopNestedScroll();
8419        }
8420
8421        return result;
8422    }
8423
8424    /**
8425     * Filter the touch event to apply security policies.
8426     *
8427     * @param event The motion event to be filtered.
8428     * @return True if the event should be dispatched, false if the event should be dropped.
8429     *
8430     * @see #getFilterTouchesWhenObscured
8431     */
8432    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8433        //noinspection RedundantIfStatement
8434        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8435                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8436            // Window is obscured, drop this touch.
8437            return false;
8438        }
8439        return true;
8440    }
8441
8442    /**
8443     * Pass a trackball motion event down to the focused view.
8444     *
8445     * @param event The motion event to be dispatched.
8446     * @return True if the event was handled by the view, false otherwise.
8447     */
8448    public boolean dispatchTrackballEvent(MotionEvent event) {
8449        if (mInputEventConsistencyVerifier != null) {
8450            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8451        }
8452
8453        return onTrackballEvent(event);
8454    }
8455
8456    /**
8457     * Dispatch a generic motion event.
8458     * <p>
8459     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8460     * are delivered to the view under the pointer.  All other generic motion events are
8461     * delivered to the focused view.  Hover events are handled specially and are delivered
8462     * to {@link #onHoverEvent(MotionEvent)}.
8463     * </p>
8464     *
8465     * @param event The motion event to be dispatched.
8466     * @return True if the event was handled by the view, false otherwise.
8467     */
8468    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8469        if (mInputEventConsistencyVerifier != null) {
8470            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8471        }
8472
8473        final int source = event.getSource();
8474        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8475            final int action = event.getAction();
8476            if (action == MotionEvent.ACTION_HOVER_ENTER
8477                    || action == MotionEvent.ACTION_HOVER_MOVE
8478                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8479                if (dispatchHoverEvent(event)) {
8480                    return true;
8481                }
8482            } else if (dispatchGenericPointerEvent(event)) {
8483                return true;
8484            }
8485        } else if (dispatchGenericFocusedEvent(event)) {
8486            return true;
8487        }
8488
8489        if (dispatchGenericMotionEventInternal(event)) {
8490            return true;
8491        }
8492
8493        if (mInputEventConsistencyVerifier != null) {
8494            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8495        }
8496        return false;
8497    }
8498
8499    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8500        //noinspection SimplifiableIfStatement
8501        ListenerInfo li = mListenerInfo;
8502        if (li != null && li.mOnGenericMotionListener != null
8503                && (mViewFlags & ENABLED_MASK) == ENABLED
8504                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8505            return true;
8506        }
8507
8508        if (onGenericMotionEvent(event)) {
8509            return true;
8510        }
8511
8512        if (mInputEventConsistencyVerifier != null) {
8513            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8514        }
8515        return false;
8516    }
8517
8518    /**
8519     * Dispatch a hover event.
8520     * <p>
8521     * Do not call this method directly.
8522     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8523     * </p>
8524     *
8525     * @param event The motion event to be dispatched.
8526     * @return True if the event was handled by the view, false otherwise.
8527     */
8528    protected boolean dispatchHoverEvent(MotionEvent event) {
8529        ListenerInfo li = mListenerInfo;
8530        //noinspection SimplifiableIfStatement
8531        if (li != null && li.mOnHoverListener != null
8532                && (mViewFlags & ENABLED_MASK) == ENABLED
8533                && li.mOnHoverListener.onHover(this, event)) {
8534            return true;
8535        }
8536
8537        return onHoverEvent(event);
8538    }
8539
8540    /**
8541     * Returns true if the view has a child to which it has recently sent
8542     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8543     * it does not have a hovered child, then it must be the innermost hovered view.
8544     * @hide
8545     */
8546    protected boolean hasHoveredChild() {
8547        return false;
8548    }
8549
8550    /**
8551     * Dispatch a generic motion event to the view under the first pointer.
8552     * <p>
8553     * Do not call this method directly.
8554     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8555     * </p>
8556     *
8557     * @param event The motion event to be dispatched.
8558     * @return True if the event was handled by the view, false otherwise.
8559     */
8560    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8561        return false;
8562    }
8563
8564    /**
8565     * Dispatch a generic motion event to the currently focused view.
8566     * <p>
8567     * Do not call this method directly.
8568     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8569     * </p>
8570     *
8571     * @param event The motion event to be dispatched.
8572     * @return True if the event was handled by the view, false otherwise.
8573     */
8574    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8575        return false;
8576    }
8577
8578    /**
8579     * Dispatch a pointer event.
8580     * <p>
8581     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8582     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8583     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8584     * and should not be expected to handle other pointing device features.
8585     * </p>
8586     *
8587     * @param event The motion event to be dispatched.
8588     * @return True if the event was handled by the view, false otherwise.
8589     * @hide
8590     */
8591    public final boolean dispatchPointerEvent(MotionEvent event) {
8592        if (event.isTouchEvent()) {
8593            return dispatchTouchEvent(event);
8594        } else {
8595            return dispatchGenericMotionEvent(event);
8596        }
8597    }
8598
8599    /**
8600     * Called when the window containing this view gains or loses window focus.
8601     * ViewGroups should override to route to their children.
8602     *
8603     * @param hasFocus True if the window containing this view now has focus,
8604     *        false otherwise.
8605     */
8606    public void dispatchWindowFocusChanged(boolean hasFocus) {
8607        onWindowFocusChanged(hasFocus);
8608    }
8609
8610    /**
8611     * Called when the window containing this view gains or loses focus.  Note
8612     * that this is separate from view focus: to receive key events, both
8613     * your view and its window must have focus.  If a window is displayed
8614     * on top of yours that takes input focus, then your own window will lose
8615     * focus but the view focus will remain unchanged.
8616     *
8617     * @param hasWindowFocus True if the window containing this view now has
8618     *        focus, false otherwise.
8619     */
8620    public void onWindowFocusChanged(boolean hasWindowFocus) {
8621        InputMethodManager imm = InputMethodManager.peekInstance();
8622        if (!hasWindowFocus) {
8623            if (isPressed()) {
8624                setPressed(false);
8625            }
8626            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8627                imm.focusOut(this);
8628            }
8629            removeLongPressCallback();
8630            removeTapCallback();
8631            onFocusLost();
8632        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8633            imm.focusIn(this);
8634        }
8635        refreshDrawableState();
8636    }
8637
8638    /**
8639     * Returns true if this view is in a window that currently has window focus.
8640     * Note that this is not the same as the view itself having focus.
8641     *
8642     * @return True if this view is in a window that currently has window focus.
8643     */
8644    public boolean hasWindowFocus() {
8645        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8646    }
8647
8648    /**
8649     * Dispatch a view visibility change down the view hierarchy.
8650     * ViewGroups should override to route to their children.
8651     * @param changedView The view whose visibility changed. Could be 'this' or
8652     * an ancestor view.
8653     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8654     * {@link #INVISIBLE} or {@link #GONE}.
8655     */
8656    protected void dispatchVisibilityChanged(@NonNull View changedView,
8657            @Visibility int visibility) {
8658        onVisibilityChanged(changedView, visibility);
8659    }
8660
8661    /**
8662     * Called when the visibility of the view or an ancestor of the view is changed.
8663     * @param changedView The view whose visibility changed. Could be 'this' or
8664     * an ancestor view.
8665     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8666     * {@link #INVISIBLE} or {@link #GONE}.
8667     */
8668    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8669        if (visibility == VISIBLE) {
8670            if (mAttachInfo != null) {
8671                initialAwakenScrollBars();
8672            } else {
8673                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8674            }
8675        }
8676    }
8677
8678    /**
8679     * Dispatch a hint about whether this view is displayed. For instance, when
8680     * a View moves out of the screen, it might receives a display hint indicating
8681     * the view is not displayed. Applications should not <em>rely</em> on this hint
8682     * as there is no guarantee that they will receive one.
8683     *
8684     * @param hint A hint about whether or not this view is displayed:
8685     * {@link #VISIBLE} or {@link #INVISIBLE}.
8686     */
8687    public void dispatchDisplayHint(@Visibility int hint) {
8688        onDisplayHint(hint);
8689    }
8690
8691    /**
8692     * Gives this view a hint about whether is displayed or not. For instance, when
8693     * a View moves out of the screen, it might receives a display hint indicating
8694     * the view is not displayed. Applications should not <em>rely</em> on this hint
8695     * as there is no guarantee that they will receive one.
8696     *
8697     * @param hint A hint about whether or not this view is displayed:
8698     * {@link #VISIBLE} or {@link #INVISIBLE}.
8699     */
8700    protected void onDisplayHint(@Visibility int hint) {
8701    }
8702
8703    /**
8704     * Dispatch a window visibility change down the view hierarchy.
8705     * ViewGroups should override to route to their children.
8706     *
8707     * @param visibility The new visibility of the window.
8708     *
8709     * @see #onWindowVisibilityChanged(int)
8710     */
8711    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8712        onWindowVisibilityChanged(visibility);
8713    }
8714
8715    /**
8716     * Called when the window containing has change its visibility
8717     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8718     * that this tells you whether or not your window is being made visible
8719     * to the window manager; this does <em>not</em> tell you whether or not
8720     * your window is obscured by other windows on the screen, even if it
8721     * is itself visible.
8722     *
8723     * @param visibility The new visibility of the window.
8724     */
8725    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8726        if (visibility == VISIBLE) {
8727            initialAwakenScrollBars();
8728        }
8729    }
8730
8731    /**
8732     * Returns the current visibility of the window this view is attached to
8733     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8734     *
8735     * @return Returns the current visibility of the view's window.
8736     */
8737    @Visibility
8738    public int getWindowVisibility() {
8739        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8740    }
8741
8742    /**
8743     * Retrieve the overall visible display size in which the window this view is
8744     * attached to has been positioned in.  This takes into account screen
8745     * decorations above the window, for both cases where the window itself
8746     * is being position inside of them or the window is being placed under
8747     * then and covered insets are used for the window to position its content
8748     * inside.  In effect, this tells you the available area where content can
8749     * be placed and remain visible to users.
8750     *
8751     * <p>This function requires an IPC back to the window manager to retrieve
8752     * the requested information, so should not be used in performance critical
8753     * code like drawing.
8754     *
8755     * @param outRect Filled in with the visible display frame.  If the view
8756     * is not attached to a window, this is simply the raw display size.
8757     */
8758    public void getWindowVisibleDisplayFrame(Rect outRect) {
8759        if (mAttachInfo != null) {
8760            try {
8761                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8762            } catch (RemoteException e) {
8763                return;
8764            }
8765            // XXX This is really broken, and probably all needs to be done
8766            // in the window manager, and we need to know more about whether
8767            // we want the area behind or in front of the IME.
8768            final Rect insets = mAttachInfo.mVisibleInsets;
8769            outRect.left += insets.left;
8770            outRect.top += insets.top;
8771            outRect.right -= insets.right;
8772            outRect.bottom -= insets.bottom;
8773            return;
8774        }
8775        // The view is not attached to a display so we don't have a context.
8776        // Make a best guess about the display size.
8777        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8778        d.getRectSize(outRect);
8779    }
8780
8781    /**
8782     * Dispatch a notification about a resource configuration change down
8783     * the view hierarchy.
8784     * ViewGroups should override to route to their children.
8785     *
8786     * @param newConfig The new resource configuration.
8787     *
8788     * @see #onConfigurationChanged(android.content.res.Configuration)
8789     */
8790    public void dispatchConfigurationChanged(Configuration newConfig) {
8791        onConfigurationChanged(newConfig);
8792    }
8793
8794    /**
8795     * Called when the current configuration of the resources being used
8796     * by the application have changed.  You can use this to decide when
8797     * to reload resources that can changed based on orientation and other
8798     * configuration characterstics.  You only need to use this if you are
8799     * not relying on the normal {@link android.app.Activity} mechanism of
8800     * recreating the activity instance upon a configuration change.
8801     *
8802     * @param newConfig The new resource configuration.
8803     */
8804    protected void onConfigurationChanged(Configuration newConfig) {
8805    }
8806
8807    /**
8808     * Private function to aggregate all per-view attributes in to the view
8809     * root.
8810     */
8811    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8812        performCollectViewAttributes(attachInfo, visibility);
8813    }
8814
8815    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8816        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8817            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8818                attachInfo.mKeepScreenOn = true;
8819            }
8820            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8821            ListenerInfo li = mListenerInfo;
8822            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8823                attachInfo.mHasSystemUiListeners = true;
8824            }
8825        }
8826    }
8827
8828    void needGlobalAttributesUpdate(boolean force) {
8829        final AttachInfo ai = mAttachInfo;
8830        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8831            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8832                    || ai.mHasSystemUiListeners) {
8833                ai.mRecomputeGlobalAttributes = true;
8834            }
8835        }
8836    }
8837
8838    /**
8839     * Returns whether the device is currently in touch mode.  Touch mode is entered
8840     * once the user begins interacting with the device by touch, and affects various
8841     * things like whether focus is always visible to the user.
8842     *
8843     * @return Whether the device is in touch mode.
8844     */
8845    @ViewDebug.ExportedProperty
8846    public boolean isInTouchMode() {
8847        if (mAttachInfo != null) {
8848            return mAttachInfo.mInTouchMode;
8849        } else {
8850            return ViewRootImpl.isInTouchMode();
8851        }
8852    }
8853
8854    /**
8855     * Returns the context the view is running in, through which it can
8856     * access the current theme, resources, etc.
8857     *
8858     * @return The view's Context.
8859     */
8860    @ViewDebug.CapturedViewProperty
8861    public final Context getContext() {
8862        return mContext;
8863    }
8864
8865    /**
8866     * Handle a key event before it is processed by any input method
8867     * associated with the view hierarchy.  This can be used to intercept
8868     * key events in special situations before the IME consumes them; a
8869     * typical example would be handling the BACK key to update the application's
8870     * UI instead of allowing the IME to see it and close itself.
8871     *
8872     * @param keyCode The value in event.getKeyCode().
8873     * @param event Description of the key event.
8874     * @return If you handled the event, return true. If you want to allow the
8875     *         event to be handled by the next receiver, return false.
8876     */
8877    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8878        return false;
8879    }
8880
8881    /**
8882     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8883     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8884     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8885     * is released, if the view is enabled and clickable.
8886     *
8887     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8888     * although some may elect to do so in some situations. Do not rely on this to
8889     * catch software key presses.
8890     *
8891     * @param keyCode A key code that represents the button pressed, from
8892     *                {@link android.view.KeyEvent}.
8893     * @param event   The KeyEvent object that defines the button action.
8894     */
8895    public boolean onKeyDown(int keyCode, KeyEvent event) {
8896        boolean result = false;
8897
8898        if (KeyEvent.isConfirmKey(keyCode)) {
8899            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8900                return true;
8901            }
8902            // Long clickable items don't necessarily have to be clickable
8903            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8904                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8905                    (event.getRepeatCount() == 0)) {
8906                setPressed(true);
8907                checkForLongClick(0);
8908                return true;
8909            }
8910        }
8911        return result;
8912    }
8913
8914    /**
8915     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8916     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8917     * the event).
8918     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8919     * although some may elect to do so in some situations. Do not rely on this to
8920     * catch software key presses.
8921     */
8922    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8923        return false;
8924    }
8925
8926    /**
8927     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8928     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8929     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8930     * {@link KeyEvent#KEYCODE_ENTER} is released.
8931     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8932     * although some may elect to do so in some situations. Do not rely on this to
8933     * catch software key presses.
8934     *
8935     * @param keyCode A key code that represents the button pressed, from
8936     *                {@link android.view.KeyEvent}.
8937     * @param event   The KeyEvent object that defines the button action.
8938     */
8939    public boolean onKeyUp(int keyCode, KeyEvent event) {
8940        if (KeyEvent.isConfirmKey(keyCode)) {
8941            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8942                return true;
8943            }
8944            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8945                setPressed(false);
8946
8947                if (!mHasPerformedLongPress) {
8948                    // This is a tap, so remove the longpress check
8949                    removeLongPressCallback();
8950                    return performClick();
8951                }
8952            }
8953        }
8954        return false;
8955    }
8956
8957    /**
8958     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8959     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8960     * the event).
8961     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8962     * although some may elect to do so in some situations. Do not rely on this to
8963     * catch software key presses.
8964     *
8965     * @param keyCode     A key code that represents the button pressed, from
8966     *                    {@link android.view.KeyEvent}.
8967     * @param repeatCount The number of times the action was made.
8968     * @param event       The KeyEvent object that defines the button action.
8969     */
8970    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8971        return false;
8972    }
8973
8974    /**
8975     * Called on the focused view when a key shortcut event is not handled.
8976     * Override this method to implement local key shortcuts for the View.
8977     * Key shortcuts can also be implemented by setting the
8978     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8979     *
8980     * @param keyCode The value in event.getKeyCode().
8981     * @param event Description of the key event.
8982     * @return If you handled the event, return true. If you want to allow the
8983     *         event to be handled by the next receiver, return false.
8984     */
8985    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8986        return false;
8987    }
8988
8989    /**
8990     * Check whether the called view is a text editor, in which case it
8991     * would make sense to automatically display a soft input window for
8992     * it.  Subclasses should override this if they implement
8993     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8994     * a call on that method would return a non-null InputConnection, and
8995     * they are really a first-class editor that the user would normally
8996     * start typing on when the go into a window containing your view.
8997     *
8998     * <p>The default implementation always returns false.  This does
8999     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9000     * will not be called or the user can not otherwise perform edits on your
9001     * view; it is just a hint to the system that this is not the primary
9002     * purpose of this view.
9003     *
9004     * @return Returns true if this view is a text editor, else false.
9005     */
9006    public boolean onCheckIsTextEditor() {
9007        return false;
9008    }
9009
9010    /**
9011     * Create a new InputConnection for an InputMethod to interact
9012     * with the view.  The default implementation returns null, since it doesn't
9013     * support input methods.  You can override this to implement such support.
9014     * This is only needed for views that take focus and text input.
9015     *
9016     * <p>When implementing this, you probably also want to implement
9017     * {@link #onCheckIsTextEditor()} to indicate you will return a
9018     * non-null InputConnection.</p>
9019     *
9020     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9021     * object correctly and in its entirety, so that the connected IME can rely
9022     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9023     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9024     * must be filled in with the correct cursor position for IMEs to work correctly
9025     * with your application.</p>
9026     *
9027     * @param outAttrs Fill in with attribute information about the connection.
9028     */
9029    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9030        return null;
9031    }
9032
9033    /**
9034     * Called by the {@link android.view.inputmethod.InputMethodManager}
9035     * when a view who is not the current
9036     * input connection target is trying to make a call on the manager.  The
9037     * default implementation returns false; you can override this to return
9038     * true for certain views if you are performing InputConnection proxying
9039     * to them.
9040     * @param view The View that is making the InputMethodManager call.
9041     * @return Return true to allow the call, false to reject.
9042     */
9043    public boolean checkInputConnectionProxy(View view) {
9044        return false;
9045    }
9046
9047    /**
9048     * Show the context menu for this view. It is not safe to hold on to the
9049     * menu after returning from this method.
9050     *
9051     * You should normally not overload this method. Overload
9052     * {@link #onCreateContextMenu(ContextMenu)} or define an
9053     * {@link OnCreateContextMenuListener} to add items to the context menu.
9054     *
9055     * @param menu The context menu to populate
9056     */
9057    public void createContextMenu(ContextMenu menu) {
9058        ContextMenuInfo menuInfo = getContextMenuInfo();
9059
9060        // Sets the current menu info so all items added to menu will have
9061        // my extra info set.
9062        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9063
9064        onCreateContextMenu(menu);
9065        ListenerInfo li = mListenerInfo;
9066        if (li != null && li.mOnCreateContextMenuListener != null) {
9067            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9068        }
9069
9070        // Clear the extra information so subsequent items that aren't mine don't
9071        // have my extra info.
9072        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9073
9074        if (mParent != null) {
9075            mParent.createContextMenu(menu);
9076        }
9077    }
9078
9079    /**
9080     * Views should implement this if they have extra information to associate
9081     * with the context menu. The return result is supplied as a parameter to
9082     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9083     * callback.
9084     *
9085     * @return Extra information about the item for which the context menu
9086     *         should be shown. This information will vary across different
9087     *         subclasses of View.
9088     */
9089    protected ContextMenuInfo getContextMenuInfo() {
9090        return null;
9091    }
9092
9093    /**
9094     * Views should implement this if the view itself is going to add items to
9095     * the context menu.
9096     *
9097     * @param menu the context menu to populate
9098     */
9099    protected void onCreateContextMenu(ContextMenu menu) {
9100    }
9101
9102    /**
9103     * Implement this method to handle trackball motion events.  The
9104     * <em>relative</em> movement of the trackball since the last event
9105     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9106     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9107     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9108     * they will often be fractional values, representing the more fine-grained
9109     * movement information available from a trackball).
9110     *
9111     * @param event The motion event.
9112     * @return True if the event was handled, false otherwise.
9113     */
9114    public boolean onTrackballEvent(MotionEvent event) {
9115        return false;
9116    }
9117
9118    /**
9119     * Implement this method to handle generic motion events.
9120     * <p>
9121     * Generic motion events describe joystick movements, mouse hovers, track pad
9122     * touches, scroll wheel movements and other input events.  The
9123     * {@link MotionEvent#getSource() source} of the motion event specifies
9124     * the class of input that was received.  Implementations of this method
9125     * must examine the bits in the source before processing the event.
9126     * The following code example shows how this is done.
9127     * </p><p>
9128     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9129     * are delivered to the view under the pointer.  All other generic motion events are
9130     * delivered to the focused view.
9131     * </p>
9132     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9133     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9134     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9135     *             // process the joystick movement...
9136     *             return true;
9137     *         }
9138     *     }
9139     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9140     *         switch (event.getAction()) {
9141     *             case MotionEvent.ACTION_HOVER_MOVE:
9142     *                 // process the mouse hover movement...
9143     *                 return true;
9144     *             case MotionEvent.ACTION_SCROLL:
9145     *                 // process the scroll wheel movement...
9146     *                 return true;
9147     *         }
9148     *     }
9149     *     return super.onGenericMotionEvent(event);
9150     * }</pre>
9151     *
9152     * @param event The generic motion event being processed.
9153     * @return True if the event was handled, false otherwise.
9154     */
9155    public boolean onGenericMotionEvent(MotionEvent event) {
9156        return false;
9157    }
9158
9159    /**
9160     * Implement this method to handle hover events.
9161     * <p>
9162     * This method is called whenever a pointer is hovering into, over, or out of the
9163     * bounds of a view and the view is not currently being touched.
9164     * Hover events are represented as pointer events with action
9165     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9166     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9167     * </p>
9168     * <ul>
9169     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9170     * when the pointer enters the bounds of the view.</li>
9171     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9172     * when the pointer has already entered the bounds of the view and has moved.</li>
9173     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9174     * when the pointer has exited the bounds of the view or when the pointer is
9175     * about to go down due to a button click, tap, or similar user action that
9176     * causes the view to be touched.</li>
9177     * </ul>
9178     * <p>
9179     * The view should implement this method to return true to indicate that it is
9180     * handling the hover event, such as by changing its drawable state.
9181     * </p><p>
9182     * The default implementation calls {@link #setHovered} to update the hovered state
9183     * of the view when a hover enter or hover exit event is received, if the view
9184     * is enabled and is clickable.  The default implementation also sends hover
9185     * accessibility events.
9186     * </p>
9187     *
9188     * @param event The motion event that describes the hover.
9189     * @return True if the view handled the hover event.
9190     *
9191     * @see #isHovered
9192     * @see #setHovered
9193     * @see #onHoverChanged
9194     */
9195    public boolean onHoverEvent(MotionEvent event) {
9196        // The root view may receive hover (or touch) events that are outside the bounds of
9197        // the window.  This code ensures that we only send accessibility events for
9198        // hovers that are actually within the bounds of the root view.
9199        final int action = event.getActionMasked();
9200        if (!mSendingHoverAccessibilityEvents) {
9201            if ((action == MotionEvent.ACTION_HOVER_ENTER
9202                    || action == MotionEvent.ACTION_HOVER_MOVE)
9203                    && !hasHoveredChild()
9204                    && pointInView(event.getX(), event.getY())) {
9205                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9206                mSendingHoverAccessibilityEvents = true;
9207            }
9208        } else {
9209            if (action == MotionEvent.ACTION_HOVER_EXIT
9210                    || (action == MotionEvent.ACTION_MOVE
9211                            && !pointInView(event.getX(), event.getY()))) {
9212                mSendingHoverAccessibilityEvents = false;
9213                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9214            }
9215        }
9216
9217        if (isHoverable()) {
9218            switch (action) {
9219                case MotionEvent.ACTION_HOVER_ENTER:
9220                    setHovered(true);
9221                    break;
9222                case MotionEvent.ACTION_HOVER_EXIT:
9223                    setHovered(false);
9224                    break;
9225            }
9226
9227            // Dispatch the event to onGenericMotionEvent before returning true.
9228            // This is to provide compatibility with existing applications that
9229            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9230            // break because of the new default handling for hoverable views
9231            // in onHoverEvent.
9232            // Note that onGenericMotionEvent will be called by default when
9233            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9234            dispatchGenericMotionEventInternal(event);
9235            // The event was already handled by calling setHovered(), so always
9236            // return true.
9237            return true;
9238        }
9239
9240        return false;
9241    }
9242
9243    /**
9244     * Returns true if the view should handle {@link #onHoverEvent}
9245     * by calling {@link #setHovered} to change its hovered state.
9246     *
9247     * @return True if the view is hoverable.
9248     */
9249    private boolean isHoverable() {
9250        final int viewFlags = mViewFlags;
9251        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9252            return false;
9253        }
9254
9255        return (viewFlags & CLICKABLE) == CLICKABLE
9256                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9257    }
9258
9259    /**
9260     * Returns true if the view is currently hovered.
9261     *
9262     * @return True if the view is currently hovered.
9263     *
9264     * @see #setHovered
9265     * @see #onHoverChanged
9266     */
9267    @ViewDebug.ExportedProperty
9268    public boolean isHovered() {
9269        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9270    }
9271
9272    /**
9273     * Sets whether the view is currently hovered.
9274     * <p>
9275     * Calling this method also changes the drawable state of the view.  This
9276     * enables the view to react to hover by using different drawable resources
9277     * to change its appearance.
9278     * </p><p>
9279     * The {@link #onHoverChanged} method is called when the hovered state changes.
9280     * </p>
9281     *
9282     * @param hovered True if the view is hovered.
9283     *
9284     * @see #isHovered
9285     * @see #onHoverChanged
9286     */
9287    public void setHovered(boolean hovered) {
9288        if (hovered) {
9289            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9290                mPrivateFlags |= PFLAG_HOVERED;
9291                refreshDrawableState();
9292                onHoverChanged(true);
9293            }
9294        } else {
9295            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9296                mPrivateFlags &= ~PFLAG_HOVERED;
9297                refreshDrawableState();
9298                onHoverChanged(false);
9299            }
9300        }
9301    }
9302
9303    /**
9304     * Implement this method to handle hover state changes.
9305     * <p>
9306     * This method is called whenever the hover state changes as a result of a
9307     * call to {@link #setHovered}.
9308     * </p>
9309     *
9310     * @param hovered The current hover state, as returned by {@link #isHovered}.
9311     *
9312     * @see #isHovered
9313     * @see #setHovered
9314     */
9315    public void onHoverChanged(boolean hovered) {
9316    }
9317
9318    /**
9319     * Implement this method to handle touch screen motion events.
9320     * <p>
9321     * If this method is used to detect click actions, it is recommended that
9322     * the actions be performed by implementing and calling
9323     * {@link #performClick()}. This will ensure consistent system behavior,
9324     * including:
9325     * <ul>
9326     * <li>obeying click sound preferences
9327     * <li>dispatching OnClickListener calls
9328     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9329     * accessibility features are enabled
9330     * </ul>
9331     *
9332     * @param event The motion event.
9333     * @return True if the event was handled, false otherwise.
9334     */
9335    public boolean onTouchEvent(MotionEvent event) {
9336        final float x = event.getX();
9337        final float y = event.getY();
9338        final int viewFlags = mViewFlags;
9339
9340        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9341            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9342                setPressed(false);
9343            }
9344            // A disabled view that is clickable still consumes the touch
9345            // events, it just doesn't respond to them.
9346            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9347                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9348        }
9349
9350        if (mTouchDelegate != null) {
9351            if (mTouchDelegate.onTouchEvent(event)) {
9352                return true;
9353            }
9354        }
9355
9356        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9357                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9358            switch (event.getAction()) {
9359                case MotionEvent.ACTION_UP:
9360                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9361                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9362                        // take focus if we don't have it already and we should in
9363                        // touch mode.
9364                        boolean focusTaken = false;
9365                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9366                            focusTaken = requestFocus();
9367                        }
9368
9369                        if (prepressed) {
9370                            // The button is being released before we actually
9371                            // showed it as pressed.  Make it show the pressed
9372                            // state now (before scheduling the click) to ensure
9373                            // the user sees it.
9374                            setPressed(true, x, y);
9375                       }
9376
9377                        if (!mHasPerformedLongPress) {
9378                            // This is a tap, so remove the longpress check
9379                            removeLongPressCallback();
9380
9381                            // Only perform take click actions if we were in the pressed state
9382                            if (!focusTaken) {
9383                                // Use a Runnable and post this rather than calling
9384                                // performClick directly. This lets other visual state
9385                                // of the view update before click actions start.
9386                                if (mPerformClick == null) {
9387                                    mPerformClick = new PerformClick();
9388                                }
9389                                if (!post(mPerformClick)) {
9390                                    performClick();
9391                                }
9392                            }
9393                        }
9394
9395                        if (mUnsetPressedState == null) {
9396                            mUnsetPressedState = new UnsetPressedState();
9397                        }
9398
9399                        if (prepressed) {
9400                            postDelayed(mUnsetPressedState,
9401                                    ViewConfiguration.getPressedStateDuration());
9402                        } else if (!post(mUnsetPressedState)) {
9403                            // If the post failed, unpress right now
9404                            mUnsetPressedState.run();
9405                        }
9406
9407                        removeTapCallback();
9408                    }
9409                    break;
9410
9411                case MotionEvent.ACTION_DOWN:
9412                    mHasPerformedLongPress = false;
9413
9414                    if (performButtonActionOnTouchDown(event)) {
9415                        break;
9416                    }
9417
9418                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9419                    boolean isInScrollingContainer = isInScrollingContainer();
9420
9421                    // For views inside a scrolling container, delay the pressed feedback for
9422                    // a short period in case this is a scroll.
9423                    if (isInScrollingContainer) {
9424                        mPrivateFlags |= PFLAG_PREPRESSED;
9425                        if (mPendingCheckForTap == null) {
9426                            mPendingCheckForTap = new CheckForTap();
9427                        }
9428                        mPendingCheckForTap.x = event.getX();
9429                        mPendingCheckForTap.y = event.getY();
9430                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9431                    } else {
9432                        // Not inside a scrolling container, so show the feedback right away
9433                        setPressed(true, x, y);
9434                        checkForLongClick(0);
9435                    }
9436                    break;
9437
9438                case MotionEvent.ACTION_CANCEL:
9439                    setPressed(false);
9440                    removeTapCallback();
9441                    removeLongPressCallback();
9442                    break;
9443
9444                case MotionEvent.ACTION_MOVE:
9445                    drawableHotspotChanged(x, y);
9446
9447                    // Be lenient about moving outside of buttons
9448                    if (!pointInView(x, y, mTouchSlop)) {
9449                        // Outside button
9450                        removeTapCallback();
9451                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9452                            // Remove any future long press/tap checks
9453                            removeLongPressCallback();
9454
9455                            setPressed(false);
9456                        }
9457                    }
9458                    break;
9459            }
9460
9461            return true;
9462        }
9463
9464        return false;
9465    }
9466
9467    /**
9468     * @hide
9469     */
9470    public boolean isInScrollingContainer() {
9471        ViewParent p = getParent();
9472        while (p != null && p instanceof ViewGroup) {
9473            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9474                return true;
9475            }
9476            p = p.getParent();
9477        }
9478        return false;
9479    }
9480
9481    /**
9482     * Remove the longpress detection timer.
9483     */
9484    private void removeLongPressCallback() {
9485        if (mPendingCheckForLongPress != null) {
9486          removeCallbacks(mPendingCheckForLongPress);
9487        }
9488    }
9489
9490    /**
9491     * Remove the pending click action
9492     */
9493    private void removePerformClickCallback() {
9494        if (mPerformClick != null) {
9495            removeCallbacks(mPerformClick);
9496        }
9497    }
9498
9499    /**
9500     * Remove the prepress detection timer.
9501     */
9502    private void removeUnsetPressCallback() {
9503        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9504            setPressed(false);
9505            removeCallbacks(mUnsetPressedState);
9506        }
9507    }
9508
9509    /**
9510     * Remove the tap detection timer.
9511     */
9512    private void removeTapCallback() {
9513        if (mPendingCheckForTap != null) {
9514            mPrivateFlags &= ~PFLAG_PREPRESSED;
9515            removeCallbacks(mPendingCheckForTap);
9516        }
9517    }
9518
9519    /**
9520     * Cancels a pending long press.  Your subclass can use this if you
9521     * want the context menu to come up if the user presses and holds
9522     * at the same place, but you don't want it to come up if they press
9523     * and then move around enough to cause scrolling.
9524     */
9525    public void cancelLongPress() {
9526        removeLongPressCallback();
9527
9528        /*
9529         * The prepressed state handled by the tap callback is a display
9530         * construct, but the tap callback will post a long press callback
9531         * less its own timeout. Remove it here.
9532         */
9533        removeTapCallback();
9534    }
9535
9536    /**
9537     * Remove the pending callback for sending a
9538     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9539     */
9540    private void removeSendViewScrolledAccessibilityEventCallback() {
9541        if (mSendViewScrolledAccessibilityEvent != null) {
9542            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9543            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9544        }
9545    }
9546
9547    /**
9548     * Sets the TouchDelegate for this View.
9549     */
9550    public void setTouchDelegate(TouchDelegate delegate) {
9551        mTouchDelegate = delegate;
9552    }
9553
9554    /**
9555     * Gets the TouchDelegate for this View.
9556     */
9557    public TouchDelegate getTouchDelegate() {
9558        return mTouchDelegate;
9559    }
9560
9561    /**
9562     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9563     *
9564     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9565     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9566     * available. This method should only be called for touch events.
9567     *
9568     * <p class="note">This api is not intended for most applications. Buffered dispatch
9569     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9570     * streams will not improve your input latency. Side effects include: increased latency,
9571     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9572     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9573     * you.</p>
9574     */
9575    public final void requestUnbufferedDispatch(MotionEvent event) {
9576        final int action = event.getAction();
9577        if (mAttachInfo == null
9578                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9579                || !event.isTouchEvent()) {
9580            return;
9581        }
9582        mAttachInfo.mUnbufferedDispatchRequested = true;
9583    }
9584
9585    /**
9586     * Set flags controlling behavior of this view.
9587     *
9588     * @param flags Constant indicating the value which should be set
9589     * @param mask Constant indicating the bit range that should be changed
9590     */
9591    void setFlags(int flags, int mask) {
9592        final boolean accessibilityEnabled =
9593                AccessibilityManager.getInstance(mContext).isEnabled();
9594        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9595
9596        int old = mViewFlags;
9597        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9598
9599        int changed = mViewFlags ^ old;
9600        if (changed == 0) {
9601            return;
9602        }
9603        int privateFlags = mPrivateFlags;
9604
9605        /* Check if the FOCUSABLE bit has changed */
9606        if (((changed & FOCUSABLE_MASK) != 0) &&
9607                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9608            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9609                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9610                /* Give up focus if we are no longer focusable */
9611                clearFocus();
9612            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9613                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9614                /*
9615                 * Tell the view system that we are now available to take focus
9616                 * if no one else already has it.
9617                 */
9618                if (mParent != null) mParent.focusableViewAvailable(this);
9619            }
9620        }
9621
9622        final int newVisibility = flags & VISIBILITY_MASK;
9623        if (newVisibility == VISIBLE) {
9624            if ((changed & VISIBILITY_MASK) != 0) {
9625                /*
9626                 * If this view is becoming visible, invalidate it in case it changed while
9627                 * it was not visible. Marking it drawn ensures that the invalidation will
9628                 * go through.
9629                 */
9630                mPrivateFlags |= PFLAG_DRAWN;
9631                invalidate(true);
9632
9633                needGlobalAttributesUpdate(true);
9634
9635                // a view becoming visible is worth notifying the parent
9636                // about in case nothing has focus.  even if this specific view
9637                // isn't focusable, it may contain something that is, so let
9638                // the root view try to give this focus if nothing else does.
9639                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9640                    mParent.focusableViewAvailable(this);
9641                }
9642            }
9643        }
9644
9645        /* Check if the GONE bit has changed */
9646        if ((changed & GONE) != 0) {
9647            needGlobalAttributesUpdate(false);
9648            requestLayout();
9649
9650            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9651                if (hasFocus()) clearFocus();
9652                clearAccessibilityFocus();
9653                destroyDrawingCache();
9654                if (mParent instanceof View) {
9655                    // GONE views noop invalidation, so invalidate the parent
9656                    ((View) mParent).invalidate(true);
9657                }
9658                // Mark the view drawn to ensure that it gets invalidated properly the next
9659                // time it is visible and gets invalidated
9660                mPrivateFlags |= PFLAG_DRAWN;
9661            }
9662            if (mAttachInfo != null) {
9663                mAttachInfo.mViewVisibilityChanged = true;
9664            }
9665        }
9666
9667        /* Check if the VISIBLE bit has changed */
9668        if ((changed & INVISIBLE) != 0) {
9669            needGlobalAttributesUpdate(false);
9670            /*
9671             * If this view is becoming invisible, set the DRAWN flag so that
9672             * the next invalidate() will not be skipped.
9673             */
9674            mPrivateFlags |= PFLAG_DRAWN;
9675
9676            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9677                // root view becoming invisible shouldn't clear focus and accessibility focus
9678                if (getRootView() != this) {
9679                    if (hasFocus()) clearFocus();
9680                    clearAccessibilityFocus();
9681                }
9682            }
9683            if (mAttachInfo != null) {
9684                mAttachInfo.mViewVisibilityChanged = true;
9685            }
9686        }
9687
9688        if ((changed & VISIBILITY_MASK) != 0) {
9689            // If the view is invisible, cleanup its display list to free up resources
9690            if (newVisibility != VISIBLE && mAttachInfo != null) {
9691                cleanupDraw();
9692            }
9693
9694            if (mParent instanceof ViewGroup) {
9695                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9696                        (changed & VISIBILITY_MASK), newVisibility);
9697                ((View) mParent).invalidate(true);
9698            } else if (mParent != null) {
9699                mParent.invalidateChild(this, null);
9700            }
9701            dispatchVisibilityChanged(this, newVisibility);
9702
9703            notifySubtreeAccessibilityStateChangedIfNeeded();
9704        }
9705
9706        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9707            destroyDrawingCache();
9708        }
9709
9710        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9711            destroyDrawingCache();
9712            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9713            invalidateParentCaches();
9714        }
9715
9716        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9717            destroyDrawingCache();
9718            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9719        }
9720
9721        if ((changed & DRAW_MASK) != 0) {
9722            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9723                if (mBackground != null) {
9724                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9725                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9726                } else {
9727                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9728                }
9729            } else {
9730                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9731            }
9732            requestLayout();
9733            invalidate(true);
9734        }
9735
9736        if ((changed & KEEP_SCREEN_ON) != 0) {
9737            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9738                mParent.recomputeViewAttributes(this);
9739            }
9740        }
9741
9742        if (accessibilityEnabled) {
9743            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9744                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9745                if (oldIncludeForAccessibility != includeForAccessibility()) {
9746                    notifySubtreeAccessibilityStateChangedIfNeeded();
9747                } else {
9748                    notifyViewAccessibilityStateChangedIfNeeded(
9749                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9750                }
9751            } else if ((changed & ENABLED_MASK) != 0) {
9752                notifyViewAccessibilityStateChangedIfNeeded(
9753                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9754            }
9755        }
9756    }
9757
9758    /**
9759     * Change the view's z order in the tree, so it's on top of other sibling
9760     * views. This ordering change may affect layout, if the parent container
9761     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9762     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9763     * method should be followed by calls to {@link #requestLayout()} and
9764     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9765     * with the new child ordering.
9766     *
9767     * @see ViewGroup#bringChildToFront(View)
9768     */
9769    public void bringToFront() {
9770        if (mParent != null) {
9771            mParent.bringChildToFront(this);
9772        }
9773    }
9774
9775    /**
9776     * This is called in response to an internal scroll in this view (i.e., the
9777     * view scrolled its own contents). This is typically as a result of
9778     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9779     * called.
9780     *
9781     * @param l Current horizontal scroll origin.
9782     * @param t Current vertical scroll origin.
9783     * @param oldl Previous horizontal scroll origin.
9784     * @param oldt Previous vertical scroll origin.
9785     */
9786    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9787        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9788            postSendViewScrolledAccessibilityEventCallback();
9789        }
9790
9791        mBackgroundSizeChanged = true;
9792
9793        final AttachInfo ai = mAttachInfo;
9794        if (ai != null) {
9795            ai.mViewScrollChanged = true;
9796        }
9797    }
9798
9799    /**
9800     * Interface definition for a callback to be invoked when the layout bounds of a view
9801     * changes due to layout processing.
9802     */
9803    public interface OnLayoutChangeListener {
9804        /**
9805         * Called when the layout bounds of a view changes due to layout processing.
9806         *
9807         * @param v The view whose bounds have changed.
9808         * @param left The new value of the view's left property.
9809         * @param top The new value of the view's top property.
9810         * @param right The new value of the view's right property.
9811         * @param bottom The new value of the view's bottom property.
9812         * @param oldLeft The previous value of the view's left property.
9813         * @param oldTop The previous value of the view's top property.
9814         * @param oldRight The previous value of the view's right property.
9815         * @param oldBottom The previous value of the view's bottom property.
9816         */
9817        void onLayoutChange(View v, int left, int top, int right, int bottom,
9818            int oldLeft, int oldTop, int oldRight, int oldBottom);
9819    }
9820
9821    /**
9822     * This is called during layout when the size of this view has changed. If
9823     * you were just added to the view hierarchy, you're called with the old
9824     * values of 0.
9825     *
9826     * @param w Current width of this view.
9827     * @param h Current height of this view.
9828     * @param oldw Old width of this view.
9829     * @param oldh Old height of this view.
9830     */
9831    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9832    }
9833
9834    /**
9835     * Called by draw to draw the child views. This may be overridden
9836     * by derived classes to gain control just before its children are drawn
9837     * (but after its own view has been drawn).
9838     * @param canvas the canvas on which to draw the view
9839     */
9840    protected void dispatchDraw(Canvas canvas) {
9841
9842    }
9843
9844    /**
9845     * Gets the parent of this view. Note that the parent is a
9846     * ViewParent and not necessarily a View.
9847     *
9848     * @return Parent of this view.
9849     */
9850    public final ViewParent getParent() {
9851        return mParent;
9852    }
9853
9854    /**
9855     * Set the horizontal scrolled position of your view. This will cause a call to
9856     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9857     * invalidated.
9858     * @param value the x position to scroll to
9859     */
9860    public void setScrollX(int value) {
9861        scrollTo(value, mScrollY);
9862    }
9863
9864    /**
9865     * Set the vertical scrolled position of your view. This will cause a call to
9866     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9867     * invalidated.
9868     * @param value the y position to scroll to
9869     */
9870    public void setScrollY(int value) {
9871        scrollTo(mScrollX, value);
9872    }
9873
9874    /**
9875     * Return the scrolled left position of this view. This is the left edge of
9876     * the displayed part of your view. You do not need to draw any pixels
9877     * farther left, since those are outside of the frame of your view on
9878     * screen.
9879     *
9880     * @return The left edge of the displayed part of your view, in pixels.
9881     */
9882    public final int getScrollX() {
9883        return mScrollX;
9884    }
9885
9886    /**
9887     * Return the scrolled top position of this view. This is the top edge of
9888     * the displayed part of your view. You do not need to draw any pixels above
9889     * it, since those are outside of the frame of your view on screen.
9890     *
9891     * @return The top edge of the displayed part of your view, in pixels.
9892     */
9893    public final int getScrollY() {
9894        return mScrollY;
9895    }
9896
9897    /**
9898     * Return the width of the your view.
9899     *
9900     * @return The width of your view, in pixels.
9901     */
9902    @ViewDebug.ExportedProperty(category = "layout")
9903    public final int getWidth() {
9904        return mRight - mLeft;
9905    }
9906
9907    /**
9908     * Return the height of your view.
9909     *
9910     * @return The height of your view, in pixels.
9911     */
9912    @ViewDebug.ExportedProperty(category = "layout")
9913    public final int getHeight() {
9914        return mBottom - mTop;
9915    }
9916
9917    /**
9918     * Return the visible drawing bounds of your view. Fills in the output
9919     * rectangle with the values from getScrollX(), getScrollY(),
9920     * getWidth(), and getHeight(). These bounds do not account for any
9921     * transformation properties currently set on the view, such as
9922     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9923     *
9924     * @param outRect The (scrolled) drawing bounds of the view.
9925     */
9926    public void getDrawingRect(Rect outRect) {
9927        outRect.left = mScrollX;
9928        outRect.top = mScrollY;
9929        outRect.right = mScrollX + (mRight - mLeft);
9930        outRect.bottom = mScrollY + (mBottom - mTop);
9931    }
9932
9933    /**
9934     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9935     * raw width component (that is the result is masked by
9936     * {@link #MEASURED_SIZE_MASK}).
9937     *
9938     * @return The raw measured width of this view.
9939     */
9940    public final int getMeasuredWidth() {
9941        return mMeasuredWidth & MEASURED_SIZE_MASK;
9942    }
9943
9944    /**
9945     * Return the full width measurement information for this view as computed
9946     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9947     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9948     * This should be used during measurement and layout calculations only. Use
9949     * {@link #getWidth()} to see how wide a view is after layout.
9950     *
9951     * @return The measured width of this view as a bit mask.
9952     */
9953    public final int getMeasuredWidthAndState() {
9954        return mMeasuredWidth;
9955    }
9956
9957    /**
9958     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9959     * raw width component (that is the result is masked by
9960     * {@link #MEASURED_SIZE_MASK}).
9961     *
9962     * @return The raw measured height of this view.
9963     */
9964    public final int getMeasuredHeight() {
9965        return mMeasuredHeight & MEASURED_SIZE_MASK;
9966    }
9967
9968    /**
9969     * Return the full height measurement information for this view as computed
9970     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9971     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9972     * This should be used during measurement and layout calculations only. Use
9973     * {@link #getHeight()} to see how wide a view is after layout.
9974     *
9975     * @return The measured width of this view as a bit mask.
9976     */
9977    public final int getMeasuredHeightAndState() {
9978        return mMeasuredHeight;
9979    }
9980
9981    /**
9982     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9983     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9984     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9985     * and the height component is at the shifted bits
9986     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9987     */
9988    public final int getMeasuredState() {
9989        return (mMeasuredWidth&MEASURED_STATE_MASK)
9990                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9991                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9992    }
9993
9994    /**
9995     * The transform matrix of this view, which is calculated based on the current
9996     * rotation, scale, and pivot properties.
9997     *
9998     * @see #getRotation()
9999     * @see #getScaleX()
10000     * @see #getScaleY()
10001     * @see #getPivotX()
10002     * @see #getPivotY()
10003     * @return The current transform matrix for the view
10004     */
10005    public Matrix getMatrix() {
10006        ensureTransformationInfo();
10007        final Matrix matrix = mTransformationInfo.mMatrix;
10008        mRenderNode.getMatrix(matrix);
10009        return matrix;
10010    }
10011
10012    /**
10013     * Returns true if the transform matrix is the identity matrix.
10014     * Recomputes the matrix if necessary.
10015     *
10016     * @return True if the transform matrix is the identity matrix, false otherwise.
10017     */
10018    final boolean hasIdentityMatrix() {
10019        return mRenderNode.hasIdentityMatrix();
10020    }
10021
10022    void ensureTransformationInfo() {
10023        if (mTransformationInfo == null) {
10024            mTransformationInfo = new TransformationInfo();
10025        }
10026    }
10027
10028   /**
10029     * Utility method to retrieve the inverse of the current mMatrix property.
10030     * We cache the matrix to avoid recalculating it when transform properties
10031     * have not changed.
10032     *
10033     * @return The inverse of the current matrix of this view.
10034     * @hide
10035     */
10036    public final Matrix getInverseMatrix() {
10037        ensureTransformationInfo();
10038        if (mTransformationInfo.mInverseMatrix == null) {
10039            mTransformationInfo.mInverseMatrix = new Matrix();
10040        }
10041        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10042        mRenderNode.getInverseMatrix(matrix);
10043        return matrix;
10044    }
10045
10046    /**
10047     * Gets the distance along the Z axis from the camera to this view.
10048     *
10049     * @see #setCameraDistance(float)
10050     *
10051     * @return The distance along the Z axis.
10052     */
10053    public float getCameraDistance() {
10054        final float dpi = mResources.getDisplayMetrics().densityDpi;
10055        return -(mRenderNode.getCameraDistance() * dpi);
10056    }
10057
10058    /**
10059     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10060     * views are drawn) from the camera to this view. The camera's distance
10061     * affects 3D transformations, for instance rotations around the X and Y
10062     * axis. If the rotationX or rotationY properties are changed and this view is
10063     * large (more than half the size of the screen), it is recommended to always
10064     * use a camera distance that's greater than the height (X axis rotation) or
10065     * the width (Y axis rotation) of this view.</p>
10066     *
10067     * <p>The distance of the camera from the view plane can have an affect on the
10068     * perspective distortion of the view when it is rotated around the x or y axis.
10069     * For example, a large distance will result in a large viewing angle, and there
10070     * will not be much perspective distortion of the view as it rotates. A short
10071     * distance may cause much more perspective distortion upon rotation, and can
10072     * also result in some drawing artifacts if the rotated view ends up partially
10073     * behind the camera (which is why the recommendation is to use a distance at
10074     * least as far as the size of the view, if the view is to be rotated.)</p>
10075     *
10076     * <p>The distance is expressed in "depth pixels." The default distance depends
10077     * on the screen density. For instance, on a medium density display, the
10078     * default distance is 1280. On a high density display, the default distance
10079     * is 1920.</p>
10080     *
10081     * <p>If you want to specify a distance that leads to visually consistent
10082     * results across various densities, use the following formula:</p>
10083     * <pre>
10084     * float scale = context.getResources().getDisplayMetrics().density;
10085     * view.setCameraDistance(distance * scale);
10086     * </pre>
10087     *
10088     * <p>The density scale factor of a high density display is 1.5,
10089     * and 1920 = 1280 * 1.5.</p>
10090     *
10091     * @param distance The distance in "depth pixels", if negative the opposite
10092     *        value is used
10093     *
10094     * @see #setRotationX(float)
10095     * @see #setRotationY(float)
10096     */
10097    public void setCameraDistance(float distance) {
10098        final float dpi = mResources.getDisplayMetrics().densityDpi;
10099
10100        invalidateViewProperty(true, false);
10101        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10102        invalidateViewProperty(false, false);
10103
10104        invalidateParentIfNeededAndWasQuickRejected();
10105    }
10106
10107    /**
10108     * The degrees that the view is rotated around the pivot point.
10109     *
10110     * @see #setRotation(float)
10111     * @see #getPivotX()
10112     * @see #getPivotY()
10113     *
10114     * @return The degrees of rotation.
10115     */
10116    @ViewDebug.ExportedProperty(category = "drawing")
10117    public float getRotation() {
10118        return mRenderNode.getRotation();
10119    }
10120
10121    /**
10122     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10123     * result in clockwise rotation.
10124     *
10125     * @param rotation The degrees of rotation.
10126     *
10127     * @see #getRotation()
10128     * @see #getPivotX()
10129     * @see #getPivotY()
10130     * @see #setRotationX(float)
10131     * @see #setRotationY(float)
10132     *
10133     * @attr ref android.R.styleable#View_rotation
10134     */
10135    public void setRotation(float rotation) {
10136        if (rotation != getRotation()) {
10137            // Double-invalidation is necessary to capture view's old and new areas
10138            invalidateViewProperty(true, false);
10139            mRenderNode.setRotation(rotation);
10140            invalidateViewProperty(false, true);
10141
10142            invalidateParentIfNeededAndWasQuickRejected();
10143            notifySubtreeAccessibilityStateChangedIfNeeded();
10144        }
10145    }
10146
10147    /**
10148     * The degrees that the view is rotated around the vertical axis through the pivot point.
10149     *
10150     * @see #getPivotX()
10151     * @see #getPivotY()
10152     * @see #setRotationY(float)
10153     *
10154     * @return The degrees of Y rotation.
10155     */
10156    @ViewDebug.ExportedProperty(category = "drawing")
10157    public float getRotationY() {
10158        return mRenderNode.getRotationY();
10159    }
10160
10161    /**
10162     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10163     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10164     * down the y axis.
10165     *
10166     * When rotating large views, it is recommended to adjust the camera distance
10167     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10168     *
10169     * @param rotationY The degrees of Y rotation.
10170     *
10171     * @see #getRotationY()
10172     * @see #getPivotX()
10173     * @see #getPivotY()
10174     * @see #setRotation(float)
10175     * @see #setRotationX(float)
10176     * @see #setCameraDistance(float)
10177     *
10178     * @attr ref android.R.styleable#View_rotationY
10179     */
10180    public void setRotationY(float rotationY) {
10181        if (rotationY != getRotationY()) {
10182            invalidateViewProperty(true, false);
10183            mRenderNode.setRotationY(rotationY);
10184            invalidateViewProperty(false, true);
10185
10186            invalidateParentIfNeededAndWasQuickRejected();
10187            notifySubtreeAccessibilityStateChangedIfNeeded();
10188        }
10189    }
10190
10191    /**
10192     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10193     *
10194     * @see #getPivotX()
10195     * @see #getPivotY()
10196     * @see #setRotationX(float)
10197     *
10198     * @return The degrees of X rotation.
10199     */
10200    @ViewDebug.ExportedProperty(category = "drawing")
10201    public float getRotationX() {
10202        return mRenderNode.getRotationX();
10203    }
10204
10205    /**
10206     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10207     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10208     * x axis.
10209     *
10210     * When rotating large views, it is recommended to adjust the camera distance
10211     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10212     *
10213     * @param rotationX The degrees of X rotation.
10214     *
10215     * @see #getRotationX()
10216     * @see #getPivotX()
10217     * @see #getPivotY()
10218     * @see #setRotation(float)
10219     * @see #setRotationY(float)
10220     * @see #setCameraDistance(float)
10221     *
10222     * @attr ref android.R.styleable#View_rotationX
10223     */
10224    public void setRotationX(float rotationX) {
10225        if (rotationX != getRotationX()) {
10226            invalidateViewProperty(true, false);
10227            mRenderNode.setRotationX(rotationX);
10228            invalidateViewProperty(false, true);
10229
10230            invalidateParentIfNeededAndWasQuickRejected();
10231            notifySubtreeAccessibilityStateChangedIfNeeded();
10232        }
10233    }
10234
10235    /**
10236     * The amount that the view is scaled in x around the pivot point, as a proportion of
10237     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10238     *
10239     * <p>By default, this is 1.0f.
10240     *
10241     * @see #getPivotX()
10242     * @see #getPivotY()
10243     * @return The scaling factor.
10244     */
10245    @ViewDebug.ExportedProperty(category = "drawing")
10246    public float getScaleX() {
10247        return mRenderNode.getScaleX();
10248    }
10249
10250    /**
10251     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10252     * the view's unscaled width. A value of 1 means that no scaling is applied.
10253     *
10254     * @param scaleX The scaling factor.
10255     * @see #getPivotX()
10256     * @see #getPivotY()
10257     *
10258     * @attr ref android.R.styleable#View_scaleX
10259     */
10260    public void setScaleX(float scaleX) {
10261        if (scaleX != getScaleX()) {
10262            invalidateViewProperty(true, false);
10263            mRenderNode.setScaleX(scaleX);
10264            invalidateViewProperty(false, true);
10265
10266            invalidateParentIfNeededAndWasQuickRejected();
10267            notifySubtreeAccessibilityStateChangedIfNeeded();
10268        }
10269    }
10270
10271    /**
10272     * The amount that the view is scaled in y around the pivot point, as a proportion of
10273     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10274     *
10275     * <p>By default, this is 1.0f.
10276     *
10277     * @see #getPivotX()
10278     * @see #getPivotY()
10279     * @return The scaling factor.
10280     */
10281    @ViewDebug.ExportedProperty(category = "drawing")
10282    public float getScaleY() {
10283        return mRenderNode.getScaleY();
10284    }
10285
10286    /**
10287     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10288     * the view's unscaled width. A value of 1 means that no scaling is applied.
10289     *
10290     * @param scaleY The scaling factor.
10291     * @see #getPivotX()
10292     * @see #getPivotY()
10293     *
10294     * @attr ref android.R.styleable#View_scaleY
10295     */
10296    public void setScaleY(float scaleY) {
10297        if (scaleY != getScaleY()) {
10298            invalidateViewProperty(true, false);
10299            mRenderNode.setScaleY(scaleY);
10300            invalidateViewProperty(false, true);
10301
10302            invalidateParentIfNeededAndWasQuickRejected();
10303            notifySubtreeAccessibilityStateChangedIfNeeded();
10304        }
10305    }
10306
10307    /**
10308     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10309     * and {@link #setScaleX(float) scaled}.
10310     *
10311     * @see #getRotation()
10312     * @see #getScaleX()
10313     * @see #getScaleY()
10314     * @see #getPivotY()
10315     * @return The x location of the pivot point.
10316     *
10317     * @attr ref android.R.styleable#View_transformPivotX
10318     */
10319    @ViewDebug.ExportedProperty(category = "drawing")
10320    public float getPivotX() {
10321        return mRenderNode.getPivotX();
10322    }
10323
10324    /**
10325     * Sets the x location of the point around which the view is
10326     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10327     * By default, the pivot point is centered on the object.
10328     * Setting this property disables this behavior and causes the view to use only the
10329     * explicitly set pivotX and pivotY values.
10330     *
10331     * @param pivotX The x location of the pivot point.
10332     * @see #getRotation()
10333     * @see #getScaleX()
10334     * @see #getScaleY()
10335     * @see #getPivotY()
10336     *
10337     * @attr ref android.R.styleable#View_transformPivotX
10338     */
10339    public void setPivotX(float pivotX) {
10340        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10341            invalidateViewProperty(true, false);
10342            mRenderNode.setPivotX(pivotX);
10343            invalidateViewProperty(false, true);
10344
10345            invalidateParentIfNeededAndWasQuickRejected();
10346        }
10347    }
10348
10349    /**
10350     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10351     * and {@link #setScaleY(float) scaled}.
10352     *
10353     * @see #getRotation()
10354     * @see #getScaleX()
10355     * @see #getScaleY()
10356     * @see #getPivotY()
10357     * @return The y location of the pivot point.
10358     *
10359     * @attr ref android.R.styleable#View_transformPivotY
10360     */
10361    @ViewDebug.ExportedProperty(category = "drawing")
10362    public float getPivotY() {
10363        return mRenderNode.getPivotY();
10364    }
10365
10366    /**
10367     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10368     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10369     * Setting this property disables this behavior and causes the view to use only the
10370     * explicitly set pivotX and pivotY values.
10371     *
10372     * @param pivotY The y location of the pivot point.
10373     * @see #getRotation()
10374     * @see #getScaleX()
10375     * @see #getScaleY()
10376     * @see #getPivotY()
10377     *
10378     * @attr ref android.R.styleable#View_transformPivotY
10379     */
10380    public void setPivotY(float pivotY) {
10381        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10382            invalidateViewProperty(true, false);
10383            mRenderNode.setPivotY(pivotY);
10384            invalidateViewProperty(false, true);
10385
10386            invalidateParentIfNeededAndWasQuickRejected();
10387        }
10388    }
10389
10390    /**
10391     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10392     * completely transparent and 1 means the view is completely opaque.
10393     *
10394     * <p>By default this is 1.0f.
10395     * @return The opacity of the view.
10396     */
10397    @ViewDebug.ExportedProperty(category = "drawing")
10398    public float getAlpha() {
10399        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10400    }
10401
10402    /**
10403     * Returns whether this View has content which overlaps.
10404     *
10405     * <p>This function, intended to be overridden by specific View types, is an optimization when
10406     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10407     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10408     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10409     * directly. An example of overlapping rendering is a TextView with a background image, such as
10410     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10411     * ImageView with only the foreground image. The default implementation returns true; subclasses
10412     * should override if they have cases which can be optimized.</p>
10413     *
10414     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10415     * necessitates that a View return true if it uses the methods internally without passing the
10416     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10417     *
10418     * @return true if the content in this view might overlap, false otherwise.
10419     */
10420    @ViewDebug.ExportedProperty(category = "drawing")
10421    public boolean hasOverlappingRendering() {
10422        return true;
10423    }
10424
10425    /**
10426     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10427     * completely transparent and 1 means the view is completely opaque.</p>
10428     *
10429     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10430     * performance implications, especially for large views. It is best to use the alpha property
10431     * sparingly and transiently, as in the case of fading animations.</p>
10432     *
10433     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10434     * strongly recommended for performance reasons to either override
10435     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10436     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10437     *
10438     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10439     * responsible for applying the opacity itself.</p>
10440     *
10441     * <p>Note that if the view is backed by a
10442     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10443     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10444     * 1.0 will supercede the alpha of the layer paint.</p>
10445     *
10446     * @param alpha The opacity of the view.
10447     *
10448     * @see #hasOverlappingRendering()
10449     * @see #setLayerType(int, android.graphics.Paint)
10450     *
10451     * @attr ref android.R.styleable#View_alpha
10452     */
10453    public void setAlpha(float alpha) {
10454        ensureTransformationInfo();
10455        if (mTransformationInfo.mAlpha != alpha) {
10456            mTransformationInfo.mAlpha = alpha;
10457            if (onSetAlpha((int) (alpha * 255))) {
10458                mPrivateFlags |= PFLAG_ALPHA_SET;
10459                // subclass is handling alpha - don't optimize rendering cache invalidation
10460                invalidateParentCaches();
10461                invalidate(true);
10462            } else {
10463                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10464                invalidateViewProperty(true, false);
10465                mRenderNode.setAlpha(getFinalAlpha());
10466                notifyViewAccessibilityStateChangedIfNeeded(
10467                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10468            }
10469        }
10470    }
10471
10472    /**
10473     * Faster version of setAlpha() which performs the same steps except there are
10474     * no calls to invalidate(). The caller of this function should perform proper invalidation
10475     * on the parent and this object. The return value indicates whether the subclass handles
10476     * alpha (the return value for onSetAlpha()).
10477     *
10478     * @param alpha The new value for the alpha property
10479     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10480     *         the new value for the alpha property is different from the old value
10481     */
10482    boolean setAlphaNoInvalidation(float alpha) {
10483        ensureTransformationInfo();
10484        if (mTransformationInfo.mAlpha != alpha) {
10485            mTransformationInfo.mAlpha = alpha;
10486            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10487            if (subclassHandlesAlpha) {
10488                mPrivateFlags |= PFLAG_ALPHA_SET;
10489                return true;
10490            } else {
10491                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10492                mRenderNode.setAlpha(getFinalAlpha());
10493            }
10494        }
10495        return false;
10496    }
10497
10498    /**
10499     * This property is hidden and intended only for use by the Fade transition, which
10500     * animates it to produce a visual translucency that does not side-effect (or get
10501     * affected by) the real alpha property. This value is composited with the other
10502     * alpha value (and the AlphaAnimation value, when that is present) to produce
10503     * a final visual translucency result, which is what is passed into the DisplayList.
10504     *
10505     * @hide
10506     */
10507    public void setTransitionAlpha(float alpha) {
10508        ensureTransformationInfo();
10509        if (mTransformationInfo.mTransitionAlpha != alpha) {
10510            mTransformationInfo.mTransitionAlpha = alpha;
10511            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10512            invalidateViewProperty(true, false);
10513            mRenderNode.setAlpha(getFinalAlpha());
10514        }
10515    }
10516
10517    /**
10518     * Calculates the visual alpha of this view, which is a combination of the actual
10519     * alpha value and the transitionAlpha value (if set).
10520     */
10521    private float getFinalAlpha() {
10522        if (mTransformationInfo != null) {
10523            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10524        }
10525        return 1;
10526    }
10527
10528    /**
10529     * This property is hidden and intended only for use by the Fade transition, which
10530     * animates it to produce a visual translucency that does not side-effect (or get
10531     * affected by) the real alpha property. This value is composited with the other
10532     * alpha value (and the AlphaAnimation value, when that is present) to produce
10533     * a final visual translucency result, which is what is passed into the DisplayList.
10534     *
10535     * @hide
10536     */
10537    @ViewDebug.ExportedProperty(category = "drawing")
10538    public float getTransitionAlpha() {
10539        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10540    }
10541
10542    /**
10543     * Top position of this view relative to its parent.
10544     *
10545     * @return The top of this view, in pixels.
10546     */
10547    @ViewDebug.CapturedViewProperty
10548    public final int getTop() {
10549        return mTop;
10550    }
10551
10552    /**
10553     * Sets the top position of this view relative to its parent. This method is meant to be called
10554     * by the layout system and should not generally be called otherwise, because the property
10555     * may be changed at any time by the layout.
10556     *
10557     * @param top The top of this view, in pixels.
10558     */
10559    public final void setTop(int top) {
10560        if (top != mTop) {
10561            final boolean matrixIsIdentity = hasIdentityMatrix();
10562            if (matrixIsIdentity) {
10563                if (mAttachInfo != null) {
10564                    int minTop;
10565                    int yLoc;
10566                    if (top < mTop) {
10567                        minTop = top;
10568                        yLoc = top - mTop;
10569                    } else {
10570                        minTop = mTop;
10571                        yLoc = 0;
10572                    }
10573                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10574                }
10575            } else {
10576                // Double-invalidation is necessary to capture view's old and new areas
10577                invalidate(true);
10578            }
10579
10580            int width = mRight - mLeft;
10581            int oldHeight = mBottom - mTop;
10582
10583            mTop = top;
10584            mRenderNode.setTop(mTop);
10585
10586            sizeChange(width, mBottom - mTop, width, oldHeight);
10587
10588            if (!matrixIsIdentity) {
10589                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10590                invalidate(true);
10591            }
10592            mBackgroundSizeChanged = true;
10593            invalidateParentIfNeeded();
10594            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10595                // View was rejected last time it was drawn by its parent; this may have changed
10596                invalidateParentIfNeeded();
10597            }
10598        }
10599    }
10600
10601    /**
10602     * Bottom position of this view relative to its parent.
10603     *
10604     * @return The bottom of this view, in pixels.
10605     */
10606    @ViewDebug.CapturedViewProperty
10607    public final int getBottom() {
10608        return mBottom;
10609    }
10610
10611    /**
10612     * True if this view has changed since the last time being drawn.
10613     *
10614     * @return The dirty state of this view.
10615     */
10616    public boolean isDirty() {
10617        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10618    }
10619
10620    /**
10621     * Sets the bottom position of this view relative to its parent. This method is meant to be
10622     * called by the layout system and should not generally be called otherwise, because the
10623     * property may be changed at any time by the layout.
10624     *
10625     * @param bottom The bottom of this view, in pixels.
10626     */
10627    public final void setBottom(int bottom) {
10628        if (bottom != mBottom) {
10629            final boolean matrixIsIdentity = hasIdentityMatrix();
10630            if (matrixIsIdentity) {
10631                if (mAttachInfo != null) {
10632                    int maxBottom;
10633                    if (bottom < mBottom) {
10634                        maxBottom = mBottom;
10635                    } else {
10636                        maxBottom = bottom;
10637                    }
10638                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10639                }
10640            } else {
10641                // Double-invalidation is necessary to capture view's old and new areas
10642                invalidate(true);
10643            }
10644
10645            int width = mRight - mLeft;
10646            int oldHeight = mBottom - mTop;
10647
10648            mBottom = bottom;
10649            mRenderNode.setBottom(mBottom);
10650
10651            sizeChange(width, mBottom - mTop, width, oldHeight);
10652
10653            if (!matrixIsIdentity) {
10654                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10655                invalidate(true);
10656            }
10657            mBackgroundSizeChanged = true;
10658            invalidateParentIfNeeded();
10659            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10660                // View was rejected last time it was drawn by its parent; this may have changed
10661                invalidateParentIfNeeded();
10662            }
10663        }
10664    }
10665
10666    /**
10667     * Left position of this view relative to its parent.
10668     *
10669     * @return The left edge of this view, in pixels.
10670     */
10671    @ViewDebug.CapturedViewProperty
10672    public final int getLeft() {
10673        return mLeft;
10674    }
10675
10676    /**
10677     * Sets the left position of this view relative to its parent. This method is meant to be called
10678     * by the layout system and should not generally be called otherwise, because the property
10679     * may be changed at any time by the layout.
10680     *
10681     * @param left The left of this view, in pixels.
10682     */
10683    public final void setLeft(int left) {
10684        if (left != mLeft) {
10685            final boolean matrixIsIdentity = hasIdentityMatrix();
10686            if (matrixIsIdentity) {
10687                if (mAttachInfo != null) {
10688                    int minLeft;
10689                    int xLoc;
10690                    if (left < mLeft) {
10691                        minLeft = left;
10692                        xLoc = left - mLeft;
10693                    } else {
10694                        minLeft = mLeft;
10695                        xLoc = 0;
10696                    }
10697                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10698                }
10699            } else {
10700                // Double-invalidation is necessary to capture view's old and new areas
10701                invalidate(true);
10702            }
10703
10704            int oldWidth = mRight - mLeft;
10705            int height = mBottom - mTop;
10706
10707            mLeft = left;
10708            mRenderNode.setLeft(left);
10709
10710            sizeChange(mRight - mLeft, height, oldWidth, height);
10711
10712            if (!matrixIsIdentity) {
10713                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10714                invalidate(true);
10715            }
10716            mBackgroundSizeChanged = true;
10717            invalidateParentIfNeeded();
10718            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10719                // View was rejected last time it was drawn by its parent; this may have changed
10720                invalidateParentIfNeeded();
10721            }
10722        }
10723    }
10724
10725    /**
10726     * Right position of this view relative to its parent.
10727     *
10728     * @return The right edge of this view, in pixels.
10729     */
10730    @ViewDebug.CapturedViewProperty
10731    public final int getRight() {
10732        return mRight;
10733    }
10734
10735    /**
10736     * Sets the right position of this view relative to its parent. This method is meant to be called
10737     * by the layout system and should not generally be called otherwise, because the property
10738     * may be changed at any time by the layout.
10739     *
10740     * @param right The right of this view, in pixels.
10741     */
10742    public final void setRight(int right) {
10743        if (right != mRight) {
10744            final boolean matrixIsIdentity = hasIdentityMatrix();
10745            if (matrixIsIdentity) {
10746                if (mAttachInfo != null) {
10747                    int maxRight;
10748                    if (right < mRight) {
10749                        maxRight = mRight;
10750                    } else {
10751                        maxRight = right;
10752                    }
10753                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10754                }
10755            } else {
10756                // Double-invalidation is necessary to capture view's old and new areas
10757                invalidate(true);
10758            }
10759
10760            int oldWidth = mRight - mLeft;
10761            int height = mBottom - mTop;
10762
10763            mRight = right;
10764            mRenderNode.setRight(mRight);
10765
10766            sizeChange(mRight - mLeft, height, oldWidth, height);
10767
10768            if (!matrixIsIdentity) {
10769                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10770                invalidate(true);
10771            }
10772            mBackgroundSizeChanged = true;
10773            invalidateParentIfNeeded();
10774            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10775                // View was rejected last time it was drawn by its parent; this may have changed
10776                invalidateParentIfNeeded();
10777            }
10778        }
10779    }
10780
10781    /**
10782     * The visual x position of this view, in pixels. This is equivalent to the
10783     * {@link #setTranslationX(float) translationX} property plus the current
10784     * {@link #getLeft() left} property.
10785     *
10786     * @return The visual x position of this view, in pixels.
10787     */
10788    @ViewDebug.ExportedProperty(category = "drawing")
10789    public float getX() {
10790        return mLeft + getTranslationX();
10791    }
10792
10793    /**
10794     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10795     * {@link #setTranslationX(float) translationX} property to be the difference between
10796     * the x value passed in and the current {@link #getLeft() left} property.
10797     *
10798     * @param x The visual x position of this view, in pixels.
10799     */
10800    public void setX(float x) {
10801        setTranslationX(x - mLeft);
10802    }
10803
10804    /**
10805     * The visual y position of this view, in pixels. This is equivalent to the
10806     * {@link #setTranslationY(float) translationY} property plus the current
10807     * {@link #getTop() top} property.
10808     *
10809     * @return The visual y position of this view, in pixels.
10810     */
10811    @ViewDebug.ExportedProperty(category = "drawing")
10812    public float getY() {
10813        return mTop + getTranslationY();
10814    }
10815
10816    /**
10817     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10818     * {@link #setTranslationY(float) translationY} property to be the difference between
10819     * the y value passed in and the current {@link #getTop() top} property.
10820     *
10821     * @param y The visual y position of this view, in pixels.
10822     */
10823    public void setY(float y) {
10824        setTranslationY(y - mTop);
10825    }
10826
10827    /**
10828     * The visual z position of this view, in pixels. This is equivalent to the
10829     * {@link #setTranslationZ(float) translationZ} property plus the current
10830     * {@link #getElevation() elevation} property.
10831     *
10832     * @return The visual z position of this view, in pixels.
10833     */
10834    @ViewDebug.ExportedProperty(category = "drawing")
10835    public float getZ() {
10836        return getElevation() + getTranslationZ();
10837    }
10838
10839    /**
10840     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10841     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10842     * the x value passed in and the current {@link #getElevation() elevation} property.
10843     *
10844     * @param z The visual z position of this view, in pixels.
10845     */
10846    public void setZ(float z) {
10847        setTranslationZ(z - getElevation());
10848    }
10849
10850    /**
10851     * The base elevation of this view relative to its parent, in pixels.
10852     *
10853     * @return The base depth position of the view, in pixels.
10854     */
10855    @ViewDebug.ExportedProperty(category = "drawing")
10856    public float getElevation() {
10857        return mRenderNode.getElevation();
10858    }
10859
10860    /**
10861     * Sets the base elevation of this view, in pixels.
10862     *
10863     * @attr ref android.R.styleable#View_elevation
10864     */
10865    public void setElevation(float elevation) {
10866        if (elevation != getElevation()) {
10867            invalidateViewProperty(true, false);
10868            mRenderNode.setElevation(elevation);
10869            invalidateViewProperty(false, true);
10870
10871            invalidateParentIfNeededAndWasQuickRejected();
10872        }
10873    }
10874
10875    /**
10876     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10877     * This position is post-layout, in addition to wherever the object's
10878     * layout placed it.
10879     *
10880     * @return The horizontal position of this view relative to its left position, in pixels.
10881     */
10882    @ViewDebug.ExportedProperty(category = "drawing")
10883    public float getTranslationX() {
10884        return mRenderNode.getTranslationX();
10885    }
10886
10887    /**
10888     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10889     * This effectively positions the object post-layout, in addition to wherever the object's
10890     * layout placed it.
10891     *
10892     * @param translationX The horizontal position of this view relative to its left position,
10893     * in pixels.
10894     *
10895     * @attr ref android.R.styleable#View_translationX
10896     */
10897    public void setTranslationX(float translationX) {
10898        if (translationX != getTranslationX()) {
10899            invalidateViewProperty(true, false);
10900            mRenderNode.setTranslationX(translationX);
10901            invalidateViewProperty(false, true);
10902
10903            invalidateParentIfNeededAndWasQuickRejected();
10904            notifySubtreeAccessibilityStateChangedIfNeeded();
10905        }
10906    }
10907
10908    /**
10909     * The vertical location of this view relative to its {@link #getTop() top} position.
10910     * This position is post-layout, in addition to wherever the object's
10911     * layout placed it.
10912     *
10913     * @return The vertical position of this view relative to its top position,
10914     * in pixels.
10915     */
10916    @ViewDebug.ExportedProperty(category = "drawing")
10917    public float getTranslationY() {
10918        return mRenderNode.getTranslationY();
10919    }
10920
10921    /**
10922     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10923     * This effectively positions the object post-layout, in addition to wherever the object's
10924     * layout placed it.
10925     *
10926     * @param translationY The vertical position of this view relative to its top position,
10927     * in pixels.
10928     *
10929     * @attr ref android.R.styleable#View_translationY
10930     */
10931    public void setTranslationY(float translationY) {
10932        if (translationY != getTranslationY()) {
10933            invalidateViewProperty(true, false);
10934            mRenderNode.setTranslationY(translationY);
10935            invalidateViewProperty(false, true);
10936
10937            invalidateParentIfNeededAndWasQuickRejected();
10938        }
10939    }
10940
10941    /**
10942     * The depth location of this view relative to its {@link #getElevation() elevation}.
10943     *
10944     * @return The depth of this view relative to its elevation.
10945     */
10946    @ViewDebug.ExportedProperty(category = "drawing")
10947    public float getTranslationZ() {
10948        return mRenderNode.getTranslationZ();
10949    }
10950
10951    /**
10952     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10953     *
10954     * @attr ref android.R.styleable#View_translationZ
10955     */
10956    public void setTranslationZ(float translationZ) {
10957        if (translationZ != getTranslationZ()) {
10958            invalidateViewProperty(true, false);
10959            mRenderNode.setTranslationZ(translationZ);
10960            invalidateViewProperty(false, true);
10961
10962            invalidateParentIfNeededAndWasQuickRejected();
10963        }
10964    }
10965
10966    /** @hide */
10967    public void setAnimationMatrix(Matrix matrix) {
10968        invalidateViewProperty(true, false);
10969        mRenderNode.setAnimationMatrix(matrix);
10970        invalidateViewProperty(false, true);
10971
10972        invalidateParentIfNeededAndWasQuickRejected();
10973    }
10974
10975    /**
10976     * Returns the current StateListAnimator if exists.
10977     *
10978     * @return StateListAnimator or null if it does not exists
10979     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10980     */
10981    public StateListAnimator getStateListAnimator() {
10982        return mStateListAnimator;
10983    }
10984
10985    /**
10986     * Attaches the provided StateListAnimator to this View.
10987     * <p>
10988     * Any previously attached StateListAnimator will be detached.
10989     *
10990     * @param stateListAnimator The StateListAnimator to update the view
10991     * @see {@link android.animation.StateListAnimator}
10992     */
10993    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10994        if (mStateListAnimator == stateListAnimator) {
10995            return;
10996        }
10997        if (mStateListAnimator != null) {
10998            mStateListAnimator.setTarget(null);
10999        }
11000        mStateListAnimator = stateListAnimator;
11001        if (stateListAnimator != null) {
11002            stateListAnimator.setTarget(this);
11003            if (isAttachedToWindow()) {
11004                stateListAnimator.setState(getDrawableState());
11005            }
11006        }
11007    }
11008
11009    /**
11010     * Returns whether the Outline should be used to clip the contents of the View.
11011     * <p>
11012     * Note that this flag will only be respected if the View's Outline returns true from
11013     * {@link Outline#canClip()}.
11014     *
11015     * @see #setOutlineProvider(ViewOutlineProvider)
11016     * @see #setClipToOutline(boolean)
11017     */
11018    public final boolean getClipToOutline() {
11019        return mRenderNode.getClipToOutline();
11020    }
11021
11022    /**
11023     * Sets whether the View's Outline should be used to clip the contents of the View.
11024     * <p>
11025     * Only a single non-rectangular clip can be applied on a View at any time.
11026     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11027     * circular reveal} animation take priority over Outline clipping, and
11028     * child Outline clipping takes priority over Outline clipping done by a
11029     * parent.
11030     * <p>
11031     * Note that this flag will only be respected if the View's Outline returns true from
11032     * {@link Outline#canClip()}.
11033     *
11034     * @see #setOutlineProvider(ViewOutlineProvider)
11035     * @see #getClipToOutline()
11036     */
11037    public void setClipToOutline(boolean clipToOutline) {
11038        damageInParent();
11039        if (getClipToOutline() != clipToOutline) {
11040            mRenderNode.setClipToOutline(clipToOutline);
11041        }
11042    }
11043
11044    // correspond to the enum values of View_outlineProvider
11045    private static final int PROVIDER_BACKGROUND = 0;
11046    private static final int PROVIDER_NONE = 1;
11047    private static final int PROVIDER_BOUNDS = 2;
11048    private static final int PROVIDER_PADDED_BOUNDS = 3;
11049    private void setOutlineProviderFromAttribute(int providerInt) {
11050        switch (providerInt) {
11051            case PROVIDER_BACKGROUND:
11052                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11053                break;
11054            case PROVIDER_NONE:
11055                setOutlineProvider(null);
11056                break;
11057            case PROVIDER_BOUNDS:
11058                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11059                break;
11060            case PROVIDER_PADDED_BOUNDS:
11061                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11062                break;
11063        }
11064    }
11065
11066    /**
11067     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11068     * the shape of the shadow it casts, and enables outline clipping.
11069     * <p>
11070     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11071     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11072     * outline provider with this method allows this behavior to be overridden.
11073     * <p>
11074     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11075     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11076     * <p>
11077     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11078     *
11079     * @see #setClipToOutline(boolean)
11080     * @see #getClipToOutline()
11081     * @see #getOutlineProvider()
11082     */
11083    public void setOutlineProvider(ViewOutlineProvider provider) {
11084        mOutlineProvider = provider;
11085        invalidateOutline();
11086    }
11087
11088    /**
11089     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11090     * that defines the shape of the shadow it casts, and enables outline clipping.
11091     *
11092     * @see #setOutlineProvider(ViewOutlineProvider)
11093     */
11094    public ViewOutlineProvider getOutlineProvider() {
11095        return mOutlineProvider;
11096    }
11097
11098    /**
11099     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11100     *
11101     * @see #setOutlineProvider(ViewOutlineProvider)
11102     */
11103    public void invalidateOutline() {
11104        mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
11105
11106        notifySubtreeAccessibilityStateChangedIfNeeded();
11107        invalidateViewProperty(false, false);
11108    }
11109
11110    /**
11111     * Internal version of {@link #invalidateOutline()} which invalidates the
11112     * outline without invalidating the view itself. This is intended to be called from
11113     * within methods in the View class itself which are the result of the view being
11114     * invalidated already. For example, when we are drawing the background of a View,
11115     * we invalidate the outline in case it changed in the meantime, but we do not
11116     * need to invalidate the view because we're already drawing the background as part
11117     * of drawing the view in response to an earlier invalidation of the view.
11118     */
11119    private void rebuildOutline() {
11120        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11121        if (mAttachInfo == null) return;
11122
11123        if (mOutlineProvider == null) {
11124            // no provider, remove outline
11125            mRenderNode.setOutline(null);
11126        } else {
11127            final Outline outline = mAttachInfo.mTmpOutline;
11128            outline.setEmpty();
11129            outline.setAlpha(1.0f);
11130
11131            mOutlineProvider.getOutline(this, outline);
11132            mRenderNode.setOutline(outline);
11133        }
11134    }
11135
11136    /**
11137     * HierarchyViewer only
11138     *
11139     * @hide
11140     */
11141    @ViewDebug.ExportedProperty(category = "drawing")
11142    public boolean hasShadow() {
11143        return mRenderNode.hasShadow();
11144    }
11145
11146
11147    /** @hide */
11148    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11149        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11150        invalidateViewProperty(false, false);
11151    }
11152
11153    /**
11154     * Hit rectangle in parent's coordinates
11155     *
11156     * @param outRect The hit rectangle of the view.
11157     */
11158    public void getHitRect(Rect outRect) {
11159        if (hasIdentityMatrix() || mAttachInfo == null) {
11160            outRect.set(mLeft, mTop, mRight, mBottom);
11161        } else {
11162            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11163            tmpRect.set(0, 0, getWidth(), getHeight());
11164            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11165            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11166                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11167        }
11168    }
11169
11170    /**
11171     * Determines whether the given point, in local coordinates is inside the view.
11172     */
11173    /*package*/ final boolean pointInView(float localX, float localY) {
11174        return localX >= 0 && localX < (mRight - mLeft)
11175                && localY >= 0 && localY < (mBottom - mTop);
11176    }
11177
11178    /**
11179     * Utility method to determine whether the given point, in local coordinates,
11180     * is inside the view, where the area of the view is expanded by the slop factor.
11181     * This method is called while processing touch-move events to determine if the event
11182     * is still within the view.
11183     *
11184     * @hide
11185     */
11186    public boolean pointInView(float localX, float localY, float slop) {
11187        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11188                localY < ((mBottom - mTop) + slop);
11189    }
11190
11191    /**
11192     * When a view has focus and the user navigates away from it, the next view is searched for
11193     * starting from the rectangle filled in by this method.
11194     *
11195     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11196     * of the view.  However, if your view maintains some idea of internal selection,
11197     * such as a cursor, or a selected row or column, you should override this method and
11198     * fill in a more specific rectangle.
11199     *
11200     * @param r The rectangle to fill in, in this view's coordinates.
11201     */
11202    public void getFocusedRect(Rect r) {
11203        getDrawingRect(r);
11204    }
11205
11206    /**
11207     * If some part of this view is not clipped by any of its parents, then
11208     * return that area in r in global (root) coordinates. To convert r to local
11209     * coordinates (without taking possible View rotations into account), offset
11210     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11211     * If the view is completely clipped or translated out, return false.
11212     *
11213     * @param r If true is returned, r holds the global coordinates of the
11214     *        visible portion of this view.
11215     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11216     *        between this view and its root. globalOffet may be null.
11217     * @return true if r is non-empty (i.e. part of the view is visible at the
11218     *         root level.
11219     */
11220    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11221        int width = mRight - mLeft;
11222        int height = mBottom - mTop;
11223        if (width > 0 && height > 0) {
11224            r.set(0, 0, width, height);
11225            if (globalOffset != null) {
11226                globalOffset.set(-mScrollX, -mScrollY);
11227            }
11228            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11229        }
11230        return false;
11231    }
11232
11233    public final boolean getGlobalVisibleRect(Rect r) {
11234        return getGlobalVisibleRect(r, null);
11235    }
11236
11237    public final boolean getLocalVisibleRect(Rect r) {
11238        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11239        if (getGlobalVisibleRect(r, offset)) {
11240            r.offset(-offset.x, -offset.y); // make r local
11241            return true;
11242        }
11243        return false;
11244    }
11245
11246    /**
11247     * Offset this view's vertical location by the specified number of pixels.
11248     *
11249     * @param offset the number of pixels to offset the view by
11250     */
11251    public void offsetTopAndBottom(int offset) {
11252        if (offset != 0) {
11253            final boolean matrixIsIdentity = hasIdentityMatrix();
11254            if (matrixIsIdentity) {
11255                if (isHardwareAccelerated()) {
11256                    invalidateViewProperty(false, false);
11257                } else {
11258                    final ViewParent p = mParent;
11259                    if (p != null && mAttachInfo != null) {
11260                        final Rect r = mAttachInfo.mTmpInvalRect;
11261                        int minTop;
11262                        int maxBottom;
11263                        int yLoc;
11264                        if (offset < 0) {
11265                            minTop = mTop + offset;
11266                            maxBottom = mBottom;
11267                            yLoc = offset;
11268                        } else {
11269                            minTop = mTop;
11270                            maxBottom = mBottom + offset;
11271                            yLoc = 0;
11272                        }
11273                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11274                        p.invalidateChild(this, r);
11275                    }
11276                }
11277            } else {
11278                invalidateViewProperty(false, false);
11279            }
11280
11281            mTop += offset;
11282            mBottom += offset;
11283            mRenderNode.offsetTopAndBottom(offset);
11284            if (isHardwareAccelerated()) {
11285                invalidateViewProperty(false, false);
11286            } else {
11287                if (!matrixIsIdentity) {
11288                    invalidateViewProperty(false, true);
11289                }
11290                invalidateParentIfNeeded();
11291            }
11292            notifySubtreeAccessibilityStateChangedIfNeeded();
11293        }
11294    }
11295
11296    /**
11297     * Offset this view's horizontal location by the specified amount of pixels.
11298     *
11299     * @param offset the number of pixels to offset the view by
11300     */
11301    public void offsetLeftAndRight(int offset) {
11302        if (offset != 0) {
11303            final boolean matrixIsIdentity = hasIdentityMatrix();
11304            if (matrixIsIdentity) {
11305                if (isHardwareAccelerated()) {
11306                    invalidateViewProperty(false, false);
11307                } else {
11308                    final ViewParent p = mParent;
11309                    if (p != null && mAttachInfo != null) {
11310                        final Rect r = mAttachInfo.mTmpInvalRect;
11311                        int minLeft;
11312                        int maxRight;
11313                        if (offset < 0) {
11314                            minLeft = mLeft + offset;
11315                            maxRight = mRight;
11316                        } else {
11317                            minLeft = mLeft;
11318                            maxRight = mRight + offset;
11319                        }
11320                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11321                        p.invalidateChild(this, r);
11322                    }
11323                }
11324            } else {
11325                invalidateViewProperty(false, false);
11326            }
11327
11328            mLeft += offset;
11329            mRight += offset;
11330            mRenderNode.offsetLeftAndRight(offset);
11331            if (isHardwareAccelerated()) {
11332                invalidateViewProperty(false, false);
11333            } else {
11334                if (!matrixIsIdentity) {
11335                    invalidateViewProperty(false, true);
11336                }
11337                invalidateParentIfNeeded();
11338            }
11339            notifySubtreeAccessibilityStateChangedIfNeeded();
11340        }
11341    }
11342
11343    /**
11344     * Get the LayoutParams associated with this view. All views should have
11345     * layout parameters. These supply parameters to the <i>parent</i> of this
11346     * view specifying how it should be arranged. There are many subclasses of
11347     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11348     * of ViewGroup that are responsible for arranging their children.
11349     *
11350     * This method may return null if this View is not attached to a parent
11351     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11352     * was not invoked successfully. When a View is attached to a parent
11353     * ViewGroup, this method must not return null.
11354     *
11355     * @return The LayoutParams associated with this view, or null if no
11356     *         parameters have been set yet
11357     */
11358    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11359    public ViewGroup.LayoutParams getLayoutParams() {
11360        return mLayoutParams;
11361    }
11362
11363    /**
11364     * Set the layout parameters associated with this view. These supply
11365     * parameters to the <i>parent</i> of this view specifying how it should be
11366     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11367     * correspond to the different subclasses of ViewGroup that are responsible
11368     * for arranging their children.
11369     *
11370     * @param params The layout parameters for this view, cannot be null
11371     */
11372    public void setLayoutParams(ViewGroup.LayoutParams params) {
11373        if (params == null) {
11374            throw new NullPointerException("Layout parameters cannot be null");
11375        }
11376        mLayoutParams = params;
11377        resolveLayoutParams();
11378        if (mParent instanceof ViewGroup) {
11379            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11380        }
11381        requestLayout();
11382    }
11383
11384    /**
11385     * Resolve the layout parameters depending on the resolved layout direction
11386     *
11387     * @hide
11388     */
11389    public void resolveLayoutParams() {
11390        if (mLayoutParams != null) {
11391            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11392        }
11393    }
11394
11395    /**
11396     * Set the scrolled position of your view. This will cause a call to
11397     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11398     * invalidated.
11399     * @param x the x position to scroll to
11400     * @param y the y position to scroll to
11401     */
11402    public void scrollTo(int x, int y) {
11403        if (mScrollX != x || mScrollY != y) {
11404            int oldX = mScrollX;
11405            int oldY = mScrollY;
11406            mScrollX = x;
11407            mScrollY = y;
11408            invalidateParentCaches();
11409            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11410            if (!awakenScrollBars()) {
11411                postInvalidateOnAnimation();
11412            }
11413        }
11414    }
11415
11416    /**
11417     * Move the scrolled position of your view. This will cause a call to
11418     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11419     * invalidated.
11420     * @param x the amount of pixels to scroll by horizontally
11421     * @param y the amount of pixels to scroll by vertically
11422     */
11423    public void scrollBy(int x, int y) {
11424        scrollTo(mScrollX + x, mScrollY + y);
11425    }
11426
11427    /**
11428     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11429     * animation to fade the scrollbars out after a default delay. If a subclass
11430     * provides animated scrolling, the start delay should equal the duration
11431     * of the scrolling animation.</p>
11432     *
11433     * <p>The animation starts only if at least one of the scrollbars is
11434     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11435     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11436     * this method returns true, and false otherwise. If the animation is
11437     * started, this method calls {@link #invalidate()}; in that case the
11438     * caller should not call {@link #invalidate()}.</p>
11439     *
11440     * <p>This method should be invoked every time a subclass directly updates
11441     * the scroll parameters.</p>
11442     *
11443     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11444     * and {@link #scrollTo(int, int)}.</p>
11445     *
11446     * @return true if the animation is played, false otherwise
11447     *
11448     * @see #awakenScrollBars(int)
11449     * @see #scrollBy(int, int)
11450     * @see #scrollTo(int, int)
11451     * @see #isHorizontalScrollBarEnabled()
11452     * @see #isVerticalScrollBarEnabled()
11453     * @see #setHorizontalScrollBarEnabled(boolean)
11454     * @see #setVerticalScrollBarEnabled(boolean)
11455     */
11456    protected boolean awakenScrollBars() {
11457        return mScrollCache != null &&
11458                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11459    }
11460
11461    /**
11462     * Trigger the scrollbars to draw.
11463     * This method differs from awakenScrollBars() only in its default duration.
11464     * initialAwakenScrollBars() will show the scroll bars for longer than
11465     * usual to give the user more of a chance to notice them.
11466     *
11467     * @return true if the animation is played, false otherwise.
11468     */
11469    private boolean initialAwakenScrollBars() {
11470        return mScrollCache != null &&
11471                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11472    }
11473
11474    /**
11475     * <p>
11476     * Trigger the scrollbars to draw. When invoked this method starts an
11477     * animation to fade the scrollbars out after a fixed delay. If a subclass
11478     * provides animated scrolling, the start delay should equal the duration of
11479     * the scrolling animation.
11480     * </p>
11481     *
11482     * <p>
11483     * The animation starts only if at least one of the scrollbars is enabled,
11484     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11485     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11486     * this method returns true, and false otherwise. If the animation is
11487     * started, this method calls {@link #invalidate()}; in that case the caller
11488     * should not call {@link #invalidate()}.
11489     * </p>
11490     *
11491     * <p>
11492     * This method should be invoked everytime a subclass directly updates the
11493     * scroll parameters.
11494     * </p>
11495     *
11496     * @param startDelay the delay, in milliseconds, after which the animation
11497     *        should start; when the delay is 0, the animation starts
11498     *        immediately
11499     * @return true if the animation is played, false otherwise
11500     *
11501     * @see #scrollBy(int, int)
11502     * @see #scrollTo(int, int)
11503     * @see #isHorizontalScrollBarEnabled()
11504     * @see #isVerticalScrollBarEnabled()
11505     * @see #setHorizontalScrollBarEnabled(boolean)
11506     * @see #setVerticalScrollBarEnabled(boolean)
11507     */
11508    protected boolean awakenScrollBars(int startDelay) {
11509        return awakenScrollBars(startDelay, true);
11510    }
11511
11512    /**
11513     * <p>
11514     * Trigger the scrollbars to draw. When invoked this method starts an
11515     * animation to fade the scrollbars out after a fixed delay. If a subclass
11516     * provides animated scrolling, the start delay should equal the duration of
11517     * the scrolling animation.
11518     * </p>
11519     *
11520     * <p>
11521     * The animation starts only if at least one of the scrollbars is enabled,
11522     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11523     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11524     * this method returns true, and false otherwise. If the animation is
11525     * started, this method calls {@link #invalidate()} if the invalidate parameter
11526     * is set to true; in that case the caller
11527     * should not call {@link #invalidate()}.
11528     * </p>
11529     *
11530     * <p>
11531     * This method should be invoked everytime a subclass directly updates the
11532     * scroll parameters.
11533     * </p>
11534     *
11535     * @param startDelay the delay, in milliseconds, after which the animation
11536     *        should start; when the delay is 0, the animation starts
11537     *        immediately
11538     *
11539     * @param invalidate Wheter this method should call invalidate
11540     *
11541     * @return true if the animation is played, false otherwise
11542     *
11543     * @see #scrollBy(int, int)
11544     * @see #scrollTo(int, int)
11545     * @see #isHorizontalScrollBarEnabled()
11546     * @see #isVerticalScrollBarEnabled()
11547     * @see #setHorizontalScrollBarEnabled(boolean)
11548     * @see #setVerticalScrollBarEnabled(boolean)
11549     */
11550    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11551        final ScrollabilityCache scrollCache = mScrollCache;
11552
11553        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11554            return false;
11555        }
11556
11557        if (scrollCache.scrollBar == null) {
11558            scrollCache.scrollBar = new ScrollBarDrawable();
11559        }
11560
11561        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11562
11563            if (invalidate) {
11564                // Invalidate to show the scrollbars
11565                postInvalidateOnAnimation();
11566            }
11567
11568            if (scrollCache.state == ScrollabilityCache.OFF) {
11569                // FIXME: this is copied from WindowManagerService.
11570                // We should get this value from the system when it
11571                // is possible to do so.
11572                final int KEY_REPEAT_FIRST_DELAY = 750;
11573                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11574            }
11575
11576            // Tell mScrollCache when we should start fading. This may
11577            // extend the fade start time if one was already scheduled
11578            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11579            scrollCache.fadeStartTime = fadeStartTime;
11580            scrollCache.state = ScrollabilityCache.ON;
11581
11582            // Schedule our fader to run, unscheduling any old ones first
11583            if (mAttachInfo != null) {
11584                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11585                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11586            }
11587
11588            return true;
11589        }
11590
11591        return false;
11592    }
11593
11594    /**
11595     * Do not invalidate views which are not visible and which are not running an animation. They
11596     * will not get drawn and they should not set dirty flags as if they will be drawn
11597     */
11598    private boolean skipInvalidate() {
11599        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11600                (!(mParent instanceof ViewGroup) ||
11601                        !((ViewGroup) mParent).isViewTransitioning(this));
11602    }
11603
11604    /**
11605     * Mark the area defined by dirty as needing to be drawn. If the view is
11606     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11607     * point in the future.
11608     * <p>
11609     * This must be called from a UI thread. To call from a non-UI thread, call
11610     * {@link #postInvalidate()}.
11611     * <p>
11612     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11613     * {@code dirty}.
11614     *
11615     * @param dirty the rectangle representing the bounds of the dirty region
11616     */
11617    public void invalidate(Rect dirty) {
11618        final int scrollX = mScrollX;
11619        final int scrollY = mScrollY;
11620        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11621                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11622    }
11623
11624    /**
11625     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11626     * coordinates of the dirty rect are relative to the view. If the view is
11627     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11628     * point in the future.
11629     * <p>
11630     * This must be called from a UI thread. To call from a non-UI thread, call
11631     * {@link #postInvalidate()}.
11632     *
11633     * @param l the left position of the dirty region
11634     * @param t the top position of the dirty region
11635     * @param r the right position of the dirty region
11636     * @param b the bottom position of the dirty region
11637     */
11638    public void invalidate(int l, int t, int r, int b) {
11639        final int scrollX = mScrollX;
11640        final int scrollY = mScrollY;
11641        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11642    }
11643
11644    /**
11645     * Invalidate the whole view. If the view is visible,
11646     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11647     * the future.
11648     * <p>
11649     * This must be called from a UI thread. To call from a non-UI thread, call
11650     * {@link #postInvalidate()}.
11651     */
11652    public void invalidate() {
11653        invalidate(true);
11654    }
11655
11656    /**
11657     * This is where the invalidate() work actually happens. A full invalidate()
11658     * causes the drawing cache to be invalidated, but this function can be
11659     * called with invalidateCache set to false to skip that invalidation step
11660     * for cases that do not need it (for example, a component that remains at
11661     * the same dimensions with the same content).
11662     *
11663     * @param invalidateCache Whether the drawing cache for this view should be
11664     *            invalidated as well. This is usually true for a full
11665     *            invalidate, but may be set to false if the View's contents or
11666     *            dimensions have not changed.
11667     */
11668    void invalidate(boolean invalidateCache) {
11669        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11670    }
11671
11672    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11673            boolean fullInvalidate) {
11674        if (mGhostView != null) {
11675            mGhostView.invalidate(invalidateCache);
11676            return;
11677        }
11678
11679        if (skipInvalidate()) {
11680            return;
11681        }
11682
11683        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11684                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11685                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11686                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11687            if (fullInvalidate) {
11688                mLastIsOpaque = isOpaque();
11689                mPrivateFlags &= ~PFLAG_DRAWN;
11690            }
11691
11692            mPrivateFlags |= PFLAG_DIRTY;
11693
11694            if (invalidateCache) {
11695                mPrivateFlags |= PFLAG_INVALIDATED;
11696                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11697            }
11698
11699            // Propagate the damage rectangle to the parent view.
11700            final AttachInfo ai = mAttachInfo;
11701            final ViewParent p = mParent;
11702            if (p != null && ai != null && l < r && t < b) {
11703                final Rect damage = ai.mTmpInvalRect;
11704                damage.set(l, t, r, b);
11705                p.invalidateChild(this, damage);
11706            }
11707
11708            // Damage the entire projection receiver, if necessary.
11709            if (mBackground != null && mBackground.isProjected()) {
11710                final View receiver = getProjectionReceiver();
11711                if (receiver != null) {
11712                    receiver.damageInParent();
11713                }
11714            }
11715
11716            // Damage the entire IsolatedZVolume receiving this view's shadow.
11717            if (isHardwareAccelerated() && getZ() != 0) {
11718                damageShadowReceiver();
11719            }
11720        }
11721    }
11722
11723    /**
11724     * @return this view's projection receiver, or {@code null} if none exists
11725     */
11726    private View getProjectionReceiver() {
11727        ViewParent p = getParent();
11728        while (p != null && p instanceof View) {
11729            final View v = (View) p;
11730            if (v.isProjectionReceiver()) {
11731                return v;
11732            }
11733            p = p.getParent();
11734        }
11735
11736        return null;
11737    }
11738
11739    /**
11740     * @return whether the view is a projection receiver
11741     */
11742    private boolean isProjectionReceiver() {
11743        return mBackground != null;
11744    }
11745
11746    /**
11747     * Damage area of the screen that can be covered by this View's shadow.
11748     *
11749     * This method will guarantee that any changes to shadows cast by a View
11750     * are damaged on the screen for future redraw.
11751     */
11752    private void damageShadowReceiver() {
11753        final AttachInfo ai = mAttachInfo;
11754        if (ai != null) {
11755            ViewParent p = getParent();
11756            if (p != null && p instanceof ViewGroup) {
11757                final ViewGroup vg = (ViewGroup) p;
11758                vg.damageInParent();
11759            }
11760        }
11761    }
11762
11763    /**
11764     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11765     * set any flags or handle all of the cases handled by the default invalidation methods.
11766     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11767     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11768     * walk up the hierarchy, transforming the dirty rect as necessary.
11769     *
11770     * The method also handles normal invalidation logic if display list properties are not
11771     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11772     * backup approach, to handle these cases used in the various property-setting methods.
11773     *
11774     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11775     * are not being used in this view
11776     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11777     * list properties are not being used in this view
11778     */
11779    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11780        if (!isHardwareAccelerated()
11781                || !mRenderNode.isValid()
11782                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11783            if (invalidateParent) {
11784                invalidateParentCaches();
11785            }
11786            if (forceRedraw) {
11787                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11788            }
11789            invalidate(false);
11790        } else {
11791            damageInParent();
11792        }
11793        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11794            damageShadowReceiver();
11795        }
11796    }
11797
11798    /**
11799     * Tells the parent view to damage this view's bounds.
11800     *
11801     * @hide
11802     */
11803    protected void damageInParent() {
11804        final AttachInfo ai = mAttachInfo;
11805        final ViewParent p = mParent;
11806        if (p != null && ai != null) {
11807            final Rect r = ai.mTmpInvalRect;
11808            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11809            if (mParent instanceof ViewGroup) {
11810                ((ViewGroup) mParent).damageChild(this, r);
11811            } else {
11812                mParent.invalidateChild(this, r);
11813            }
11814        }
11815    }
11816
11817    /**
11818     * Utility method to transform a given Rect by the current matrix of this view.
11819     */
11820    void transformRect(final Rect rect) {
11821        if (!getMatrix().isIdentity()) {
11822            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11823            boundingRect.set(rect);
11824            getMatrix().mapRect(boundingRect);
11825            rect.set((int) Math.floor(boundingRect.left),
11826                    (int) Math.floor(boundingRect.top),
11827                    (int) Math.ceil(boundingRect.right),
11828                    (int) Math.ceil(boundingRect.bottom));
11829        }
11830    }
11831
11832    /**
11833     * Used to indicate that the parent of this view should clear its caches. This functionality
11834     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11835     * which is necessary when various parent-managed properties of the view change, such as
11836     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11837     * clears the parent caches and does not causes an invalidate event.
11838     *
11839     * @hide
11840     */
11841    protected void invalidateParentCaches() {
11842        if (mParent instanceof View) {
11843            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11844        }
11845    }
11846
11847    /**
11848     * Used to indicate that the parent of this view should be invalidated. This functionality
11849     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11850     * which is necessary when various parent-managed properties of the view change, such as
11851     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11852     * an invalidation event to the parent.
11853     *
11854     * @hide
11855     */
11856    protected void invalidateParentIfNeeded() {
11857        if (isHardwareAccelerated() && mParent instanceof View) {
11858            ((View) mParent).invalidate(true);
11859        }
11860    }
11861
11862    /**
11863     * @hide
11864     */
11865    protected void invalidateParentIfNeededAndWasQuickRejected() {
11866        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11867            // View was rejected last time it was drawn by its parent; this may have changed
11868            invalidateParentIfNeeded();
11869        }
11870    }
11871
11872    /**
11873     * Indicates whether this View is opaque. An opaque View guarantees that it will
11874     * draw all the pixels overlapping its bounds using a fully opaque color.
11875     *
11876     * Subclasses of View should override this method whenever possible to indicate
11877     * whether an instance is opaque. Opaque Views are treated in a special way by
11878     * the View hierarchy, possibly allowing it to perform optimizations during
11879     * invalidate/draw passes.
11880     *
11881     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11882     */
11883    @ViewDebug.ExportedProperty(category = "drawing")
11884    public boolean isOpaque() {
11885        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11886                getFinalAlpha() >= 1.0f;
11887    }
11888
11889    /**
11890     * @hide
11891     */
11892    protected void computeOpaqueFlags() {
11893        // Opaque if:
11894        //   - Has a background
11895        //   - Background is opaque
11896        //   - Doesn't have scrollbars or scrollbars overlay
11897
11898        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11899            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11900        } else {
11901            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11902        }
11903
11904        final int flags = mViewFlags;
11905        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11906                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11907                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11908            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11909        } else {
11910            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11911        }
11912    }
11913
11914    /**
11915     * @hide
11916     */
11917    protected boolean hasOpaqueScrollbars() {
11918        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11919    }
11920
11921    /**
11922     * @return A handler associated with the thread running the View. This
11923     * handler can be used to pump events in the UI events queue.
11924     */
11925    public Handler getHandler() {
11926        final AttachInfo attachInfo = mAttachInfo;
11927        if (attachInfo != null) {
11928            return attachInfo.mHandler;
11929        }
11930        return null;
11931    }
11932
11933    /**
11934     * Gets the view root associated with the View.
11935     * @return The view root, or null if none.
11936     * @hide
11937     */
11938    public ViewRootImpl getViewRootImpl() {
11939        if (mAttachInfo != null) {
11940            return mAttachInfo.mViewRootImpl;
11941        }
11942        return null;
11943    }
11944
11945    /**
11946     * @hide
11947     */
11948    public HardwareRenderer getHardwareRenderer() {
11949        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11950    }
11951
11952    /**
11953     * <p>Causes the Runnable to be added to the message queue.
11954     * The runnable will be run on the user interface thread.</p>
11955     *
11956     * @param action The Runnable that will be executed.
11957     *
11958     * @return Returns true if the Runnable was successfully placed in to the
11959     *         message queue.  Returns false on failure, usually because the
11960     *         looper processing the message queue is exiting.
11961     *
11962     * @see #postDelayed
11963     * @see #removeCallbacks
11964     */
11965    public boolean post(Runnable action) {
11966        final AttachInfo attachInfo = mAttachInfo;
11967        if (attachInfo != null) {
11968            return attachInfo.mHandler.post(action);
11969        }
11970        // Assume that post will succeed later
11971        ViewRootImpl.getRunQueue().post(action);
11972        return true;
11973    }
11974
11975    /**
11976     * <p>Causes the Runnable to be added to the message queue, to be run
11977     * after the specified amount of time elapses.
11978     * The runnable will be run on the user interface thread.</p>
11979     *
11980     * @param action The Runnable that will be executed.
11981     * @param delayMillis The delay (in milliseconds) until the Runnable
11982     *        will be executed.
11983     *
11984     * @return true if the Runnable was successfully placed in to the
11985     *         message queue.  Returns false on failure, usually because the
11986     *         looper processing the message queue is exiting.  Note that a
11987     *         result of true does not mean the Runnable will be processed --
11988     *         if the looper is quit before the delivery time of the message
11989     *         occurs then the message will be dropped.
11990     *
11991     * @see #post
11992     * @see #removeCallbacks
11993     */
11994    public boolean postDelayed(Runnable action, long delayMillis) {
11995        final AttachInfo attachInfo = mAttachInfo;
11996        if (attachInfo != null) {
11997            return attachInfo.mHandler.postDelayed(action, delayMillis);
11998        }
11999        // Assume that post will succeed later
12000        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12001        return true;
12002    }
12003
12004    /**
12005     * <p>Causes the Runnable to execute on the next animation time step.
12006     * The runnable will be run on the user interface thread.</p>
12007     *
12008     * @param action The Runnable that will be executed.
12009     *
12010     * @see #postOnAnimationDelayed
12011     * @see #removeCallbacks
12012     */
12013    public void postOnAnimation(Runnable action) {
12014        final AttachInfo attachInfo = mAttachInfo;
12015        if (attachInfo != null) {
12016            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12017                    Choreographer.CALLBACK_ANIMATION, action, null);
12018        } else {
12019            // Assume that post will succeed later
12020            ViewRootImpl.getRunQueue().post(action);
12021        }
12022    }
12023
12024    /**
12025     * <p>Causes the Runnable to execute on the next animation time step,
12026     * after the specified amount of time elapses.
12027     * The runnable will be run on the user interface thread.</p>
12028     *
12029     * @param action The Runnable that will be executed.
12030     * @param delayMillis The delay (in milliseconds) until the Runnable
12031     *        will be executed.
12032     *
12033     * @see #postOnAnimation
12034     * @see #removeCallbacks
12035     */
12036    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12037        final AttachInfo attachInfo = mAttachInfo;
12038        if (attachInfo != null) {
12039            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12040                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12041        } else {
12042            // Assume that post will succeed later
12043            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12044        }
12045    }
12046
12047    /**
12048     * <p>Removes the specified Runnable from the message queue.</p>
12049     *
12050     * @param action The Runnable to remove from the message handling queue
12051     *
12052     * @return true if this view could ask the Handler to remove the Runnable,
12053     *         false otherwise. When the returned value is true, the Runnable
12054     *         may or may not have been actually removed from the message queue
12055     *         (for instance, if the Runnable was not in the queue already.)
12056     *
12057     * @see #post
12058     * @see #postDelayed
12059     * @see #postOnAnimation
12060     * @see #postOnAnimationDelayed
12061     */
12062    public boolean removeCallbacks(Runnable action) {
12063        if (action != null) {
12064            final AttachInfo attachInfo = mAttachInfo;
12065            if (attachInfo != null) {
12066                attachInfo.mHandler.removeCallbacks(action);
12067                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12068                        Choreographer.CALLBACK_ANIMATION, action, null);
12069            }
12070            // Assume that post will succeed later
12071            ViewRootImpl.getRunQueue().removeCallbacks(action);
12072        }
12073        return true;
12074    }
12075
12076    /**
12077     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12078     * Use this to invalidate the View from a non-UI thread.</p>
12079     *
12080     * <p>This method can be invoked from outside of the UI thread
12081     * only when this View is attached to a window.</p>
12082     *
12083     * @see #invalidate()
12084     * @see #postInvalidateDelayed(long)
12085     */
12086    public void postInvalidate() {
12087        postInvalidateDelayed(0);
12088    }
12089
12090    /**
12091     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12092     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12093     *
12094     * <p>This method can be invoked from outside of the UI thread
12095     * only when this View is attached to a window.</p>
12096     *
12097     * @param left The left coordinate of the rectangle to invalidate.
12098     * @param top The top coordinate of the rectangle to invalidate.
12099     * @param right The right coordinate of the rectangle to invalidate.
12100     * @param bottom The bottom coordinate of the rectangle to invalidate.
12101     *
12102     * @see #invalidate(int, int, int, int)
12103     * @see #invalidate(Rect)
12104     * @see #postInvalidateDelayed(long, int, int, int, int)
12105     */
12106    public void postInvalidate(int left, int top, int right, int bottom) {
12107        postInvalidateDelayed(0, left, top, right, bottom);
12108    }
12109
12110    /**
12111     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12112     * loop. Waits for the specified amount of time.</p>
12113     *
12114     * <p>This method can be invoked from outside of the UI thread
12115     * only when this View is attached to a window.</p>
12116     *
12117     * @param delayMilliseconds the duration in milliseconds to delay the
12118     *         invalidation by
12119     *
12120     * @see #invalidate()
12121     * @see #postInvalidate()
12122     */
12123    public void postInvalidateDelayed(long delayMilliseconds) {
12124        // We try only with the AttachInfo because there's no point in invalidating
12125        // if we are not attached to our window
12126        final AttachInfo attachInfo = mAttachInfo;
12127        if (attachInfo != null) {
12128            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12129        }
12130    }
12131
12132    /**
12133     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12134     * through the event loop. Waits for the specified amount of time.</p>
12135     *
12136     * <p>This method can be invoked from outside of the UI thread
12137     * only when this View is attached to a window.</p>
12138     *
12139     * @param delayMilliseconds the duration in milliseconds to delay the
12140     *         invalidation by
12141     * @param left The left coordinate of the rectangle to invalidate.
12142     * @param top The top coordinate of the rectangle to invalidate.
12143     * @param right The right coordinate of the rectangle to invalidate.
12144     * @param bottom The bottom coordinate of the rectangle to invalidate.
12145     *
12146     * @see #invalidate(int, int, int, int)
12147     * @see #invalidate(Rect)
12148     * @see #postInvalidate(int, int, int, int)
12149     */
12150    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12151            int right, int bottom) {
12152
12153        // We try only with the AttachInfo because there's no point in invalidating
12154        // if we are not attached to our window
12155        final AttachInfo attachInfo = mAttachInfo;
12156        if (attachInfo != null) {
12157            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12158            info.target = this;
12159            info.left = left;
12160            info.top = top;
12161            info.right = right;
12162            info.bottom = bottom;
12163
12164            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12165        }
12166    }
12167
12168    /**
12169     * <p>Cause an invalidate to happen on the next animation time step, typically the
12170     * next display frame.</p>
12171     *
12172     * <p>This method can be invoked from outside of the UI thread
12173     * only when this View is attached to a window.</p>
12174     *
12175     * @see #invalidate()
12176     */
12177    public void postInvalidateOnAnimation() {
12178        // We try only with the AttachInfo because there's no point in invalidating
12179        // if we are not attached to our window
12180        final AttachInfo attachInfo = mAttachInfo;
12181        if (attachInfo != null) {
12182            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12183        }
12184    }
12185
12186    /**
12187     * <p>Cause an invalidate of the specified area to happen on the next animation
12188     * time step, typically the next display frame.</p>
12189     *
12190     * <p>This method can be invoked from outside of the UI thread
12191     * only when this View is attached to a window.</p>
12192     *
12193     * @param left The left coordinate of the rectangle to invalidate.
12194     * @param top The top coordinate of the rectangle to invalidate.
12195     * @param right The right coordinate of the rectangle to invalidate.
12196     * @param bottom The bottom coordinate of the rectangle to invalidate.
12197     *
12198     * @see #invalidate(int, int, int, int)
12199     * @see #invalidate(Rect)
12200     */
12201    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12202        // We try only with the AttachInfo because there's no point in invalidating
12203        // if we are not attached to our window
12204        final AttachInfo attachInfo = mAttachInfo;
12205        if (attachInfo != null) {
12206            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12207            info.target = this;
12208            info.left = left;
12209            info.top = top;
12210            info.right = right;
12211            info.bottom = bottom;
12212
12213            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12214        }
12215    }
12216
12217    /**
12218     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12219     * This event is sent at most once every
12220     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12221     */
12222    private void postSendViewScrolledAccessibilityEventCallback() {
12223        if (mSendViewScrolledAccessibilityEvent == null) {
12224            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12225        }
12226        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12227            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12228            postDelayed(mSendViewScrolledAccessibilityEvent,
12229                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12230        }
12231    }
12232
12233    /**
12234     * Called by a parent to request that a child update its values for mScrollX
12235     * and mScrollY if necessary. This will typically be done if the child is
12236     * animating a scroll using a {@link android.widget.Scroller Scroller}
12237     * object.
12238     */
12239    public void computeScroll() {
12240    }
12241
12242    /**
12243     * <p>Indicate whether the horizontal edges are faded when the view is
12244     * scrolled horizontally.</p>
12245     *
12246     * @return true if the horizontal edges should are faded on scroll, false
12247     *         otherwise
12248     *
12249     * @see #setHorizontalFadingEdgeEnabled(boolean)
12250     *
12251     * @attr ref android.R.styleable#View_requiresFadingEdge
12252     */
12253    public boolean isHorizontalFadingEdgeEnabled() {
12254        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12255    }
12256
12257    /**
12258     * <p>Define whether the horizontal edges should be faded when this view
12259     * is scrolled horizontally.</p>
12260     *
12261     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12262     *                                    be faded when the view is scrolled
12263     *                                    horizontally
12264     *
12265     * @see #isHorizontalFadingEdgeEnabled()
12266     *
12267     * @attr ref android.R.styleable#View_requiresFadingEdge
12268     */
12269    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12270        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12271            if (horizontalFadingEdgeEnabled) {
12272                initScrollCache();
12273            }
12274
12275            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12276        }
12277    }
12278
12279    /**
12280     * <p>Indicate whether the vertical edges are faded when the view is
12281     * scrolled horizontally.</p>
12282     *
12283     * @return true if the vertical edges should are faded on scroll, false
12284     *         otherwise
12285     *
12286     * @see #setVerticalFadingEdgeEnabled(boolean)
12287     *
12288     * @attr ref android.R.styleable#View_requiresFadingEdge
12289     */
12290    public boolean isVerticalFadingEdgeEnabled() {
12291        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12292    }
12293
12294    /**
12295     * <p>Define whether the vertical edges should be faded when this view
12296     * is scrolled vertically.</p>
12297     *
12298     * @param verticalFadingEdgeEnabled true if the vertical edges should
12299     *                                  be faded when the view is scrolled
12300     *                                  vertically
12301     *
12302     * @see #isVerticalFadingEdgeEnabled()
12303     *
12304     * @attr ref android.R.styleable#View_requiresFadingEdge
12305     */
12306    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12307        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12308            if (verticalFadingEdgeEnabled) {
12309                initScrollCache();
12310            }
12311
12312            mViewFlags ^= FADING_EDGE_VERTICAL;
12313        }
12314    }
12315
12316    /**
12317     * Returns the strength, or intensity, of the top faded edge. The strength is
12318     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12319     * returns 0.0 or 1.0 but no value in between.
12320     *
12321     * Subclasses should override this method to provide a smoother fade transition
12322     * when scrolling occurs.
12323     *
12324     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12325     */
12326    protected float getTopFadingEdgeStrength() {
12327        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12328    }
12329
12330    /**
12331     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12332     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12333     * returns 0.0 or 1.0 but no value in between.
12334     *
12335     * Subclasses should override this method to provide a smoother fade transition
12336     * when scrolling occurs.
12337     *
12338     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12339     */
12340    protected float getBottomFadingEdgeStrength() {
12341        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12342                computeVerticalScrollRange() ? 1.0f : 0.0f;
12343    }
12344
12345    /**
12346     * Returns the strength, or intensity, of the left faded edge. The strength is
12347     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12348     * returns 0.0 or 1.0 but no value in between.
12349     *
12350     * Subclasses should override this method to provide a smoother fade transition
12351     * when scrolling occurs.
12352     *
12353     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12354     */
12355    protected float getLeftFadingEdgeStrength() {
12356        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12357    }
12358
12359    /**
12360     * Returns the strength, or intensity, of the right faded edge. The strength is
12361     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12362     * returns 0.0 or 1.0 but no value in between.
12363     *
12364     * Subclasses should override this method to provide a smoother fade transition
12365     * when scrolling occurs.
12366     *
12367     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12368     */
12369    protected float getRightFadingEdgeStrength() {
12370        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12371                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12372    }
12373
12374    /**
12375     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12376     * scrollbar is not drawn by default.</p>
12377     *
12378     * @return true if the horizontal scrollbar should be painted, false
12379     *         otherwise
12380     *
12381     * @see #setHorizontalScrollBarEnabled(boolean)
12382     */
12383    public boolean isHorizontalScrollBarEnabled() {
12384        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12385    }
12386
12387    /**
12388     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12389     * scrollbar is not drawn by default.</p>
12390     *
12391     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12392     *                                   be painted
12393     *
12394     * @see #isHorizontalScrollBarEnabled()
12395     */
12396    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12397        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12398            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12399            computeOpaqueFlags();
12400            resolvePadding();
12401        }
12402    }
12403
12404    /**
12405     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12406     * scrollbar is not drawn by default.</p>
12407     *
12408     * @return true if the vertical scrollbar should be painted, false
12409     *         otherwise
12410     *
12411     * @see #setVerticalScrollBarEnabled(boolean)
12412     */
12413    public boolean isVerticalScrollBarEnabled() {
12414        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12415    }
12416
12417    /**
12418     * <p>Define whether the vertical scrollbar should be drawn or not. The
12419     * scrollbar is not drawn by default.</p>
12420     *
12421     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12422     *                                 be painted
12423     *
12424     * @see #isVerticalScrollBarEnabled()
12425     */
12426    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12427        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12428            mViewFlags ^= SCROLLBARS_VERTICAL;
12429            computeOpaqueFlags();
12430            resolvePadding();
12431        }
12432    }
12433
12434    /**
12435     * @hide
12436     */
12437    protected void recomputePadding() {
12438        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12439    }
12440
12441    /**
12442     * Define whether scrollbars will fade when the view is not scrolling.
12443     *
12444     * @param fadeScrollbars wheter to enable fading
12445     *
12446     * @attr ref android.R.styleable#View_fadeScrollbars
12447     */
12448    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12449        initScrollCache();
12450        final ScrollabilityCache scrollabilityCache = mScrollCache;
12451        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12452        if (fadeScrollbars) {
12453            scrollabilityCache.state = ScrollabilityCache.OFF;
12454        } else {
12455            scrollabilityCache.state = ScrollabilityCache.ON;
12456        }
12457    }
12458
12459    /**
12460     *
12461     * Returns true if scrollbars will fade when this view is not scrolling
12462     *
12463     * @return true if scrollbar fading is enabled
12464     *
12465     * @attr ref android.R.styleable#View_fadeScrollbars
12466     */
12467    public boolean isScrollbarFadingEnabled() {
12468        return mScrollCache != null && mScrollCache.fadeScrollBars;
12469    }
12470
12471    /**
12472     *
12473     * Returns the delay before scrollbars fade.
12474     *
12475     * @return the delay before scrollbars fade
12476     *
12477     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12478     */
12479    public int getScrollBarDefaultDelayBeforeFade() {
12480        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12481                mScrollCache.scrollBarDefaultDelayBeforeFade;
12482    }
12483
12484    /**
12485     * Define the delay before scrollbars fade.
12486     *
12487     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12488     *
12489     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12490     */
12491    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12492        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12493    }
12494
12495    /**
12496     *
12497     * Returns the scrollbar fade duration.
12498     *
12499     * @return the scrollbar fade duration
12500     *
12501     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12502     */
12503    public int getScrollBarFadeDuration() {
12504        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12505                mScrollCache.scrollBarFadeDuration;
12506    }
12507
12508    /**
12509     * Define the scrollbar fade duration.
12510     *
12511     * @param scrollBarFadeDuration - the scrollbar fade duration
12512     *
12513     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12514     */
12515    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12516        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12517    }
12518
12519    /**
12520     *
12521     * Returns the scrollbar size.
12522     *
12523     * @return the scrollbar size
12524     *
12525     * @attr ref android.R.styleable#View_scrollbarSize
12526     */
12527    public int getScrollBarSize() {
12528        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12529                mScrollCache.scrollBarSize;
12530    }
12531
12532    /**
12533     * Define the scrollbar size.
12534     *
12535     * @param scrollBarSize - the scrollbar size
12536     *
12537     * @attr ref android.R.styleable#View_scrollbarSize
12538     */
12539    public void setScrollBarSize(int scrollBarSize) {
12540        getScrollCache().scrollBarSize = scrollBarSize;
12541    }
12542
12543    /**
12544     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12545     * inset. When inset, they add to the padding of the view. And the scrollbars
12546     * can be drawn inside the padding area or on the edge of the view. For example,
12547     * if a view has a background drawable and you want to draw the scrollbars
12548     * inside the padding specified by the drawable, you can use
12549     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12550     * appear at the edge of the view, ignoring the padding, then you can use
12551     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12552     * @param style the style of the scrollbars. Should be one of
12553     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12554     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12555     * @see #SCROLLBARS_INSIDE_OVERLAY
12556     * @see #SCROLLBARS_INSIDE_INSET
12557     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12558     * @see #SCROLLBARS_OUTSIDE_INSET
12559     *
12560     * @attr ref android.R.styleable#View_scrollbarStyle
12561     */
12562    public void setScrollBarStyle(@ScrollBarStyle int style) {
12563        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12564            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12565            computeOpaqueFlags();
12566            resolvePadding();
12567        }
12568    }
12569
12570    /**
12571     * <p>Returns the current scrollbar style.</p>
12572     * @return the current scrollbar style
12573     * @see #SCROLLBARS_INSIDE_OVERLAY
12574     * @see #SCROLLBARS_INSIDE_INSET
12575     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12576     * @see #SCROLLBARS_OUTSIDE_INSET
12577     *
12578     * @attr ref android.R.styleable#View_scrollbarStyle
12579     */
12580    @ViewDebug.ExportedProperty(mapping = {
12581            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12582            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12583            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12584            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12585    })
12586    @ScrollBarStyle
12587    public int getScrollBarStyle() {
12588        return mViewFlags & SCROLLBARS_STYLE_MASK;
12589    }
12590
12591    /**
12592     * <p>Compute the horizontal range that the horizontal scrollbar
12593     * represents.</p>
12594     *
12595     * <p>The range is expressed in arbitrary units that must be the same as the
12596     * units used by {@link #computeHorizontalScrollExtent()} and
12597     * {@link #computeHorizontalScrollOffset()}.</p>
12598     *
12599     * <p>The default range is the drawing width of this view.</p>
12600     *
12601     * @return the total horizontal range represented by the horizontal
12602     *         scrollbar
12603     *
12604     * @see #computeHorizontalScrollExtent()
12605     * @see #computeHorizontalScrollOffset()
12606     * @see android.widget.ScrollBarDrawable
12607     */
12608    protected int computeHorizontalScrollRange() {
12609        return getWidth();
12610    }
12611
12612    /**
12613     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12614     * within the horizontal range. This value is used to compute the position
12615     * of the thumb within the scrollbar's track.</p>
12616     *
12617     * <p>The range is expressed in arbitrary units that must be the same as the
12618     * units used by {@link #computeHorizontalScrollRange()} and
12619     * {@link #computeHorizontalScrollExtent()}.</p>
12620     *
12621     * <p>The default offset is the scroll offset of this view.</p>
12622     *
12623     * @return the horizontal offset of the scrollbar's thumb
12624     *
12625     * @see #computeHorizontalScrollRange()
12626     * @see #computeHorizontalScrollExtent()
12627     * @see android.widget.ScrollBarDrawable
12628     */
12629    protected int computeHorizontalScrollOffset() {
12630        return mScrollX;
12631    }
12632
12633    /**
12634     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12635     * within the horizontal range. This value is used to compute the length
12636     * of the thumb within the scrollbar's track.</p>
12637     *
12638     * <p>The range is expressed in arbitrary units that must be the same as the
12639     * units used by {@link #computeHorizontalScrollRange()} and
12640     * {@link #computeHorizontalScrollOffset()}.</p>
12641     *
12642     * <p>The default extent is the drawing width of this view.</p>
12643     *
12644     * @return the horizontal extent of the scrollbar's thumb
12645     *
12646     * @see #computeHorizontalScrollRange()
12647     * @see #computeHorizontalScrollOffset()
12648     * @see android.widget.ScrollBarDrawable
12649     */
12650    protected int computeHorizontalScrollExtent() {
12651        return getWidth();
12652    }
12653
12654    /**
12655     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12656     *
12657     * <p>The range is expressed in arbitrary units that must be the same as the
12658     * units used by {@link #computeVerticalScrollExtent()} and
12659     * {@link #computeVerticalScrollOffset()}.</p>
12660     *
12661     * @return the total vertical range represented by the vertical scrollbar
12662     *
12663     * <p>The default range is the drawing height of this view.</p>
12664     *
12665     * @see #computeVerticalScrollExtent()
12666     * @see #computeVerticalScrollOffset()
12667     * @see android.widget.ScrollBarDrawable
12668     */
12669    protected int computeVerticalScrollRange() {
12670        return getHeight();
12671    }
12672
12673    /**
12674     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12675     * within the horizontal range. This value is used to compute the position
12676     * of the thumb within the scrollbar's track.</p>
12677     *
12678     * <p>The range is expressed in arbitrary units that must be the same as the
12679     * units used by {@link #computeVerticalScrollRange()} and
12680     * {@link #computeVerticalScrollExtent()}.</p>
12681     *
12682     * <p>The default offset is the scroll offset of this view.</p>
12683     *
12684     * @return the vertical offset of the scrollbar's thumb
12685     *
12686     * @see #computeVerticalScrollRange()
12687     * @see #computeVerticalScrollExtent()
12688     * @see android.widget.ScrollBarDrawable
12689     */
12690    protected int computeVerticalScrollOffset() {
12691        return mScrollY;
12692    }
12693
12694    /**
12695     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12696     * within the vertical range. This value is used to compute the length
12697     * of the thumb within the scrollbar's track.</p>
12698     *
12699     * <p>The range is expressed in arbitrary units that must be the same as the
12700     * units used by {@link #computeVerticalScrollRange()} and
12701     * {@link #computeVerticalScrollOffset()}.</p>
12702     *
12703     * <p>The default extent is the drawing height of this view.</p>
12704     *
12705     * @return the vertical extent of the scrollbar's thumb
12706     *
12707     * @see #computeVerticalScrollRange()
12708     * @see #computeVerticalScrollOffset()
12709     * @see android.widget.ScrollBarDrawable
12710     */
12711    protected int computeVerticalScrollExtent() {
12712        return getHeight();
12713    }
12714
12715    /**
12716     * Check if this view can be scrolled horizontally in a certain direction.
12717     *
12718     * @param direction Negative to check scrolling left, positive to check scrolling right.
12719     * @return true if this view can be scrolled in the specified direction, false otherwise.
12720     */
12721    public boolean canScrollHorizontally(int direction) {
12722        final int offset = computeHorizontalScrollOffset();
12723        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12724        if (range == 0) return false;
12725        if (direction < 0) {
12726            return offset > 0;
12727        } else {
12728            return offset < range - 1;
12729        }
12730    }
12731
12732    /**
12733     * Check if this view can be scrolled vertically in a certain direction.
12734     *
12735     * @param direction Negative to check scrolling up, positive to check scrolling down.
12736     * @return true if this view can be scrolled in the specified direction, false otherwise.
12737     */
12738    public boolean canScrollVertically(int direction) {
12739        final int offset = computeVerticalScrollOffset();
12740        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12741        if (range == 0) return false;
12742        if (direction < 0) {
12743            return offset > 0;
12744        } else {
12745            return offset < range - 1;
12746        }
12747    }
12748
12749    /**
12750     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12751     * scrollbars are painted only if they have been awakened first.</p>
12752     *
12753     * @param canvas the canvas on which to draw the scrollbars
12754     *
12755     * @see #awakenScrollBars(int)
12756     */
12757    protected final void onDrawScrollBars(Canvas canvas) {
12758        // scrollbars are drawn only when the animation is running
12759        final ScrollabilityCache cache = mScrollCache;
12760        if (cache != null) {
12761
12762            int state = cache.state;
12763
12764            if (state == ScrollabilityCache.OFF) {
12765                return;
12766            }
12767
12768            boolean invalidate = false;
12769
12770            if (state == ScrollabilityCache.FADING) {
12771                // We're fading -- get our fade interpolation
12772                if (cache.interpolatorValues == null) {
12773                    cache.interpolatorValues = new float[1];
12774                }
12775
12776                float[] values = cache.interpolatorValues;
12777
12778                // Stops the animation if we're done
12779                if (cache.scrollBarInterpolator.timeToValues(values) ==
12780                        Interpolator.Result.FREEZE_END) {
12781                    cache.state = ScrollabilityCache.OFF;
12782                } else {
12783                    cache.scrollBar.setAlpha(Math.round(values[0]));
12784                }
12785
12786                // This will make the scroll bars inval themselves after
12787                // drawing. We only want this when we're fading so that
12788                // we prevent excessive redraws
12789                invalidate = true;
12790            } else {
12791                // We're just on -- but we may have been fading before so
12792                // reset alpha
12793                cache.scrollBar.setAlpha(255);
12794            }
12795
12796
12797            final int viewFlags = mViewFlags;
12798
12799            final boolean drawHorizontalScrollBar =
12800                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12801            final boolean drawVerticalScrollBar =
12802                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12803                && !isVerticalScrollBarHidden();
12804
12805            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12806                final int width = mRight - mLeft;
12807                final int height = mBottom - mTop;
12808
12809                final ScrollBarDrawable scrollBar = cache.scrollBar;
12810
12811                final int scrollX = mScrollX;
12812                final int scrollY = mScrollY;
12813                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12814
12815                int left;
12816                int top;
12817                int right;
12818                int bottom;
12819
12820                if (drawHorizontalScrollBar) {
12821                    int size = scrollBar.getSize(false);
12822                    if (size <= 0) {
12823                        size = cache.scrollBarSize;
12824                    }
12825
12826                    scrollBar.setParameters(computeHorizontalScrollRange(),
12827                                            computeHorizontalScrollOffset(),
12828                                            computeHorizontalScrollExtent(), false);
12829                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12830                            getVerticalScrollbarWidth() : 0;
12831                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12832                    left = scrollX + (mPaddingLeft & inside);
12833                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12834                    bottom = top + size;
12835                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12836                    if (invalidate) {
12837                        invalidate(left, top, right, bottom);
12838                    }
12839                }
12840
12841                if (drawVerticalScrollBar) {
12842                    int size = scrollBar.getSize(true);
12843                    if (size <= 0) {
12844                        size = cache.scrollBarSize;
12845                    }
12846
12847                    scrollBar.setParameters(computeVerticalScrollRange(),
12848                                            computeVerticalScrollOffset(),
12849                                            computeVerticalScrollExtent(), true);
12850                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12851                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12852                        verticalScrollbarPosition = isLayoutRtl() ?
12853                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12854                    }
12855                    switch (verticalScrollbarPosition) {
12856                        default:
12857                        case SCROLLBAR_POSITION_RIGHT:
12858                            left = scrollX + width - size - (mUserPaddingRight & inside);
12859                            break;
12860                        case SCROLLBAR_POSITION_LEFT:
12861                            left = scrollX + (mUserPaddingLeft & inside);
12862                            break;
12863                    }
12864                    top = scrollY + (mPaddingTop & inside);
12865                    right = left + size;
12866                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12867                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12868                    if (invalidate) {
12869                        invalidate(left, top, right, bottom);
12870                    }
12871                }
12872            }
12873        }
12874    }
12875
12876    /**
12877     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12878     * FastScroller is visible.
12879     * @return whether to temporarily hide the vertical scrollbar
12880     * @hide
12881     */
12882    protected boolean isVerticalScrollBarHidden() {
12883        return false;
12884    }
12885
12886    /**
12887     * <p>Draw the horizontal scrollbar if
12888     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12889     *
12890     * @param canvas the canvas on which to draw the scrollbar
12891     * @param scrollBar the scrollbar's drawable
12892     *
12893     * @see #isHorizontalScrollBarEnabled()
12894     * @see #computeHorizontalScrollRange()
12895     * @see #computeHorizontalScrollExtent()
12896     * @see #computeHorizontalScrollOffset()
12897     * @see android.widget.ScrollBarDrawable
12898     * @hide
12899     */
12900    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12901            int l, int t, int r, int b) {
12902        scrollBar.setBounds(l, t, r, b);
12903        scrollBar.draw(canvas);
12904    }
12905
12906    /**
12907     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12908     * returns true.</p>
12909     *
12910     * @param canvas the canvas on which to draw the scrollbar
12911     * @param scrollBar the scrollbar's drawable
12912     *
12913     * @see #isVerticalScrollBarEnabled()
12914     * @see #computeVerticalScrollRange()
12915     * @see #computeVerticalScrollExtent()
12916     * @see #computeVerticalScrollOffset()
12917     * @see android.widget.ScrollBarDrawable
12918     * @hide
12919     */
12920    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12921            int l, int t, int r, int b) {
12922        scrollBar.setBounds(l, t, r, b);
12923        scrollBar.draw(canvas);
12924    }
12925
12926    /**
12927     * Implement this to do your drawing.
12928     *
12929     * @param canvas the canvas on which the background will be drawn
12930     */
12931    protected void onDraw(Canvas canvas) {
12932    }
12933
12934    /*
12935     * Caller is responsible for calling requestLayout if necessary.
12936     * (This allows addViewInLayout to not request a new layout.)
12937     */
12938    void assignParent(ViewParent parent) {
12939        if (mParent == null) {
12940            mParent = parent;
12941        } else if (parent == null) {
12942            mParent = null;
12943        } else {
12944            throw new RuntimeException("view " + this + " being added, but"
12945                    + " it already has a parent");
12946        }
12947    }
12948
12949    /**
12950     * This is called when the view is attached to a window.  At this point it
12951     * has a Surface and will start drawing.  Note that this function is
12952     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12953     * however it may be called any time before the first onDraw -- including
12954     * before or after {@link #onMeasure(int, int)}.
12955     *
12956     * @see #onDetachedFromWindow()
12957     */
12958    protected void onAttachedToWindow() {
12959        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12960            mParent.requestTransparentRegion(this);
12961        }
12962
12963        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12964            initialAwakenScrollBars();
12965            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12966        }
12967
12968        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12969
12970        jumpDrawablesToCurrentState();
12971
12972        resetSubtreeAccessibilityStateChanged();
12973
12974        // rebuild, since Outline not maintained while View is detached
12975        rebuildOutline();
12976
12977        if (isFocused()) {
12978            InputMethodManager imm = InputMethodManager.peekInstance();
12979            imm.focusIn(this);
12980        }
12981    }
12982
12983    /**
12984     * Resolve all RTL related properties.
12985     *
12986     * @return true if resolution of RTL properties has been done
12987     *
12988     * @hide
12989     */
12990    public boolean resolveRtlPropertiesIfNeeded() {
12991        if (!needRtlPropertiesResolution()) return false;
12992
12993        // Order is important here: LayoutDirection MUST be resolved first
12994        if (!isLayoutDirectionResolved()) {
12995            resolveLayoutDirection();
12996            resolveLayoutParams();
12997        }
12998        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12999        if (!isTextDirectionResolved()) {
13000            resolveTextDirection();
13001        }
13002        if (!isTextAlignmentResolved()) {
13003            resolveTextAlignment();
13004        }
13005        // Should resolve Drawables before Padding because we need the layout direction of the
13006        // Drawable to correctly resolve Padding.
13007        if (!isDrawablesResolved()) {
13008            resolveDrawables();
13009        }
13010        if (!isPaddingResolved()) {
13011            resolvePadding();
13012        }
13013        onRtlPropertiesChanged(getLayoutDirection());
13014        return true;
13015    }
13016
13017    /**
13018     * Reset resolution of all RTL related properties.
13019     *
13020     * @hide
13021     */
13022    public void resetRtlProperties() {
13023        resetResolvedLayoutDirection();
13024        resetResolvedTextDirection();
13025        resetResolvedTextAlignment();
13026        resetResolvedPadding();
13027        resetResolvedDrawables();
13028    }
13029
13030    /**
13031     * @see #onScreenStateChanged(int)
13032     */
13033    void dispatchScreenStateChanged(int screenState) {
13034        onScreenStateChanged(screenState);
13035    }
13036
13037    /**
13038     * This method is called whenever the state of the screen this view is
13039     * attached to changes. A state change will usually occurs when the screen
13040     * turns on or off (whether it happens automatically or the user does it
13041     * manually.)
13042     *
13043     * @param screenState The new state of the screen. Can be either
13044     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13045     */
13046    public void onScreenStateChanged(int screenState) {
13047    }
13048
13049    /**
13050     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13051     */
13052    private boolean hasRtlSupport() {
13053        return mContext.getApplicationInfo().hasRtlSupport();
13054    }
13055
13056    /**
13057     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13058     * RTL not supported)
13059     */
13060    private boolean isRtlCompatibilityMode() {
13061        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13062        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13063    }
13064
13065    /**
13066     * @return true if RTL properties need resolution.
13067     *
13068     */
13069    private boolean needRtlPropertiesResolution() {
13070        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13071    }
13072
13073    /**
13074     * Called when any RTL property (layout direction or text direction or text alignment) has
13075     * been changed.
13076     *
13077     * Subclasses need to override this method to take care of cached information that depends on the
13078     * resolved layout direction, or to inform child views that inherit their layout direction.
13079     *
13080     * The default implementation does nothing.
13081     *
13082     * @param layoutDirection the direction of the layout
13083     *
13084     * @see #LAYOUT_DIRECTION_LTR
13085     * @see #LAYOUT_DIRECTION_RTL
13086     */
13087    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13088    }
13089
13090    /**
13091     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13092     * that the parent directionality can and will be resolved before its children.
13093     *
13094     * @return true if resolution has been done, false otherwise.
13095     *
13096     * @hide
13097     */
13098    public boolean resolveLayoutDirection() {
13099        // Clear any previous layout direction resolution
13100        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13101
13102        if (hasRtlSupport()) {
13103            // Set resolved depending on layout direction
13104            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13105                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13106                case LAYOUT_DIRECTION_INHERIT:
13107                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13108                    // later to get the correct resolved value
13109                    if (!canResolveLayoutDirection()) return false;
13110
13111                    // Parent has not yet resolved, LTR is still the default
13112                    try {
13113                        if (!mParent.isLayoutDirectionResolved()) return false;
13114
13115                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13116                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13117                        }
13118                    } catch (AbstractMethodError e) {
13119                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13120                                " does not fully implement ViewParent", e);
13121                    }
13122                    break;
13123                case LAYOUT_DIRECTION_RTL:
13124                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13125                    break;
13126                case LAYOUT_DIRECTION_LOCALE:
13127                    if((LAYOUT_DIRECTION_RTL ==
13128                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13129                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13130                    }
13131                    break;
13132                default:
13133                    // Nothing to do, LTR by default
13134            }
13135        }
13136
13137        // Set to resolved
13138        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13139        return true;
13140    }
13141
13142    /**
13143     * Check if layout direction resolution can be done.
13144     *
13145     * @return true if layout direction resolution can be done otherwise return false.
13146     */
13147    public boolean canResolveLayoutDirection() {
13148        switch (getRawLayoutDirection()) {
13149            case LAYOUT_DIRECTION_INHERIT:
13150                if (mParent != null) {
13151                    try {
13152                        return mParent.canResolveLayoutDirection();
13153                    } catch (AbstractMethodError e) {
13154                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13155                                " does not fully implement ViewParent", e);
13156                    }
13157                }
13158                return false;
13159
13160            default:
13161                return true;
13162        }
13163    }
13164
13165    /**
13166     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13167     * {@link #onMeasure(int, int)}.
13168     *
13169     * @hide
13170     */
13171    public void resetResolvedLayoutDirection() {
13172        // Reset the current resolved bits
13173        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13174    }
13175
13176    /**
13177     * @return true if the layout direction is inherited.
13178     *
13179     * @hide
13180     */
13181    public boolean isLayoutDirectionInherited() {
13182        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13183    }
13184
13185    /**
13186     * @return true if layout direction has been resolved.
13187     */
13188    public boolean isLayoutDirectionResolved() {
13189        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13190    }
13191
13192    /**
13193     * Return if padding has been resolved
13194     *
13195     * @hide
13196     */
13197    boolean isPaddingResolved() {
13198        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13199    }
13200
13201    /**
13202     * Resolves padding depending on layout direction, if applicable, and
13203     * recomputes internal padding values to adjust for scroll bars.
13204     *
13205     * @hide
13206     */
13207    public void resolvePadding() {
13208        final int resolvedLayoutDirection = getLayoutDirection();
13209
13210        if (!isRtlCompatibilityMode()) {
13211            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13212            // If start / end padding are defined, they will be resolved (hence overriding) to
13213            // left / right or right / left depending on the resolved layout direction.
13214            // If start / end padding are not defined, use the left / right ones.
13215            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13216                Rect padding = sThreadLocal.get();
13217                if (padding == null) {
13218                    padding = new Rect();
13219                    sThreadLocal.set(padding);
13220                }
13221                mBackground.getPadding(padding);
13222                if (!mLeftPaddingDefined) {
13223                    mUserPaddingLeftInitial = padding.left;
13224                }
13225                if (!mRightPaddingDefined) {
13226                    mUserPaddingRightInitial = padding.right;
13227                }
13228            }
13229            switch (resolvedLayoutDirection) {
13230                case LAYOUT_DIRECTION_RTL:
13231                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13232                        mUserPaddingRight = mUserPaddingStart;
13233                    } else {
13234                        mUserPaddingRight = mUserPaddingRightInitial;
13235                    }
13236                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13237                        mUserPaddingLeft = mUserPaddingEnd;
13238                    } else {
13239                        mUserPaddingLeft = mUserPaddingLeftInitial;
13240                    }
13241                    break;
13242                case LAYOUT_DIRECTION_LTR:
13243                default:
13244                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13245                        mUserPaddingLeft = mUserPaddingStart;
13246                    } else {
13247                        mUserPaddingLeft = mUserPaddingLeftInitial;
13248                    }
13249                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13250                        mUserPaddingRight = mUserPaddingEnd;
13251                    } else {
13252                        mUserPaddingRight = mUserPaddingRightInitial;
13253                    }
13254            }
13255
13256            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13257        }
13258
13259        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13260        onRtlPropertiesChanged(resolvedLayoutDirection);
13261
13262        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13263    }
13264
13265    /**
13266     * Reset the resolved layout direction.
13267     *
13268     * @hide
13269     */
13270    public void resetResolvedPadding() {
13271        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13272    }
13273
13274    /**
13275     * This is called when the view is detached from a window.  At this point it
13276     * no longer has a surface for drawing.
13277     *
13278     * @see #onAttachedToWindow()
13279     */
13280    protected void onDetachedFromWindow() {
13281    }
13282
13283    /**
13284     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13285     * after onDetachedFromWindow().
13286     *
13287     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13288     * The super method should be called at the end of the overriden method to ensure
13289     * subclasses are destroyed first
13290     *
13291     * @hide
13292     */
13293    protected void onDetachedFromWindowInternal() {
13294        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13295        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13296
13297        removeUnsetPressCallback();
13298        removeLongPressCallback();
13299        removePerformClickCallback();
13300        removeSendViewScrolledAccessibilityEventCallback();
13301        stopNestedScroll();
13302
13303        // Anything that started animating right before detach should already
13304        // be in its final state when re-attached.
13305        jumpDrawablesToCurrentState();
13306
13307        destroyDrawingCache();
13308
13309        cleanupDraw();
13310        mCurrentAnimation = null;
13311    }
13312
13313    private void cleanupDraw() {
13314        resetDisplayList();
13315        if (mAttachInfo != null) {
13316            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13317        }
13318    }
13319
13320    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13321    }
13322
13323    /**
13324     * @return The number of times this view has been attached to a window
13325     */
13326    protected int getWindowAttachCount() {
13327        return mWindowAttachCount;
13328    }
13329
13330    /**
13331     * Retrieve a unique token identifying the window this view is attached to.
13332     * @return Return the window's token for use in
13333     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13334     */
13335    public IBinder getWindowToken() {
13336        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13337    }
13338
13339    /**
13340     * Retrieve the {@link WindowId} for the window this view is
13341     * currently attached to.
13342     */
13343    public WindowId getWindowId() {
13344        if (mAttachInfo == null) {
13345            return null;
13346        }
13347        if (mAttachInfo.mWindowId == null) {
13348            try {
13349                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13350                        mAttachInfo.mWindowToken);
13351                mAttachInfo.mWindowId = new WindowId(
13352                        mAttachInfo.mIWindowId);
13353            } catch (RemoteException e) {
13354            }
13355        }
13356        return mAttachInfo.mWindowId;
13357    }
13358
13359    /**
13360     * Retrieve a unique token identifying the top-level "real" window of
13361     * the window that this view is attached to.  That is, this is like
13362     * {@link #getWindowToken}, except if the window this view in is a panel
13363     * window (attached to another containing window), then the token of
13364     * the containing window is returned instead.
13365     *
13366     * @return Returns the associated window token, either
13367     * {@link #getWindowToken()} or the containing window's token.
13368     */
13369    public IBinder getApplicationWindowToken() {
13370        AttachInfo ai = mAttachInfo;
13371        if (ai != null) {
13372            IBinder appWindowToken = ai.mPanelParentWindowToken;
13373            if (appWindowToken == null) {
13374                appWindowToken = ai.mWindowToken;
13375            }
13376            return appWindowToken;
13377        }
13378        return null;
13379    }
13380
13381    /**
13382     * Gets the logical display to which the view's window has been attached.
13383     *
13384     * @return The logical display, or null if the view is not currently attached to a window.
13385     */
13386    public Display getDisplay() {
13387        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13388    }
13389
13390    /**
13391     * Retrieve private session object this view hierarchy is using to
13392     * communicate with the window manager.
13393     * @return the session object to communicate with the window manager
13394     */
13395    /*package*/ IWindowSession getWindowSession() {
13396        return mAttachInfo != null ? mAttachInfo.mSession : null;
13397    }
13398
13399    /**
13400     * @param info the {@link android.view.View.AttachInfo} to associated with
13401     *        this view
13402     */
13403    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13404        //System.out.println("Attached! " + this);
13405        mAttachInfo = info;
13406        if (mOverlay != null) {
13407            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13408        }
13409        mWindowAttachCount++;
13410        // We will need to evaluate the drawable state at least once.
13411        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13412        if (mFloatingTreeObserver != null) {
13413            info.mTreeObserver.merge(mFloatingTreeObserver);
13414            mFloatingTreeObserver = null;
13415        }
13416        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13417            mAttachInfo.mScrollContainers.add(this);
13418            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13419        }
13420        performCollectViewAttributes(mAttachInfo, visibility);
13421        onAttachedToWindow();
13422
13423        ListenerInfo li = mListenerInfo;
13424        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13425                li != null ? li.mOnAttachStateChangeListeners : null;
13426        if (listeners != null && listeners.size() > 0) {
13427            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13428            // perform the dispatching. The iterator is a safe guard against listeners that
13429            // could mutate the list by calling the various add/remove methods. This prevents
13430            // the array from being modified while we iterate it.
13431            for (OnAttachStateChangeListener listener : listeners) {
13432                listener.onViewAttachedToWindow(this);
13433            }
13434        }
13435
13436        int vis = info.mWindowVisibility;
13437        if (vis != GONE) {
13438            onWindowVisibilityChanged(vis);
13439        }
13440        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13441            // If nobody has evaluated the drawable state yet, then do it now.
13442            refreshDrawableState();
13443        }
13444        needGlobalAttributesUpdate(false);
13445    }
13446
13447    void dispatchDetachedFromWindow() {
13448        AttachInfo info = mAttachInfo;
13449        if (info != null) {
13450            int vis = info.mWindowVisibility;
13451            if (vis != GONE) {
13452                onWindowVisibilityChanged(GONE);
13453            }
13454        }
13455
13456        onDetachedFromWindow();
13457        onDetachedFromWindowInternal();
13458
13459        ListenerInfo li = mListenerInfo;
13460        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13461                li != null ? li.mOnAttachStateChangeListeners : null;
13462        if (listeners != null && listeners.size() > 0) {
13463            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13464            // perform the dispatching. The iterator is a safe guard against listeners that
13465            // could mutate the list by calling the various add/remove methods. This prevents
13466            // the array from being modified while we iterate it.
13467            for (OnAttachStateChangeListener listener : listeners) {
13468                listener.onViewDetachedFromWindow(this);
13469            }
13470        }
13471
13472        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13473            mAttachInfo.mScrollContainers.remove(this);
13474            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13475        }
13476
13477        mAttachInfo = null;
13478        if (mOverlay != null) {
13479            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13480        }
13481    }
13482
13483    /**
13484     * Cancel any deferred high-level input events that were previously posted to the event queue.
13485     *
13486     * <p>Many views post high-level events such as click handlers to the event queue
13487     * to run deferred in order to preserve a desired user experience - clearing visible
13488     * pressed states before executing, etc. This method will abort any events of this nature
13489     * that are currently in flight.</p>
13490     *
13491     * <p>Custom views that generate their own high-level deferred input events should override
13492     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13493     *
13494     * <p>This will also cancel pending input events for any child views.</p>
13495     *
13496     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13497     * This will not impact newer events posted after this call that may occur as a result of
13498     * lower-level input events still waiting in the queue. If you are trying to prevent
13499     * double-submitted  events for the duration of some sort of asynchronous transaction
13500     * you should also take other steps to protect against unexpected double inputs e.g. calling
13501     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13502     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13503     */
13504    public final void cancelPendingInputEvents() {
13505        dispatchCancelPendingInputEvents();
13506    }
13507
13508    /**
13509     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13510     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13511     */
13512    void dispatchCancelPendingInputEvents() {
13513        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13514        onCancelPendingInputEvents();
13515        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13516            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13517                    " did not call through to super.onCancelPendingInputEvents()");
13518        }
13519    }
13520
13521    /**
13522     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13523     * a parent view.
13524     *
13525     * <p>This method is responsible for removing any pending high-level input events that were
13526     * posted to the event queue to run later. Custom view classes that post their own deferred
13527     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13528     * {@link android.os.Handler} should override this method, call
13529     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13530     * </p>
13531     */
13532    public void onCancelPendingInputEvents() {
13533        removePerformClickCallback();
13534        cancelLongPress();
13535        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13536    }
13537
13538    /**
13539     * Store this view hierarchy's frozen state into the given container.
13540     *
13541     * @param container The SparseArray in which to save the view's state.
13542     *
13543     * @see #restoreHierarchyState(android.util.SparseArray)
13544     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13545     * @see #onSaveInstanceState()
13546     */
13547    public void saveHierarchyState(SparseArray<Parcelable> container) {
13548        dispatchSaveInstanceState(container);
13549    }
13550
13551    /**
13552     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13553     * this view and its children. May be overridden to modify how freezing happens to a
13554     * view's children; for example, some views may want to not store state for their children.
13555     *
13556     * @param container The SparseArray in which to save the view's state.
13557     *
13558     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13559     * @see #saveHierarchyState(android.util.SparseArray)
13560     * @see #onSaveInstanceState()
13561     */
13562    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13563        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13564            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13565            Parcelable state = onSaveInstanceState();
13566            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13567                throw new IllegalStateException(
13568                        "Derived class did not call super.onSaveInstanceState()");
13569            }
13570            if (state != null) {
13571                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13572                // + ": " + state);
13573                container.put(mID, state);
13574            }
13575        }
13576    }
13577
13578    /**
13579     * Hook allowing a view to generate a representation of its internal state
13580     * that can later be used to create a new instance with that same state.
13581     * This state should only contain information that is not persistent or can
13582     * not be reconstructed later. For example, you will never store your
13583     * current position on screen because that will be computed again when a
13584     * new instance of the view is placed in its view hierarchy.
13585     * <p>
13586     * Some examples of things you may store here: the current cursor position
13587     * in a text view (but usually not the text itself since that is stored in a
13588     * content provider or other persistent storage), the currently selected
13589     * item in a list view.
13590     *
13591     * @return Returns a Parcelable object containing the view's current dynamic
13592     *         state, or null if there is nothing interesting to save. The
13593     *         default implementation returns null.
13594     * @see #onRestoreInstanceState(android.os.Parcelable)
13595     * @see #saveHierarchyState(android.util.SparseArray)
13596     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13597     * @see #setSaveEnabled(boolean)
13598     */
13599    protected Parcelable onSaveInstanceState() {
13600        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13601        return BaseSavedState.EMPTY_STATE;
13602    }
13603
13604    /**
13605     * Restore this view hierarchy's frozen state from the given container.
13606     *
13607     * @param container The SparseArray which holds previously frozen states.
13608     *
13609     * @see #saveHierarchyState(android.util.SparseArray)
13610     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13611     * @see #onRestoreInstanceState(android.os.Parcelable)
13612     */
13613    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13614        dispatchRestoreInstanceState(container);
13615    }
13616
13617    /**
13618     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13619     * state for this view and its children. May be overridden to modify how restoring
13620     * happens to a view's children; for example, some views may want to not store state
13621     * for their children.
13622     *
13623     * @param container The SparseArray which holds previously saved state.
13624     *
13625     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13626     * @see #restoreHierarchyState(android.util.SparseArray)
13627     * @see #onRestoreInstanceState(android.os.Parcelable)
13628     */
13629    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13630        if (mID != NO_ID) {
13631            Parcelable state = container.get(mID);
13632            if (state != null) {
13633                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13634                // + ": " + state);
13635                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13636                onRestoreInstanceState(state);
13637                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13638                    throw new IllegalStateException(
13639                            "Derived class did not call super.onRestoreInstanceState()");
13640                }
13641            }
13642        }
13643    }
13644
13645    /**
13646     * Hook allowing a view to re-apply a representation of its internal state that had previously
13647     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13648     * null state.
13649     *
13650     * @param state The frozen state that had previously been returned by
13651     *        {@link #onSaveInstanceState}.
13652     *
13653     * @see #onSaveInstanceState()
13654     * @see #restoreHierarchyState(android.util.SparseArray)
13655     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13656     */
13657    protected void onRestoreInstanceState(Parcelable state) {
13658        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13659        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13660            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13661                    + "received " + state.getClass().toString() + " instead. This usually happens "
13662                    + "when two views of different type have the same id in the same hierarchy. "
13663                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13664                    + "other views do not use the same id.");
13665        }
13666    }
13667
13668    /**
13669     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13670     *
13671     * @return the drawing start time in milliseconds
13672     */
13673    public long getDrawingTime() {
13674        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13675    }
13676
13677    /**
13678     * <p>Enables or disables the duplication of the parent's state into this view. When
13679     * duplication is enabled, this view gets its drawable state from its parent rather
13680     * than from its own internal properties.</p>
13681     *
13682     * <p>Note: in the current implementation, setting this property to true after the
13683     * view was added to a ViewGroup might have no effect at all. This property should
13684     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13685     *
13686     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13687     * property is enabled, an exception will be thrown.</p>
13688     *
13689     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13690     * parent, these states should not be affected by this method.</p>
13691     *
13692     * @param enabled True to enable duplication of the parent's drawable state, false
13693     *                to disable it.
13694     *
13695     * @see #getDrawableState()
13696     * @see #isDuplicateParentStateEnabled()
13697     */
13698    public void setDuplicateParentStateEnabled(boolean enabled) {
13699        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13700    }
13701
13702    /**
13703     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13704     *
13705     * @return True if this view's drawable state is duplicated from the parent,
13706     *         false otherwise
13707     *
13708     * @see #getDrawableState()
13709     * @see #setDuplicateParentStateEnabled(boolean)
13710     */
13711    public boolean isDuplicateParentStateEnabled() {
13712        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13713    }
13714
13715    /**
13716     * <p>Specifies the type of layer backing this view. The layer can be
13717     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13718     * {@link #LAYER_TYPE_HARDWARE}.</p>
13719     *
13720     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13721     * instance that controls how the layer is composed on screen. The following
13722     * properties of the paint are taken into account when composing the layer:</p>
13723     * <ul>
13724     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13725     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13726     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13727     * </ul>
13728     *
13729     * <p>If this view has an alpha value set to < 1.0 by calling
13730     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13731     * by this view's alpha value.</p>
13732     *
13733     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13734     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13735     * for more information on when and how to use layers.</p>
13736     *
13737     * @param layerType The type of layer to use with this view, must be one of
13738     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13739     *        {@link #LAYER_TYPE_HARDWARE}
13740     * @param paint The paint used to compose the layer. This argument is optional
13741     *        and can be null. It is ignored when the layer type is
13742     *        {@link #LAYER_TYPE_NONE}
13743     *
13744     * @see #getLayerType()
13745     * @see #LAYER_TYPE_NONE
13746     * @see #LAYER_TYPE_SOFTWARE
13747     * @see #LAYER_TYPE_HARDWARE
13748     * @see #setAlpha(float)
13749     *
13750     * @attr ref android.R.styleable#View_layerType
13751     */
13752    public void setLayerType(int layerType, Paint paint) {
13753        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13754            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13755                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13756        }
13757
13758        boolean typeChanged = mRenderNode.setLayerType(layerType);
13759
13760        if (!typeChanged) {
13761            setLayerPaint(paint);
13762            return;
13763        }
13764
13765        // Destroy any previous software drawing cache if needed
13766        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13767            destroyDrawingCache();
13768        }
13769
13770        mLayerType = layerType;
13771        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13772        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13773        mRenderNode.setLayerPaint(mLayerPaint);
13774
13775        // draw() behaves differently if we are on a layer, so we need to
13776        // invalidate() here
13777        invalidateParentCaches();
13778        invalidate(true);
13779    }
13780
13781    /**
13782     * Updates the {@link Paint} object used with the current layer (used only if the current
13783     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13784     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13785     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13786     * ensure that the view gets redrawn immediately.
13787     *
13788     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13789     * instance that controls how the layer is composed on screen. The following
13790     * properties of the paint are taken into account when composing the layer:</p>
13791     * <ul>
13792     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13793     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13794     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13795     * </ul>
13796     *
13797     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13798     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13799     *
13800     * @param paint The paint used to compose the layer. This argument is optional
13801     *        and can be null. It is ignored when the layer type is
13802     *        {@link #LAYER_TYPE_NONE}
13803     *
13804     * @see #setLayerType(int, android.graphics.Paint)
13805     */
13806    public void setLayerPaint(Paint paint) {
13807        int layerType = getLayerType();
13808        if (layerType != LAYER_TYPE_NONE) {
13809            mLayerPaint = paint == null ? new Paint() : paint;
13810            if (layerType == LAYER_TYPE_HARDWARE) {
13811                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13812                    invalidateViewProperty(false, false);
13813                }
13814            } else {
13815                invalidate();
13816            }
13817        }
13818    }
13819
13820    /**
13821     * Indicates whether this view has a static layer. A view with layer type
13822     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13823     * dynamic.
13824     */
13825    boolean hasStaticLayer() {
13826        return true;
13827    }
13828
13829    /**
13830     * Indicates what type of layer is currently associated with this view. By default
13831     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13832     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13833     * for more information on the different types of layers.
13834     *
13835     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13836     *         {@link #LAYER_TYPE_HARDWARE}
13837     *
13838     * @see #setLayerType(int, android.graphics.Paint)
13839     * @see #buildLayer()
13840     * @see #LAYER_TYPE_NONE
13841     * @see #LAYER_TYPE_SOFTWARE
13842     * @see #LAYER_TYPE_HARDWARE
13843     */
13844    public int getLayerType() {
13845        return mLayerType;
13846    }
13847
13848    /**
13849     * Forces this view's layer to be created and this view to be rendered
13850     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13851     * invoking this method will have no effect.
13852     *
13853     * This method can for instance be used to render a view into its layer before
13854     * starting an animation. If this view is complex, rendering into the layer
13855     * before starting the animation will avoid skipping frames.
13856     *
13857     * @throws IllegalStateException If this view is not attached to a window
13858     *
13859     * @see #setLayerType(int, android.graphics.Paint)
13860     */
13861    public void buildLayer() {
13862        if (mLayerType == LAYER_TYPE_NONE) return;
13863
13864        final AttachInfo attachInfo = mAttachInfo;
13865        if (attachInfo == null) {
13866            throw new IllegalStateException("This view must be attached to a window first");
13867        }
13868
13869        if (getWidth() == 0 || getHeight() == 0) {
13870            return;
13871        }
13872
13873        switch (mLayerType) {
13874            case LAYER_TYPE_HARDWARE:
13875                updateDisplayListIfDirty();
13876                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
13877                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
13878                }
13879                break;
13880            case LAYER_TYPE_SOFTWARE:
13881                buildDrawingCache(true);
13882                break;
13883        }
13884    }
13885
13886    /**
13887     * If this View draws with a HardwareLayer, returns it.
13888     * Otherwise returns null
13889     *
13890     * TODO: Only TextureView uses this, can we eliminate it?
13891     */
13892    HardwareLayer getHardwareLayer() {
13893        return null;
13894    }
13895
13896    /**
13897     * Destroys all hardware rendering resources. This method is invoked
13898     * when the system needs to reclaim resources. Upon execution of this
13899     * method, you should free any OpenGL resources created by the view.
13900     *
13901     * Note: you <strong>must</strong> call
13902     * <code>super.destroyHardwareResources()</code> when overriding
13903     * this method.
13904     *
13905     * @hide
13906     */
13907    protected void destroyHardwareResources() {
13908        // Although the Layer will be destroyed by RenderNode, we want to release
13909        // the staging display list, which is also a signal to RenderNode that it's
13910        // safe to free its copy of the display list as it knows that we will
13911        // push an updated DisplayList if we try to draw again
13912        resetDisplayList();
13913    }
13914
13915    /**
13916     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13917     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13918     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13919     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13920     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13921     * null.</p>
13922     *
13923     * <p>Enabling the drawing cache is similar to
13924     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13925     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13926     * drawing cache has no effect on rendering because the system uses a different mechanism
13927     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13928     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13929     * for information on how to enable software and hardware layers.</p>
13930     *
13931     * <p>This API can be used to manually generate
13932     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13933     * {@link #getDrawingCache()}.</p>
13934     *
13935     * @param enabled true to enable the drawing cache, false otherwise
13936     *
13937     * @see #isDrawingCacheEnabled()
13938     * @see #getDrawingCache()
13939     * @see #buildDrawingCache()
13940     * @see #setLayerType(int, android.graphics.Paint)
13941     */
13942    public void setDrawingCacheEnabled(boolean enabled) {
13943        mCachingFailed = false;
13944        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13945    }
13946
13947    /**
13948     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13949     *
13950     * @return true if the drawing cache is enabled
13951     *
13952     * @see #setDrawingCacheEnabled(boolean)
13953     * @see #getDrawingCache()
13954     */
13955    @ViewDebug.ExportedProperty(category = "drawing")
13956    public boolean isDrawingCacheEnabled() {
13957        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13958    }
13959
13960    /**
13961     * Debugging utility which recursively outputs the dirty state of a view and its
13962     * descendants.
13963     *
13964     * @hide
13965     */
13966    @SuppressWarnings({"UnusedDeclaration"})
13967    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13968        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13969                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13970                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13971                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13972        if (clear) {
13973            mPrivateFlags &= clearMask;
13974        }
13975        if (this instanceof ViewGroup) {
13976            ViewGroup parent = (ViewGroup) this;
13977            final int count = parent.getChildCount();
13978            for (int i = 0; i < count; i++) {
13979                final View child = parent.getChildAt(i);
13980                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13981            }
13982        }
13983    }
13984
13985    /**
13986     * This method is used by ViewGroup to cause its children to restore or recreate their
13987     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13988     * to recreate its own display list, which would happen if it went through the normal
13989     * draw/dispatchDraw mechanisms.
13990     *
13991     * @hide
13992     */
13993    protected void dispatchGetDisplayList() {}
13994
13995    /**
13996     * A view that is not attached or hardware accelerated cannot create a display list.
13997     * This method checks these conditions and returns the appropriate result.
13998     *
13999     * @return true if view has the ability to create a display list, false otherwise.
14000     *
14001     * @hide
14002     */
14003    public boolean canHaveDisplayList() {
14004        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14005    }
14006
14007    private void updateDisplayListIfDirty() {
14008        final RenderNode renderNode = mRenderNode;
14009        if (!canHaveDisplayList()) {
14010            // can't populate RenderNode, don't try
14011            return;
14012        }
14013
14014        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14015                || !renderNode.isValid()
14016                || (mRecreateDisplayList)) {
14017            // Don't need to recreate the display list, just need to tell our
14018            // children to restore/recreate theirs
14019            if (renderNode.isValid()
14020                    && !mRecreateDisplayList) {
14021                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14022                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14023                dispatchGetDisplayList();
14024
14025                return; // no work needed
14026            }
14027
14028            // If we got here, we're recreating it. Mark it as such to ensure that
14029            // we copy in child display lists into ours in drawChild()
14030            mRecreateDisplayList = true;
14031
14032            int width = mRight - mLeft;
14033            int height = mBottom - mTop;
14034            int layerType = getLayerType();
14035
14036            final HardwareCanvas canvas = renderNode.start(width, height);
14037            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14038
14039            try {
14040                final HardwareLayer layer = getHardwareLayer();
14041                if (layer != null && layer.isValid()) {
14042                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14043                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14044                    buildDrawingCache(true);
14045                    Bitmap cache = getDrawingCache(true);
14046                    if (cache != null) {
14047                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14048                    }
14049                } else {
14050                    computeScroll();
14051
14052                    canvas.translate(-mScrollX, -mScrollY);
14053                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14054                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14055
14056                    // Fast path for layouts with no backgrounds
14057                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14058                        dispatchDraw(canvas);
14059                        if (mOverlay != null && !mOverlay.isEmpty()) {
14060                            mOverlay.getOverlayView().draw(canvas);
14061                        }
14062                    } else {
14063                        draw(canvas);
14064                    }
14065                }
14066            } finally {
14067                renderNode.end(canvas);
14068                setDisplayListProperties(renderNode);
14069            }
14070        } else {
14071            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14072            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14073        }
14074    }
14075
14076    /**
14077     * Returns a RenderNode with View draw content recorded, which can be
14078     * used to draw this view again without executing its draw method.
14079     *
14080     * @return A RenderNode ready to replay, or null if caching is not enabled.
14081     *
14082     * @hide
14083     */
14084    public RenderNode getDisplayList() {
14085        updateDisplayListIfDirty();
14086        return mRenderNode;
14087    }
14088
14089    private void resetDisplayList() {
14090        if (mRenderNode.isValid()) {
14091            mRenderNode.destroyDisplayListData();
14092        }
14093
14094        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14095            mBackgroundRenderNode.destroyDisplayListData();
14096        }
14097    }
14098
14099    /**
14100     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14101     *
14102     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14103     *
14104     * @see #getDrawingCache(boolean)
14105     */
14106    public Bitmap getDrawingCache() {
14107        return getDrawingCache(false);
14108    }
14109
14110    /**
14111     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14112     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14113     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14114     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14115     * request the drawing cache by calling this method and draw it on screen if the
14116     * returned bitmap is not null.</p>
14117     *
14118     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14119     * this method will create a bitmap of the same size as this view. Because this bitmap
14120     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14121     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14122     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14123     * size than the view. This implies that your application must be able to handle this
14124     * size.</p>
14125     *
14126     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14127     *        the current density of the screen when the application is in compatibility
14128     *        mode.
14129     *
14130     * @return A bitmap representing this view or null if cache is disabled.
14131     *
14132     * @see #setDrawingCacheEnabled(boolean)
14133     * @see #isDrawingCacheEnabled()
14134     * @see #buildDrawingCache(boolean)
14135     * @see #destroyDrawingCache()
14136     */
14137    public Bitmap getDrawingCache(boolean autoScale) {
14138        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14139            return null;
14140        }
14141        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14142            buildDrawingCache(autoScale);
14143        }
14144        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14145    }
14146
14147    /**
14148     * <p>Frees the resources used by the drawing cache. If you call
14149     * {@link #buildDrawingCache()} manually without calling
14150     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14151     * should cleanup the cache with this method afterwards.</p>
14152     *
14153     * @see #setDrawingCacheEnabled(boolean)
14154     * @see #buildDrawingCache()
14155     * @see #getDrawingCache()
14156     */
14157    public void destroyDrawingCache() {
14158        if (mDrawingCache != null) {
14159            mDrawingCache.recycle();
14160            mDrawingCache = null;
14161        }
14162        if (mUnscaledDrawingCache != null) {
14163            mUnscaledDrawingCache.recycle();
14164            mUnscaledDrawingCache = null;
14165        }
14166    }
14167
14168    /**
14169     * Setting a solid background color for the drawing cache's bitmaps will improve
14170     * performance and memory usage. Note, though that this should only be used if this
14171     * view will always be drawn on top of a solid color.
14172     *
14173     * @param color The background color to use for the drawing cache's bitmap
14174     *
14175     * @see #setDrawingCacheEnabled(boolean)
14176     * @see #buildDrawingCache()
14177     * @see #getDrawingCache()
14178     */
14179    public void setDrawingCacheBackgroundColor(int color) {
14180        if (color != mDrawingCacheBackgroundColor) {
14181            mDrawingCacheBackgroundColor = color;
14182            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14183        }
14184    }
14185
14186    /**
14187     * @see #setDrawingCacheBackgroundColor(int)
14188     *
14189     * @return The background color to used for the drawing cache's bitmap
14190     */
14191    public int getDrawingCacheBackgroundColor() {
14192        return mDrawingCacheBackgroundColor;
14193    }
14194
14195    /**
14196     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14197     *
14198     * @see #buildDrawingCache(boolean)
14199     */
14200    public void buildDrawingCache() {
14201        buildDrawingCache(false);
14202    }
14203
14204    /**
14205     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14206     *
14207     * <p>If you call {@link #buildDrawingCache()} manually without calling
14208     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14209     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14210     *
14211     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14212     * this method will create a bitmap of the same size as this view. Because this bitmap
14213     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14214     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14215     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14216     * size than the view. This implies that your application must be able to handle this
14217     * size.</p>
14218     *
14219     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14220     * you do not need the drawing cache bitmap, calling this method will increase memory
14221     * usage and cause the view to be rendered in software once, thus negatively impacting
14222     * performance.</p>
14223     *
14224     * @see #getDrawingCache()
14225     * @see #destroyDrawingCache()
14226     */
14227    public void buildDrawingCache(boolean autoScale) {
14228        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14229                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14230            mCachingFailed = false;
14231
14232            int width = mRight - mLeft;
14233            int height = mBottom - mTop;
14234
14235            final AttachInfo attachInfo = mAttachInfo;
14236            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14237
14238            if (autoScale && scalingRequired) {
14239                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14240                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14241            }
14242
14243            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14244            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14245            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14246
14247            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14248            final long drawingCacheSize =
14249                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14250            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14251                if (width > 0 && height > 0) {
14252                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14253                            + projectedBitmapSize + " bytes, only "
14254                            + drawingCacheSize + " available");
14255                }
14256                destroyDrawingCache();
14257                mCachingFailed = true;
14258                return;
14259            }
14260
14261            boolean clear = true;
14262            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14263
14264            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14265                Bitmap.Config quality;
14266                if (!opaque) {
14267                    // Never pick ARGB_4444 because it looks awful
14268                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14269                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14270                        case DRAWING_CACHE_QUALITY_AUTO:
14271                        case DRAWING_CACHE_QUALITY_LOW:
14272                        case DRAWING_CACHE_QUALITY_HIGH:
14273                        default:
14274                            quality = Bitmap.Config.ARGB_8888;
14275                            break;
14276                    }
14277                } else {
14278                    // Optimization for translucent windows
14279                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14280                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14281                }
14282
14283                // Try to cleanup memory
14284                if (bitmap != null) bitmap.recycle();
14285
14286                try {
14287                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14288                            width, height, quality);
14289                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14290                    if (autoScale) {
14291                        mDrawingCache = bitmap;
14292                    } else {
14293                        mUnscaledDrawingCache = bitmap;
14294                    }
14295                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14296                } catch (OutOfMemoryError e) {
14297                    // If there is not enough memory to create the bitmap cache, just
14298                    // ignore the issue as bitmap caches are not required to draw the
14299                    // view hierarchy
14300                    if (autoScale) {
14301                        mDrawingCache = null;
14302                    } else {
14303                        mUnscaledDrawingCache = null;
14304                    }
14305                    mCachingFailed = true;
14306                    return;
14307                }
14308
14309                clear = drawingCacheBackgroundColor != 0;
14310            }
14311
14312            Canvas canvas;
14313            if (attachInfo != null) {
14314                canvas = attachInfo.mCanvas;
14315                if (canvas == null) {
14316                    canvas = new Canvas();
14317                }
14318                canvas.setBitmap(bitmap);
14319                // Temporarily clobber the cached Canvas in case one of our children
14320                // is also using a drawing cache. Without this, the children would
14321                // steal the canvas by attaching their own bitmap to it and bad, bad
14322                // thing would happen (invisible views, corrupted drawings, etc.)
14323                attachInfo.mCanvas = null;
14324            } else {
14325                // This case should hopefully never or seldom happen
14326                canvas = new Canvas(bitmap);
14327            }
14328
14329            if (clear) {
14330                bitmap.eraseColor(drawingCacheBackgroundColor);
14331            }
14332
14333            computeScroll();
14334            final int restoreCount = canvas.save();
14335
14336            if (autoScale && scalingRequired) {
14337                final float scale = attachInfo.mApplicationScale;
14338                canvas.scale(scale, scale);
14339            }
14340
14341            canvas.translate(-mScrollX, -mScrollY);
14342
14343            mPrivateFlags |= PFLAG_DRAWN;
14344            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14345                    mLayerType != LAYER_TYPE_NONE) {
14346                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14347            }
14348
14349            // Fast path for layouts with no backgrounds
14350            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14351                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14352                dispatchDraw(canvas);
14353                if (mOverlay != null && !mOverlay.isEmpty()) {
14354                    mOverlay.getOverlayView().draw(canvas);
14355                }
14356            } else {
14357                draw(canvas);
14358            }
14359
14360            canvas.restoreToCount(restoreCount);
14361            canvas.setBitmap(null);
14362
14363            if (attachInfo != null) {
14364                // Restore the cached Canvas for our siblings
14365                attachInfo.mCanvas = canvas;
14366            }
14367        }
14368    }
14369
14370    /**
14371     * Create a snapshot of the view into a bitmap.  We should probably make
14372     * some form of this public, but should think about the API.
14373     */
14374    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14375        int width = mRight - mLeft;
14376        int height = mBottom - mTop;
14377
14378        final AttachInfo attachInfo = mAttachInfo;
14379        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14380        width = (int) ((width * scale) + 0.5f);
14381        height = (int) ((height * scale) + 0.5f);
14382
14383        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14384                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14385        if (bitmap == null) {
14386            throw new OutOfMemoryError();
14387        }
14388
14389        Resources resources = getResources();
14390        if (resources != null) {
14391            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14392        }
14393
14394        Canvas canvas;
14395        if (attachInfo != null) {
14396            canvas = attachInfo.mCanvas;
14397            if (canvas == null) {
14398                canvas = new Canvas();
14399            }
14400            canvas.setBitmap(bitmap);
14401            // Temporarily clobber the cached Canvas in case one of our children
14402            // is also using a drawing cache. Without this, the children would
14403            // steal the canvas by attaching their own bitmap to it and bad, bad
14404            // things would happen (invisible views, corrupted drawings, etc.)
14405            attachInfo.mCanvas = null;
14406        } else {
14407            // This case should hopefully never or seldom happen
14408            canvas = new Canvas(bitmap);
14409        }
14410
14411        if ((backgroundColor & 0xff000000) != 0) {
14412            bitmap.eraseColor(backgroundColor);
14413        }
14414
14415        computeScroll();
14416        final int restoreCount = canvas.save();
14417        canvas.scale(scale, scale);
14418        canvas.translate(-mScrollX, -mScrollY);
14419
14420        // Temporarily remove the dirty mask
14421        int flags = mPrivateFlags;
14422        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14423
14424        // Fast path for layouts with no backgrounds
14425        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14426            dispatchDraw(canvas);
14427            if (mOverlay != null && !mOverlay.isEmpty()) {
14428                mOverlay.getOverlayView().draw(canvas);
14429            }
14430        } else {
14431            draw(canvas);
14432        }
14433
14434        mPrivateFlags = flags;
14435
14436        canvas.restoreToCount(restoreCount);
14437        canvas.setBitmap(null);
14438
14439        if (attachInfo != null) {
14440            // Restore the cached Canvas for our siblings
14441            attachInfo.mCanvas = canvas;
14442        }
14443
14444        return bitmap;
14445    }
14446
14447    /**
14448     * Indicates whether this View is currently in edit mode. A View is usually
14449     * in edit mode when displayed within a developer tool. For instance, if
14450     * this View is being drawn by a visual user interface builder, this method
14451     * should return true.
14452     *
14453     * Subclasses should check the return value of this method to provide
14454     * different behaviors if their normal behavior might interfere with the
14455     * host environment. For instance: the class spawns a thread in its
14456     * constructor, the drawing code relies on device-specific features, etc.
14457     *
14458     * This method is usually checked in the drawing code of custom widgets.
14459     *
14460     * @return True if this View is in edit mode, false otherwise.
14461     */
14462    public boolean isInEditMode() {
14463        return false;
14464    }
14465
14466    /**
14467     * If the View draws content inside its padding and enables fading edges,
14468     * it needs to support padding offsets. Padding offsets are added to the
14469     * fading edges to extend the length of the fade so that it covers pixels
14470     * drawn inside the padding.
14471     *
14472     * Subclasses of this class should override this method if they need
14473     * to draw content inside the padding.
14474     *
14475     * @return True if padding offset must be applied, false otherwise.
14476     *
14477     * @see #getLeftPaddingOffset()
14478     * @see #getRightPaddingOffset()
14479     * @see #getTopPaddingOffset()
14480     * @see #getBottomPaddingOffset()
14481     *
14482     * @since CURRENT
14483     */
14484    protected boolean isPaddingOffsetRequired() {
14485        return false;
14486    }
14487
14488    /**
14489     * Amount by which to extend the left fading region. Called only when
14490     * {@link #isPaddingOffsetRequired()} returns true.
14491     *
14492     * @return The left padding offset in pixels.
14493     *
14494     * @see #isPaddingOffsetRequired()
14495     *
14496     * @since CURRENT
14497     */
14498    protected int getLeftPaddingOffset() {
14499        return 0;
14500    }
14501
14502    /**
14503     * Amount by which to extend the right fading region. Called only when
14504     * {@link #isPaddingOffsetRequired()} returns true.
14505     *
14506     * @return The right padding offset in pixels.
14507     *
14508     * @see #isPaddingOffsetRequired()
14509     *
14510     * @since CURRENT
14511     */
14512    protected int getRightPaddingOffset() {
14513        return 0;
14514    }
14515
14516    /**
14517     * Amount by which to extend the top fading region. Called only when
14518     * {@link #isPaddingOffsetRequired()} returns true.
14519     *
14520     * @return The top padding offset in pixels.
14521     *
14522     * @see #isPaddingOffsetRequired()
14523     *
14524     * @since CURRENT
14525     */
14526    protected int getTopPaddingOffset() {
14527        return 0;
14528    }
14529
14530    /**
14531     * Amount by which to extend the bottom fading region. Called only when
14532     * {@link #isPaddingOffsetRequired()} returns true.
14533     *
14534     * @return The bottom padding offset in pixels.
14535     *
14536     * @see #isPaddingOffsetRequired()
14537     *
14538     * @since CURRENT
14539     */
14540    protected int getBottomPaddingOffset() {
14541        return 0;
14542    }
14543
14544    /**
14545     * @hide
14546     * @param offsetRequired
14547     */
14548    protected int getFadeTop(boolean offsetRequired) {
14549        int top = mPaddingTop;
14550        if (offsetRequired) top += getTopPaddingOffset();
14551        return top;
14552    }
14553
14554    /**
14555     * @hide
14556     * @param offsetRequired
14557     */
14558    protected int getFadeHeight(boolean offsetRequired) {
14559        int padding = mPaddingTop;
14560        if (offsetRequired) padding += getTopPaddingOffset();
14561        return mBottom - mTop - mPaddingBottom - padding;
14562    }
14563
14564    /**
14565     * <p>Indicates whether this view is attached to a hardware accelerated
14566     * window or not.</p>
14567     *
14568     * <p>Even if this method returns true, it does not mean that every call
14569     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14570     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14571     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14572     * window is hardware accelerated,
14573     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14574     * return false, and this method will return true.</p>
14575     *
14576     * @return True if the view is attached to a window and the window is
14577     *         hardware accelerated; false in any other case.
14578     */
14579    @ViewDebug.ExportedProperty(category = "drawing")
14580    public boolean isHardwareAccelerated() {
14581        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14582    }
14583
14584    /**
14585     * Sets a rectangular area on this view to which the view will be clipped
14586     * when it is drawn. Setting the value to null will remove the clip bounds
14587     * and the view will draw normally, using its full bounds.
14588     *
14589     * @param clipBounds The rectangular area, in the local coordinates of
14590     * this view, to which future drawing operations will be clipped.
14591     */
14592    public void setClipBounds(Rect clipBounds) {
14593        if (clipBounds != null) {
14594            if (clipBounds.equals(mClipBounds)) {
14595                return;
14596            }
14597            if (mClipBounds == null) {
14598                invalidate();
14599                mClipBounds = new Rect(clipBounds);
14600            } else {
14601                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14602                        Math.min(mClipBounds.top, clipBounds.top),
14603                        Math.max(mClipBounds.right, clipBounds.right),
14604                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14605                mClipBounds.set(clipBounds);
14606            }
14607        } else {
14608            if (mClipBounds != null) {
14609                invalidate();
14610                mClipBounds = null;
14611            }
14612        }
14613        mRenderNode.setClipBounds(mClipBounds);
14614    }
14615
14616    /**
14617     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14618     *
14619     * @return A copy of the current clip bounds if clip bounds are set,
14620     * otherwise null.
14621     */
14622    public Rect getClipBounds() {
14623        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14624    }
14625
14626    /**
14627     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14628     * case of an active Animation being run on the view.
14629     */
14630    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14631            Animation a, boolean scalingRequired) {
14632        Transformation invalidationTransform;
14633        final int flags = parent.mGroupFlags;
14634        final boolean initialized = a.isInitialized();
14635        if (!initialized) {
14636            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14637            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14638            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14639            onAnimationStart();
14640        }
14641
14642        final Transformation t = parent.getChildTransformation();
14643        boolean more = a.getTransformation(drawingTime, t, 1f);
14644        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14645            if (parent.mInvalidationTransformation == null) {
14646                parent.mInvalidationTransformation = new Transformation();
14647            }
14648            invalidationTransform = parent.mInvalidationTransformation;
14649            a.getTransformation(drawingTime, invalidationTransform, 1f);
14650        } else {
14651            invalidationTransform = t;
14652        }
14653
14654        if (more) {
14655            if (!a.willChangeBounds()) {
14656                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14657                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14658                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14659                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14660                    // The child need to draw an animation, potentially offscreen, so
14661                    // make sure we do not cancel invalidate requests
14662                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14663                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14664                }
14665            } else {
14666                if (parent.mInvalidateRegion == null) {
14667                    parent.mInvalidateRegion = new RectF();
14668                }
14669                final RectF region = parent.mInvalidateRegion;
14670                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14671                        invalidationTransform);
14672
14673                // The child need to draw an animation, potentially offscreen, so
14674                // make sure we do not cancel invalidate requests
14675                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14676
14677                final int left = mLeft + (int) region.left;
14678                final int top = mTop + (int) region.top;
14679                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14680                        top + (int) (region.height() + .5f));
14681            }
14682        }
14683        return more;
14684    }
14685
14686    /**
14687     * This method is called by getDisplayList() when a display list is recorded for a View.
14688     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14689     */
14690    void setDisplayListProperties(RenderNode renderNode) {
14691        if (renderNode != null) {
14692            if ((mPrivateFlags3 & PFLAG3_OUTLINE_INVALID) != 0) {
14693                rebuildOutline();
14694                mPrivateFlags3 &= ~PFLAG3_OUTLINE_INVALID;
14695            }
14696            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14697            if (mParent instanceof ViewGroup) {
14698                renderNode.setClipToBounds(
14699                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14700            }
14701            float alpha = 1;
14702            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14703                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14704                ViewGroup parentVG = (ViewGroup) mParent;
14705                final Transformation t = parentVG.getChildTransformation();
14706                if (parentVG.getChildStaticTransformation(this, t)) {
14707                    final int transformType = t.getTransformationType();
14708                    if (transformType != Transformation.TYPE_IDENTITY) {
14709                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14710                            alpha = t.getAlpha();
14711                        }
14712                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14713                            renderNode.setStaticMatrix(t.getMatrix());
14714                        }
14715                    }
14716                }
14717            }
14718            if (mTransformationInfo != null) {
14719                alpha *= getFinalAlpha();
14720                if (alpha < 1) {
14721                    final int multipliedAlpha = (int) (255 * alpha);
14722                    if (onSetAlpha(multipliedAlpha)) {
14723                        alpha = 1;
14724                    }
14725                }
14726                renderNode.setAlpha(alpha);
14727            } else if (alpha < 1) {
14728                renderNode.setAlpha(alpha);
14729            }
14730        }
14731    }
14732
14733    /**
14734     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14735     * This draw() method is an implementation detail and is not intended to be overridden or
14736     * to be called from anywhere else other than ViewGroup.drawChild().
14737     */
14738    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14739        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14740        boolean more = false;
14741        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14742        final int flags = parent.mGroupFlags;
14743
14744        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14745            parent.getChildTransformation().clear();
14746            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14747        }
14748
14749        Transformation transformToApply = null;
14750        boolean concatMatrix = false;
14751
14752        boolean scalingRequired = false;
14753        boolean caching;
14754        int layerType = getLayerType();
14755
14756        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14757        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14758                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14759            caching = true;
14760            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14761            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14762        } else {
14763            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14764        }
14765
14766        final Animation a = getAnimation();
14767        if (a != null) {
14768            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14769            concatMatrix = a.willChangeTransformationMatrix();
14770            if (concatMatrix) {
14771                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14772            }
14773            transformToApply = parent.getChildTransformation();
14774        } else {
14775            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14776                // No longer animating: clear out old animation matrix
14777                mRenderNode.setAnimationMatrix(null);
14778                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14779            }
14780            if (!usingRenderNodeProperties &&
14781                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14782                final Transformation t = parent.getChildTransformation();
14783                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14784                if (hasTransform) {
14785                    final int transformType = t.getTransformationType();
14786                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14787                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14788                }
14789            }
14790        }
14791
14792        concatMatrix |= !childHasIdentityMatrix;
14793
14794        // Sets the flag as early as possible to allow draw() implementations
14795        // to call invalidate() successfully when doing animations
14796        mPrivateFlags |= PFLAG_DRAWN;
14797
14798        if (!concatMatrix &&
14799                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14800                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14801                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14802                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14803            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14804            return more;
14805        }
14806        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14807
14808        if (hardwareAccelerated) {
14809            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14810            // retain the flag's value temporarily in the mRecreateDisplayList flag
14811            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14812            mPrivateFlags &= ~PFLAG_INVALIDATED;
14813        }
14814
14815        RenderNode renderNode = null;
14816        Bitmap cache = null;
14817        boolean hasDisplayList = false;
14818        if (caching) {
14819            if (!hardwareAccelerated) {
14820                if (layerType != LAYER_TYPE_NONE) {
14821                    layerType = LAYER_TYPE_SOFTWARE;
14822                    buildDrawingCache(true);
14823                }
14824                cache = getDrawingCache(true);
14825            } else {
14826                switch (layerType) {
14827                    case LAYER_TYPE_SOFTWARE:
14828                        if (usingRenderNodeProperties) {
14829                            hasDisplayList = canHaveDisplayList();
14830                        } else {
14831                            buildDrawingCache(true);
14832                            cache = getDrawingCache(true);
14833                        }
14834                        break;
14835                    case LAYER_TYPE_HARDWARE:
14836                        if (usingRenderNodeProperties) {
14837                            hasDisplayList = canHaveDisplayList();
14838                        }
14839                        break;
14840                    case LAYER_TYPE_NONE:
14841                        // Delay getting the display list until animation-driven alpha values are
14842                        // set up and possibly passed on to the view
14843                        hasDisplayList = canHaveDisplayList();
14844                        break;
14845                }
14846            }
14847        }
14848        usingRenderNodeProperties &= hasDisplayList;
14849        if (usingRenderNodeProperties) {
14850            renderNode = getDisplayList();
14851            if (!renderNode.isValid()) {
14852                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14853                // to getDisplayList(), the display list will be marked invalid and we should not
14854                // try to use it again.
14855                renderNode = null;
14856                hasDisplayList = false;
14857                usingRenderNodeProperties = false;
14858            }
14859        }
14860
14861        int sx = 0;
14862        int sy = 0;
14863        if (!hasDisplayList) {
14864            computeScroll();
14865            sx = mScrollX;
14866            sy = mScrollY;
14867        }
14868
14869        final boolean hasNoCache = cache == null || hasDisplayList;
14870        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14871                layerType != LAYER_TYPE_HARDWARE;
14872
14873        int restoreTo = -1;
14874        if (!usingRenderNodeProperties || transformToApply != null) {
14875            restoreTo = canvas.save();
14876        }
14877        if (offsetForScroll) {
14878            canvas.translate(mLeft - sx, mTop - sy);
14879        } else {
14880            if (!usingRenderNodeProperties) {
14881                canvas.translate(mLeft, mTop);
14882            }
14883            if (scalingRequired) {
14884                if (usingRenderNodeProperties) {
14885                    // TODO: Might not need this if we put everything inside the DL
14886                    restoreTo = canvas.save();
14887                }
14888                // mAttachInfo cannot be null, otherwise scalingRequired == false
14889                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14890                canvas.scale(scale, scale);
14891            }
14892        }
14893
14894        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14895        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14896                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14897            if (transformToApply != null || !childHasIdentityMatrix) {
14898                int transX = 0;
14899                int transY = 0;
14900
14901                if (offsetForScroll) {
14902                    transX = -sx;
14903                    transY = -sy;
14904                }
14905
14906                if (transformToApply != null) {
14907                    if (concatMatrix) {
14908                        if (usingRenderNodeProperties) {
14909                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14910                        } else {
14911                            // Undo the scroll translation, apply the transformation matrix,
14912                            // then redo the scroll translate to get the correct result.
14913                            canvas.translate(-transX, -transY);
14914                            canvas.concat(transformToApply.getMatrix());
14915                            canvas.translate(transX, transY);
14916                        }
14917                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14918                    }
14919
14920                    float transformAlpha = transformToApply.getAlpha();
14921                    if (transformAlpha < 1) {
14922                        alpha *= transformAlpha;
14923                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14924                    }
14925                }
14926
14927                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14928                    canvas.translate(-transX, -transY);
14929                    canvas.concat(getMatrix());
14930                    canvas.translate(transX, transY);
14931                }
14932            }
14933
14934            // Deal with alpha if it is or used to be <1
14935            if (alpha < 1 ||
14936                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14937                if (alpha < 1) {
14938                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14939                } else {
14940                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14941                }
14942                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14943                if (hasNoCache) {
14944                    final int multipliedAlpha = (int) (255 * alpha);
14945                    if (!onSetAlpha(multipliedAlpha)) {
14946                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14947                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14948                                layerType != LAYER_TYPE_NONE) {
14949                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14950                        }
14951                        if (usingRenderNodeProperties) {
14952                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14953                        } else  if (layerType == LAYER_TYPE_NONE) {
14954                            final int scrollX = hasDisplayList ? 0 : sx;
14955                            final int scrollY = hasDisplayList ? 0 : sy;
14956                            canvas.saveLayerAlpha(scrollX, scrollY,
14957                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14958                                    multipliedAlpha, layerFlags);
14959                        }
14960                    } else {
14961                        // Alpha is handled by the child directly, clobber the layer's alpha
14962                        mPrivateFlags |= PFLAG_ALPHA_SET;
14963                    }
14964                }
14965            }
14966        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14967            onSetAlpha(255);
14968            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14969        }
14970
14971        if (!usingRenderNodeProperties) {
14972            // apply clips directly, since RenderNode won't do it for this draw
14973            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14974                    && cache == null) {
14975                if (offsetForScroll) {
14976                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14977                } else {
14978                    if (!scalingRequired || cache == null) {
14979                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14980                    } else {
14981                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14982                    }
14983                }
14984            }
14985
14986            if (mClipBounds != null) {
14987                // clip bounds ignore scroll
14988                canvas.clipRect(mClipBounds);
14989            }
14990        }
14991
14992
14993
14994        if (!usingRenderNodeProperties && hasDisplayList) {
14995            renderNode = getDisplayList();
14996            if (!renderNode.isValid()) {
14997                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14998                // to getDisplayList(), the display list will be marked invalid and we should not
14999                // try to use it again.
15000                renderNode = null;
15001                hasDisplayList = false;
15002            }
15003        }
15004
15005        if (hasNoCache) {
15006            boolean layerRendered = false;
15007            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
15008                final HardwareLayer layer = getHardwareLayer();
15009                if (layer != null && layer.isValid()) {
15010                    int restoreAlpha = mLayerPaint.getAlpha();
15011                    mLayerPaint.setAlpha((int) (alpha * 255));
15012                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
15013                    mLayerPaint.setAlpha(restoreAlpha);
15014                    layerRendered = true;
15015                } else {
15016                    final int scrollX = hasDisplayList ? 0 : sx;
15017                    final int scrollY = hasDisplayList ? 0 : sy;
15018                    canvas.saveLayer(scrollX, scrollY,
15019                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
15020                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
15021                }
15022            }
15023
15024            if (!layerRendered) {
15025                if (!hasDisplayList) {
15026                    // Fast path for layouts with no backgrounds
15027                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15028                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15029                        dispatchDraw(canvas);
15030                    } else {
15031                        draw(canvas);
15032                    }
15033                } else {
15034                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15035                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
15036                }
15037            }
15038        } else if (cache != null) {
15039            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15040            Paint cachePaint;
15041            int restoreAlpha = 0;
15042
15043            if (layerType == LAYER_TYPE_NONE) {
15044                cachePaint = parent.mCachePaint;
15045                if (cachePaint == null) {
15046                    cachePaint = new Paint();
15047                    cachePaint.setDither(false);
15048                    parent.mCachePaint = cachePaint;
15049                }
15050            } else {
15051                cachePaint = mLayerPaint;
15052                restoreAlpha = mLayerPaint.getAlpha();
15053            }
15054            cachePaint.setAlpha((int) (alpha * 255));
15055            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15056            cachePaint.setAlpha(restoreAlpha);
15057        }
15058
15059        if (restoreTo >= 0) {
15060            canvas.restoreToCount(restoreTo);
15061        }
15062
15063        if (a != null && !more) {
15064            if (!hardwareAccelerated && !a.getFillAfter()) {
15065                onSetAlpha(255);
15066            }
15067            parent.finishAnimatingView(this, a);
15068        }
15069
15070        if (more && hardwareAccelerated) {
15071            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15072                // alpha animations should cause the child to recreate its display list
15073                invalidate(true);
15074            }
15075        }
15076
15077        mRecreateDisplayList = false;
15078
15079        return more;
15080    }
15081
15082    /**
15083     * Manually render this view (and all of its children) to the given Canvas.
15084     * The view must have already done a full layout before this function is
15085     * called.  When implementing a view, implement
15086     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15087     * If you do need to override this method, call the superclass version.
15088     *
15089     * @param canvas The Canvas to which the View is rendered.
15090     */
15091    public void draw(Canvas canvas) {
15092        final int privateFlags = mPrivateFlags;
15093        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15094                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15095        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15096
15097        /*
15098         * Draw traversal performs several drawing steps which must be executed
15099         * in the appropriate order:
15100         *
15101         *      1. Draw the background
15102         *      2. If necessary, save the canvas' layers to prepare for fading
15103         *      3. Draw view's content
15104         *      4. Draw children
15105         *      5. If necessary, draw the fading edges and restore layers
15106         *      6. Draw decorations (scrollbars for instance)
15107         */
15108
15109        // Step 1, draw the background, if needed
15110        int saveCount;
15111
15112        if (!dirtyOpaque) {
15113            drawBackground(canvas);
15114        }
15115
15116        // skip step 2 & 5 if possible (common case)
15117        final int viewFlags = mViewFlags;
15118        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15119        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15120        if (!verticalEdges && !horizontalEdges) {
15121            // Step 3, draw the content
15122            if (!dirtyOpaque) onDraw(canvas);
15123
15124            // Step 4, draw the children
15125            dispatchDraw(canvas);
15126
15127            // Step 6, draw decorations (scrollbars)
15128            onDrawScrollBars(canvas);
15129
15130            if (mOverlay != null && !mOverlay.isEmpty()) {
15131                mOverlay.getOverlayView().dispatchDraw(canvas);
15132            }
15133
15134            // we're done...
15135            return;
15136        }
15137
15138        /*
15139         * Here we do the full fledged routine...
15140         * (this is an uncommon case where speed matters less,
15141         * this is why we repeat some of the tests that have been
15142         * done above)
15143         */
15144
15145        boolean drawTop = false;
15146        boolean drawBottom = false;
15147        boolean drawLeft = false;
15148        boolean drawRight = false;
15149
15150        float topFadeStrength = 0.0f;
15151        float bottomFadeStrength = 0.0f;
15152        float leftFadeStrength = 0.0f;
15153        float rightFadeStrength = 0.0f;
15154
15155        // Step 2, save the canvas' layers
15156        int paddingLeft = mPaddingLeft;
15157
15158        final boolean offsetRequired = isPaddingOffsetRequired();
15159        if (offsetRequired) {
15160            paddingLeft += getLeftPaddingOffset();
15161        }
15162
15163        int left = mScrollX + paddingLeft;
15164        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15165        int top = mScrollY + getFadeTop(offsetRequired);
15166        int bottom = top + getFadeHeight(offsetRequired);
15167
15168        if (offsetRequired) {
15169            right += getRightPaddingOffset();
15170            bottom += getBottomPaddingOffset();
15171        }
15172
15173        final ScrollabilityCache scrollabilityCache = mScrollCache;
15174        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15175        int length = (int) fadeHeight;
15176
15177        // clip the fade length if top and bottom fades overlap
15178        // overlapping fades produce odd-looking artifacts
15179        if (verticalEdges && (top + length > bottom - length)) {
15180            length = (bottom - top) / 2;
15181        }
15182
15183        // also clip horizontal fades if necessary
15184        if (horizontalEdges && (left + length > right - length)) {
15185            length = (right - left) / 2;
15186        }
15187
15188        if (verticalEdges) {
15189            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15190            drawTop = topFadeStrength * fadeHeight > 1.0f;
15191            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15192            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15193        }
15194
15195        if (horizontalEdges) {
15196            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15197            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15198            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15199            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15200        }
15201
15202        saveCount = canvas.getSaveCount();
15203
15204        int solidColor = getSolidColor();
15205        if (solidColor == 0) {
15206            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15207
15208            if (drawTop) {
15209                canvas.saveLayer(left, top, right, top + length, null, flags);
15210            }
15211
15212            if (drawBottom) {
15213                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15214            }
15215
15216            if (drawLeft) {
15217                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15218            }
15219
15220            if (drawRight) {
15221                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15222            }
15223        } else {
15224            scrollabilityCache.setFadeColor(solidColor);
15225        }
15226
15227        // Step 3, draw the content
15228        if (!dirtyOpaque) onDraw(canvas);
15229
15230        // Step 4, draw the children
15231        dispatchDraw(canvas);
15232
15233        // Step 5, draw the fade effect and restore layers
15234        final Paint p = scrollabilityCache.paint;
15235        final Matrix matrix = scrollabilityCache.matrix;
15236        final Shader fade = scrollabilityCache.shader;
15237
15238        if (drawTop) {
15239            matrix.setScale(1, fadeHeight * topFadeStrength);
15240            matrix.postTranslate(left, top);
15241            fade.setLocalMatrix(matrix);
15242            p.setShader(fade);
15243            canvas.drawRect(left, top, right, top + length, p);
15244        }
15245
15246        if (drawBottom) {
15247            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15248            matrix.postRotate(180);
15249            matrix.postTranslate(left, bottom);
15250            fade.setLocalMatrix(matrix);
15251            p.setShader(fade);
15252            canvas.drawRect(left, bottom - length, right, bottom, p);
15253        }
15254
15255        if (drawLeft) {
15256            matrix.setScale(1, fadeHeight * leftFadeStrength);
15257            matrix.postRotate(-90);
15258            matrix.postTranslate(left, top);
15259            fade.setLocalMatrix(matrix);
15260            p.setShader(fade);
15261            canvas.drawRect(left, top, left + length, bottom, p);
15262        }
15263
15264        if (drawRight) {
15265            matrix.setScale(1, fadeHeight * rightFadeStrength);
15266            matrix.postRotate(90);
15267            matrix.postTranslate(right, top);
15268            fade.setLocalMatrix(matrix);
15269            p.setShader(fade);
15270            canvas.drawRect(right - length, top, right, bottom, p);
15271        }
15272
15273        canvas.restoreToCount(saveCount);
15274
15275        // Step 6, draw decorations (scrollbars)
15276        onDrawScrollBars(canvas);
15277
15278        if (mOverlay != null && !mOverlay.isEmpty()) {
15279            mOverlay.getOverlayView().dispatchDraw(canvas);
15280        }
15281    }
15282
15283    /**
15284     * Draws the background onto the specified canvas.
15285     *
15286     * @param canvas Canvas on which to draw the background
15287     */
15288    private void drawBackground(Canvas canvas) {
15289        final Drawable background = mBackground;
15290        if (background == null) {
15291            return;
15292        }
15293
15294        if (mBackgroundSizeChanged) {
15295            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15296            mBackgroundSizeChanged = false;
15297            mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
15298        }
15299
15300        // Attempt to use a display list if requested.
15301        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15302                && mAttachInfo.mHardwareRenderer != null) {
15303            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15304
15305            final RenderNode displayList = mBackgroundRenderNode;
15306            if (displayList != null && displayList.isValid()) {
15307                setBackgroundDisplayListProperties(displayList);
15308                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15309                return;
15310            }
15311        }
15312
15313        final int scrollX = mScrollX;
15314        final int scrollY = mScrollY;
15315        if ((scrollX | scrollY) == 0) {
15316            background.draw(canvas);
15317        } else {
15318            canvas.translate(scrollX, scrollY);
15319            background.draw(canvas);
15320            canvas.translate(-scrollX, -scrollY);
15321        }
15322    }
15323
15324    /**
15325     * Set up background drawable display list properties.
15326     *
15327     * @param displayList Valid display list for the background drawable
15328     */
15329    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15330        displayList.setTranslationX(mScrollX);
15331        displayList.setTranslationY(mScrollY);
15332    }
15333
15334    /**
15335     * Creates a new display list or updates the existing display list for the
15336     * specified Drawable.
15337     *
15338     * @param drawable Drawable for which to create a display list
15339     * @param renderNode Existing RenderNode, or {@code null}
15340     * @return A valid display list for the specified drawable
15341     */
15342    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15343        if (renderNode == null) {
15344            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15345        }
15346
15347        final Rect bounds = drawable.getBounds();
15348        final int width = bounds.width();
15349        final int height = bounds.height();
15350        final HardwareCanvas canvas = renderNode.start(width, height);
15351        try {
15352            drawable.draw(canvas);
15353        } finally {
15354            renderNode.end(canvas);
15355        }
15356
15357        // Set up drawable properties that are view-independent.
15358        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15359        renderNode.setProjectBackwards(drawable.isProjected());
15360        renderNode.setProjectionReceiver(true);
15361        renderNode.setClipToBounds(false);
15362        return renderNode;
15363    }
15364
15365    /**
15366     * Returns the overlay for this view, creating it if it does not yet exist.
15367     * Adding drawables to the overlay will cause them to be displayed whenever
15368     * the view itself is redrawn. Objects in the overlay should be actively
15369     * managed: remove them when they should not be displayed anymore. The
15370     * overlay will always have the same size as its host view.
15371     *
15372     * <p>Note: Overlays do not currently work correctly with {@link
15373     * SurfaceView} or {@link TextureView}; contents in overlays for these
15374     * types of views may not display correctly.</p>
15375     *
15376     * @return The ViewOverlay object for this view.
15377     * @see ViewOverlay
15378     */
15379    public ViewOverlay getOverlay() {
15380        if (mOverlay == null) {
15381            mOverlay = new ViewOverlay(mContext, this);
15382        }
15383        return mOverlay;
15384    }
15385
15386    /**
15387     * Override this if your view is known to always be drawn on top of a solid color background,
15388     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15389     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15390     * should be set to 0xFF.
15391     *
15392     * @see #setVerticalFadingEdgeEnabled(boolean)
15393     * @see #setHorizontalFadingEdgeEnabled(boolean)
15394     *
15395     * @return The known solid color background for this view, or 0 if the color may vary
15396     */
15397    @ViewDebug.ExportedProperty(category = "drawing")
15398    public int getSolidColor() {
15399        return 0;
15400    }
15401
15402    /**
15403     * Build a human readable string representation of the specified view flags.
15404     *
15405     * @param flags the view flags to convert to a string
15406     * @return a String representing the supplied flags
15407     */
15408    private static String printFlags(int flags) {
15409        String output = "";
15410        int numFlags = 0;
15411        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15412            output += "TAKES_FOCUS";
15413            numFlags++;
15414        }
15415
15416        switch (flags & VISIBILITY_MASK) {
15417        case INVISIBLE:
15418            if (numFlags > 0) {
15419                output += " ";
15420            }
15421            output += "INVISIBLE";
15422            // USELESS HERE numFlags++;
15423            break;
15424        case GONE:
15425            if (numFlags > 0) {
15426                output += " ";
15427            }
15428            output += "GONE";
15429            // USELESS HERE numFlags++;
15430            break;
15431        default:
15432            break;
15433        }
15434        return output;
15435    }
15436
15437    /**
15438     * Build a human readable string representation of the specified private
15439     * view flags.
15440     *
15441     * @param privateFlags the private view flags to convert to a string
15442     * @return a String representing the supplied flags
15443     */
15444    private static String printPrivateFlags(int privateFlags) {
15445        String output = "";
15446        int numFlags = 0;
15447
15448        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15449            output += "WANTS_FOCUS";
15450            numFlags++;
15451        }
15452
15453        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15454            if (numFlags > 0) {
15455                output += " ";
15456            }
15457            output += "FOCUSED";
15458            numFlags++;
15459        }
15460
15461        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15462            if (numFlags > 0) {
15463                output += " ";
15464            }
15465            output += "SELECTED";
15466            numFlags++;
15467        }
15468
15469        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15470            if (numFlags > 0) {
15471                output += " ";
15472            }
15473            output += "IS_ROOT_NAMESPACE";
15474            numFlags++;
15475        }
15476
15477        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15478            if (numFlags > 0) {
15479                output += " ";
15480            }
15481            output += "HAS_BOUNDS";
15482            numFlags++;
15483        }
15484
15485        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15486            if (numFlags > 0) {
15487                output += " ";
15488            }
15489            output += "DRAWN";
15490            // USELESS HERE numFlags++;
15491        }
15492        return output;
15493    }
15494
15495    /**
15496     * <p>Indicates whether or not this view's layout will be requested during
15497     * the next hierarchy layout pass.</p>
15498     *
15499     * @return true if the layout will be forced during next layout pass
15500     */
15501    public boolean isLayoutRequested() {
15502        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15503    }
15504
15505    /**
15506     * Return true if o is a ViewGroup that is laying out using optical bounds.
15507     * @hide
15508     */
15509    public static boolean isLayoutModeOptical(Object o) {
15510        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15511    }
15512
15513    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15514        Insets parentInsets = mParent instanceof View ?
15515                ((View) mParent).getOpticalInsets() : Insets.NONE;
15516        Insets childInsets = getOpticalInsets();
15517        return setFrame(
15518                left   + parentInsets.left - childInsets.left,
15519                top    + parentInsets.top  - childInsets.top,
15520                right  + parentInsets.left + childInsets.right,
15521                bottom + parentInsets.top  + childInsets.bottom);
15522    }
15523
15524    /**
15525     * Assign a size and position to a view and all of its
15526     * descendants
15527     *
15528     * <p>This is the second phase of the layout mechanism.
15529     * (The first is measuring). In this phase, each parent calls
15530     * layout on all of its children to position them.
15531     * This is typically done using the child measurements
15532     * that were stored in the measure pass().</p>
15533     *
15534     * <p>Derived classes should not override this method.
15535     * Derived classes with children should override
15536     * onLayout. In that method, they should
15537     * call layout on each of their children.</p>
15538     *
15539     * @param l Left position, relative to parent
15540     * @param t Top position, relative to parent
15541     * @param r Right position, relative to parent
15542     * @param b Bottom position, relative to parent
15543     */
15544    @SuppressWarnings({"unchecked"})
15545    public void layout(int l, int t, int r, int b) {
15546        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15547            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15548            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15549        }
15550
15551        int oldL = mLeft;
15552        int oldT = mTop;
15553        int oldB = mBottom;
15554        int oldR = mRight;
15555
15556        boolean changed = isLayoutModeOptical(mParent) ?
15557                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15558
15559        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15560            onLayout(changed, l, t, r, b);
15561            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15562
15563            ListenerInfo li = mListenerInfo;
15564            if (li != null && li.mOnLayoutChangeListeners != null) {
15565                ArrayList<OnLayoutChangeListener> listenersCopy =
15566                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15567                int numListeners = listenersCopy.size();
15568                for (int i = 0; i < numListeners; ++i) {
15569                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15570                }
15571            }
15572        }
15573
15574        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15575        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15576    }
15577
15578    /**
15579     * Called from layout when this view should
15580     * assign a size and position to each of its children.
15581     *
15582     * Derived classes with children should override
15583     * this method and call layout on each of
15584     * their children.
15585     * @param changed This is a new size or position for this view
15586     * @param left Left position, relative to parent
15587     * @param top Top position, relative to parent
15588     * @param right Right position, relative to parent
15589     * @param bottom Bottom position, relative to parent
15590     */
15591    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15592    }
15593
15594    /**
15595     * Assign a size and position to this view.
15596     *
15597     * This is called from layout.
15598     *
15599     * @param left Left position, relative to parent
15600     * @param top Top position, relative to parent
15601     * @param right Right position, relative to parent
15602     * @param bottom Bottom position, relative to parent
15603     * @return true if the new size and position are different than the
15604     *         previous ones
15605     * {@hide}
15606     */
15607    protected boolean setFrame(int left, int top, int right, int bottom) {
15608        boolean changed = false;
15609
15610        if (DBG) {
15611            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15612                    + right + "," + bottom + ")");
15613        }
15614
15615        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15616            changed = true;
15617
15618            // Remember our drawn bit
15619            int drawn = mPrivateFlags & PFLAG_DRAWN;
15620
15621            int oldWidth = mRight - mLeft;
15622            int oldHeight = mBottom - mTop;
15623            int newWidth = right - left;
15624            int newHeight = bottom - top;
15625            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15626
15627            // Invalidate our old position
15628            invalidate(sizeChanged);
15629
15630            mLeft = left;
15631            mTop = top;
15632            mRight = right;
15633            mBottom = bottom;
15634            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15635
15636            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15637
15638
15639            if (sizeChanged) {
15640                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15641            }
15642
15643            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
15644                // If we are visible, force the DRAWN bit to on so that
15645                // this invalidate will go through (at least to our parent).
15646                // This is because someone may have invalidated this view
15647                // before this call to setFrame came in, thereby clearing
15648                // the DRAWN bit.
15649                mPrivateFlags |= PFLAG_DRAWN;
15650                invalidate(sizeChanged);
15651                // parent display list may need to be recreated based on a change in the bounds
15652                // of any child
15653                invalidateParentCaches();
15654            }
15655
15656            // Reset drawn bit to original value (invalidate turns it off)
15657            mPrivateFlags |= drawn;
15658
15659            mBackgroundSizeChanged = true;
15660
15661            notifySubtreeAccessibilityStateChangedIfNeeded();
15662        }
15663        return changed;
15664    }
15665
15666    /**
15667     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
15668     * @hide
15669     */
15670    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
15671        setFrame(left, top, right, bottom);
15672    }
15673
15674    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15675        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15676        if (mOverlay != null) {
15677            mOverlay.getOverlayView().setRight(newWidth);
15678            mOverlay.getOverlayView().setBottom(newHeight);
15679        }
15680        mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
15681    }
15682
15683    /**
15684     * Finalize inflating a view from XML.  This is called as the last phase
15685     * of inflation, after all child views have been added.
15686     *
15687     * <p>Even if the subclass overrides onFinishInflate, they should always be
15688     * sure to call the super method, so that we get called.
15689     */
15690    protected void onFinishInflate() {
15691    }
15692
15693    /**
15694     * Returns the resources associated with this view.
15695     *
15696     * @return Resources object.
15697     */
15698    public Resources getResources() {
15699        return mResources;
15700    }
15701
15702    /**
15703     * Invalidates the specified Drawable.
15704     *
15705     * @param drawable the drawable to invalidate
15706     */
15707    @Override
15708    public void invalidateDrawable(@NonNull Drawable drawable) {
15709        if (verifyDrawable(drawable)) {
15710            final Rect dirty = drawable.getDirtyBounds();
15711            final int scrollX = mScrollX;
15712            final int scrollY = mScrollY;
15713
15714            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15715                    dirty.right + scrollX, dirty.bottom + scrollY);
15716
15717            mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
15718        }
15719    }
15720
15721    /**
15722     * Schedules an action on a drawable to occur at a specified time.
15723     *
15724     * @param who the recipient of the action
15725     * @param what the action to run on the drawable
15726     * @param when the time at which the action must occur. Uses the
15727     *        {@link SystemClock#uptimeMillis} timebase.
15728     */
15729    @Override
15730    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15731        if (verifyDrawable(who) && what != null) {
15732            final long delay = when - SystemClock.uptimeMillis();
15733            if (mAttachInfo != null) {
15734                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15735                        Choreographer.CALLBACK_ANIMATION, what, who,
15736                        Choreographer.subtractFrameDelay(delay));
15737            } else {
15738                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15739            }
15740        }
15741    }
15742
15743    /**
15744     * Cancels a scheduled action on a drawable.
15745     *
15746     * @param who the recipient of the action
15747     * @param what the action to cancel
15748     */
15749    @Override
15750    public void unscheduleDrawable(Drawable who, Runnable what) {
15751        if (verifyDrawable(who) && what != null) {
15752            if (mAttachInfo != null) {
15753                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15754                        Choreographer.CALLBACK_ANIMATION, what, who);
15755            }
15756            ViewRootImpl.getRunQueue().removeCallbacks(what);
15757        }
15758    }
15759
15760    /**
15761     * Unschedule any events associated with the given Drawable.  This can be
15762     * used when selecting a new Drawable into a view, so that the previous
15763     * one is completely unscheduled.
15764     *
15765     * @param who The Drawable to unschedule.
15766     *
15767     * @see #drawableStateChanged
15768     */
15769    public void unscheduleDrawable(Drawable who) {
15770        if (mAttachInfo != null && who != null) {
15771            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15772                    Choreographer.CALLBACK_ANIMATION, null, who);
15773        }
15774    }
15775
15776    /**
15777     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15778     * that the View directionality can and will be resolved before its Drawables.
15779     *
15780     * Will call {@link View#onResolveDrawables} when resolution is done.
15781     *
15782     * @hide
15783     */
15784    protected void resolveDrawables() {
15785        // Drawables resolution may need to happen before resolving the layout direction (which is
15786        // done only during the measure() call).
15787        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15788        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15789        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15790        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15791        // direction to be resolved as its resolved value will be the same as its raw value.
15792        if (!isLayoutDirectionResolved() &&
15793                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15794            return;
15795        }
15796
15797        final int layoutDirection = isLayoutDirectionResolved() ?
15798                getLayoutDirection() : getRawLayoutDirection();
15799
15800        if (mBackground != null) {
15801            mBackground.setLayoutDirection(layoutDirection);
15802        }
15803        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15804        onResolveDrawables(layoutDirection);
15805    }
15806
15807    /**
15808     * Called when layout direction has been resolved.
15809     *
15810     * The default implementation does nothing.
15811     *
15812     * @param layoutDirection The resolved layout direction.
15813     *
15814     * @see #LAYOUT_DIRECTION_LTR
15815     * @see #LAYOUT_DIRECTION_RTL
15816     *
15817     * @hide
15818     */
15819    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15820    }
15821
15822    /**
15823     * @hide
15824     */
15825    protected void resetResolvedDrawables() {
15826        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15827    }
15828
15829    private boolean isDrawablesResolved() {
15830        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15831    }
15832
15833    /**
15834     * If your view subclass is displaying its own Drawable objects, it should
15835     * override this function and return true for any Drawable it is
15836     * displaying.  This allows animations for those drawables to be
15837     * scheduled.
15838     *
15839     * <p>Be sure to call through to the super class when overriding this
15840     * function.
15841     *
15842     * @param who The Drawable to verify.  Return true if it is one you are
15843     *            displaying, else return the result of calling through to the
15844     *            super class.
15845     *
15846     * @return boolean If true than the Drawable is being displayed in the
15847     *         view; else false and it is not allowed to animate.
15848     *
15849     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15850     * @see #drawableStateChanged()
15851     */
15852    protected boolean verifyDrawable(Drawable who) {
15853        return who == mBackground;
15854    }
15855
15856    /**
15857     * This function is called whenever the state of the view changes in such
15858     * a way that it impacts the state of drawables being shown.
15859     * <p>
15860     * If the View has a StateListAnimator, it will also be called to run necessary state
15861     * change animations.
15862     * <p>
15863     * Be sure to call through to the superclass when overriding this function.
15864     *
15865     * @see Drawable#setState(int[])
15866     */
15867    protected void drawableStateChanged() {
15868        final Drawable d = mBackground;
15869        if (d != null && d.isStateful()) {
15870            d.setState(getDrawableState());
15871        }
15872
15873        if (mStateListAnimator != null) {
15874            mStateListAnimator.setState(getDrawableState());
15875        }
15876    }
15877
15878    /**
15879     * This function is called whenever the view hotspot changes and needs to
15880     * be propagated to drawables managed by the view.
15881     * <p>
15882     * Be sure to call through to the superclass when overriding this function.
15883     *
15884     * @param x hotspot x coordinate
15885     * @param y hotspot y coordinate
15886     */
15887    public void drawableHotspotChanged(float x, float y) {
15888        if (mBackground != null) {
15889            mBackground.setHotspot(x, y);
15890        }
15891    }
15892
15893    /**
15894     * Call this to force a view to update its drawable state. This will cause
15895     * drawableStateChanged to be called on this view. Views that are interested
15896     * in the new state should call getDrawableState.
15897     *
15898     * @see #drawableStateChanged
15899     * @see #getDrawableState
15900     */
15901    public void refreshDrawableState() {
15902        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15903        drawableStateChanged();
15904
15905        ViewParent parent = mParent;
15906        if (parent != null) {
15907            parent.childDrawableStateChanged(this);
15908        }
15909    }
15910
15911    /**
15912     * Return an array of resource IDs of the drawable states representing the
15913     * current state of the view.
15914     *
15915     * @return The current drawable state
15916     *
15917     * @see Drawable#setState(int[])
15918     * @see #drawableStateChanged()
15919     * @see #onCreateDrawableState(int)
15920     */
15921    public final int[] getDrawableState() {
15922        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15923            return mDrawableState;
15924        } else {
15925            mDrawableState = onCreateDrawableState(0);
15926            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15927            return mDrawableState;
15928        }
15929    }
15930
15931    /**
15932     * Generate the new {@link android.graphics.drawable.Drawable} state for
15933     * this view. This is called by the view
15934     * system when the cached Drawable state is determined to be invalid.  To
15935     * retrieve the current state, you should use {@link #getDrawableState}.
15936     *
15937     * @param extraSpace if non-zero, this is the number of extra entries you
15938     * would like in the returned array in which you can place your own
15939     * states.
15940     *
15941     * @return Returns an array holding the current {@link Drawable} state of
15942     * the view.
15943     *
15944     * @see #mergeDrawableStates(int[], int[])
15945     */
15946    protected int[] onCreateDrawableState(int extraSpace) {
15947        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15948                mParent instanceof View) {
15949            return ((View) mParent).onCreateDrawableState(extraSpace);
15950        }
15951
15952        int[] drawableState;
15953
15954        int privateFlags = mPrivateFlags;
15955
15956        int viewStateIndex = 0;
15957        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15958        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15959        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15960        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15961        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15962        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15963        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15964                HardwareRenderer.isAvailable()) {
15965            // This is set if HW acceleration is requested, even if the current
15966            // process doesn't allow it.  This is just to allow app preview
15967            // windows to better match their app.
15968            viewStateIndex |= VIEW_STATE_ACCELERATED;
15969        }
15970        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15971
15972        final int privateFlags2 = mPrivateFlags2;
15973        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15974        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15975
15976        drawableState = VIEW_STATE_SETS[viewStateIndex];
15977
15978        //noinspection ConstantIfStatement
15979        if (false) {
15980            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15981            Log.i("View", toString()
15982                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15983                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15984                    + " fo=" + hasFocus()
15985                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15986                    + " wf=" + hasWindowFocus()
15987                    + ": " + Arrays.toString(drawableState));
15988        }
15989
15990        if (extraSpace == 0) {
15991            return drawableState;
15992        }
15993
15994        final int[] fullState;
15995        if (drawableState != null) {
15996            fullState = new int[drawableState.length + extraSpace];
15997            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15998        } else {
15999            fullState = new int[extraSpace];
16000        }
16001
16002        return fullState;
16003    }
16004
16005    /**
16006     * Merge your own state values in <var>additionalState</var> into the base
16007     * state values <var>baseState</var> that were returned by
16008     * {@link #onCreateDrawableState(int)}.
16009     *
16010     * @param baseState The base state values returned by
16011     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16012     * own additional state values.
16013     *
16014     * @param additionalState The additional state values you would like
16015     * added to <var>baseState</var>; this array is not modified.
16016     *
16017     * @return As a convenience, the <var>baseState</var> array you originally
16018     * passed into the function is returned.
16019     *
16020     * @see #onCreateDrawableState(int)
16021     */
16022    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16023        final int N = baseState.length;
16024        int i = N - 1;
16025        while (i >= 0 && baseState[i] == 0) {
16026            i--;
16027        }
16028        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16029        return baseState;
16030    }
16031
16032    /**
16033     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16034     * on all Drawable objects associated with this view.
16035     * <p>
16036     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16037     * attached to this view.
16038     */
16039    public void jumpDrawablesToCurrentState() {
16040        if (mBackground != null) {
16041            mBackground.jumpToCurrentState();
16042        }
16043        if (mStateListAnimator != null) {
16044            mStateListAnimator.jumpToCurrentState();
16045        }
16046    }
16047
16048    /**
16049     * Sets the background color for this view.
16050     * @param color the color of the background
16051     */
16052    @RemotableViewMethod
16053    public void setBackgroundColor(int color) {
16054        if (mBackground instanceof ColorDrawable) {
16055            ((ColorDrawable) mBackground.mutate()).setColor(color);
16056            computeOpaqueFlags();
16057            mBackgroundResource = 0;
16058        } else {
16059            setBackground(new ColorDrawable(color));
16060        }
16061    }
16062
16063    /**
16064     * Set the background to a given resource. The resource should refer to
16065     * a Drawable object or 0 to remove the background.
16066     * @param resid The identifier of the resource.
16067     *
16068     * @attr ref android.R.styleable#View_background
16069     */
16070    @RemotableViewMethod
16071    public void setBackgroundResource(int resid) {
16072        if (resid != 0 && resid == mBackgroundResource) {
16073            return;
16074        }
16075
16076        Drawable d = null;
16077        if (resid != 0) {
16078            d = mContext.getDrawable(resid);
16079        }
16080        setBackground(d);
16081
16082        mBackgroundResource = resid;
16083    }
16084
16085    /**
16086     * Set the background to a given Drawable, or remove the background. If the
16087     * background has padding, this View's padding is set to the background's
16088     * padding. However, when a background is removed, this View's padding isn't
16089     * touched. If setting the padding is desired, please use
16090     * {@link #setPadding(int, int, int, int)}.
16091     *
16092     * @param background The Drawable to use as the background, or null to remove the
16093     *        background
16094     */
16095    public void setBackground(Drawable background) {
16096        //noinspection deprecation
16097        setBackgroundDrawable(background);
16098    }
16099
16100    /**
16101     * @deprecated use {@link #setBackground(Drawable)} instead
16102     */
16103    @Deprecated
16104    public void setBackgroundDrawable(Drawable background) {
16105        computeOpaqueFlags();
16106
16107        if (background == mBackground) {
16108            return;
16109        }
16110
16111        boolean requestLayout = false;
16112
16113        mBackgroundResource = 0;
16114
16115        /*
16116         * Regardless of whether we're setting a new background or not, we want
16117         * to clear the previous drawable.
16118         */
16119        if (mBackground != null) {
16120            mBackground.setCallback(null);
16121            unscheduleDrawable(mBackground);
16122        }
16123
16124        if (background != null) {
16125            Rect padding = sThreadLocal.get();
16126            if (padding == null) {
16127                padding = new Rect();
16128                sThreadLocal.set(padding);
16129            }
16130            resetResolvedDrawables();
16131            background.setLayoutDirection(getLayoutDirection());
16132            if (background.getPadding(padding)) {
16133                resetResolvedPadding();
16134                switch (background.getLayoutDirection()) {
16135                    case LAYOUT_DIRECTION_RTL:
16136                        mUserPaddingLeftInitial = padding.right;
16137                        mUserPaddingRightInitial = padding.left;
16138                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16139                        break;
16140                    case LAYOUT_DIRECTION_LTR:
16141                    default:
16142                        mUserPaddingLeftInitial = padding.left;
16143                        mUserPaddingRightInitial = padding.right;
16144                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16145                }
16146                mLeftPaddingDefined = false;
16147                mRightPaddingDefined = false;
16148            }
16149
16150            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16151            // if it has a different minimum size, we should layout again
16152            if (mBackground == null
16153                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16154                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16155                requestLayout = true;
16156            }
16157
16158            background.setCallback(this);
16159            if (background.isStateful()) {
16160                background.setState(getDrawableState());
16161            }
16162            background.setVisible(getVisibility() == VISIBLE, false);
16163            mBackground = background;
16164
16165            applyBackgroundTint();
16166
16167            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16168                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16169                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16170                requestLayout = true;
16171            }
16172        } else {
16173            /* Remove the background */
16174            mBackground = null;
16175
16176            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16177                /*
16178                 * This view ONLY drew the background before and we're removing
16179                 * the background, so now it won't draw anything
16180                 * (hence we SKIP_DRAW)
16181                 */
16182                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16183                mPrivateFlags |= PFLAG_SKIP_DRAW;
16184            }
16185
16186            /*
16187             * When the background is set, we try to apply its padding to this
16188             * View. When the background is removed, we don't touch this View's
16189             * padding. This is noted in the Javadocs. Hence, we don't need to
16190             * requestLayout(), the invalidate() below is sufficient.
16191             */
16192
16193            // The old background's minimum size could have affected this
16194            // View's layout, so let's requestLayout
16195            requestLayout = true;
16196        }
16197
16198        computeOpaqueFlags();
16199
16200        if (requestLayout) {
16201            requestLayout();
16202        }
16203
16204        mBackgroundSizeChanged = true;
16205        invalidate(true);
16206    }
16207
16208    /**
16209     * Gets the background drawable
16210     *
16211     * @return The drawable used as the background for this view, if any.
16212     *
16213     * @see #setBackground(Drawable)
16214     *
16215     * @attr ref android.R.styleable#View_background
16216     */
16217    public Drawable getBackground() {
16218        return mBackground;
16219    }
16220
16221    /**
16222     * Applies a tint to the background drawable. Does not modify the current tint
16223     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16224     * <p>
16225     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16226     * mutate the drawable and apply the specified tint and tint mode using
16227     * {@link Drawable#setTintList(ColorStateList)}.
16228     *
16229     * @param tint the tint to apply, may be {@code null} to clear tint
16230     *
16231     * @attr ref android.R.styleable#View_backgroundTint
16232     * @see #getBackgroundTintList()
16233     * @see Drawable#setTintList(ColorStateList)
16234     */
16235    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16236        if (mBackgroundTint == null) {
16237            mBackgroundTint = new TintInfo();
16238        }
16239        mBackgroundTint.mTintList = tint;
16240        mBackgroundTint.mHasTintList = true;
16241
16242        applyBackgroundTint();
16243    }
16244
16245    /**
16246     * Return the tint applied to the background drawable, if specified.
16247     *
16248     * @return the tint applied to the background drawable
16249     * @attr ref android.R.styleable#View_backgroundTint
16250     * @see #setBackgroundTintList(ColorStateList)
16251     */
16252    @Nullable
16253    public ColorStateList getBackgroundTintList() {
16254        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16255    }
16256
16257    /**
16258     * Specifies the blending mode used to apply the tint specified by
16259     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16260     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16261     *
16262     * @param tintMode the blending mode used to apply the tint, may be
16263     *                 {@code null} to clear tint
16264     * @attr ref android.R.styleable#View_backgroundTintMode
16265     * @see #getBackgroundTintMode()
16266     * @see Drawable#setTintMode(PorterDuff.Mode)
16267     */
16268    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16269        if (mBackgroundTint == null) {
16270            mBackgroundTint = new TintInfo();
16271        }
16272        mBackgroundTint.mTintMode = tintMode;
16273        mBackgroundTint.mHasTintMode = true;
16274
16275        applyBackgroundTint();
16276    }
16277
16278    /**
16279     * Return the blending mode used to apply the tint to the background
16280     * drawable, if specified.
16281     *
16282     * @return the blending mode used to apply the tint to the background
16283     *         drawable
16284     * @attr ref android.R.styleable#View_backgroundTintMode
16285     * @see #setBackgroundTintMode(PorterDuff.Mode)
16286     */
16287    @Nullable
16288    public PorterDuff.Mode getBackgroundTintMode() {
16289        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16290    }
16291
16292    private void applyBackgroundTint() {
16293        if (mBackground != null && mBackgroundTint != null) {
16294            final TintInfo tintInfo = mBackgroundTint;
16295            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16296                mBackground = mBackground.mutate();
16297
16298                if (tintInfo.mHasTintList) {
16299                    mBackground.setTintList(tintInfo.mTintList);
16300                }
16301
16302                if (tintInfo.mHasTintMode) {
16303                    mBackground.setTintMode(tintInfo.mTintMode);
16304                }
16305            }
16306        }
16307    }
16308
16309    /**
16310     * Sets the padding. The view may add on the space required to display
16311     * the scrollbars, depending on the style and visibility of the scrollbars.
16312     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16313     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16314     * from the values set in this call.
16315     *
16316     * @attr ref android.R.styleable#View_padding
16317     * @attr ref android.R.styleable#View_paddingBottom
16318     * @attr ref android.R.styleable#View_paddingLeft
16319     * @attr ref android.R.styleable#View_paddingRight
16320     * @attr ref android.R.styleable#View_paddingTop
16321     * @param left the left padding in pixels
16322     * @param top the top padding in pixels
16323     * @param right the right padding in pixels
16324     * @param bottom the bottom padding in pixels
16325     */
16326    public void setPadding(int left, int top, int right, int bottom) {
16327        resetResolvedPadding();
16328
16329        mUserPaddingStart = UNDEFINED_PADDING;
16330        mUserPaddingEnd = UNDEFINED_PADDING;
16331
16332        mUserPaddingLeftInitial = left;
16333        mUserPaddingRightInitial = right;
16334
16335        mLeftPaddingDefined = true;
16336        mRightPaddingDefined = true;
16337
16338        internalSetPadding(left, top, right, bottom);
16339    }
16340
16341    /**
16342     * @hide
16343     */
16344    protected void internalSetPadding(int left, int top, int right, int bottom) {
16345        mUserPaddingLeft = left;
16346        mUserPaddingRight = right;
16347        mUserPaddingBottom = bottom;
16348
16349        final int viewFlags = mViewFlags;
16350        boolean changed = false;
16351
16352        // Common case is there are no scroll bars.
16353        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16354            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16355                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16356                        ? 0 : getVerticalScrollbarWidth();
16357                switch (mVerticalScrollbarPosition) {
16358                    case SCROLLBAR_POSITION_DEFAULT:
16359                        if (isLayoutRtl()) {
16360                            left += offset;
16361                        } else {
16362                            right += offset;
16363                        }
16364                        break;
16365                    case SCROLLBAR_POSITION_RIGHT:
16366                        right += offset;
16367                        break;
16368                    case SCROLLBAR_POSITION_LEFT:
16369                        left += offset;
16370                        break;
16371                }
16372            }
16373            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16374                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16375                        ? 0 : getHorizontalScrollbarHeight();
16376            }
16377        }
16378
16379        if (mPaddingLeft != left) {
16380            changed = true;
16381            mPaddingLeft = left;
16382        }
16383        if (mPaddingTop != top) {
16384            changed = true;
16385            mPaddingTop = top;
16386        }
16387        if (mPaddingRight != right) {
16388            changed = true;
16389            mPaddingRight = right;
16390        }
16391        if (mPaddingBottom != bottom) {
16392            changed = true;
16393            mPaddingBottom = bottom;
16394        }
16395
16396        if (changed) {
16397            requestLayout();
16398        }
16399    }
16400
16401    /**
16402     * Sets the relative padding. The view may add on the space required to display
16403     * the scrollbars, depending on the style and visibility of the scrollbars.
16404     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16405     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16406     * from the values set in this call.
16407     *
16408     * @attr ref android.R.styleable#View_padding
16409     * @attr ref android.R.styleable#View_paddingBottom
16410     * @attr ref android.R.styleable#View_paddingStart
16411     * @attr ref android.R.styleable#View_paddingEnd
16412     * @attr ref android.R.styleable#View_paddingTop
16413     * @param start the start padding in pixels
16414     * @param top the top padding in pixels
16415     * @param end the end padding in pixels
16416     * @param bottom the bottom padding in pixels
16417     */
16418    public void setPaddingRelative(int start, int top, int end, int bottom) {
16419        resetResolvedPadding();
16420
16421        mUserPaddingStart = start;
16422        mUserPaddingEnd = end;
16423        mLeftPaddingDefined = true;
16424        mRightPaddingDefined = true;
16425
16426        switch(getLayoutDirection()) {
16427            case LAYOUT_DIRECTION_RTL:
16428                mUserPaddingLeftInitial = end;
16429                mUserPaddingRightInitial = start;
16430                internalSetPadding(end, top, start, bottom);
16431                break;
16432            case LAYOUT_DIRECTION_LTR:
16433            default:
16434                mUserPaddingLeftInitial = start;
16435                mUserPaddingRightInitial = end;
16436                internalSetPadding(start, top, end, bottom);
16437        }
16438    }
16439
16440    /**
16441     * Returns the top padding of this view.
16442     *
16443     * @return the top padding in pixels
16444     */
16445    public int getPaddingTop() {
16446        return mPaddingTop;
16447    }
16448
16449    /**
16450     * Returns the bottom padding of this view. If there are inset and enabled
16451     * scrollbars, this value may include the space required to display the
16452     * scrollbars as well.
16453     *
16454     * @return the bottom padding in pixels
16455     */
16456    public int getPaddingBottom() {
16457        return mPaddingBottom;
16458    }
16459
16460    /**
16461     * Returns the left padding of this view. If there are inset and enabled
16462     * scrollbars, this value may include the space required to display the
16463     * scrollbars as well.
16464     *
16465     * @return the left padding in pixels
16466     */
16467    public int getPaddingLeft() {
16468        if (!isPaddingResolved()) {
16469            resolvePadding();
16470        }
16471        return mPaddingLeft;
16472    }
16473
16474    /**
16475     * Returns the start padding of this view depending on its resolved layout direction.
16476     * If there are inset and enabled scrollbars, this value may include the space
16477     * required to display the scrollbars as well.
16478     *
16479     * @return the start padding in pixels
16480     */
16481    public int getPaddingStart() {
16482        if (!isPaddingResolved()) {
16483            resolvePadding();
16484        }
16485        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16486                mPaddingRight : mPaddingLeft;
16487    }
16488
16489    /**
16490     * Returns the right padding of this view. If there are inset and enabled
16491     * scrollbars, this value may include the space required to display the
16492     * scrollbars as well.
16493     *
16494     * @return the right padding in pixels
16495     */
16496    public int getPaddingRight() {
16497        if (!isPaddingResolved()) {
16498            resolvePadding();
16499        }
16500        return mPaddingRight;
16501    }
16502
16503    /**
16504     * Returns the end padding of this view depending on its resolved layout direction.
16505     * If there are inset and enabled scrollbars, this value may include the space
16506     * required to display the scrollbars as well.
16507     *
16508     * @return the end padding in pixels
16509     */
16510    public int getPaddingEnd() {
16511        if (!isPaddingResolved()) {
16512            resolvePadding();
16513        }
16514        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16515                mPaddingLeft : mPaddingRight;
16516    }
16517
16518    /**
16519     * Return if the padding as been set thru relative values
16520     * {@link #setPaddingRelative(int, int, int, int)} or thru
16521     * @attr ref android.R.styleable#View_paddingStart or
16522     * @attr ref android.R.styleable#View_paddingEnd
16523     *
16524     * @return true if the padding is relative or false if it is not.
16525     */
16526    public boolean isPaddingRelative() {
16527        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16528    }
16529
16530    Insets computeOpticalInsets() {
16531        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16532    }
16533
16534    /**
16535     * @hide
16536     */
16537    public void resetPaddingToInitialValues() {
16538        if (isRtlCompatibilityMode()) {
16539            mPaddingLeft = mUserPaddingLeftInitial;
16540            mPaddingRight = mUserPaddingRightInitial;
16541            return;
16542        }
16543        if (isLayoutRtl()) {
16544            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16545            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16546        } else {
16547            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16548            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16549        }
16550    }
16551
16552    /**
16553     * @hide
16554     */
16555    public Insets getOpticalInsets() {
16556        if (mLayoutInsets == null) {
16557            mLayoutInsets = computeOpticalInsets();
16558        }
16559        return mLayoutInsets;
16560    }
16561
16562    /**
16563     * Set this view's optical insets.
16564     *
16565     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16566     * property. Views that compute their own optical insets should call it as part of measurement.
16567     * This method does not request layout. If you are setting optical insets outside of
16568     * measure/layout itself you will want to call requestLayout() yourself.
16569     * </p>
16570     * @hide
16571     */
16572    public void setOpticalInsets(Insets insets) {
16573        mLayoutInsets = insets;
16574    }
16575
16576    /**
16577     * Changes the selection state of this view. A view can be selected or not.
16578     * Note that selection is not the same as focus. Views are typically
16579     * selected in the context of an AdapterView like ListView or GridView;
16580     * the selected view is the view that is highlighted.
16581     *
16582     * @param selected true if the view must be selected, false otherwise
16583     */
16584    public void setSelected(boolean selected) {
16585        //noinspection DoubleNegation
16586        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16587            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16588            if (!selected) resetPressedState();
16589            invalidate(true);
16590            refreshDrawableState();
16591            dispatchSetSelected(selected);
16592            if (selected) {
16593                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
16594            } else {
16595                notifyViewAccessibilityStateChangedIfNeeded(
16596                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16597            }
16598        }
16599    }
16600
16601    /**
16602     * Dispatch setSelected to all of this View's children.
16603     *
16604     * @see #setSelected(boolean)
16605     *
16606     * @param selected The new selected state
16607     */
16608    protected void dispatchSetSelected(boolean selected) {
16609    }
16610
16611    /**
16612     * Indicates the selection state of this view.
16613     *
16614     * @return true if the view is selected, false otherwise
16615     */
16616    @ViewDebug.ExportedProperty
16617    public boolean isSelected() {
16618        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16619    }
16620
16621    /**
16622     * Changes the activated state of this view. A view can be activated or not.
16623     * Note that activation is not the same as selection.  Selection is
16624     * a transient property, representing the view (hierarchy) the user is
16625     * currently interacting with.  Activation is a longer-term state that the
16626     * user can move views in and out of.  For example, in a list view with
16627     * single or multiple selection enabled, the views in the current selection
16628     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16629     * here.)  The activated state is propagated down to children of the view it
16630     * is set on.
16631     *
16632     * @param activated true if the view must be activated, false otherwise
16633     */
16634    public void setActivated(boolean activated) {
16635        //noinspection DoubleNegation
16636        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16637            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16638            invalidate(true);
16639            refreshDrawableState();
16640            dispatchSetActivated(activated);
16641        }
16642    }
16643
16644    /**
16645     * Dispatch setActivated to all of this View's children.
16646     *
16647     * @see #setActivated(boolean)
16648     *
16649     * @param activated The new activated state
16650     */
16651    protected void dispatchSetActivated(boolean activated) {
16652    }
16653
16654    /**
16655     * Indicates the activation state of this view.
16656     *
16657     * @return true if the view is activated, false otherwise
16658     */
16659    @ViewDebug.ExportedProperty
16660    public boolean isActivated() {
16661        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16662    }
16663
16664    /**
16665     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16666     * observer can be used to get notifications when global events, like
16667     * layout, happen.
16668     *
16669     * The returned ViewTreeObserver observer is not guaranteed to remain
16670     * valid for the lifetime of this View. If the caller of this method keeps
16671     * a long-lived reference to ViewTreeObserver, it should always check for
16672     * the return value of {@link ViewTreeObserver#isAlive()}.
16673     *
16674     * @return The ViewTreeObserver for this view's hierarchy.
16675     */
16676    public ViewTreeObserver getViewTreeObserver() {
16677        if (mAttachInfo != null) {
16678            return mAttachInfo.mTreeObserver;
16679        }
16680        if (mFloatingTreeObserver == null) {
16681            mFloatingTreeObserver = new ViewTreeObserver();
16682        }
16683        return mFloatingTreeObserver;
16684    }
16685
16686    /**
16687     * <p>Finds the topmost view in the current view hierarchy.</p>
16688     *
16689     * @return the topmost view containing this view
16690     */
16691    public View getRootView() {
16692        if (mAttachInfo != null) {
16693            final View v = mAttachInfo.mRootView;
16694            if (v != null) {
16695                return v;
16696            }
16697        }
16698
16699        View parent = this;
16700
16701        while (parent.mParent != null && parent.mParent instanceof View) {
16702            parent = (View) parent.mParent;
16703        }
16704
16705        return parent;
16706    }
16707
16708    /**
16709     * Transforms a motion event from view-local coordinates to on-screen
16710     * coordinates.
16711     *
16712     * @param ev the view-local motion event
16713     * @return false if the transformation could not be applied
16714     * @hide
16715     */
16716    public boolean toGlobalMotionEvent(MotionEvent ev) {
16717        final AttachInfo info = mAttachInfo;
16718        if (info == null) {
16719            return false;
16720        }
16721
16722        final Matrix m = info.mTmpMatrix;
16723        m.set(Matrix.IDENTITY_MATRIX);
16724        transformMatrixToGlobal(m);
16725        ev.transform(m);
16726        return true;
16727    }
16728
16729    /**
16730     * Transforms a motion event from on-screen coordinates to view-local
16731     * coordinates.
16732     *
16733     * @param ev the on-screen motion event
16734     * @return false if the transformation could not be applied
16735     * @hide
16736     */
16737    public boolean toLocalMotionEvent(MotionEvent ev) {
16738        final AttachInfo info = mAttachInfo;
16739        if (info == null) {
16740            return false;
16741        }
16742
16743        final Matrix m = info.mTmpMatrix;
16744        m.set(Matrix.IDENTITY_MATRIX);
16745        transformMatrixToLocal(m);
16746        ev.transform(m);
16747        return true;
16748    }
16749
16750    /**
16751     * Modifies the input matrix such that it maps view-local coordinates to
16752     * on-screen coordinates.
16753     *
16754     * @param m input matrix to modify
16755     * @hide
16756     */
16757    public void transformMatrixToGlobal(Matrix m) {
16758        final ViewParent parent = mParent;
16759        if (parent instanceof View) {
16760            final View vp = (View) parent;
16761            vp.transformMatrixToGlobal(m);
16762            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16763        } else if (parent instanceof ViewRootImpl) {
16764            final ViewRootImpl vr = (ViewRootImpl) parent;
16765            vr.transformMatrixToGlobal(m);
16766            m.preTranslate(0, -vr.mCurScrollY);
16767        }
16768
16769        m.preTranslate(mLeft, mTop);
16770
16771        if (!hasIdentityMatrix()) {
16772            m.preConcat(getMatrix());
16773        }
16774    }
16775
16776    /**
16777     * Modifies the input matrix such that it maps on-screen coordinates to
16778     * view-local coordinates.
16779     *
16780     * @param m input matrix to modify
16781     * @hide
16782     */
16783    public void transformMatrixToLocal(Matrix m) {
16784        final ViewParent parent = mParent;
16785        if (parent instanceof View) {
16786            final View vp = (View) parent;
16787            vp.transformMatrixToLocal(m);
16788            m.postTranslate(vp.mScrollX, vp.mScrollY);
16789        } else if (parent instanceof ViewRootImpl) {
16790            final ViewRootImpl vr = (ViewRootImpl) parent;
16791            vr.transformMatrixToLocal(m);
16792            m.postTranslate(0, vr.mCurScrollY);
16793        }
16794
16795        m.postTranslate(-mLeft, -mTop);
16796
16797        if (!hasIdentityMatrix()) {
16798            m.postConcat(getInverseMatrix());
16799        }
16800    }
16801
16802    /**
16803     * @hide
16804     */
16805    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16806            @ViewDebug.IntToString(from = 0, to = "x"),
16807            @ViewDebug.IntToString(from = 1, to = "y")
16808    })
16809    public int[] getLocationOnScreen() {
16810        int[] location = new int[2];
16811        getLocationOnScreen(location);
16812        return location;
16813    }
16814
16815    /**
16816     * <p>Computes the coordinates of this view on the screen. The argument
16817     * must be an array of two integers. After the method returns, the array
16818     * contains the x and y location in that order.</p>
16819     *
16820     * @param location an array of two integers in which to hold the coordinates
16821     */
16822    public void getLocationOnScreen(int[] location) {
16823        getLocationInWindow(location);
16824
16825        final AttachInfo info = mAttachInfo;
16826        if (info != null) {
16827            location[0] += info.mWindowLeft;
16828            location[1] += info.mWindowTop;
16829        }
16830    }
16831
16832    /**
16833     * <p>Computes the coordinates of this view in its window. The argument
16834     * must be an array of two integers. After the method returns, the array
16835     * contains the x and y location in that order.</p>
16836     *
16837     * @param location an array of two integers in which to hold the coordinates
16838     */
16839    public void getLocationInWindow(int[] location) {
16840        if (location == null || location.length < 2) {
16841            throw new IllegalArgumentException("location must be an array of two integers");
16842        }
16843
16844        if (mAttachInfo == null) {
16845            // When the view is not attached to a window, this method does not make sense
16846            location[0] = location[1] = 0;
16847            return;
16848        }
16849
16850        float[] position = mAttachInfo.mTmpTransformLocation;
16851        position[0] = position[1] = 0.0f;
16852
16853        if (!hasIdentityMatrix()) {
16854            getMatrix().mapPoints(position);
16855        }
16856
16857        position[0] += mLeft;
16858        position[1] += mTop;
16859
16860        ViewParent viewParent = mParent;
16861        while (viewParent instanceof View) {
16862            final View view = (View) viewParent;
16863
16864            position[0] -= view.mScrollX;
16865            position[1] -= view.mScrollY;
16866
16867            if (!view.hasIdentityMatrix()) {
16868                view.getMatrix().mapPoints(position);
16869            }
16870
16871            position[0] += view.mLeft;
16872            position[1] += view.mTop;
16873
16874            viewParent = view.mParent;
16875         }
16876
16877        if (viewParent instanceof ViewRootImpl) {
16878            // *cough*
16879            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16880            position[1] -= vr.mCurScrollY;
16881        }
16882
16883        location[0] = (int) (position[0] + 0.5f);
16884        location[1] = (int) (position[1] + 0.5f);
16885    }
16886
16887    /**
16888     * {@hide}
16889     * @param id the id of the view to be found
16890     * @return the view of the specified id, null if cannot be found
16891     */
16892    protected View findViewTraversal(int id) {
16893        if (id == mID) {
16894            return this;
16895        }
16896        return null;
16897    }
16898
16899    /**
16900     * {@hide}
16901     * @param tag the tag of the view to be found
16902     * @return the view of specified tag, null if cannot be found
16903     */
16904    protected View findViewWithTagTraversal(Object tag) {
16905        if (tag != null && tag.equals(mTag)) {
16906            return this;
16907        }
16908        return null;
16909    }
16910
16911    /**
16912     * {@hide}
16913     * @param predicate The predicate to evaluate.
16914     * @param childToSkip If not null, ignores this child during the recursive traversal.
16915     * @return The first view that matches the predicate or null.
16916     */
16917    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16918        if (predicate.apply(this)) {
16919            return this;
16920        }
16921        return null;
16922    }
16923
16924    /**
16925     * Look for a child view with the given id.  If this view has the given
16926     * id, return this view.
16927     *
16928     * @param id The id to search for.
16929     * @return The view that has the given id in the hierarchy or null
16930     */
16931    public final View findViewById(int id) {
16932        if (id < 0) {
16933            return null;
16934        }
16935        return findViewTraversal(id);
16936    }
16937
16938    /**
16939     * Finds a view by its unuque and stable accessibility id.
16940     *
16941     * @param accessibilityId The searched accessibility id.
16942     * @return The found view.
16943     */
16944    final View findViewByAccessibilityId(int accessibilityId) {
16945        if (accessibilityId < 0) {
16946            return null;
16947        }
16948        return findViewByAccessibilityIdTraversal(accessibilityId);
16949    }
16950
16951    /**
16952     * Performs the traversal to find a view by its unuque and stable accessibility id.
16953     *
16954     * <strong>Note:</strong>This method does not stop at the root namespace
16955     * boundary since the user can touch the screen at an arbitrary location
16956     * potentially crossing the root namespace bounday which will send an
16957     * accessibility event to accessibility services and they should be able
16958     * to obtain the event source. Also accessibility ids are guaranteed to be
16959     * unique in the window.
16960     *
16961     * @param accessibilityId The accessibility id.
16962     * @return The found view.
16963     *
16964     * @hide
16965     */
16966    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16967        if (getAccessibilityViewId() == accessibilityId) {
16968            return this;
16969        }
16970        return null;
16971    }
16972
16973    /**
16974     * Look for a child view with the given tag.  If this view has the given
16975     * tag, return this view.
16976     *
16977     * @param tag The tag to search for, using "tag.equals(getTag())".
16978     * @return The View that has the given tag in the hierarchy or null
16979     */
16980    public final View findViewWithTag(Object tag) {
16981        if (tag == null) {
16982            return null;
16983        }
16984        return findViewWithTagTraversal(tag);
16985    }
16986
16987    /**
16988     * {@hide}
16989     * Look for a child view that matches the specified predicate.
16990     * If this view matches the predicate, return this view.
16991     *
16992     * @param predicate The predicate to evaluate.
16993     * @return The first view that matches the predicate or null.
16994     */
16995    public final View findViewByPredicate(Predicate<View> predicate) {
16996        return findViewByPredicateTraversal(predicate, null);
16997    }
16998
16999    /**
17000     * {@hide}
17001     * Look for a child view that matches the specified predicate,
17002     * starting with the specified view and its descendents and then
17003     * recusively searching the ancestors and siblings of that view
17004     * until this view is reached.
17005     *
17006     * This method is useful in cases where the predicate does not match
17007     * a single unique view (perhaps multiple views use the same id)
17008     * and we are trying to find the view that is "closest" in scope to the
17009     * starting view.
17010     *
17011     * @param start The view to start from.
17012     * @param predicate The predicate to evaluate.
17013     * @return The first view that matches the predicate or null.
17014     */
17015    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17016        View childToSkip = null;
17017        for (;;) {
17018            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17019            if (view != null || start == this) {
17020                return view;
17021            }
17022
17023            ViewParent parent = start.getParent();
17024            if (parent == null || !(parent instanceof View)) {
17025                return null;
17026            }
17027
17028            childToSkip = start;
17029            start = (View) parent;
17030        }
17031    }
17032
17033    /**
17034     * Sets the identifier for this view. The identifier does not have to be
17035     * unique in this view's hierarchy. The identifier should be a positive
17036     * number.
17037     *
17038     * @see #NO_ID
17039     * @see #getId()
17040     * @see #findViewById(int)
17041     *
17042     * @param id a number used to identify the view
17043     *
17044     * @attr ref android.R.styleable#View_id
17045     */
17046    public void setId(int id) {
17047        mID = id;
17048        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17049            mID = generateViewId();
17050        }
17051    }
17052
17053    /**
17054     * {@hide}
17055     *
17056     * @param isRoot true if the view belongs to the root namespace, false
17057     *        otherwise
17058     */
17059    public void setIsRootNamespace(boolean isRoot) {
17060        if (isRoot) {
17061            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17062        } else {
17063            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17064        }
17065    }
17066
17067    /**
17068     * {@hide}
17069     *
17070     * @return true if the view belongs to the root namespace, false otherwise
17071     */
17072    public boolean isRootNamespace() {
17073        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17074    }
17075
17076    /**
17077     * Returns this view's identifier.
17078     *
17079     * @return a positive integer used to identify the view or {@link #NO_ID}
17080     *         if the view has no ID
17081     *
17082     * @see #setId(int)
17083     * @see #findViewById(int)
17084     * @attr ref android.R.styleable#View_id
17085     */
17086    @ViewDebug.CapturedViewProperty
17087    public int getId() {
17088        return mID;
17089    }
17090
17091    /**
17092     * Returns this view's tag.
17093     *
17094     * @return the Object stored in this view as a tag, or {@code null} if not
17095     *         set
17096     *
17097     * @see #setTag(Object)
17098     * @see #getTag(int)
17099     */
17100    @ViewDebug.ExportedProperty
17101    public Object getTag() {
17102        return mTag;
17103    }
17104
17105    /**
17106     * Sets the tag associated with this view. A tag can be used to mark
17107     * a view in its hierarchy and does not have to be unique within the
17108     * hierarchy. Tags can also be used to store data within a view without
17109     * resorting to another data structure.
17110     *
17111     * @param tag an Object to tag the view with
17112     *
17113     * @see #getTag()
17114     * @see #setTag(int, Object)
17115     */
17116    public void setTag(final Object tag) {
17117        mTag = tag;
17118    }
17119
17120    /**
17121     * Returns the tag associated with this view and the specified key.
17122     *
17123     * @param key The key identifying the tag
17124     *
17125     * @return the Object stored in this view as a tag, or {@code null} if not
17126     *         set
17127     *
17128     * @see #setTag(int, Object)
17129     * @see #getTag()
17130     */
17131    public Object getTag(int key) {
17132        if (mKeyedTags != null) return mKeyedTags.get(key);
17133        return null;
17134    }
17135
17136    /**
17137     * Sets a tag associated with this view and a key. A tag can be used
17138     * to mark a view in its hierarchy and does not have to be unique within
17139     * the hierarchy. Tags can also be used to store data within a view
17140     * without resorting to another data structure.
17141     *
17142     * The specified key should be an id declared in the resources of the
17143     * application to ensure it is unique (see the <a
17144     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17145     * Keys identified as belonging to
17146     * the Android framework or not associated with any package will cause
17147     * an {@link IllegalArgumentException} to be thrown.
17148     *
17149     * @param key The key identifying the tag
17150     * @param tag An Object to tag the view with
17151     *
17152     * @throws IllegalArgumentException If they specified key is not valid
17153     *
17154     * @see #setTag(Object)
17155     * @see #getTag(int)
17156     */
17157    public void setTag(int key, final Object tag) {
17158        // If the package id is 0x00 or 0x01, it's either an undefined package
17159        // or a framework id
17160        if ((key >>> 24) < 2) {
17161            throw new IllegalArgumentException("The key must be an application-specific "
17162                    + "resource id.");
17163        }
17164
17165        setKeyedTag(key, tag);
17166    }
17167
17168    /**
17169     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17170     * framework id.
17171     *
17172     * @hide
17173     */
17174    public void setTagInternal(int key, Object tag) {
17175        if ((key >>> 24) != 0x1) {
17176            throw new IllegalArgumentException("The key must be a framework-specific "
17177                    + "resource id.");
17178        }
17179
17180        setKeyedTag(key, tag);
17181    }
17182
17183    private void setKeyedTag(int key, Object tag) {
17184        if (mKeyedTags == null) {
17185            mKeyedTags = new SparseArray<Object>(2);
17186        }
17187
17188        mKeyedTags.put(key, tag);
17189    }
17190
17191    /**
17192     * Prints information about this view in the log output, with the tag
17193     * {@link #VIEW_LOG_TAG}.
17194     *
17195     * @hide
17196     */
17197    public void debug() {
17198        debug(0);
17199    }
17200
17201    /**
17202     * Prints information about this view in the log output, with the tag
17203     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17204     * indentation defined by the <code>depth</code>.
17205     *
17206     * @param depth the indentation level
17207     *
17208     * @hide
17209     */
17210    protected void debug(int depth) {
17211        String output = debugIndent(depth - 1);
17212
17213        output += "+ " + this;
17214        int id = getId();
17215        if (id != -1) {
17216            output += " (id=" + id + ")";
17217        }
17218        Object tag = getTag();
17219        if (tag != null) {
17220            output += " (tag=" + tag + ")";
17221        }
17222        Log.d(VIEW_LOG_TAG, output);
17223
17224        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17225            output = debugIndent(depth) + " FOCUSED";
17226            Log.d(VIEW_LOG_TAG, output);
17227        }
17228
17229        output = debugIndent(depth);
17230        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17231                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17232                + "} ";
17233        Log.d(VIEW_LOG_TAG, output);
17234
17235        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17236                || mPaddingBottom != 0) {
17237            output = debugIndent(depth);
17238            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17239                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17240            Log.d(VIEW_LOG_TAG, output);
17241        }
17242
17243        output = debugIndent(depth);
17244        output += "mMeasureWidth=" + mMeasuredWidth +
17245                " mMeasureHeight=" + mMeasuredHeight;
17246        Log.d(VIEW_LOG_TAG, output);
17247
17248        output = debugIndent(depth);
17249        if (mLayoutParams == null) {
17250            output += "BAD! no layout params";
17251        } else {
17252            output = mLayoutParams.debug(output);
17253        }
17254        Log.d(VIEW_LOG_TAG, output);
17255
17256        output = debugIndent(depth);
17257        output += "flags={";
17258        output += View.printFlags(mViewFlags);
17259        output += "}";
17260        Log.d(VIEW_LOG_TAG, output);
17261
17262        output = debugIndent(depth);
17263        output += "privateFlags={";
17264        output += View.printPrivateFlags(mPrivateFlags);
17265        output += "}";
17266        Log.d(VIEW_LOG_TAG, output);
17267    }
17268
17269    /**
17270     * Creates a string of whitespaces used for indentation.
17271     *
17272     * @param depth the indentation level
17273     * @return a String containing (depth * 2 + 3) * 2 white spaces
17274     *
17275     * @hide
17276     */
17277    protected static String debugIndent(int depth) {
17278        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17279        for (int i = 0; i < (depth * 2) + 3; i++) {
17280            spaces.append(' ').append(' ');
17281        }
17282        return spaces.toString();
17283    }
17284
17285    /**
17286     * <p>Return the offset of the widget's text baseline from the widget's top
17287     * boundary. If this widget does not support baseline alignment, this
17288     * method returns -1. </p>
17289     *
17290     * @return the offset of the baseline within the widget's bounds or -1
17291     *         if baseline alignment is not supported
17292     */
17293    @ViewDebug.ExportedProperty(category = "layout")
17294    public int getBaseline() {
17295        return -1;
17296    }
17297
17298    /**
17299     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17300     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17301     * a layout pass.
17302     *
17303     * @return whether the view hierarchy is currently undergoing a layout pass
17304     */
17305    public boolean isInLayout() {
17306        ViewRootImpl viewRoot = getViewRootImpl();
17307        return (viewRoot != null && viewRoot.isInLayout());
17308    }
17309
17310    /**
17311     * Call this when something has changed which has invalidated the
17312     * layout of this view. This will schedule a layout pass of the view
17313     * tree. This should not be called while the view hierarchy is currently in a layout
17314     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17315     * end of the current layout pass (and then layout will run again) or after the current
17316     * frame is drawn and the next layout occurs.
17317     *
17318     * <p>Subclasses which override this method should call the superclass method to
17319     * handle possible request-during-layout errors correctly.</p>
17320     */
17321    public void requestLayout() {
17322        if (mMeasureCache != null) mMeasureCache.clear();
17323
17324        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17325            // Only trigger request-during-layout logic if this is the view requesting it,
17326            // not the views in its parent hierarchy
17327            ViewRootImpl viewRoot = getViewRootImpl();
17328            if (viewRoot != null && viewRoot.isInLayout()) {
17329                if (!viewRoot.requestLayoutDuringLayout(this)) {
17330                    return;
17331                }
17332            }
17333            mAttachInfo.mViewRequestingLayout = this;
17334        }
17335
17336        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17337        mPrivateFlags |= PFLAG_INVALIDATED;
17338
17339        if (mParent != null && !mParent.isLayoutRequested()) {
17340            mParent.requestLayout();
17341        }
17342        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17343            mAttachInfo.mViewRequestingLayout = null;
17344        }
17345    }
17346
17347    /**
17348     * Forces this view to be laid out during the next layout pass.
17349     * This method does not call requestLayout() or forceLayout()
17350     * on the parent.
17351     */
17352    public void forceLayout() {
17353        if (mMeasureCache != null) mMeasureCache.clear();
17354
17355        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17356        mPrivateFlags |= PFLAG_INVALIDATED;
17357    }
17358
17359    /**
17360     * <p>
17361     * This is called to find out how big a view should be. The parent
17362     * supplies constraint information in the width and height parameters.
17363     * </p>
17364     *
17365     * <p>
17366     * The actual measurement work of a view is performed in
17367     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17368     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17369     * </p>
17370     *
17371     *
17372     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17373     *        parent
17374     * @param heightMeasureSpec Vertical space requirements as imposed by the
17375     *        parent
17376     *
17377     * @see #onMeasure(int, int)
17378     */
17379    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17380        boolean optical = isLayoutModeOptical(this);
17381        if (optical != isLayoutModeOptical(mParent)) {
17382            Insets insets = getOpticalInsets();
17383            int oWidth  = insets.left + insets.right;
17384            int oHeight = insets.top  + insets.bottom;
17385            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17386            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17387        }
17388
17389        // Suppress sign extension for the low bytes
17390        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17391        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17392
17393        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17394        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
17395                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
17396        final boolean matchingSize = isExactly &&
17397                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
17398                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
17399        if (forceLayout || !matchingSize &&
17400                (widthMeasureSpec != mOldWidthMeasureSpec ||
17401                        heightMeasureSpec != mOldHeightMeasureSpec)) {
17402
17403            // first clears the measured dimension flag
17404            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17405
17406            resolveRtlPropertiesIfNeeded();
17407
17408            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
17409            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17410                // measure ourselves, this should set the measured dimension flag back
17411                onMeasure(widthMeasureSpec, heightMeasureSpec);
17412                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17413            } else {
17414                long value = mMeasureCache.valueAt(cacheIndex);
17415                // Casting a long to int drops the high 32 bits, no mask needed
17416                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17417                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17418            }
17419
17420            // flag not set, setMeasuredDimension() was not invoked, we raise
17421            // an exception to warn the developer
17422            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17423                throw new IllegalStateException("onMeasure() did not set the"
17424                        + " measured dimension by calling"
17425                        + " setMeasuredDimension()");
17426            }
17427
17428            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17429        }
17430
17431        mOldWidthMeasureSpec = widthMeasureSpec;
17432        mOldHeightMeasureSpec = heightMeasureSpec;
17433
17434        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17435                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17436    }
17437
17438    /**
17439     * <p>
17440     * Measure the view and its content to determine the measured width and the
17441     * measured height. This method is invoked by {@link #measure(int, int)} and
17442     * should be overriden by subclasses to provide accurate and efficient
17443     * measurement of their contents.
17444     * </p>
17445     *
17446     * <p>
17447     * <strong>CONTRACT:</strong> When overriding this method, you
17448     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17449     * measured width and height of this view. Failure to do so will trigger an
17450     * <code>IllegalStateException</code>, thrown by
17451     * {@link #measure(int, int)}. Calling the superclass'
17452     * {@link #onMeasure(int, int)} is a valid use.
17453     * </p>
17454     *
17455     * <p>
17456     * The base class implementation of measure defaults to the background size,
17457     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17458     * override {@link #onMeasure(int, int)} to provide better measurements of
17459     * their content.
17460     * </p>
17461     *
17462     * <p>
17463     * If this method is overridden, it is the subclass's responsibility to make
17464     * sure the measured height and width are at least the view's minimum height
17465     * and width ({@link #getSuggestedMinimumHeight()} and
17466     * {@link #getSuggestedMinimumWidth()}).
17467     * </p>
17468     *
17469     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17470     *                         The requirements are encoded with
17471     *                         {@link android.view.View.MeasureSpec}.
17472     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17473     *                         The requirements are encoded with
17474     *                         {@link android.view.View.MeasureSpec}.
17475     *
17476     * @see #getMeasuredWidth()
17477     * @see #getMeasuredHeight()
17478     * @see #setMeasuredDimension(int, int)
17479     * @see #getSuggestedMinimumHeight()
17480     * @see #getSuggestedMinimumWidth()
17481     * @see android.view.View.MeasureSpec#getMode(int)
17482     * @see android.view.View.MeasureSpec#getSize(int)
17483     */
17484    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17485        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17486                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17487    }
17488
17489    /**
17490     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17491     * measured width and measured height. Failing to do so will trigger an
17492     * exception at measurement time.</p>
17493     *
17494     * @param measuredWidth The measured width of this view.  May be a complex
17495     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17496     * {@link #MEASURED_STATE_TOO_SMALL}.
17497     * @param measuredHeight The measured height of this view.  May be a complex
17498     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17499     * {@link #MEASURED_STATE_TOO_SMALL}.
17500     */
17501    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17502        boolean optical = isLayoutModeOptical(this);
17503        if (optical != isLayoutModeOptical(mParent)) {
17504            Insets insets = getOpticalInsets();
17505            int opticalWidth  = insets.left + insets.right;
17506            int opticalHeight = insets.top  + insets.bottom;
17507
17508            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17509            measuredHeight += optical ? opticalHeight : -opticalHeight;
17510        }
17511        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17512    }
17513
17514    /**
17515     * Sets the measured dimension without extra processing for things like optical bounds.
17516     * Useful for reapplying consistent values that have already been cooked with adjustments
17517     * for optical bounds, etc. such as those from the measurement cache.
17518     *
17519     * @param measuredWidth The measured width of this view.  May be a complex
17520     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17521     * {@link #MEASURED_STATE_TOO_SMALL}.
17522     * @param measuredHeight The measured height of this view.  May be a complex
17523     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17524     * {@link #MEASURED_STATE_TOO_SMALL}.
17525     */
17526    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17527        mMeasuredWidth = measuredWidth;
17528        mMeasuredHeight = measuredHeight;
17529
17530        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17531    }
17532
17533    /**
17534     * Merge two states as returned by {@link #getMeasuredState()}.
17535     * @param curState The current state as returned from a view or the result
17536     * of combining multiple views.
17537     * @param newState The new view state to combine.
17538     * @return Returns a new integer reflecting the combination of the two
17539     * states.
17540     */
17541    public static int combineMeasuredStates(int curState, int newState) {
17542        return curState | newState;
17543    }
17544
17545    /**
17546     * Version of {@link #resolveSizeAndState(int, int, int)}
17547     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17548     */
17549    public static int resolveSize(int size, int measureSpec) {
17550        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17551    }
17552
17553    /**
17554     * Utility to reconcile a desired size and state, with constraints imposed
17555     * by a MeasureSpec.  Will take the desired size, unless a different size
17556     * is imposed by the constraints.  The returned value is a compound integer,
17557     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17558     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17559     * size is smaller than the size the view wants to be.
17560     *
17561     * @param size How big the view wants to be
17562     * @param measureSpec Constraints imposed by the parent
17563     * @return Size information bit mask as defined by
17564     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17565     */
17566    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17567        int result = size;
17568        int specMode = MeasureSpec.getMode(measureSpec);
17569        int specSize =  MeasureSpec.getSize(measureSpec);
17570        switch (specMode) {
17571        case MeasureSpec.UNSPECIFIED:
17572            result = size;
17573            break;
17574        case MeasureSpec.AT_MOST:
17575            if (specSize < size) {
17576                result = specSize | MEASURED_STATE_TOO_SMALL;
17577            } else {
17578                result = size;
17579            }
17580            break;
17581        case MeasureSpec.EXACTLY:
17582            result = specSize;
17583            break;
17584        }
17585        return result | (childMeasuredState&MEASURED_STATE_MASK);
17586    }
17587
17588    /**
17589     * Utility to return a default size. Uses the supplied size if the
17590     * MeasureSpec imposed no constraints. Will get larger if allowed
17591     * by the MeasureSpec.
17592     *
17593     * @param size Default size for this view
17594     * @param measureSpec Constraints imposed by the parent
17595     * @return The size this view should be.
17596     */
17597    public static int getDefaultSize(int size, int measureSpec) {
17598        int result = size;
17599        int specMode = MeasureSpec.getMode(measureSpec);
17600        int specSize = MeasureSpec.getSize(measureSpec);
17601
17602        switch (specMode) {
17603        case MeasureSpec.UNSPECIFIED:
17604            result = size;
17605            break;
17606        case MeasureSpec.AT_MOST:
17607        case MeasureSpec.EXACTLY:
17608            result = specSize;
17609            break;
17610        }
17611        return result;
17612    }
17613
17614    /**
17615     * Returns the suggested minimum height that the view should use. This
17616     * returns the maximum of the view's minimum height
17617     * and the background's minimum height
17618     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17619     * <p>
17620     * When being used in {@link #onMeasure(int, int)}, the caller should still
17621     * ensure the returned height is within the requirements of the parent.
17622     *
17623     * @return The suggested minimum height of the view.
17624     */
17625    protected int getSuggestedMinimumHeight() {
17626        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17627
17628    }
17629
17630    /**
17631     * Returns the suggested minimum width that the view should use. This
17632     * returns the maximum of the view's minimum width)
17633     * and the background's minimum width
17634     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17635     * <p>
17636     * When being used in {@link #onMeasure(int, int)}, the caller should still
17637     * ensure the returned width is within the requirements of the parent.
17638     *
17639     * @return The suggested minimum width of the view.
17640     */
17641    protected int getSuggestedMinimumWidth() {
17642        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17643    }
17644
17645    /**
17646     * Returns the minimum height of the view.
17647     *
17648     * @return the minimum height the view will try to be.
17649     *
17650     * @see #setMinimumHeight(int)
17651     *
17652     * @attr ref android.R.styleable#View_minHeight
17653     */
17654    public int getMinimumHeight() {
17655        return mMinHeight;
17656    }
17657
17658    /**
17659     * Sets the minimum height of the view. It is not guaranteed the view will
17660     * be able to achieve this minimum height (for example, if its parent layout
17661     * constrains it with less available height).
17662     *
17663     * @param minHeight The minimum height the view will try to be.
17664     *
17665     * @see #getMinimumHeight()
17666     *
17667     * @attr ref android.R.styleable#View_minHeight
17668     */
17669    public void setMinimumHeight(int minHeight) {
17670        mMinHeight = minHeight;
17671        requestLayout();
17672    }
17673
17674    /**
17675     * Returns the minimum width of the view.
17676     *
17677     * @return the minimum width the view will try to be.
17678     *
17679     * @see #setMinimumWidth(int)
17680     *
17681     * @attr ref android.R.styleable#View_minWidth
17682     */
17683    public int getMinimumWidth() {
17684        return mMinWidth;
17685    }
17686
17687    /**
17688     * Sets the minimum width of the view. It is not guaranteed the view will
17689     * be able to achieve this minimum width (for example, if its parent layout
17690     * constrains it with less available width).
17691     *
17692     * @param minWidth The minimum width the view will try to be.
17693     *
17694     * @see #getMinimumWidth()
17695     *
17696     * @attr ref android.R.styleable#View_minWidth
17697     */
17698    public void setMinimumWidth(int minWidth) {
17699        mMinWidth = minWidth;
17700        requestLayout();
17701
17702    }
17703
17704    /**
17705     * Get the animation currently associated with this view.
17706     *
17707     * @return The animation that is currently playing or
17708     *         scheduled to play for this view.
17709     */
17710    public Animation getAnimation() {
17711        return mCurrentAnimation;
17712    }
17713
17714    /**
17715     * Start the specified animation now.
17716     *
17717     * @param animation the animation to start now
17718     */
17719    public void startAnimation(Animation animation) {
17720        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17721        setAnimation(animation);
17722        invalidateParentCaches();
17723        invalidate(true);
17724    }
17725
17726    /**
17727     * Cancels any animations for this view.
17728     */
17729    public void clearAnimation() {
17730        if (mCurrentAnimation != null) {
17731            mCurrentAnimation.detach();
17732        }
17733        mCurrentAnimation = null;
17734        invalidateParentIfNeeded();
17735    }
17736
17737    /**
17738     * Sets the next animation to play for this view.
17739     * If you want the animation to play immediately, use
17740     * {@link #startAnimation(android.view.animation.Animation)} instead.
17741     * This method provides allows fine-grained
17742     * control over the start time and invalidation, but you
17743     * must make sure that 1) the animation has a start time set, and
17744     * 2) the view's parent (which controls animations on its children)
17745     * will be invalidated when the animation is supposed to
17746     * start.
17747     *
17748     * @param animation The next animation, or null.
17749     */
17750    public void setAnimation(Animation animation) {
17751        mCurrentAnimation = animation;
17752
17753        if (animation != null) {
17754            // If the screen is off assume the animation start time is now instead of
17755            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17756            // would cause the animation to start when the screen turns back on
17757            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17758                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17759                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17760            }
17761            animation.reset();
17762        }
17763    }
17764
17765    /**
17766     * Invoked by a parent ViewGroup to notify the start of the animation
17767     * currently associated with this view. If you override this method,
17768     * always call super.onAnimationStart();
17769     *
17770     * @see #setAnimation(android.view.animation.Animation)
17771     * @see #getAnimation()
17772     */
17773    protected void onAnimationStart() {
17774        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17775    }
17776
17777    /**
17778     * Invoked by a parent ViewGroup to notify the end of the animation
17779     * currently associated with this view. If you override this method,
17780     * always call super.onAnimationEnd();
17781     *
17782     * @see #setAnimation(android.view.animation.Animation)
17783     * @see #getAnimation()
17784     */
17785    protected void onAnimationEnd() {
17786        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17787    }
17788
17789    /**
17790     * Invoked if there is a Transform that involves alpha. Subclass that can
17791     * draw themselves with the specified alpha should return true, and then
17792     * respect that alpha when their onDraw() is called. If this returns false
17793     * then the view may be redirected to draw into an offscreen buffer to
17794     * fulfill the request, which will look fine, but may be slower than if the
17795     * subclass handles it internally. The default implementation returns false.
17796     *
17797     * @param alpha The alpha (0..255) to apply to the view's drawing
17798     * @return true if the view can draw with the specified alpha.
17799     */
17800    protected boolean onSetAlpha(int alpha) {
17801        return false;
17802    }
17803
17804    /**
17805     * This is used by the RootView to perform an optimization when
17806     * the view hierarchy contains one or several SurfaceView.
17807     * SurfaceView is always considered transparent, but its children are not,
17808     * therefore all View objects remove themselves from the global transparent
17809     * region (passed as a parameter to this function).
17810     *
17811     * @param region The transparent region for this ViewAncestor (window).
17812     *
17813     * @return Returns true if the effective visibility of the view at this
17814     * point is opaque, regardless of the transparent region; returns false
17815     * if it is possible for underlying windows to be seen behind the view.
17816     *
17817     * {@hide}
17818     */
17819    public boolean gatherTransparentRegion(Region region) {
17820        final AttachInfo attachInfo = mAttachInfo;
17821        if (region != null && attachInfo != null) {
17822            final int pflags = mPrivateFlags;
17823            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17824                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17825                // remove it from the transparent region.
17826                final int[] location = attachInfo.mTransparentLocation;
17827                getLocationInWindow(location);
17828                region.op(location[0], location[1], location[0] + mRight - mLeft,
17829                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17830            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17831                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17832                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17833                // exists, so we remove the background drawable's non-transparent
17834                // parts from this transparent region.
17835                applyDrawableToTransparentRegion(mBackground, region);
17836            }
17837        }
17838        return true;
17839    }
17840
17841    /**
17842     * Play a sound effect for this view.
17843     *
17844     * <p>The framework will play sound effects for some built in actions, such as
17845     * clicking, but you may wish to play these effects in your widget,
17846     * for instance, for internal navigation.
17847     *
17848     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17849     * {@link #isSoundEffectsEnabled()} is true.
17850     *
17851     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17852     */
17853    public void playSoundEffect(int soundConstant) {
17854        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17855            return;
17856        }
17857        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17858    }
17859
17860    /**
17861     * BZZZTT!!1!
17862     *
17863     * <p>Provide haptic feedback to the user for this view.
17864     *
17865     * <p>The framework will provide haptic feedback for some built in actions,
17866     * such as long presses, but you may wish to provide feedback for your
17867     * own widget.
17868     *
17869     * <p>The feedback will only be performed if
17870     * {@link #isHapticFeedbackEnabled()} is true.
17871     *
17872     * @param feedbackConstant One of the constants defined in
17873     * {@link HapticFeedbackConstants}
17874     */
17875    public boolean performHapticFeedback(int feedbackConstant) {
17876        return performHapticFeedback(feedbackConstant, 0);
17877    }
17878
17879    /**
17880     * BZZZTT!!1!
17881     *
17882     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17883     *
17884     * @param feedbackConstant One of the constants defined in
17885     * {@link HapticFeedbackConstants}
17886     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17887     */
17888    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17889        if (mAttachInfo == null) {
17890            return false;
17891        }
17892        //noinspection SimplifiableIfStatement
17893        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17894                && !isHapticFeedbackEnabled()) {
17895            return false;
17896        }
17897        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17898                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17899    }
17900
17901    /**
17902     * Request that the visibility of the status bar or other screen/window
17903     * decorations be changed.
17904     *
17905     * <p>This method is used to put the over device UI into temporary modes
17906     * where the user's attention is focused more on the application content,
17907     * by dimming or hiding surrounding system affordances.  This is typically
17908     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17909     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17910     * to be placed behind the action bar (and with these flags other system
17911     * affordances) so that smooth transitions between hiding and showing them
17912     * can be done.
17913     *
17914     * <p>Two representative examples of the use of system UI visibility is
17915     * implementing a content browsing application (like a magazine reader)
17916     * and a video playing application.
17917     *
17918     * <p>The first code shows a typical implementation of a View in a content
17919     * browsing application.  In this implementation, the application goes
17920     * into a content-oriented mode by hiding the status bar and action bar,
17921     * and putting the navigation elements into lights out mode.  The user can
17922     * then interact with content while in this mode.  Such an application should
17923     * provide an easy way for the user to toggle out of the mode (such as to
17924     * check information in the status bar or access notifications).  In the
17925     * implementation here, this is done simply by tapping on the content.
17926     *
17927     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17928     *      content}
17929     *
17930     * <p>This second code sample shows a typical implementation of a View
17931     * in a video playing application.  In this situation, while the video is
17932     * playing the application would like to go into a complete full-screen mode,
17933     * to use as much of the display as possible for the video.  When in this state
17934     * the user can not interact with the application; the system intercepts
17935     * touching on the screen to pop the UI out of full screen mode.  See
17936     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17937     *
17938     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17939     *      content}
17940     *
17941     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17942     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17943     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17944     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17945     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17946     */
17947    public void setSystemUiVisibility(int visibility) {
17948        if (visibility != mSystemUiVisibility) {
17949            mSystemUiVisibility = visibility;
17950            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17951                mParent.recomputeViewAttributes(this);
17952            }
17953        }
17954    }
17955
17956    /**
17957     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17958     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17959     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17960     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17961     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17962     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17963     */
17964    public int getSystemUiVisibility() {
17965        return mSystemUiVisibility;
17966    }
17967
17968    /**
17969     * Returns the current system UI visibility that is currently set for
17970     * the entire window.  This is the combination of the
17971     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17972     * views in the window.
17973     */
17974    public int getWindowSystemUiVisibility() {
17975        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17976    }
17977
17978    /**
17979     * Override to find out when the window's requested system UI visibility
17980     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17981     * This is different from the callbacks received through
17982     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17983     * in that this is only telling you about the local request of the window,
17984     * not the actual values applied by the system.
17985     */
17986    public void onWindowSystemUiVisibilityChanged(int visible) {
17987    }
17988
17989    /**
17990     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17991     * the view hierarchy.
17992     */
17993    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17994        onWindowSystemUiVisibilityChanged(visible);
17995    }
17996
17997    /**
17998     * Set a listener to receive callbacks when the visibility of the system bar changes.
17999     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18000     */
18001    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18002        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18003        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18004            mParent.recomputeViewAttributes(this);
18005        }
18006    }
18007
18008    /**
18009     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18010     * the view hierarchy.
18011     */
18012    public void dispatchSystemUiVisibilityChanged(int visibility) {
18013        ListenerInfo li = mListenerInfo;
18014        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18015            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18016                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18017        }
18018    }
18019
18020    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18021        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18022        if (val != mSystemUiVisibility) {
18023            setSystemUiVisibility(val);
18024            return true;
18025        }
18026        return false;
18027    }
18028
18029    /** @hide */
18030    public void setDisabledSystemUiVisibility(int flags) {
18031        if (mAttachInfo != null) {
18032            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18033                mAttachInfo.mDisabledSystemUiVisibility = flags;
18034                if (mParent != null) {
18035                    mParent.recomputeViewAttributes(this);
18036                }
18037            }
18038        }
18039    }
18040
18041    /**
18042     * Creates an image that the system displays during the drag and drop
18043     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18044     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18045     * appearance as the given View. The default also positions the center of the drag shadow
18046     * directly under the touch point. If no View is provided (the constructor with no parameters
18047     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18048     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
18049     * default is an invisible drag shadow.
18050     * <p>
18051     * You are not required to use the View you provide to the constructor as the basis of the
18052     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18053     * anything you want as the drag shadow.
18054     * </p>
18055     * <p>
18056     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18057     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18058     *  size and position of the drag shadow. It uses this data to construct a
18059     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18060     *  so that your application can draw the shadow image in the Canvas.
18061     * </p>
18062     *
18063     * <div class="special reference">
18064     * <h3>Developer Guides</h3>
18065     * <p>For a guide to implementing drag and drop features, read the
18066     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18067     * </div>
18068     */
18069    public static class DragShadowBuilder {
18070        private final WeakReference<View> mView;
18071
18072        /**
18073         * Constructs a shadow image builder based on a View. By default, the resulting drag
18074         * shadow will have the same appearance and dimensions as the View, with the touch point
18075         * over the center of the View.
18076         * @param view A View. Any View in scope can be used.
18077         */
18078        public DragShadowBuilder(View view) {
18079            mView = new WeakReference<View>(view);
18080        }
18081
18082        /**
18083         * Construct a shadow builder object with no associated View.  This
18084         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18085         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18086         * to supply the drag shadow's dimensions and appearance without
18087         * reference to any View object. If they are not overridden, then the result is an
18088         * invisible drag shadow.
18089         */
18090        public DragShadowBuilder() {
18091            mView = new WeakReference<View>(null);
18092        }
18093
18094        /**
18095         * Returns the View object that had been passed to the
18096         * {@link #View.DragShadowBuilder(View)}
18097         * constructor.  If that View parameter was {@code null} or if the
18098         * {@link #View.DragShadowBuilder()}
18099         * constructor was used to instantiate the builder object, this method will return
18100         * null.
18101         *
18102         * @return The View object associate with this builder object.
18103         */
18104        @SuppressWarnings({"JavadocReference"})
18105        final public View getView() {
18106            return mView.get();
18107        }
18108
18109        /**
18110         * Provides the metrics for the shadow image. These include the dimensions of
18111         * the shadow image, and the point within that shadow that should
18112         * be centered under the touch location while dragging.
18113         * <p>
18114         * The default implementation sets the dimensions of the shadow to be the
18115         * same as the dimensions of the View itself and centers the shadow under
18116         * the touch point.
18117         * </p>
18118         *
18119         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18120         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18121         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18122         * image.
18123         *
18124         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18125         * shadow image that should be underneath the touch point during the drag and drop
18126         * operation. Your application must set {@link android.graphics.Point#x} to the
18127         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18128         */
18129        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18130            final View view = mView.get();
18131            if (view != null) {
18132                shadowSize.set(view.getWidth(), view.getHeight());
18133                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18134            } else {
18135                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18136            }
18137        }
18138
18139        /**
18140         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18141         * based on the dimensions it received from the
18142         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18143         *
18144         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18145         */
18146        public void onDrawShadow(Canvas canvas) {
18147            final View view = mView.get();
18148            if (view != null) {
18149                view.draw(canvas);
18150            } else {
18151                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18152            }
18153        }
18154    }
18155
18156    /**
18157     * Starts a drag and drop operation. When your application calls this method, it passes a
18158     * {@link android.view.View.DragShadowBuilder} object to the system. The
18159     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18160     * to get metrics for the drag shadow, and then calls the object's
18161     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18162     * <p>
18163     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18164     *  drag events to all the View objects in your application that are currently visible. It does
18165     *  this either by calling the View object's drag listener (an implementation of
18166     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18167     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18168     *  Both are passed a {@link android.view.DragEvent} object that has a
18169     *  {@link android.view.DragEvent#getAction()} value of
18170     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18171     * </p>
18172     * <p>
18173     * Your application can invoke startDrag() on any attached View object. The View object does not
18174     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18175     * be related to the View the user selected for dragging.
18176     * </p>
18177     * @param data A {@link android.content.ClipData} object pointing to the data to be
18178     * transferred by the drag and drop operation.
18179     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
18180     * drag shadow.
18181     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
18182     * drop operation. This Object is put into every DragEvent object sent by the system during the
18183     * current drag.
18184     * <p>
18185     * myLocalState is a lightweight mechanism for the sending information from the dragged View
18186     * to the target Views. For example, it can contain flags that differentiate between a
18187     * a copy operation and a move operation.
18188     * </p>
18189     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
18190     * so the parameter should be set to 0.
18191     * @return {@code true} if the method completes successfully, or
18192     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
18193     * do a drag, and so no drag operation is in progress.
18194     */
18195    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18196            Object myLocalState, int flags) {
18197        if (ViewDebug.DEBUG_DRAG) {
18198            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18199        }
18200        boolean okay = false;
18201
18202        Point shadowSize = new Point();
18203        Point shadowTouchPoint = new Point();
18204        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18205
18206        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18207                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18208            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18209        }
18210
18211        if (ViewDebug.DEBUG_DRAG) {
18212            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18213                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18214        }
18215        Surface surface = new Surface();
18216        try {
18217            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18218                    flags, shadowSize.x, shadowSize.y, surface);
18219            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18220                    + " surface=" + surface);
18221            if (token != null) {
18222                Canvas canvas = surface.lockCanvas(null);
18223                try {
18224                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18225                    shadowBuilder.onDrawShadow(canvas);
18226                } finally {
18227                    surface.unlockCanvasAndPost(canvas);
18228                }
18229
18230                final ViewRootImpl root = getViewRootImpl();
18231
18232                // Cache the local state object for delivery with DragEvents
18233                root.setLocalDragState(myLocalState);
18234
18235                // repurpose 'shadowSize' for the last touch point
18236                root.getLastTouchPoint(shadowSize);
18237
18238                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18239                        shadowSize.x, shadowSize.y,
18240                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18241                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18242
18243                // Off and running!  Release our local surface instance; the drag
18244                // shadow surface is now managed by the system process.
18245                surface.release();
18246            }
18247        } catch (Exception e) {
18248            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18249            surface.destroy();
18250        }
18251
18252        return okay;
18253    }
18254
18255    /**
18256     * Handles drag events sent by the system following a call to
18257     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18258     *<p>
18259     * When the system calls this method, it passes a
18260     * {@link android.view.DragEvent} object. A call to
18261     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18262     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18263     * operation.
18264     * @param event The {@link android.view.DragEvent} sent by the system.
18265     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18266     * in DragEvent, indicating the type of drag event represented by this object.
18267     * @return {@code true} if the method was successful, otherwise {@code false}.
18268     * <p>
18269     *  The method should return {@code true} in response to an action type of
18270     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18271     *  operation.
18272     * </p>
18273     * <p>
18274     *  The method should also return {@code true} in response to an action type of
18275     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18276     *  {@code false} if it didn't.
18277     * </p>
18278     */
18279    public boolean onDragEvent(DragEvent event) {
18280        return false;
18281    }
18282
18283    /**
18284     * Detects if this View is enabled and has a drag event listener.
18285     * If both are true, then it calls the drag event listener with the
18286     * {@link android.view.DragEvent} it received. If the drag event listener returns
18287     * {@code true}, then dispatchDragEvent() returns {@code true}.
18288     * <p>
18289     * For all other cases, the method calls the
18290     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18291     * method and returns its result.
18292     * </p>
18293     * <p>
18294     * This ensures that a drag event is always consumed, even if the View does not have a drag
18295     * event listener. However, if the View has a listener and the listener returns true, then
18296     * onDragEvent() is not called.
18297     * </p>
18298     */
18299    public boolean dispatchDragEvent(DragEvent event) {
18300        ListenerInfo li = mListenerInfo;
18301        //noinspection SimplifiableIfStatement
18302        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18303                && li.mOnDragListener.onDrag(this, event)) {
18304            return true;
18305        }
18306        return onDragEvent(event);
18307    }
18308
18309    boolean canAcceptDrag() {
18310        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18311    }
18312
18313    /**
18314     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18315     * it is ever exposed at all.
18316     * @hide
18317     */
18318    public void onCloseSystemDialogs(String reason) {
18319    }
18320
18321    /**
18322     * Given a Drawable whose bounds have been set to draw into this view,
18323     * update a Region being computed for
18324     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18325     * that any non-transparent parts of the Drawable are removed from the
18326     * given transparent region.
18327     *
18328     * @param dr The Drawable whose transparency is to be applied to the region.
18329     * @param region A Region holding the current transparency information,
18330     * where any parts of the region that are set are considered to be
18331     * transparent.  On return, this region will be modified to have the
18332     * transparency information reduced by the corresponding parts of the
18333     * Drawable that are not transparent.
18334     * {@hide}
18335     */
18336    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18337        if (DBG) {
18338            Log.i("View", "Getting transparent region for: " + this);
18339        }
18340        final Region r = dr.getTransparentRegion();
18341        final Rect db = dr.getBounds();
18342        final AttachInfo attachInfo = mAttachInfo;
18343        if (r != null && attachInfo != null) {
18344            final int w = getRight()-getLeft();
18345            final int h = getBottom()-getTop();
18346            if (db.left > 0) {
18347                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18348                r.op(0, 0, db.left, h, Region.Op.UNION);
18349            }
18350            if (db.right < w) {
18351                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18352                r.op(db.right, 0, w, h, Region.Op.UNION);
18353            }
18354            if (db.top > 0) {
18355                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18356                r.op(0, 0, w, db.top, Region.Op.UNION);
18357            }
18358            if (db.bottom < h) {
18359                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18360                r.op(0, db.bottom, w, h, Region.Op.UNION);
18361            }
18362            final int[] location = attachInfo.mTransparentLocation;
18363            getLocationInWindow(location);
18364            r.translate(location[0], location[1]);
18365            region.op(r, Region.Op.INTERSECT);
18366        } else {
18367            region.op(db, Region.Op.DIFFERENCE);
18368        }
18369    }
18370
18371    private void checkForLongClick(int delayOffset) {
18372        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18373            mHasPerformedLongPress = false;
18374
18375            if (mPendingCheckForLongPress == null) {
18376                mPendingCheckForLongPress = new CheckForLongPress();
18377            }
18378            mPendingCheckForLongPress.rememberWindowAttachCount();
18379            postDelayed(mPendingCheckForLongPress,
18380                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18381        }
18382    }
18383
18384    /**
18385     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18386     * LayoutInflater} class, which provides a full range of options for view inflation.
18387     *
18388     * @param context The Context object for your activity or application.
18389     * @param resource The resource ID to inflate
18390     * @param root A view group that will be the parent.  Used to properly inflate the
18391     * layout_* parameters.
18392     * @see LayoutInflater
18393     */
18394    public static View inflate(Context context, int resource, ViewGroup root) {
18395        LayoutInflater factory = LayoutInflater.from(context);
18396        return factory.inflate(resource, root);
18397    }
18398
18399    /**
18400     * Scroll the view with standard behavior for scrolling beyond the normal
18401     * content boundaries. Views that call this method should override
18402     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18403     * results of an over-scroll operation.
18404     *
18405     * Views can use this method to handle any touch or fling-based scrolling.
18406     *
18407     * @param deltaX Change in X in pixels
18408     * @param deltaY Change in Y in pixels
18409     * @param scrollX Current X scroll value in pixels before applying deltaX
18410     * @param scrollY Current Y scroll value in pixels before applying deltaY
18411     * @param scrollRangeX Maximum content scroll range along the X axis
18412     * @param scrollRangeY Maximum content scroll range along the Y axis
18413     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18414     *          along the X axis.
18415     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18416     *          along the Y axis.
18417     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18418     * @return true if scrolling was clamped to an over-scroll boundary along either
18419     *          axis, false otherwise.
18420     */
18421    @SuppressWarnings({"UnusedParameters"})
18422    protected boolean overScrollBy(int deltaX, int deltaY,
18423            int scrollX, int scrollY,
18424            int scrollRangeX, int scrollRangeY,
18425            int maxOverScrollX, int maxOverScrollY,
18426            boolean isTouchEvent) {
18427        final int overScrollMode = mOverScrollMode;
18428        final boolean canScrollHorizontal =
18429                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18430        final boolean canScrollVertical =
18431                computeVerticalScrollRange() > computeVerticalScrollExtent();
18432        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18433                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18434        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18435                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18436
18437        int newScrollX = scrollX + deltaX;
18438        if (!overScrollHorizontal) {
18439            maxOverScrollX = 0;
18440        }
18441
18442        int newScrollY = scrollY + deltaY;
18443        if (!overScrollVertical) {
18444            maxOverScrollY = 0;
18445        }
18446
18447        // Clamp values if at the limits and record
18448        final int left = -maxOverScrollX;
18449        final int right = maxOverScrollX + scrollRangeX;
18450        final int top = -maxOverScrollY;
18451        final int bottom = maxOverScrollY + scrollRangeY;
18452
18453        boolean clampedX = false;
18454        if (newScrollX > right) {
18455            newScrollX = right;
18456            clampedX = true;
18457        } else if (newScrollX < left) {
18458            newScrollX = left;
18459            clampedX = true;
18460        }
18461
18462        boolean clampedY = false;
18463        if (newScrollY > bottom) {
18464            newScrollY = bottom;
18465            clampedY = true;
18466        } else if (newScrollY < top) {
18467            newScrollY = top;
18468            clampedY = true;
18469        }
18470
18471        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18472
18473        return clampedX || clampedY;
18474    }
18475
18476    /**
18477     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18478     * respond to the results of an over-scroll operation.
18479     *
18480     * @param scrollX New X scroll value in pixels
18481     * @param scrollY New Y scroll value in pixels
18482     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18483     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18484     */
18485    protected void onOverScrolled(int scrollX, int scrollY,
18486            boolean clampedX, boolean clampedY) {
18487        // Intentionally empty.
18488    }
18489
18490    /**
18491     * Returns the over-scroll mode for this view. The result will be
18492     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18493     * (allow over-scrolling only if the view content is larger than the container),
18494     * or {@link #OVER_SCROLL_NEVER}.
18495     *
18496     * @return This view's over-scroll mode.
18497     */
18498    public int getOverScrollMode() {
18499        return mOverScrollMode;
18500    }
18501
18502    /**
18503     * Set the over-scroll mode for this view. Valid over-scroll modes are
18504     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18505     * (allow over-scrolling only if the view content is larger than the container),
18506     * or {@link #OVER_SCROLL_NEVER}.
18507     *
18508     * Setting the over-scroll mode of a view will have an effect only if the
18509     * view is capable of scrolling.
18510     *
18511     * @param overScrollMode The new over-scroll mode for this view.
18512     */
18513    public void setOverScrollMode(int overScrollMode) {
18514        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18515                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18516                overScrollMode != OVER_SCROLL_NEVER) {
18517            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18518        }
18519        mOverScrollMode = overScrollMode;
18520    }
18521
18522    /**
18523     * Enable or disable nested scrolling for this view.
18524     *
18525     * <p>If this property is set to true the view will be permitted to initiate nested
18526     * scrolling operations with a compatible parent view in the current hierarchy. If this
18527     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18528     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18529     * the nested scroll.</p>
18530     *
18531     * @param enabled true to enable nested scrolling, false to disable
18532     *
18533     * @see #isNestedScrollingEnabled()
18534     */
18535    public void setNestedScrollingEnabled(boolean enabled) {
18536        if (enabled) {
18537            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18538        } else {
18539            stopNestedScroll();
18540            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18541        }
18542    }
18543
18544    /**
18545     * Returns true if nested scrolling is enabled for this view.
18546     *
18547     * <p>If nested scrolling is enabled and this View class implementation supports it,
18548     * this view will act as a nested scrolling child view when applicable, forwarding data
18549     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18550     * parent.</p>
18551     *
18552     * @return true if nested scrolling is enabled
18553     *
18554     * @see #setNestedScrollingEnabled(boolean)
18555     */
18556    public boolean isNestedScrollingEnabled() {
18557        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18558                PFLAG3_NESTED_SCROLLING_ENABLED;
18559    }
18560
18561    /**
18562     * Begin a nestable scroll operation along the given axes.
18563     *
18564     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18565     *
18566     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18567     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18568     * In the case of touch scrolling the nested scroll will be terminated automatically in
18569     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18570     * In the event of programmatic scrolling the caller must explicitly call
18571     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18572     *
18573     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18574     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18575     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18576     *
18577     * <p>At each incremental step of the scroll the caller should invoke
18578     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18579     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18580     * parent at least partially consumed the scroll and the caller should adjust the amount it
18581     * scrolls by.</p>
18582     *
18583     * <p>After applying the remainder of the scroll delta the caller should invoke
18584     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18585     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18586     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18587     * </p>
18588     *
18589     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18590     *             {@link #SCROLL_AXIS_VERTICAL}.
18591     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18592     *         the current gesture.
18593     *
18594     * @see #stopNestedScroll()
18595     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18596     * @see #dispatchNestedScroll(int, int, int, int, int[])
18597     */
18598    public boolean startNestedScroll(int axes) {
18599        if (hasNestedScrollingParent()) {
18600            // Already in progress
18601            return true;
18602        }
18603        if (isNestedScrollingEnabled()) {
18604            ViewParent p = getParent();
18605            View child = this;
18606            while (p != null) {
18607                try {
18608                    if (p.onStartNestedScroll(child, this, axes)) {
18609                        mNestedScrollingParent = p;
18610                        p.onNestedScrollAccepted(child, this, axes);
18611                        return true;
18612                    }
18613                } catch (AbstractMethodError e) {
18614                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18615                            "method onStartNestedScroll", e);
18616                    // Allow the search upward to continue
18617                }
18618                if (p instanceof View) {
18619                    child = (View) p;
18620                }
18621                p = p.getParent();
18622            }
18623        }
18624        return false;
18625    }
18626
18627    /**
18628     * Stop a nested scroll in progress.
18629     *
18630     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18631     *
18632     * @see #startNestedScroll(int)
18633     */
18634    public void stopNestedScroll() {
18635        if (mNestedScrollingParent != null) {
18636            mNestedScrollingParent.onStopNestedScroll(this);
18637            mNestedScrollingParent = null;
18638        }
18639    }
18640
18641    /**
18642     * Returns true if this view has a nested scrolling parent.
18643     *
18644     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18645     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18646     *
18647     * @return whether this view has a nested scrolling parent
18648     */
18649    public boolean hasNestedScrollingParent() {
18650        return mNestedScrollingParent != null;
18651    }
18652
18653    /**
18654     * Dispatch one step of a nested scroll in progress.
18655     *
18656     * <p>Implementations of views that support nested scrolling should call this to report
18657     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18658     * is not currently in progress or nested scrolling is not
18659     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18660     *
18661     * <p>Compatible View implementations should also call
18662     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18663     * consuming a component of the scroll event themselves.</p>
18664     *
18665     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18666     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18667     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18668     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18669     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18670     *                       in local view coordinates of this view from before this operation
18671     *                       to after it completes. View implementations may use this to adjust
18672     *                       expected input coordinate tracking.
18673     * @return true if the event was dispatched, false if it could not be dispatched.
18674     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18675     */
18676    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18677            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18678        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18679            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18680                int startX = 0;
18681                int startY = 0;
18682                if (offsetInWindow != null) {
18683                    getLocationInWindow(offsetInWindow);
18684                    startX = offsetInWindow[0];
18685                    startY = offsetInWindow[1];
18686                }
18687
18688                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18689                        dxUnconsumed, dyUnconsumed);
18690
18691                if (offsetInWindow != null) {
18692                    getLocationInWindow(offsetInWindow);
18693                    offsetInWindow[0] -= startX;
18694                    offsetInWindow[1] -= startY;
18695                }
18696                return true;
18697            } else if (offsetInWindow != null) {
18698                // No motion, no dispatch. Keep offsetInWindow up to date.
18699                offsetInWindow[0] = 0;
18700                offsetInWindow[1] = 0;
18701            }
18702        }
18703        return false;
18704    }
18705
18706    /**
18707     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18708     *
18709     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18710     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18711     * scrolling operation to consume some or all of the scroll operation before the child view
18712     * consumes it.</p>
18713     *
18714     * @param dx Horizontal scroll distance in pixels
18715     * @param dy Vertical scroll distance in pixels
18716     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18717     *                 and consumed[1] the consumed dy.
18718     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18719     *                       in local view coordinates of this view from before this operation
18720     *                       to after it completes. View implementations may use this to adjust
18721     *                       expected input coordinate tracking.
18722     * @return true if the parent consumed some or all of the scroll delta
18723     * @see #dispatchNestedScroll(int, int, int, int, int[])
18724     */
18725    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18726        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18727            if (dx != 0 || dy != 0) {
18728                int startX = 0;
18729                int startY = 0;
18730                if (offsetInWindow != null) {
18731                    getLocationInWindow(offsetInWindow);
18732                    startX = offsetInWindow[0];
18733                    startY = offsetInWindow[1];
18734                }
18735
18736                if (consumed == null) {
18737                    if (mTempNestedScrollConsumed == null) {
18738                        mTempNestedScrollConsumed = new int[2];
18739                    }
18740                    consumed = mTempNestedScrollConsumed;
18741                }
18742                consumed[0] = 0;
18743                consumed[1] = 0;
18744                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18745
18746                if (offsetInWindow != null) {
18747                    getLocationInWindow(offsetInWindow);
18748                    offsetInWindow[0] -= startX;
18749                    offsetInWindow[1] -= startY;
18750                }
18751                return consumed[0] != 0 || consumed[1] != 0;
18752            } else if (offsetInWindow != null) {
18753                offsetInWindow[0] = 0;
18754                offsetInWindow[1] = 0;
18755            }
18756        }
18757        return false;
18758    }
18759
18760    /**
18761     * Dispatch a fling to a nested scrolling parent.
18762     *
18763     * <p>This method should be used to indicate that a nested scrolling child has detected
18764     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18765     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18766     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18767     * along a scrollable axis.</p>
18768     *
18769     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18770     * its own content, it can use this method to delegate the fling to its nested scrolling
18771     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18772     *
18773     * @param velocityX Horizontal fling velocity in pixels per second
18774     * @param velocityY Vertical fling velocity in pixels per second
18775     * @param consumed true if the child consumed the fling, false otherwise
18776     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18777     */
18778    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18779        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18780            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18781        }
18782        return false;
18783    }
18784
18785    /**
18786     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18787     *
18788     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18789     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18790     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18791     * before the child view consumes it. If this method returns <code>true</code>, a nested
18792     * parent view consumed the fling and this view should not scroll as a result.</p>
18793     *
18794     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18795     * the fling at a time. If a parent view consumed the fling this method will return false.
18796     * Custom view implementations should account for this in two ways:</p>
18797     *
18798     * <ul>
18799     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18800     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18801     *     position regardless.</li>
18802     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18803     *     even to settle back to a valid idle position.</li>
18804     * </ul>
18805     *
18806     * <p>Views should also not offer fling velocities to nested parent views along an axis
18807     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18808     * should not offer a horizontal fling velocity to its parents since scrolling along that
18809     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18810     *
18811     * @param velocityX Horizontal fling velocity in pixels per second
18812     * @param velocityY Vertical fling velocity in pixels per second
18813     * @return true if a nested scrolling parent consumed the fling
18814     */
18815    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18816        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18817            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18818        }
18819        return false;
18820    }
18821
18822    /**
18823     * Gets a scale factor that determines the distance the view should scroll
18824     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18825     * @return The vertical scroll scale factor.
18826     * @hide
18827     */
18828    protected float getVerticalScrollFactor() {
18829        if (mVerticalScrollFactor == 0) {
18830            TypedValue outValue = new TypedValue();
18831            if (!mContext.getTheme().resolveAttribute(
18832                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18833                throw new IllegalStateException(
18834                        "Expected theme to define listPreferredItemHeight.");
18835            }
18836            mVerticalScrollFactor = outValue.getDimension(
18837                    mContext.getResources().getDisplayMetrics());
18838        }
18839        return mVerticalScrollFactor;
18840    }
18841
18842    /**
18843     * Gets a scale factor that determines the distance the view should scroll
18844     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18845     * @return The horizontal scroll scale factor.
18846     * @hide
18847     */
18848    protected float getHorizontalScrollFactor() {
18849        // TODO: Should use something else.
18850        return getVerticalScrollFactor();
18851    }
18852
18853    /**
18854     * Return the value specifying the text direction or policy that was set with
18855     * {@link #setTextDirection(int)}.
18856     *
18857     * @return the defined text direction. It can be one of:
18858     *
18859     * {@link #TEXT_DIRECTION_INHERIT},
18860     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18861     * {@link #TEXT_DIRECTION_ANY_RTL},
18862     * {@link #TEXT_DIRECTION_LTR},
18863     * {@link #TEXT_DIRECTION_RTL},
18864     * {@link #TEXT_DIRECTION_LOCALE}
18865     *
18866     * @attr ref android.R.styleable#View_textDirection
18867     *
18868     * @hide
18869     */
18870    @ViewDebug.ExportedProperty(category = "text", mapping = {
18871            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18872            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18873            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18874            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18875            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18876            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18877    })
18878    public int getRawTextDirection() {
18879        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18880    }
18881
18882    /**
18883     * Set the text direction.
18884     *
18885     * @param textDirection the direction to set. Should be one of:
18886     *
18887     * {@link #TEXT_DIRECTION_INHERIT},
18888     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18889     * {@link #TEXT_DIRECTION_ANY_RTL},
18890     * {@link #TEXT_DIRECTION_LTR},
18891     * {@link #TEXT_DIRECTION_RTL},
18892     * {@link #TEXT_DIRECTION_LOCALE}
18893     *
18894     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18895     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18896     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18897     *
18898     * @attr ref android.R.styleable#View_textDirection
18899     */
18900    public void setTextDirection(int textDirection) {
18901        if (getRawTextDirection() != textDirection) {
18902            // Reset the current text direction and the resolved one
18903            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18904            resetResolvedTextDirection();
18905            // Set the new text direction
18906            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18907            // Do resolution
18908            resolveTextDirection();
18909            // Notify change
18910            onRtlPropertiesChanged(getLayoutDirection());
18911            // Refresh
18912            requestLayout();
18913            invalidate(true);
18914        }
18915    }
18916
18917    /**
18918     * Return the resolved text direction.
18919     *
18920     * @return the resolved text direction. Returns one of:
18921     *
18922     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18923     * {@link #TEXT_DIRECTION_ANY_RTL},
18924     * {@link #TEXT_DIRECTION_LTR},
18925     * {@link #TEXT_DIRECTION_RTL},
18926     * {@link #TEXT_DIRECTION_LOCALE}
18927     *
18928     * @attr ref android.R.styleable#View_textDirection
18929     */
18930    @ViewDebug.ExportedProperty(category = "text", mapping = {
18931            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18932            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18933            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18934            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18935            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18936            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18937    })
18938    public int getTextDirection() {
18939        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18940    }
18941
18942    /**
18943     * Resolve the text direction.
18944     *
18945     * @return true if resolution has been done, false otherwise.
18946     *
18947     * @hide
18948     */
18949    public boolean resolveTextDirection() {
18950        // Reset any previous text direction resolution
18951        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18952
18953        if (hasRtlSupport()) {
18954            // Set resolved text direction flag depending on text direction flag
18955            final int textDirection = getRawTextDirection();
18956            switch(textDirection) {
18957                case TEXT_DIRECTION_INHERIT:
18958                    if (!canResolveTextDirection()) {
18959                        // We cannot do the resolution if there is no parent, so use the default one
18960                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18961                        // Resolution will need to happen again later
18962                        return false;
18963                    }
18964
18965                    // Parent has not yet resolved, so we still return the default
18966                    try {
18967                        if (!mParent.isTextDirectionResolved()) {
18968                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18969                            // Resolution will need to happen again later
18970                            return false;
18971                        }
18972                    } catch (AbstractMethodError e) {
18973                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18974                                " does not fully implement ViewParent", e);
18975                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18976                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18977                        return true;
18978                    }
18979
18980                    // Set current resolved direction to the same value as the parent's one
18981                    int parentResolvedDirection;
18982                    try {
18983                        parentResolvedDirection = mParent.getTextDirection();
18984                    } catch (AbstractMethodError e) {
18985                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18986                                " does not fully implement ViewParent", e);
18987                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18988                    }
18989                    switch (parentResolvedDirection) {
18990                        case TEXT_DIRECTION_FIRST_STRONG:
18991                        case TEXT_DIRECTION_ANY_RTL:
18992                        case TEXT_DIRECTION_LTR:
18993                        case TEXT_DIRECTION_RTL:
18994                        case TEXT_DIRECTION_LOCALE:
18995                            mPrivateFlags2 |=
18996                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18997                            break;
18998                        default:
18999                            // Default resolved direction is "first strong" heuristic
19000                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19001                    }
19002                    break;
19003                case TEXT_DIRECTION_FIRST_STRONG:
19004                case TEXT_DIRECTION_ANY_RTL:
19005                case TEXT_DIRECTION_LTR:
19006                case TEXT_DIRECTION_RTL:
19007                case TEXT_DIRECTION_LOCALE:
19008                    // Resolved direction is the same as text direction
19009                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19010                    break;
19011                default:
19012                    // Default resolved direction is "first strong" heuristic
19013                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19014            }
19015        } else {
19016            // Default resolved direction is "first strong" heuristic
19017            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19018        }
19019
19020        // Set to resolved
19021        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19022        return true;
19023    }
19024
19025    /**
19026     * Check if text direction resolution can be done.
19027     *
19028     * @return true if text direction resolution can be done otherwise return false.
19029     */
19030    public boolean canResolveTextDirection() {
19031        switch (getRawTextDirection()) {
19032            case TEXT_DIRECTION_INHERIT:
19033                if (mParent != null) {
19034                    try {
19035                        return mParent.canResolveTextDirection();
19036                    } catch (AbstractMethodError e) {
19037                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19038                                " does not fully implement ViewParent", e);
19039                    }
19040                }
19041                return false;
19042
19043            default:
19044                return true;
19045        }
19046    }
19047
19048    /**
19049     * Reset resolved text direction. Text direction will be resolved during a call to
19050     * {@link #onMeasure(int, int)}.
19051     *
19052     * @hide
19053     */
19054    public void resetResolvedTextDirection() {
19055        // Reset any previous text direction resolution
19056        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19057        // Set to default value
19058        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19059    }
19060
19061    /**
19062     * @return true if text direction is inherited.
19063     *
19064     * @hide
19065     */
19066    public boolean isTextDirectionInherited() {
19067        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19068    }
19069
19070    /**
19071     * @return true if text direction is resolved.
19072     */
19073    public boolean isTextDirectionResolved() {
19074        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19075    }
19076
19077    /**
19078     * Return the value specifying the text alignment or policy that was set with
19079     * {@link #setTextAlignment(int)}.
19080     *
19081     * @return the defined text alignment. It can be one of:
19082     *
19083     * {@link #TEXT_ALIGNMENT_INHERIT},
19084     * {@link #TEXT_ALIGNMENT_GRAVITY},
19085     * {@link #TEXT_ALIGNMENT_CENTER},
19086     * {@link #TEXT_ALIGNMENT_TEXT_START},
19087     * {@link #TEXT_ALIGNMENT_TEXT_END},
19088     * {@link #TEXT_ALIGNMENT_VIEW_START},
19089     * {@link #TEXT_ALIGNMENT_VIEW_END}
19090     *
19091     * @attr ref android.R.styleable#View_textAlignment
19092     *
19093     * @hide
19094     */
19095    @ViewDebug.ExportedProperty(category = "text", mapping = {
19096            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19097            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19098            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19099            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19100            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19101            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19102            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19103    })
19104    @TextAlignment
19105    public int getRawTextAlignment() {
19106        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19107    }
19108
19109    /**
19110     * Set the text alignment.
19111     *
19112     * @param textAlignment The text alignment to set. Should be one of
19113     *
19114     * {@link #TEXT_ALIGNMENT_INHERIT},
19115     * {@link #TEXT_ALIGNMENT_GRAVITY},
19116     * {@link #TEXT_ALIGNMENT_CENTER},
19117     * {@link #TEXT_ALIGNMENT_TEXT_START},
19118     * {@link #TEXT_ALIGNMENT_TEXT_END},
19119     * {@link #TEXT_ALIGNMENT_VIEW_START},
19120     * {@link #TEXT_ALIGNMENT_VIEW_END}
19121     *
19122     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19123     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19124     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19125     *
19126     * @attr ref android.R.styleable#View_textAlignment
19127     */
19128    public void setTextAlignment(@TextAlignment int textAlignment) {
19129        if (textAlignment != getRawTextAlignment()) {
19130            // Reset the current and resolved text alignment
19131            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19132            resetResolvedTextAlignment();
19133            // Set the new text alignment
19134            mPrivateFlags2 |=
19135                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19136            // Do resolution
19137            resolveTextAlignment();
19138            // Notify change
19139            onRtlPropertiesChanged(getLayoutDirection());
19140            // Refresh
19141            requestLayout();
19142            invalidate(true);
19143        }
19144    }
19145
19146    /**
19147     * Return the resolved text alignment.
19148     *
19149     * @return the resolved text alignment. Returns one of:
19150     *
19151     * {@link #TEXT_ALIGNMENT_GRAVITY},
19152     * {@link #TEXT_ALIGNMENT_CENTER},
19153     * {@link #TEXT_ALIGNMENT_TEXT_START},
19154     * {@link #TEXT_ALIGNMENT_TEXT_END},
19155     * {@link #TEXT_ALIGNMENT_VIEW_START},
19156     * {@link #TEXT_ALIGNMENT_VIEW_END}
19157     *
19158     * @attr ref android.R.styleable#View_textAlignment
19159     */
19160    @ViewDebug.ExportedProperty(category = "text", mapping = {
19161            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19162            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19163            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19164            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19165            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19166            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19167            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19168    })
19169    @TextAlignment
19170    public int getTextAlignment() {
19171        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
19172                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
19173    }
19174
19175    /**
19176     * Resolve the text alignment.
19177     *
19178     * @return true if resolution has been done, false otherwise.
19179     *
19180     * @hide
19181     */
19182    public boolean resolveTextAlignment() {
19183        // Reset any previous text alignment resolution
19184        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19185
19186        if (hasRtlSupport()) {
19187            // Set resolved text alignment flag depending on text alignment flag
19188            final int textAlignment = getRawTextAlignment();
19189            switch (textAlignment) {
19190                case TEXT_ALIGNMENT_INHERIT:
19191                    // Check if we can resolve the text alignment
19192                    if (!canResolveTextAlignment()) {
19193                        // We cannot do the resolution if there is no parent so use the default
19194                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19195                        // Resolution will need to happen again later
19196                        return false;
19197                    }
19198
19199                    // Parent has not yet resolved, so we still return the default
19200                    try {
19201                        if (!mParent.isTextAlignmentResolved()) {
19202                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19203                            // Resolution will need to happen again later
19204                            return false;
19205                        }
19206                    } catch (AbstractMethodError e) {
19207                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19208                                " does not fully implement ViewParent", e);
19209                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19210                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19211                        return true;
19212                    }
19213
19214                    int parentResolvedTextAlignment;
19215                    try {
19216                        parentResolvedTextAlignment = mParent.getTextAlignment();
19217                    } catch (AbstractMethodError e) {
19218                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19219                                " does not fully implement ViewParent", e);
19220                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19221                    }
19222                    switch (parentResolvedTextAlignment) {
19223                        case TEXT_ALIGNMENT_GRAVITY:
19224                        case TEXT_ALIGNMENT_TEXT_START:
19225                        case TEXT_ALIGNMENT_TEXT_END:
19226                        case TEXT_ALIGNMENT_CENTER:
19227                        case TEXT_ALIGNMENT_VIEW_START:
19228                        case TEXT_ALIGNMENT_VIEW_END:
19229                            // Resolved text alignment is the same as the parent resolved
19230                            // text alignment
19231                            mPrivateFlags2 |=
19232                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19233                            break;
19234                        default:
19235                            // Use default resolved text alignment
19236                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19237                    }
19238                    break;
19239                case TEXT_ALIGNMENT_GRAVITY:
19240                case TEXT_ALIGNMENT_TEXT_START:
19241                case TEXT_ALIGNMENT_TEXT_END:
19242                case TEXT_ALIGNMENT_CENTER:
19243                case TEXT_ALIGNMENT_VIEW_START:
19244                case TEXT_ALIGNMENT_VIEW_END:
19245                    // Resolved text alignment is the same as text alignment
19246                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19247                    break;
19248                default:
19249                    // Use default resolved text alignment
19250                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19251            }
19252        } else {
19253            // Use default resolved text alignment
19254            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19255        }
19256
19257        // Set the resolved
19258        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19259        return true;
19260    }
19261
19262    /**
19263     * Check if text alignment resolution can be done.
19264     *
19265     * @return true if text alignment resolution can be done otherwise return false.
19266     */
19267    public boolean canResolveTextAlignment() {
19268        switch (getRawTextAlignment()) {
19269            case TEXT_DIRECTION_INHERIT:
19270                if (mParent != null) {
19271                    try {
19272                        return mParent.canResolveTextAlignment();
19273                    } catch (AbstractMethodError e) {
19274                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19275                                " does not fully implement ViewParent", e);
19276                    }
19277                }
19278                return false;
19279
19280            default:
19281                return true;
19282        }
19283    }
19284
19285    /**
19286     * Reset resolved text alignment. Text alignment will be resolved during a call to
19287     * {@link #onMeasure(int, int)}.
19288     *
19289     * @hide
19290     */
19291    public void resetResolvedTextAlignment() {
19292        // Reset any previous text alignment resolution
19293        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19294        // Set to default
19295        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19296    }
19297
19298    /**
19299     * @return true if text alignment is inherited.
19300     *
19301     * @hide
19302     */
19303    public boolean isTextAlignmentInherited() {
19304        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19305    }
19306
19307    /**
19308     * @return true if text alignment is resolved.
19309     */
19310    public boolean isTextAlignmentResolved() {
19311        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19312    }
19313
19314    /**
19315     * Generate a value suitable for use in {@link #setId(int)}.
19316     * This value will not collide with ID values generated at build time by aapt for R.id.
19317     *
19318     * @return a generated ID value
19319     */
19320    public static int generateViewId() {
19321        for (;;) {
19322            final int result = sNextGeneratedId.get();
19323            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19324            int newValue = result + 1;
19325            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19326            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19327                return result;
19328            }
19329        }
19330    }
19331
19332    /**
19333     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19334     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19335     *                           a normal View or a ViewGroup with
19336     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19337     * @hide
19338     */
19339    public void captureTransitioningViews(List<View> transitioningViews) {
19340        if (getVisibility() == View.VISIBLE) {
19341            transitioningViews.add(this);
19342        }
19343    }
19344
19345    /**
19346     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19347     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19348     * @hide
19349     */
19350    public void findNamedViews(Map<String, View> namedElements) {
19351        if (getVisibility() == VISIBLE || mGhostView != null) {
19352            String transitionName = getTransitionName();
19353            if (transitionName != null) {
19354                namedElements.put(transitionName, this);
19355            }
19356        }
19357    }
19358
19359    //
19360    // Properties
19361    //
19362    /**
19363     * A Property wrapper around the <code>alpha</code> functionality handled by the
19364     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19365     */
19366    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19367        @Override
19368        public void setValue(View object, float value) {
19369            object.setAlpha(value);
19370        }
19371
19372        @Override
19373        public Float get(View object) {
19374            return object.getAlpha();
19375        }
19376    };
19377
19378    /**
19379     * A Property wrapper around the <code>translationX</code> functionality handled by the
19380     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19381     */
19382    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19383        @Override
19384        public void setValue(View object, float value) {
19385            object.setTranslationX(value);
19386        }
19387
19388                @Override
19389        public Float get(View object) {
19390            return object.getTranslationX();
19391        }
19392    };
19393
19394    /**
19395     * A Property wrapper around the <code>translationY</code> functionality handled by the
19396     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19397     */
19398    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19399        @Override
19400        public void setValue(View object, float value) {
19401            object.setTranslationY(value);
19402        }
19403
19404        @Override
19405        public Float get(View object) {
19406            return object.getTranslationY();
19407        }
19408    };
19409
19410    /**
19411     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19412     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19413     */
19414    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19415        @Override
19416        public void setValue(View object, float value) {
19417            object.setTranslationZ(value);
19418        }
19419
19420        @Override
19421        public Float get(View object) {
19422            return object.getTranslationZ();
19423        }
19424    };
19425
19426    /**
19427     * A Property wrapper around the <code>x</code> functionality handled by the
19428     * {@link View#setX(float)} and {@link View#getX()} methods.
19429     */
19430    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19431        @Override
19432        public void setValue(View object, float value) {
19433            object.setX(value);
19434        }
19435
19436        @Override
19437        public Float get(View object) {
19438            return object.getX();
19439        }
19440    };
19441
19442    /**
19443     * A Property wrapper around the <code>y</code> functionality handled by the
19444     * {@link View#setY(float)} and {@link View#getY()} methods.
19445     */
19446    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19447        @Override
19448        public void setValue(View object, float value) {
19449            object.setY(value);
19450        }
19451
19452        @Override
19453        public Float get(View object) {
19454            return object.getY();
19455        }
19456    };
19457
19458    /**
19459     * A Property wrapper around the <code>z</code> functionality handled by the
19460     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19461     */
19462    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19463        @Override
19464        public void setValue(View object, float value) {
19465            object.setZ(value);
19466        }
19467
19468        @Override
19469        public Float get(View object) {
19470            return object.getZ();
19471        }
19472    };
19473
19474    /**
19475     * A Property wrapper around the <code>rotation</code> functionality handled by the
19476     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19477     */
19478    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19479        @Override
19480        public void setValue(View object, float value) {
19481            object.setRotation(value);
19482        }
19483
19484        @Override
19485        public Float get(View object) {
19486            return object.getRotation();
19487        }
19488    };
19489
19490    /**
19491     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19492     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19493     */
19494    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19495        @Override
19496        public void setValue(View object, float value) {
19497            object.setRotationX(value);
19498        }
19499
19500        @Override
19501        public Float get(View object) {
19502            return object.getRotationX();
19503        }
19504    };
19505
19506    /**
19507     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19508     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19509     */
19510    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19511        @Override
19512        public void setValue(View object, float value) {
19513            object.setRotationY(value);
19514        }
19515
19516        @Override
19517        public Float get(View object) {
19518            return object.getRotationY();
19519        }
19520    };
19521
19522    /**
19523     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19524     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19525     */
19526    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19527        @Override
19528        public void setValue(View object, float value) {
19529            object.setScaleX(value);
19530        }
19531
19532        @Override
19533        public Float get(View object) {
19534            return object.getScaleX();
19535        }
19536    };
19537
19538    /**
19539     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19540     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19541     */
19542    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19543        @Override
19544        public void setValue(View object, float value) {
19545            object.setScaleY(value);
19546        }
19547
19548        @Override
19549        public Float get(View object) {
19550            return object.getScaleY();
19551        }
19552    };
19553
19554    /**
19555     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19556     * Each MeasureSpec represents a requirement for either the width or the height.
19557     * A MeasureSpec is comprised of a size and a mode. There are three possible
19558     * modes:
19559     * <dl>
19560     * <dt>UNSPECIFIED</dt>
19561     * <dd>
19562     * The parent has not imposed any constraint on the child. It can be whatever size
19563     * it wants.
19564     * </dd>
19565     *
19566     * <dt>EXACTLY</dt>
19567     * <dd>
19568     * The parent has determined an exact size for the child. The child is going to be
19569     * given those bounds regardless of how big it wants to be.
19570     * </dd>
19571     *
19572     * <dt>AT_MOST</dt>
19573     * <dd>
19574     * The child can be as large as it wants up to the specified size.
19575     * </dd>
19576     * </dl>
19577     *
19578     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19579     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19580     */
19581    public static class MeasureSpec {
19582        private static final int MODE_SHIFT = 30;
19583        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19584
19585        /**
19586         * Measure specification mode: The parent has not imposed any constraint
19587         * on the child. It can be whatever size it wants.
19588         */
19589        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19590
19591        /**
19592         * Measure specification mode: The parent has determined an exact size
19593         * for the child. The child is going to be given those bounds regardless
19594         * of how big it wants to be.
19595         */
19596        public static final int EXACTLY     = 1 << MODE_SHIFT;
19597
19598        /**
19599         * Measure specification mode: The child can be as large as it wants up
19600         * to the specified size.
19601         */
19602        public static final int AT_MOST     = 2 << MODE_SHIFT;
19603
19604        /**
19605         * Creates a measure specification based on the supplied size and mode.
19606         *
19607         * The mode must always be one of the following:
19608         * <ul>
19609         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19610         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19611         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19612         * </ul>
19613         *
19614         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19615         * implementation was such that the order of arguments did not matter
19616         * and overflow in either value could impact the resulting MeasureSpec.
19617         * {@link android.widget.RelativeLayout} was affected by this bug.
19618         * Apps targeting API levels greater than 17 will get the fixed, more strict
19619         * behavior.</p>
19620         *
19621         * @param size the size of the measure specification
19622         * @param mode the mode of the measure specification
19623         * @return the measure specification based on size and mode
19624         */
19625        public static int makeMeasureSpec(int size, int mode) {
19626            if (sUseBrokenMakeMeasureSpec) {
19627                return size + mode;
19628            } else {
19629                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19630            }
19631        }
19632
19633        /**
19634         * Extracts the mode from the supplied measure specification.
19635         *
19636         * @param measureSpec the measure specification to extract the mode from
19637         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19638         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19639         *         {@link android.view.View.MeasureSpec#EXACTLY}
19640         */
19641        public static int getMode(int measureSpec) {
19642            return (measureSpec & MODE_MASK);
19643        }
19644
19645        /**
19646         * Extracts the size from the supplied measure specification.
19647         *
19648         * @param measureSpec the measure specification to extract the size from
19649         * @return the size in pixels defined in the supplied measure specification
19650         */
19651        public static int getSize(int measureSpec) {
19652            return (measureSpec & ~MODE_MASK);
19653        }
19654
19655        static int adjust(int measureSpec, int delta) {
19656            final int mode = getMode(measureSpec);
19657            if (mode == UNSPECIFIED) {
19658                // No need to adjust size for UNSPECIFIED mode.
19659                return makeMeasureSpec(0, UNSPECIFIED);
19660            }
19661            int size = getSize(measureSpec) + delta;
19662            if (size < 0) {
19663                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19664                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19665                size = 0;
19666            }
19667            return makeMeasureSpec(size, mode);
19668        }
19669
19670        /**
19671         * Returns a String representation of the specified measure
19672         * specification.
19673         *
19674         * @param measureSpec the measure specification to convert to a String
19675         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19676         */
19677        public static String toString(int measureSpec) {
19678            int mode = getMode(measureSpec);
19679            int size = getSize(measureSpec);
19680
19681            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19682
19683            if (mode == UNSPECIFIED)
19684                sb.append("UNSPECIFIED ");
19685            else if (mode == EXACTLY)
19686                sb.append("EXACTLY ");
19687            else if (mode == AT_MOST)
19688                sb.append("AT_MOST ");
19689            else
19690                sb.append(mode).append(" ");
19691
19692            sb.append(size);
19693            return sb.toString();
19694        }
19695    }
19696
19697    private final class CheckForLongPress implements Runnable {
19698        private int mOriginalWindowAttachCount;
19699
19700        @Override
19701        public void run() {
19702            if (isPressed() && (mParent != null)
19703                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19704                if (performLongClick()) {
19705                    mHasPerformedLongPress = true;
19706                }
19707            }
19708        }
19709
19710        public void rememberWindowAttachCount() {
19711            mOriginalWindowAttachCount = mWindowAttachCount;
19712        }
19713    }
19714
19715    private final class CheckForTap implements Runnable {
19716        public float x;
19717        public float y;
19718
19719        @Override
19720        public void run() {
19721            mPrivateFlags &= ~PFLAG_PREPRESSED;
19722            setPressed(true, x, y);
19723            checkForLongClick(ViewConfiguration.getTapTimeout());
19724        }
19725    }
19726
19727    private final class PerformClick implements Runnable {
19728        @Override
19729        public void run() {
19730            performClick();
19731        }
19732    }
19733
19734    /** @hide */
19735    public void hackTurnOffWindowResizeAnim(boolean off) {
19736        mAttachInfo.mTurnOffWindowResizeAnim = off;
19737    }
19738
19739    /**
19740     * This method returns a ViewPropertyAnimator object, which can be used to animate
19741     * specific properties on this View.
19742     *
19743     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19744     */
19745    public ViewPropertyAnimator animate() {
19746        if (mAnimator == null) {
19747            mAnimator = new ViewPropertyAnimator(this);
19748        }
19749        return mAnimator;
19750    }
19751
19752    /**
19753     * Sets the name of the View to be used to identify Views in Transitions.
19754     * Names should be unique in the View hierarchy.
19755     *
19756     * @param transitionName The name of the View to uniquely identify it for Transitions.
19757     */
19758    public final void setTransitionName(String transitionName) {
19759        mTransitionName = transitionName;
19760    }
19761
19762    /**
19763     * Returns the name of the View to be used to identify Views in Transitions.
19764     * Names should be unique in the View hierarchy.
19765     *
19766     * <p>This returns null if the View has not been given a name.</p>
19767     *
19768     * @return The name used of the View to be used to identify Views in Transitions or null
19769     * if no name has been given.
19770     */
19771    @ViewDebug.ExportedProperty
19772    public String getTransitionName() {
19773        return mTransitionName;
19774    }
19775
19776    /**
19777     * Interface definition for a callback to be invoked when a hardware key event is
19778     * dispatched to this view. The callback will be invoked before the key event is
19779     * given to the view. This is only useful for hardware keyboards; a software input
19780     * method has no obligation to trigger this listener.
19781     */
19782    public interface OnKeyListener {
19783        /**
19784         * Called when a hardware key is dispatched to a view. This allows listeners to
19785         * get a chance to respond before the target view.
19786         * <p>Key presses in software keyboards will generally NOT trigger this method,
19787         * although some may elect to do so in some situations. Do not assume a
19788         * software input method has to be key-based; even if it is, it may use key presses
19789         * in a different way than you expect, so there is no way to reliably catch soft
19790         * input key presses.
19791         *
19792         * @param v The view the key has been dispatched to.
19793         * @param keyCode The code for the physical key that was pressed
19794         * @param event The KeyEvent object containing full information about
19795         *        the event.
19796         * @return True if the listener has consumed the event, false otherwise.
19797         */
19798        boolean onKey(View v, int keyCode, KeyEvent event);
19799    }
19800
19801    /**
19802     * Interface definition for a callback to be invoked when a touch event is
19803     * dispatched to this view. The callback will be invoked before the touch
19804     * event is given to the view.
19805     */
19806    public interface OnTouchListener {
19807        /**
19808         * Called when a touch event is dispatched to a view. This allows listeners to
19809         * get a chance to respond before the target view.
19810         *
19811         * @param v The view the touch event has been dispatched to.
19812         * @param event The MotionEvent object containing full information about
19813         *        the event.
19814         * @return True if the listener has consumed the event, false otherwise.
19815         */
19816        boolean onTouch(View v, MotionEvent event);
19817    }
19818
19819    /**
19820     * Interface definition for a callback to be invoked when a hover event is
19821     * dispatched to this view. The callback will be invoked before the hover
19822     * event is given to the view.
19823     */
19824    public interface OnHoverListener {
19825        /**
19826         * Called when a hover event is dispatched to a view. This allows listeners to
19827         * get a chance to respond before the target view.
19828         *
19829         * @param v The view the hover event has been dispatched to.
19830         * @param event The MotionEvent object containing full information about
19831         *        the event.
19832         * @return True if the listener has consumed the event, false otherwise.
19833         */
19834        boolean onHover(View v, MotionEvent event);
19835    }
19836
19837    /**
19838     * Interface definition for a callback to be invoked when a generic motion event is
19839     * dispatched to this view. The callback will be invoked before the generic motion
19840     * event is given to the view.
19841     */
19842    public interface OnGenericMotionListener {
19843        /**
19844         * Called when a generic motion event is dispatched to a view. This allows listeners to
19845         * get a chance to respond before the target view.
19846         *
19847         * @param v The view the generic motion event has been dispatched to.
19848         * @param event The MotionEvent object containing full information about
19849         *        the event.
19850         * @return True if the listener has consumed the event, false otherwise.
19851         */
19852        boolean onGenericMotion(View v, MotionEvent event);
19853    }
19854
19855    /**
19856     * Interface definition for a callback to be invoked when a view has been clicked and held.
19857     */
19858    public interface OnLongClickListener {
19859        /**
19860         * Called when a view has been clicked and held.
19861         *
19862         * @param v The view that was clicked and held.
19863         *
19864         * @return true if the callback consumed the long click, false otherwise.
19865         */
19866        boolean onLongClick(View v);
19867    }
19868
19869    /**
19870     * Interface definition for a callback to be invoked when a drag is being dispatched
19871     * to this view.  The callback will be invoked before the hosting view's own
19872     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19873     * onDrag(event) behavior, it should return 'false' from this callback.
19874     *
19875     * <div class="special reference">
19876     * <h3>Developer Guides</h3>
19877     * <p>For a guide to implementing drag and drop features, read the
19878     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19879     * </div>
19880     */
19881    public interface OnDragListener {
19882        /**
19883         * Called when a drag event is dispatched to a view. This allows listeners
19884         * to get a chance to override base View behavior.
19885         *
19886         * @param v The View that received the drag event.
19887         * @param event The {@link android.view.DragEvent} object for the drag event.
19888         * @return {@code true} if the drag event was handled successfully, or {@code false}
19889         * if the drag event was not handled. Note that {@code false} will trigger the View
19890         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19891         */
19892        boolean onDrag(View v, DragEvent event);
19893    }
19894
19895    /**
19896     * Interface definition for a callback to be invoked when the focus state of
19897     * a view changed.
19898     */
19899    public interface OnFocusChangeListener {
19900        /**
19901         * Called when the focus state of a view has changed.
19902         *
19903         * @param v The view whose state has changed.
19904         * @param hasFocus The new focus state of v.
19905         */
19906        void onFocusChange(View v, boolean hasFocus);
19907    }
19908
19909    /**
19910     * Interface definition for a callback to be invoked when a view is clicked.
19911     */
19912    public interface OnClickListener {
19913        /**
19914         * Called when a view has been clicked.
19915         *
19916         * @param v The view that was clicked.
19917         */
19918        void onClick(View v);
19919    }
19920
19921    /**
19922     * Interface definition for a callback to be invoked when the context menu
19923     * for this view is being built.
19924     */
19925    public interface OnCreateContextMenuListener {
19926        /**
19927         * Called when the context menu for this view is being built. It is not
19928         * safe to hold onto the menu after this method returns.
19929         *
19930         * @param menu The context menu that is being built
19931         * @param v The view for which the context menu is being built
19932         * @param menuInfo Extra information about the item for which the
19933         *            context menu should be shown. This information will vary
19934         *            depending on the class of v.
19935         */
19936        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19937    }
19938
19939    /**
19940     * Interface definition for a callback to be invoked when the status bar changes
19941     * visibility.  This reports <strong>global</strong> changes to the system UI
19942     * state, not what the application is requesting.
19943     *
19944     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19945     */
19946    public interface OnSystemUiVisibilityChangeListener {
19947        /**
19948         * Called when the status bar changes visibility because of a call to
19949         * {@link View#setSystemUiVisibility(int)}.
19950         *
19951         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19952         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19953         * This tells you the <strong>global</strong> state of these UI visibility
19954         * flags, not what your app is currently applying.
19955         */
19956        public void onSystemUiVisibilityChange(int visibility);
19957    }
19958
19959    /**
19960     * Interface definition for a callback to be invoked when this view is attached
19961     * or detached from its window.
19962     */
19963    public interface OnAttachStateChangeListener {
19964        /**
19965         * Called when the view is attached to a window.
19966         * @param v The view that was attached
19967         */
19968        public void onViewAttachedToWindow(View v);
19969        /**
19970         * Called when the view is detached from a window.
19971         * @param v The view that was detached
19972         */
19973        public void onViewDetachedFromWindow(View v);
19974    }
19975
19976    /**
19977     * Listener for applying window insets on a view in a custom way.
19978     *
19979     * <p>Apps may choose to implement this interface if they want to apply custom policy
19980     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19981     * is set, its
19982     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19983     * method will be called instead of the View's own
19984     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19985     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19986     * the View's normal behavior as part of its own.</p>
19987     */
19988    public interface OnApplyWindowInsetsListener {
19989        /**
19990         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19991         * on a View, this listener method will be called instead of the view's own
19992         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19993         *
19994         * @param v The view applying window insets
19995         * @param insets The insets to apply
19996         * @return The insets supplied, minus any insets that were consumed
19997         */
19998        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19999    }
20000
20001    private final class UnsetPressedState implements Runnable {
20002        @Override
20003        public void run() {
20004            setPressed(false);
20005        }
20006    }
20007
20008    /**
20009     * Base class for derived classes that want to save and restore their own
20010     * state in {@link android.view.View#onSaveInstanceState()}.
20011     */
20012    public static class BaseSavedState extends AbsSavedState {
20013        /**
20014         * Constructor used when reading from a parcel. Reads the state of the superclass.
20015         *
20016         * @param source
20017         */
20018        public BaseSavedState(Parcel source) {
20019            super(source);
20020        }
20021
20022        /**
20023         * Constructor called by derived classes when creating their SavedState objects
20024         *
20025         * @param superState The state of the superclass of this view
20026         */
20027        public BaseSavedState(Parcelable superState) {
20028            super(superState);
20029        }
20030
20031        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20032                new Parcelable.Creator<BaseSavedState>() {
20033            public BaseSavedState createFromParcel(Parcel in) {
20034                return new BaseSavedState(in);
20035            }
20036
20037            public BaseSavedState[] newArray(int size) {
20038                return new BaseSavedState[size];
20039            }
20040        };
20041    }
20042
20043    /**
20044     * A set of information given to a view when it is attached to its parent
20045     * window.
20046     */
20047    final static class AttachInfo {
20048        interface Callbacks {
20049            void playSoundEffect(int effectId);
20050            boolean performHapticFeedback(int effectId, boolean always);
20051        }
20052
20053        /**
20054         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20055         * to a Handler. This class contains the target (View) to invalidate and
20056         * the coordinates of the dirty rectangle.
20057         *
20058         * For performance purposes, this class also implements a pool of up to
20059         * POOL_LIMIT objects that get reused. This reduces memory allocations
20060         * whenever possible.
20061         */
20062        static class InvalidateInfo {
20063            private static final int POOL_LIMIT = 10;
20064
20065            private static final SynchronizedPool<InvalidateInfo> sPool =
20066                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20067
20068            View target;
20069
20070            int left;
20071            int top;
20072            int right;
20073            int bottom;
20074
20075            public static InvalidateInfo obtain() {
20076                InvalidateInfo instance = sPool.acquire();
20077                return (instance != null) ? instance : new InvalidateInfo();
20078            }
20079
20080            public void recycle() {
20081                target = null;
20082                sPool.release(this);
20083            }
20084        }
20085
20086        final IWindowSession mSession;
20087
20088        final IWindow mWindow;
20089
20090        final IBinder mWindowToken;
20091
20092        final Display mDisplay;
20093
20094        final Callbacks mRootCallbacks;
20095
20096        IWindowId mIWindowId;
20097        WindowId mWindowId;
20098
20099        /**
20100         * The top view of the hierarchy.
20101         */
20102        View mRootView;
20103
20104        IBinder mPanelParentWindowToken;
20105
20106        boolean mHardwareAccelerated;
20107        boolean mHardwareAccelerationRequested;
20108        HardwareRenderer mHardwareRenderer;
20109        List<RenderNode> mPendingAnimatingRenderNodes;
20110
20111        /**
20112         * The state of the display to which the window is attached, as reported
20113         * by {@link Display#getState()}.  Note that the display state constants
20114         * declared by {@link Display} do not exactly line up with the screen state
20115         * constants declared by {@link View} (there are more display states than
20116         * screen states).
20117         */
20118        int mDisplayState = Display.STATE_UNKNOWN;
20119
20120        /**
20121         * Scale factor used by the compatibility mode
20122         */
20123        float mApplicationScale;
20124
20125        /**
20126         * Indicates whether the application is in compatibility mode
20127         */
20128        boolean mScalingRequired;
20129
20130        /**
20131         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20132         */
20133        boolean mTurnOffWindowResizeAnim;
20134
20135        /**
20136         * Left position of this view's window
20137         */
20138        int mWindowLeft;
20139
20140        /**
20141         * Top position of this view's window
20142         */
20143        int mWindowTop;
20144
20145        /**
20146         * Indicates whether views need to use 32-bit drawing caches
20147         */
20148        boolean mUse32BitDrawingCache;
20149
20150        /**
20151         * For windows that are full-screen but using insets to layout inside
20152         * of the screen areas, these are the current insets to appear inside
20153         * the overscan area of the display.
20154         */
20155        final Rect mOverscanInsets = new Rect();
20156
20157        /**
20158         * For windows that are full-screen but using insets to layout inside
20159         * of the screen decorations, these are the current insets for the
20160         * content of the window.
20161         */
20162        final Rect mContentInsets = new Rect();
20163
20164        /**
20165         * For windows that are full-screen but using insets to layout inside
20166         * of the screen decorations, these are the current insets for the
20167         * actual visible parts of the window.
20168         */
20169        final Rect mVisibleInsets = new Rect();
20170
20171        /**
20172         * For windows that are full-screen but using insets to layout inside
20173         * of the screen decorations, these are the current insets for the
20174         * stable system windows.
20175         */
20176        final Rect mStableInsets = new Rect();
20177
20178        /**
20179         * The internal insets given by this window.  This value is
20180         * supplied by the client (through
20181         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
20182         * be given to the window manager when changed to be used in laying
20183         * out windows behind it.
20184         */
20185        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
20186                = new ViewTreeObserver.InternalInsetsInfo();
20187
20188        /**
20189         * Set to true when mGivenInternalInsets is non-empty.
20190         */
20191        boolean mHasNonEmptyGivenInternalInsets;
20192
20193        /**
20194         * All views in the window's hierarchy that serve as scroll containers,
20195         * used to determine if the window can be resized or must be panned
20196         * to adjust for a soft input area.
20197         */
20198        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20199
20200        final KeyEvent.DispatcherState mKeyDispatchState
20201                = new KeyEvent.DispatcherState();
20202
20203        /**
20204         * Indicates whether the view's window currently has the focus.
20205         */
20206        boolean mHasWindowFocus;
20207
20208        /**
20209         * The current visibility of the window.
20210         */
20211        int mWindowVisibility;
20212
20213        /**
20214         * Indicates the time at which drawing started to occur.
20215         */
20216        long mDrawingTime;
20217
20218        /**
20219         * Indicates whether or not ignoring the DIRTY_MASK flags.
20220         */
20221        boolean mIgnoreDirtyState;
20222
20223        /**
20224         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20225         * to avoid clearing that flag prematurely.
20226         */
20227        boolean mSetIgnoreDirtyState = false;
20228
20229        /**
20230         * Indicates whether the view's window is currently in touch mode.
20231         */
20232        boolean mInTouchMode;
20233
20234        /**
20235         * Indicates whether the view has requested unbuffered input dispatching for the current
20236         * event stream.
20237         */
20238        boolean mUnbufferedDispatchRequested;
20239
20240        /**
20241         * Indicates that ViewAncestor should trigger a global layout change
20242         * the next time it performs a traversal
20243         */
20244        boolean mRecomputeGlobalAttributes;
20245
20246        /**
20247         * Always report new attributes at next traversal.
20248         */
20249        boolean mForceReportNewAttributes;
20250
20251        /**
20252         * Set during a traveral if any views want to keep the screen on.
20253         */
20254        boolean mKeepScreenOn;
20255
20256        /**
20257         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20258         */
20259        int mSystemUiVisibility;
20260
20261        /**
20262         * Hack to force certain system UI visibility flags to be cleared.
20263         */
20264        int mDisabledSystemUiVisibility;
20265
20266        /**
20267         * Last global system UI visibility reported by the window manager.
20268         */
20269        int mGlobalSystemUiVisibility;
20270
20271        /**
20272         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20273         * attached.
20274         */
20275        boolean mHasSystemUiListeners;
20276
20277        /**
20278         * Set if the window has requested to extend into the overscan region
20279         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20280         */
20281        boolean mOverscanRequested;
20282
20283        /**
20284         * Set if the visibility of any views has changed.
20285         */
20286        boolean mViewVisibilityChanged;
20287
20288        /**
20289         * Set to true if a view has been scrolled.
20290         */
20291        boolean mViewScrollChanged;
20292
20293        /**
20294         * Set to true if high contrast mode enabled
20295         */
20296        boolean mHighContrastText;
20297
20298        /**
20299         * Global to the view hierarchy used as a temporary for dealing with
20300         * x/y points in the transparent region computations.
20301         */
20302        final int[] mTransparentLocation = new int[2];
20303
20304        /**
20305         * Global to the view hierarchy used as a temporary for dealing with
20306         * x/y points in the ViewGroup.invalidateChild implementation.
20307         */
20308        final int[] mInvalidateChildLocation = new int[2];
20309
20310        /**
20311         * Global to the view hierarchy used as a temporary for dealng with
20312         * computing absolute on-screen location.
20313         */
20314        final int[] mTmpLocation = new int[2];
20315
20316        /**
20317         * Global to the view hierarchy used as a temporary for dealing with
20318         * x/y location when view is transformed.
20319         */
20320        final float[] mTmpTransformLocation = new float[2];
20321
20322        /**
20323         * The view tree observer used to dispatch global events like
20324         * layout, pre-draw, touch mode change, etc.
20325         */
20326        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20327
20328        /**
20329         * A Canvas used by the view hierarchy to perform bitmap caching.
20330         */
20331        Canvas mCanvas;
20332
20333        /**
20334         * The view root impl.
20335         */
20336        final ViewRootImpl mViewRootImpl;
20337
20338        /**
20339         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20340         * handler can be used to pump events in the UI events queue.
20341         */
20342        final Handler mHandler;
20343
20344        /**
20345         * Temporary for use in computing invalidate rectangles while
20346         * calling up the hierarchy.
20347         */
20348        final Rect mTmpInvalRect = new Rect();
20349
20350        /**
20351         * Temporary for use in computing hit areas with transformed views
20352         */
20353        final RectF mTmpTransformRect = new RectF();
20354
20355        /**
20356         * Temporary for use in computing hit areas with transformed views
20357         */
20358        final RectF mTmpTransformRect1 = new RectF();
20359
20360        /**
20361         * Temporary list of rectanges.
20362         */
20363        final List<RectF> mTmpRectList = new ArrayList<>();
20364
20365        /**
20366         * Temporary for use in transforming invalidation rect
20367         */
20368        final Matrix mTmpMatrix = new Matrix();
20369
20370        /**
20371         * Temporary for use in transforming invalidation rect
20372         */
20373        final Transformation mTmpTransformation = new Transformation();
20374
20375        /**
20376         * Temporary for use in querying outlines from OutlineProviders
20377         */
20378        final Outline mTmpOutline = new Outline();
20379
20380        /**
20381         * Temporary list for use in collecting focusable descendents of a view.
20382         */
20383        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20384
20385        /**
20386         * The id of the window for accessibility purposes.
20387         */
20388        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20389
20390        /**
20391         * Flags related to accessibility processing.
20392         *
20393         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20394         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20395         */
20396        int mAccessibilityFetchFlags;
20397
20398        /**
20399         * The drawable for highlighting accessibility focus.
20400         */
20401        Drawable mAccessibilityFocusDrawable;
20402
20403        /**
20404         * Show where the margins, bounds and layout bounds are for each view.
20405         */
20406        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20407
20408        /**
20409         * Point used to compute visible regions.
20410         */
20411        final Point mPoint = new Point();
20412
20413        /**
20414         * Used to track which View originated a requestLayout() call, used when
20415         * requestLayout() is called during layout.
20416         */
20417        View mViewRequestingLayout;
20418
20419        /**
20420         * Creates a new set of attachment information with the specified
20421         * events handler and thread.
20422         *
20423         * @param handler the events handler the view must use
20424         */
20425        AttachInfo(IWindowSession session, IWindow window, Display display,
20426                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20427            mSession = session;
20428            mWindow = window;
20429            mWindowToken = window.asBinder();
20430            mDisplay = display;
20431            mViewRootImpl = viewRootImpl;
20432            mHandler = handler;
20433            mRootCallbacks = effectPlayer;
20434        }
20435    }
20436
20437    /**
20438     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20439     * is supported. This avoids keeping too many unused fields in most
20440     * instances of View.</p>
20441     */
20442    private static class ScrollabilityCache implements Runnable {
20443
20444        /**
20445         * Scrollbars are not visible
20446         */
20447        public static final int OFF = 0;
20448
20449        /**
20450         * Scrollbars are visible
20451         */
20452        public static final int ON = 1;
20453
20454        /**
20455         * Scrollbars are fading away
20456         */
20457        public static final int FADING = 2;
20458
20459        public boolean fadeScrollBars;
20460
20461        public int fadingEdgeLength;
20462        public int scrollBarDefaultDelayBeforeFade;
20463        public int scrollBarFadeDuration;
20464
20465        public int scrollBarSize;
20466        public ScrollBarDrawable scrollBar;
20467        public float[] interpolatorValues;
20468        public View host;
20469
20470        public final Paint paint;
20471        public final Matrix matrix;
20472        public Shader shader;
20473
20474        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20475
20476        private static final float[] OPAQUE = { 255 };
20477        private static final float[] TRANSPARENT = { 0.0f };
20478
20479        /**
20480         * When fading should start. This time moves into the future every time
20481         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20482         */
20483        public long fadeStartTime;
20484
20485
20486        /**
20487         * The current state of the scrollbars: ON, OFF, or FADING
20488         */
20489        public int state = OFF;
20490
20491        private int mLastColor;
20492
20493        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20494            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20495            scrollBarSize = configuration.getScaledScrollBarSize();
20496            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20497            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20498
20499            paint = new Paint();
20500            matrix = new Matrix();
20501            // use use a height of 1, and then wack the matrix each time we
20502            // actually use it.
20503            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20504            paint.setShader(shader);
20505            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20506
20507            this.host = host;
20508        }
20509
20510        public void setFadeColor(int color) {
20511            if (color != mLastColor) {
20512                mLastColor = color;
20513
20514                if (color != 0) {
20515                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20516                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20517                    paint.setShader(shader);
20518                    // Restore the default transfer mode (src_over)
20519                    paint.setXfermode(null);
20520                } else {
20521                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20522                    paint.setShader(shader);
20523                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20524                }
20525            }
20526        }
20527
20528        public void run() {
20529            long now = AnimationUtils.currentAnimationTimeMillis();
20530            if (now >= fadeStartTime) {
20531
20532                // the animation fades the scrollbars out by changing
20533                // the opacity (alpha) from fully opaque to fully
20534                // transparent
20535                int nextFrame = (int) now;
20536                int framesCount = 0;
20537
20538                Interpolator interpolator = scrollBarInterpolator;
20539
20540                // Start opaque
20541                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20542
20543                // End transparent
20544                nextFrame += scrollBarFadeDuration;
20545                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20546
20547                state = FADING;
20548
20549                // Kick off the fade animation
20550                host.invalidate(true);
20551            }
20552        }
20553    }
20554
20555    /**
20556     * Resuable callback for sending
20557     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20558     */
20559    private class SendViewScrolledAccessibilityEvent implements Runnable {
20560        public volatile boolean mIsPending;
20561
20562        public void run() {
20563            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20564            mIsPending = false;
20565        }
20566    }
20567
20568    /**
20569     * <p>
20570     * This class represents a delegate that can be registered in a {@link View}
20571     * to enhance accessibility support via composition rather via inheritance.
20572     * It is specifically targeted to widget developers that extend basic View
20573     * classes i.e. classes in package android.view, that would like their
20574     * applications to be backwards compatible.
20575     * </p>
20576     * <div class="special reference">
20577     * <h3>Developer Guides</h3>
20578     * <p>For more information about making applications accessible, read the
20579     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20580     * developer guide.</p>
20581     * </div>
20582     * <p>
20583     * A scenario in which a developer would like to use an accessibility delegate
20584     * is overriding a method introduced in a later API version then the minimal API
20585     * version supported by the application. For example, the method
20586     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20587     * in API version 4 when the accessibility APIs were first introduced. If a
20588     * developer would like his application to run on API version 4 devices (assuming
20589     * all other APIs used by the application are version 4 or lower) and take advantage
20590     * of this method, instead of overriding the method which would break the application's
20591     * backwards compatibility, he can override the corresponding method in this
20592     * delegate and register the delegate in the target View if the API version of
20593     * the system is high enough i.e. the API version is same or higher to the API
20594     * version that introduced
20595     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20596     * </p>
20597     * <p>
20598     * Here is an example implementation:
20599     * </p>
20600     * <code><pre><p>
20601     * if (Build.VERSION.SDK_INT >= 14) {
20602     *     // If the API version is equal of higher than the version in
20603     *     // which onInitializeAccessibilityNodeInfo was introduced we
20604     *     // register a delegate with a customized implementation.
20605     *     View view = findViewById(R.id.view_id);
20606     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20607     *         public void onInitializeAccessibilityNodeInfo(View host,
20608     *                 AccessibilityNodeInfo info) {
20609     *             // Let the default implementation populate the info.
20610     *             super.onInitializeAccessibilityNodeInfo(host, info);
20611     *             // Set some other information.
20612     *             info.setEnabled(host.isEnabled());
20613     *         }
20614     *     });
20615     * }
20616     * </code></pre></p>
20617     * <p>
20618     * This delegate contains methods that correspond to the accessibility methods
20619     * in View. If a delegate has been specified the implementation in View hands
20620     * off handling to the corresponding method in this delegate. The default
20621     * implementation the delegate methods behaves exactly as the corresponding
20622     * method in View for the case of no accessibility delegate been set. Hence,
20623     * to customize the behavior of a View method, clients can override only the
20624     * corresponding delegate method without altering the behavior of the rest
20625     * accessibility related methods of the host view.
20626     * </p>
20627     */
20628    public static class AccessibilityDelegate {
20629
20630        /**
20631         * Sends an accessibility event of the given type. If accessibility is not
20632         * enabled this method has no effect.
20633         * <p>
20634         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20635         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20636         * been set.
20637         * </p>
20638         *
20639         * @param host The View hosting the delegate.
20640         * @param eventType The type of the event to send.
20641         *
20642         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20643         */
20644        public void sendAccessibilityEvent(View host, int eventType) {
20645            host.sendAccessibilityEventInternal(eventType);
20646        }
20647
20648        /**
20649         * Performs the specified accessibility action on the view. For
20650         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20651         * <p>
20652         * The default implementation behaves as
20653         * {@link View#performAccessibilityAction(int, Bundle)
20654         *  View#performAccessibilityAction(int, Bundle)} for the case of
20655         *  no accessibility delegate been set.
20656         * </p>
20657         *
20658         * @param action The action to perform.
20659         * @return Whether the action was performed.
20660         *
20661         * @see View#performAccessibilityAction(int, Bundle)
20662         *      View#performAccessibilityAction(int, Bundle)
20663         */
20664        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20665            return host.performAccessibilityActionInternal(action, args);
20666        }
20667
20668        /**
20669         * Sends an accessibility event. This method behaves exactly as
20670         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20671         * empty {@link AccessibilityEvent} and does not perform a check whether
20672         * accessibility is enabled.
20673         * <p>
20674         * The default implementation behaves as
20675         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20676         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20677         * the case of no accessibility delegate been set.
20678         * </p>
20679         *
20680         * @param host The View hosting the delegate.
20681         * @param event The event to send.
20682         *
20683         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20684         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20685         */
20686        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20687            host.sendAccessibilityEventUncheckedInternal(event);
20688        }
20689
20690        /**
20691         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20692         * to its children for adding their text content to the event.
20693         * <p>
20694         * The default implementation behaves as
20695         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20696         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20697         * the case of no accessibility delegate been set.
20698         * </p>
20699         *
20700         * @param host The View hosting the delegate.
20701         * @param event The event.
20702         * @return True if the event population was completed.
20703         *
20704         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20705         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20706         */
20707        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20708            return host.dispatchPopulateAccessibilityEventInternal(event);
20709        }
20710
20711        /**
20712         * Gives a chance to the host View to populate the accessibility event with its
20713         * text content.
20714         * <p>
20715         * The default implementation behaves as
20716         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20717         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20718         * the case of no accessibility delegate been set.
20719         * </p>
20720         *
20721         * @param host The View hosting the delegate.
20722         * @param event The accessibility event which to populate.
20723         *
20724         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20725         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20726         */
20727        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20728            host.onPopulateAccessibilityEventInternal(event);
20729        }
20730
20731        /**
20732         * Initializes an {@link AccessibilityEvent} with information about the
20733         * the host View which is the event source.
20734         * <p>
20735         * The default implementation behaves as
20736         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20737         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20738         * the case of no accessibility delegate been set.
20739         * </p>
20740         *
20741         * @param host The View hosting the delegate.
20742         * @param event The event to initialize.
20743         *
20744         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20745         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20746         */
20747        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20748            host.onInitializeAccessibilityEventInternal(event);
20749        }
20750
20751        /**
20752         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20753         * <p>
20754         * The default implementation behaves as
20755         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20756         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20757         * the case of no accessibility delegate been set.
20758         * </p>
20759         *
20760         * @param host The View hosting the delegate.
20761         * @param info The instance to initialize.
20762         *
20763         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20764         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20765         */
20766        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20767            host.onInitializeAccessibilityNodeInfoInternal(info);
20768        }
20769
20770        /**
20771         * Called when a child of the host View has requested sending an
20772         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20773         * to augment the event.
20774         * <p>
20775         * The default implementation behaves as
20776         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20777         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20778         * the case of no accessibility delegate been set.
20779         * </p>
20780         *
20781         * @param host The View hosting the delegate.
20782         * @param child The child which requests sending the event.
20783         * @param event The event to be sent.
20784         * @return True if the event should be sent
20785         *
20786         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20787         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20788         */
20789        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20790                AccessibilityEvent event) {
20791            return host.onRequestSendAccessibilityEventInternal(child, event);
20792        }
20793
20794        /**
20795         * Gets the provider for managing a virtual view hierarchy rooted at this View
20796         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20797         * that explore the window content.
20798         * <p>
20799         * The default implementation behaves as
20800         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20801         * the case of no accessibility delegate been set.
20802         * </p>
20803         *
20804         * @return The provider.
20805         *
20806         * @see AccessibilityNodeProvider
20807         */
20808        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20809            return null;
20810        }
20811
20812        /**
20813         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20814         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20815         * This method is responsible for obtaining an accessibility node info from a
20816         * pool of reusable instances and calling
20817         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20818         * view to initialize the former.
20819         * <p>
20820         * <strong>Note:</strong> The client is responsible for recycling the obtained
20821         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20822         * creation.
20823         * </p>
20824         * <p>
20825         * The default implementation behaves as
20826         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20827         * the case of no accessibility delegate been set.
20828         * </p>
20829         * @return A populated {@link AccessibilityNodeInfo}.
20830         *
20831         * @see AccessibilityNodeInfo
20832         *
20833         * @hide
20834         */
20835        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20836            return host.createAccessibilityNodeInfoInternal();
20837        }
20838    }
20839
20840    private class MatchIdPredicate implements Predicate<View> {
20841        public int mId;
20842
20843        @Override
20844        public boolean apply(View view) {
20845            return (view.mID == mId);
20846        }
20847    }
20848
20849    private class MatchLabelForPredicate implements Predicate<View> {
20850        private int mLabeledId;
20851
20852        @Override
20853        public boolean apply(View view) {
20854            return (view.mLabelForId == mLabeledId);
20855        }
20856    }
20857
20858    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20859        private int mChangeTypes = 0;
20860        private boolean mPosted;
20861        private boolean mPostedWithDelay;
20862        private long mLastEventTimeMillis;
20863
20864        @Override
20865        public void run() {
20866            mPosted = false;
20867            mPostedWithDelay = false;
20868            mLastEventTimeMillis = SystemClock.uptimeMillis();
20869            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20870                final AccessibilityEvent event = AccessibilityEvent.obtain();
20871                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20872                event.setContentChangeTypes(mChangeTypes);
20873                sendAccessibilityEventUnchecked(event);
20874            }
20875            mChangeTypes = 0;
20876        }
20877
20878        public void runOrPost(int changeType) {
20879            mChangeTypes |= changeType;
20880
20881            // If this is a live region or the child of a live region, collect
20882            // all events from this frame and send them on the next frame.
20883            if (inLiveRegion()) {
20884                // If we're already posted with a delay, remove that.
20885                if (mPostedWithDelay) {
20886                    removeCallbacks(this);
20887                    mPostedWithDelay = false;
20888                }
20889                // Only post if we're not already posted.
20890                if (!mPosted) {
20891                    post(this);
20892                    mPosted = true;
20893                }
20894                return;
20895            }
20896
20897            if (mPosted) {
20898                return;
20899            }
20900
20901            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20902            final long minEventIntevalMillis =
20903                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20904            if (timeSinceLastMillis >= minEventIntevalMillis) {
20905                removeCallbacks(this);
20906                run();
20907            } else {
20908                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20909                mPostedWithDelay = true;
20910            }
20911        }
20912    }
20913
20914    private boolean inLiveRegion() {
20915        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20916            return true;
20917        }
20918
20919        ViewParent parent = getParent();
20920        while (parent instanceof View) {
20921            if (((View) parent).getAccessibilityLiveRegion()
20922                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20923                return true;
20924            }
20925            parent = parent.getParent();
20926        }
20927
20928        return false;
20929    }
20930
20931    /**
20932     * Dump all private flags in readable format, useful for documentation and
20933     * sanity checking.
20934     */
20935    private static void dumpFlags() {
20936        final HashMap<String, String> found = Maps.newHashMap();
20937        try {
20938            for (Field field : View.class.getDeclaredFields()) {
20939                final int modifiers = field.getModifiers();
20940                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20941                    if (field.getType().equals(int.class)) {
20942                        final int value = field.getInt(null);
20943                        dumpFlag(found, field.getName(), value);
20944                    } else if (field.getType().equals(int[].class)) {
20945                        final int[] values = (int[]) field.get(null);
20946                        for (int i = 0; i < values.length; i++) {
20947                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20948                        }
20949                    }
20950                }
20951            }
20952        } catch (IllegalAccessException e) {
20953            throw new RuntimeException(e);
20954        }
20955
20956        final ArrayList<String> keys = Lists.newArrayList();
20957        keys.addAll(found.keySet());
20958        Collections.sort(keys);
20959        for (String key : keys) {
20960            Log.d(VIEW_LOG_TAG, found.get(key));
20961        }
20962    }
20963
20964    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20965        // Sort flags by prefix, then by bits, always keeping unique keys
20966        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20967        final int prefix = name.indexOf('_');
20968        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20969        final String output = bits + " " + name;
20970        found.put(key, output);
20971    }
20972}
20973