View.java revision 8de1494557cf1d00c1c3fce439138a28de7fbd61
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.RevealAnimator;
21import android.animation.StateListAnimator;
22import android.animation.ValueAnimator;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.content.ClipData;
27import android.content.Context;
28import android.content.res.ColorStateList;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.content.res.TypedArray;
32import android.graphics.Bitmap;
33import android.graphics.Canvas;
34import android.graphics.Insets;
35import android.graphics.Interpolator;
36import android.graphics.LinearGradient;
37import android.graphics.Matrix;
38import android.graphics.Outline;
39import android.graphics.Paint;
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;
94
95import com.google.android.collect.Lists;
96import com.google.android.collect.Maps;
97
98import java.lang.annotation.Retention;
99import java.lang.annotation.RetentionPolicy;
100import java.lang.ref.WeakReference;
101import java.lang.reflect.Field;
102import java.lang.reflect.InvocationTargetException;
103import java.lang.reflect.Method;
104import java.lang.reflect.Modifier;
105import java.util.ArrayList;
106import java.util.Arrays;
107import java.util.Collections;
108import java.util.HashMap;
109import java.util.List;
110import java.util.Locale;
111import java.util.Map;
112import java.util.concurrent.CopyOnWriteArrayList;
113import java.util.concurrent.atomic.AtomicInteger;
114
115/**
116 * <p>
117 * This class represents the basic building block for user interface components. A View
118 * occupies a rectangular area on the screen and is responsible for drawing and
119 * event handling. View is the base class for <em>widgets</em>, which are
120 * used to create interactive UI components (buttons, text fields, etc.). The
121 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
122 * are invisible containers that hold other Views (or other ViewGroups) and define
123 * their layout properties.
124 * </p>
125 *
126 * <div class="special reference">
127 * <h3>Developer Guides</h3>
128 * <p>For information about using this class to develop your application's user interface,
129 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
130 * </div>
131 *
132 * <a name="Using"></a>
133 * <h3>Using Views</h3>
134 * <p>
135 * All of the views in a window are arranged in a single tree. You can add views
136 * either from code or by specifying a tree of views in one or more XML layout
137 * files. There are many specialized subclasses of views that act as controls or
138 * are capable of displaying text, images, or other content.
139 * </p>
140 * <p>
141 * Once you have created a tree of views, there are typically a few types of
142 * common operations you may wish to perform:
143 * <ul>
144 * <li><strong>Set properties:</strong> for example setting the text of a
145 * {@link android.widget.TextView}. The available properties and the methods
146 * that set them will vary among the different subclasses of views. Note that
147 * properties that are known at build time can be set in the XML layout
148 * files.</li>
149 * <li><strong>Set focus:</strong> The framework will handled moving focus in
150 * response to user input. To force focus to a specific view, call
151 * {@link #requestFocus}.</li>
152 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
153 * that will be notified when something interesting happens to the view. For
154 * example, all views will let you set a listener to be notified when the view
155 * gains or loses focus. You can register such a listener using
156 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
157 * Other view subclasses offer more specialized listeners. For example, a Button
158 * exposes a listener to notify clients when the button is clicked.</li>
159 * <li><strong>Set visibility:</strong> You can hide or show views using
160 * {@link #setVisibility(int)}.</li>
161 * </ul>
162 * </p>
163 * <p><em>
164 * Note: The Android framework is responsible for measuring, laying out and
165 * drawing views. You should not call methods that perform these actions on
166 * views yourself unless you are actually implementing a
167 * {@link android.view.ViewGroup}.
168 * </em></p>
169 *
170 * <a name="Lifecycle"></a>
171 * <h3>Implementing a Custom View</h3>
172 *
173 * <p>
174 * To implement a custom view, you will usually begin by providing overrides for
175 * some of the standard methods that the framework calls on all views. You do
176 * not need to override all of these methods. In fact, you can start by just
177 * overriding {@link #onDraw(android.graphics.Canvas)}.
178 * <table border="2" width="85%" align="center" cellpadding="5">
179 *     <thead>
180 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
181 *     </thead>
182 *
183 *     <tbody>
184 *     <tr>
185 *         <td rowspan="2">Creation</td>
186 *         <td>Constructors</td>
187 *         <td>There is a form of the constructor that are called when the view
188 *         is created from code and a form that is called when the view is
189 *         inflated from a layout file. The second form should parse and apply
190 *         any attributes defined in the layout file.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onFinishInflate()}</code></td>
195 *         <td>Called after a view and all of its children has been inflated
196 *         from XML.</td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td rowspan="3">Layout</td>
201 *         <td><code>{@link #onMeasure(int, int)}</code></td>
202 *         <td>Called to determine the size requirements for this view and all
203 *         of its children.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
208 *         <td>Called when this view should assign a size and position to all
209 *         of its children.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
214 *         <td>Called when the size of this view has changed.
215 *         </td>
216 *     </tr>
217 *
218 *     <tr>
219 *         <td>Drawing</td>
220 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
221 *         <td>Called when the view should render its content.
222 *         </td>
223 *     </tr>
224 *
225 *     <tr>
226 *         <td rowspan="4">Event processing</td>
227 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
228 *         <td>Called when a new hardware key event occurs.
229 *         </td>
230 *     </tr>
231 *     <tr>
232 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
233 *         <td>Called when a hardware key up event occurs.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
238 *         <td>Called when a trackball motion event occurs.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
243 *         <td>Called when a touch screen motion event occurs.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="2">Focus</td>
249 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
250 *         <td>Called when the view gains or loses focus.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
256 *         <td>Called when the window containing the view gains or loses focus.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td rowspan="3">Attaching</td>
262 *         <td><code>{@link #onAttachedToWindow()}</code></td>
263 *         <td>Called when the view is attached to a window.
264 *         </td>
265 *     </tr>
266 *
267 *     <tr>
268 *         <td><code>{@link #onDetachedFromWindow}</code></td>
269 *         <td>Called when the view is detached from its window.
270 *         </td>
271 *     </tr>
272 *
273 *     <tr>
274 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
275 *         <td>Called when the visibility of the window containing the view
276 *         has changed.
277 *         </td>
278 *     </tr>
279 *     </tbody>
280 *
281 * </table>
282 * </p>
283 *
284 * <a name="IDs"></a>
285 * <h3>IDs</h3>
286 * Views may have an integer id associated with them. These ids are typically
287 * assigned in the layout XML files, and are used to find specific views within
288 * the view tree. A common pattern is to:
289 * <ul>
290 * <li>Define a Button in the layout file and assign it a unique ID.
291 * <pre>
292 * &lt;Button
293 *     android:id="@+id/my_button"
294 *     android:layout_width="wrap_content"
295 *     android:layout_height="wrap_content"
296 *     android:text="@string/my_button_text"/&gt;
297 * </pre></li>
298 * <li>From the onCreate method of an Activity, find the Button
299 * <pre class="prettyprint">
300 *      Button myButton = (Button) findViewById(R.id.my_button);
301 * </pre></li>
302 * </ul>
303 * <p>
304 * View IDs need not be unique throughout the tree, but it is good practice to
305 * ensure that they are at least unique within the part of the tree you are
306 * searching.
307 * </p>
308 *
309 * <a name="Position"></a>
310 * <h3>Position</h3>
311 * <p>
312 * The geometry of a view is that of a rectangle. A view has a location,
313 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
314 * two dimensions, expressed as a width and a height. The unit for location
315 * and dimensions is the pixel.
316 * </p>
317 *
318 * <p>
319 * It is possible to retrieve the location of a view by invoking the methods
320 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
321 * coordinate of the rectangle representing the view. The latter returns the
322 * top, or Y, coordinate of the rectangle representing the view. These methods
323 * both return the location of the view relative to its parent. For instance,
324 * when getLeft() returns 20, that means the view is located 20 pixels to the
325 * right of the left edge of its direct parent.
326 * </p>
327 *
328 * <p>
329 * In addition, several convenience methods are offered to avoid unnecessary
330 * computations, namely {@link #getRight()} and {@link #getBottom()}.
331 * These methods return the coordinates of the right and bottom edges of the
332 * rectangle representing the view. For instance, calling {@link #getRight()}
333 * is similar to the following computation: <code>getLeft() + getWidth()</code>
334 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
335 * </p>
336 *
337 * <a name="SizePaddingMargins"></a>
338 * <h3>Size, padding and margins</h3>
339 * <p>
340 * The size of a view is expressed with a width and a height. A view actually
341 * possess two pairs of width and height values.
342 * </p>
343 *
344 * <p>
345 * The first pair is known as <em>measured width</em> and
346 * <em>measured height</em>. These dimensions define how big a view wants to be
347 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
348 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
349 * and {@link #getMeasuredHeight()}.
350 * </p>
351 *
352 * <p>
353 * The second pair is simply known as <em>width</em> and <em>height</em>, or
354 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
355 * dimensions define the actual size of the view on screen, at drawing time and
356 * after layout. These values may, but do not have to, be different from the
357 * measured width and height. The width and height can be obtained by calling
358 * {@link #getWidth()} and {@link #getHeight()}.
359 * </p>
360 *
361 * <p>
362 * To measure its dimensions, a view takes into account its padding. The padding
363 * is expressed in pixels for the left, top, right and bottom parts of the view.
364 * Padding can be used to offset the content of the view by a specific amount of
365 * pixels. For instance, a left padding of 2 will push the view's content by
366 * 2 pixels to the right of the left edge. Padding can be set using the
367 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
368 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
369 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
370 * {@link #getPaddingEnd()}.
371 * </p>
372 *
373 * <p>
374 * Even though a view can define a padding, it does not provide any support for
375 * margins. However, view groups provide such a support. Refer to
376 * {@link android.view.ViewGroup} and
377 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
378 * </p>
379 *
380 * <a name="Layout"></a>
381 * <h3>Layout</h3>
382 * <p>
383 * Layout is a two pass process: a measure pass and a layout pass. The measuring
384 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
385 * of the view tree. Each view pushes dimension specifications down the tree
386 * during the recursion. At the end of the measure pass, every view has stored
387 * its measurements. The second pass happens in
388 * {@link #layout(int,int,int,int)} and is also top-down. During
389 * this pass each parent is responsible for positioning all of its children
390 * using the sizes computed in the measure pass.
391 * </p>
392 *
393 * <p>
394 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
395 * {@link #getMeasuredHeight()} values must be set, along with those for all of
396 * that view's descendants. A view's measured width and measured height values
397 * must respect the constraints imposed by the view's parents. This guarantees
398 * that at the end of the measure pass, all parents accept all of their
399 * children's measurements. A parent view may call measure() more than once on
400 * its children. For example, the parent may measure each child once with
401 * unspecified dimensions to find out how big they want to be, then call
402 * measure() on them again with actual numbers if the sum of all the children's
403 * unconstrained sizes is too big or too small.
404 * </p>
405 *
406 * <p>
407 * The measure pass uses two classes to communicate dimensions. The
408 * {@link MeasureSpec} class is used by views to tell their parents how they
409 * want to be measured and positioned. The base LayoutParams class just
410 * describes how big the view wants to be for both width and height. For each
411 * dimension, it can specify one of:
412 * <ul>
413 * <li> an exact number
414 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
415 * (minus padding)
416 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
417 * enclose its content (plus padding).
418 * </ul>
419 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
420 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
421 * an X and Y value.
422 * </p>
423 *
424 * <p>
425 * MeasureSpecs are used to push requirements down the tree from parent to
426 * child. A MeasureSpec can be in one of three modes:
427 * <ul>
428 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
429 * of a child view. For example, a LinearLayout may call measure() on its child
430 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
431 * tall the child view wants to be given a width of 240 pixels.
432 * <li>EXACTLY: This is used by the parent to impose an exact size on the
433 * child. The child must use this size, and guarantee that all of its
434 * descendants will fit within this size.
435 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
436 * child. The child must guarantee that it and all of its descendants will fit
437 * within this size.
438 * </ul>
439 * </p>
440 *
441 * <p>
442 * To intiate a layout, call {@link #requestLayout}. This method is typically
443 * called by a view on itself when it believes that is can no longer fit within
444 * its current bounds.
445 * </p>
446 *
447 * <a name="Drawing"></a>
448 * <h3>Drawing</h3>
449 * <p>
450 * Drawing is handled by walking the tree and rendering each view that
451 * intersects the invalid region. Because the tree is traversed in-order,
452 * this means that parents will draw before (i.e., behind) their children, with
453 * siblings drawn in the order they appear in the tree.
454 * If you set a background drawable for a View, then the View will draw it for you
455 * before calling back to its <code>onDraw()</code> method.
456 * </p>
457 *
458 * <p>
459 * Note that the framework will not draw views that are not in the invalid region.
460 * </p>
461 *
462 * <p>
463 * To force a view to draw, call {@link #invalidate()}.
464 * </p>
465 *
466 * <a name="EventHandlingThreading"></a>
467 * <h3>Event Handling and Threading</h3>
468 * <p>
469 * The basic cycle of a view is as follows:
470 * <ol>
471 * <li>An event comes in and is dispatched to the appropriate view. The view
472 * handles the event and notifies any listeners.</li>
473 * <li>If in the course of processing the event, the view's bounds may need
474 * to be changed, the view will call {@link #requestLayout()}.</li>
475 * <li>Similarly, if in the course of processing the event the view's appearance
476 * may need to be changed, the view will call {@link #invalidate()}.</li>
477 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
478 * the framework will take care of measuring, laying out, and drawing the tree
479 * as appropriate.</li>
480 * </ol>
481 * </p>
482 *
483 * <p><em>Note: The entire view tree is single threaded. You must always be on
484 * the UI thread when calling any method on any view.</em>
485 * If you are doing work on other threads and want to update the state of a view
486 * from that thread, you should use a {@link Handler}.
487 * </p>
488 *
489 * <a name="FocusHandling"></a>
490 * <h3>Focus Handling</h3>
491 * <p>
492 * The framework will handle routine focus movement in response to user input.
493 * This includes changing the focus as views are removed or hidden, or as new
494 * views become available. Views indicate their willingness to take focus
495 * through the {@link #isFocusable} method. To change whether a view can take
496 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
497 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
498 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
499 * </p>
500 * <p>
501 * Focus movement is based on an algorithm which finds the nearest neighbor in a
502 * given direction. In rare cases, the default algorithm may not match the
503 * intended behavior of the developer. In these situations, you can provide
504 * explicit overrides by using these XML attributes in the layout file:
505 * <pre>
506 * nextFocusDown
507 * nextFocusLeft
508 * nextFocusRight
509 * nextFocusUp
510 * </pre>
511 * </p>
512 *
513 *
514 * <p>
515 * To get a particular view to take focus, call {@link #requestFocus()}.
516 * </p>
517 *
518 * <a name="TouchMode"></a>
519 * <h3>Touch Mode</h3>
520 * <p>
521 * When a user is navigating a user interface via directional keys such as a D-pad, it is
522 * necessary to give focus to actionable items such as buttons so the user can see
523 * what will take input.  If the device has touch capabilities, however, and the user
524 * begins interacting with the interface by touching it, it is no longer necessary to
525 * always highlight, or give focus to, a particular view.  This motivates a mode
526 * for interaction named 'touch mode'.
527 * </p>
528 * <p>
529 * For a touch capable device, once the user touches the screen, the device
530 * will enter touch mode.  From this point onward, only views for which
531 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
532 * Other views that are touchable, like buttons, will not take focus when touched; they will
533 * only fire the on click listeners.
534 * </p>
535 * <p>
536 * Any time a user hits a directional key, such as a D-pad direction, the view device will
537 * exit touch mode, and find a view to take focus, so that the user may resume interacting
538 * with the user interface without touching the screen again.
539 * </p>
540 * <p>
541 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
542 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
543 * </p>
544 *
545 * <a name="Scrolling"></a>
546 * <h3>Scrolling</h3>
547 * <p>
548 * The framework provides basic support for views that wish to internally
549 * scroll their content. This includes keeping track of the X and Y scroll
550 * offset as well as mechanisms for drawing scrollbars. See
551 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
552 * {@link #awakenScrollBars()} for more details.
553 * </p>
554 *
555 * <a name="Tags"></a>
556 * <h3>Tags</h3>
557 * <p>
558 * Unlike IDs, tags are not used to identify views. Tags are essentially an
559 * extra piece of information that can be associated with a view. They are most
560 * often used as a convenience to store data related to views in the views
561 * themselves rather than by putting them in a separate structure.
562 * </p>
563 *
564 * <a name="Properties"></a>
565 * <h3>Properties</h3>
566 * <p>
567 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
568 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
569 * available both in the {@link Property} form as well as in similarly-named setter/getter
570 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
571 * be used to set persistent state associated with these rendering-related properties on the view.
572 * The properties and methods can also be used in conjunction with
573 * {@link android.animation.Animator Animator}-based animations, described more in the
574 * <a href="#Animation">Animation</a> section.
575 * </p>
576 *
577 * <a name="Animation"></a>
578 * <h3>Animation</h3>
579 * <p>
580 * Starting with Android 3.0, the preferred way of animating views is to use the
581 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
582 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
583 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
584 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
585 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
586 * makes animating these View properties particularly easy and efficient.
587 * </p>
588 * <p>
589 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
590 * You can attach an {@link Animation} object to a view using
591 * {@link #setAnimation(Animation)} or
592 * {@link #startAnimation(Animation)}. The animation can alter the scale,
593 * rotation, translation and alpha of a view over time. If the animation is
594 * attached to a view that has children, the animation will affect the entire
595 * subtree rooted by that node. When an animation is started, the framework will
596 * take care of redrawing the appropriate views until the animation completes.
597 * </p>
598 *
599 * <a name="Security"></a>
600 * <h3>Security</h3>
601 * <p>
602 * Sometimes it is essential that an application be able to verify that an action
603 * is being performed with the full knowledge and consent of the user, such as
604 * granting a permission request, making a purchase or clicking on an advertisement.
605 * Unfortunately, a malicious application could try to spoof the user into
606 * performing these actions, unaware, by concealing the intended purpose of the view.
607 * As a remedy, the framework offers a touch filtering mechanism that can be used to
608 * improve the security of views that provide access to sensitive functionality.
609 * </p><p>
610 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
611 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
612 * will discard touches that are received whenever the view's window is obscured by
613 * another visible window.  As a result, the view will not receive touches whenever a
614 * toast, dialog or other window appears above the view's window.
615 * </p><p>
616 * For more fine-grained control over security, consider overriding the
617 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
618 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
619 * </p>
620 *
621 * @attr ref android.R.styleable#View_alpha
622 * @attr ref android.R.styleable#View_background
623 * @attr ref android.R.styleable#View_clickable
624 * @attr ref android.R.styleable#View_contentDescription
625 * @attr ref android.R.styleable#View_drawingCacheQuality
626 * @attr ref android.R.styleable#View_duplicateParentState
627 * @attr ref android.R.styleable#View_id
628 * @attr ref android.R.styleable#View_requiresFadingEdge
629 * @attr ref android.R.styleable#View_fadeScrollbars
630 * @attr ref android.R.styleable#View_fadingEdgeLength
631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
632 * @attr ref android.R.styleable#View_fitsSystemWindows
633 * @attr ref android.R.styleable#View_isScrollContainer
634 * @attr ref android.R.styleable#View_focusable
635 * @attr ref android.R.styleable#View_focusableInTouchMode
636 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
637 * @attr ref android.R.styleable#View_keepScreenOn
638 * @attr ref android.R.styleable#View_layerType
639 * @attr ref android.R.styleable#View_layoutDirection
640 * @attr ref android.R.styleable#View_longClickable
641 * @attr ref android.R.styleable#View_minHeight
642 * @attr ref android.R.styleable#View_minWidth
643 * @attr ref android.R.styleable#View_nextFocusDown
644 * @attr ref android.R.styleable#View_nextFocusLeft
645 * @attr ref android.R.styleable#View_nextFocusRight
646 * @attr ref android.R.styleable#View_nextFocusUp
647 * @attr ref android.R.styleable#View_onClick
648 * @attr ref android.R.styleable#View_padding
649 * @attr ref android.R.styleable#View_paddingBottom
650 * @attr ref android.R.styleable#View_paddingLeft
651 * @attr ref android.R.styleable#View_paddingRight
652 * @attr ref android.R.styleable#View_paddingTop
653 * @attr ref android.R.styleable#View_paddingStart
654 * @attr ref android.R.styleable#View_paddingEnd
655 * @attr ref android.R.styleable#View_saveEnabled
656 * @attr ref android.R.styleable#View_rotation
657 * @attr ref android.R.styleable#View_rotationX
658 * @attr ref android.R.styleable#View_rotationY
659 * @attr ref android.R.styleable#View_scaleX
660 * @attr ref android.R.styleable#View_scaleY
661 * @attr ref android.R.styleable#View_scrollX
662 * @attr ref android.R.styleable#View_scrollY
663 * @attr ref android.R.styleable#View_scrollbarSize
664 * @attr ref android.R.styleable#View_scrollbarStyle
665 * @attr ref android.R.styleable#View_scrollbars
666 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
667 * @attr ref android.R.styleable#View_scrollbarFadeDuration
668 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
669 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
670 * @attr ref android.R.styleable#View_scrollbarThumbVertical
671 * @attr ref android.R.styleable#View_scrollbarTrackVertical
672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
673 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
674 * @attr ref android.R.styleable#View_stateListAnimator
675 * @attr ref android.R.styleable#View_viewName
676 * @attr ref android.R.styleable#View_soundEffectsEnabled
677 * @attr ref android.R.styleable#View_tag
678 * @attr ref android.R.styleable#View_textAlignment
679 * @attr ref android.R.styleable#View_textDirection
680 * @attr ref android.R.styleable#View_transformPivotX
681 * @attr ref android.R.styleable#View_transformPivotY
682 * @attr ref android.R.styleable#View_translationX
683 * @attr ref android.R.styleable#View_translationY
684 * @attr ref android.R.styleable#View_translationZ
685 * @attr ref android.R.styleable#View_visibility
686 *
687 * @see android.view.ViewGroup
688 */
689public class View implements Drawable.Callback, KeyEvent.Callback,
690        AccessibilityEventSource {
691    private static final boolean DBG = false;
692
693    /**
694     * The logging tag used by this class with android.util.Log.
695     */
696    protected static final String VIEW_LOG_TAG = "View";
697
698    /**
699     * When set to true, apps will draw debugging information about their layouts.
700     *
701     * @hide
702     */
703    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
704
705    /**
706     * Used to mark a View that has no ID.
707     */
708    public static final int NO_ID = -1;
709
710    /**
711     * Signals that compatibility booleans have been initialized according to
712     * target SDK versions.
713     */
714    private static boolean sCompatibilityDone = false;
715
716    /**
717     * Use the old (broken) way of building MeasureSpecs.
718     */
719    private static boolean sUseBrokenMakeMeasureSpec = false;
720
721    /**
722     * Ignore any optimizations using the measure cache.
723     */
724    private static boolean sIgnoreMeasureCache = false;
725
726    /**
727     * Ignore the clipBounds of this view for the children.
728     */
729    static boolean sIgnoreClipBoundsForChildren = false;
730
731    /**
732     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
733     * calling setFlags.
734     */
735    private static final int NOT_FOCUSABLE = 0x00000000;
736
737    /**
738     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
739     * setFlags.
740     */
741    private static final int FOCUSABLE = 0x00000001;
742
743    /**
744     * Mask for use with setFlags indicating bits used for focus.
745     */
746    private static final int FOCUSABLE_MASK = 0x00000001;
747
748    /**
749     * This view will adjust its padding to fit sytem windows (e.g. status bar)
750     */
751    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
752
753    /** @hide */
754    @IntDef({VISIBLE, INVISIBLE, GONE})
755    @Retention(RetentionPolicy.SOURCE)
756    public @interface Visibility {}
757
758    /**
759     * This view is visible.
760     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
761     * android:visibility}.
762     */
763    public static final int VISIBLE = 0x00000000;
764
765    /**
766     * This view is invisible, but it still takes up space for layout purposes.
767     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
768     * android:visibility}.
769     */
770    public static final int INVISIBLE = 0x00000004;
771
772    /**
773     * This view is invisible, and it doesn't take any space for layout
774     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
775     * android:visibility}.
776     */
777    public static final int GONE = 0x00000008;
778
779    /**
780     * Mask for use with setFlags indicating bits used for visibility.
781     * {@hide}
782     */
783    static final int VISIBILITY_MASK = 0x0000000C;
784
785    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
786
787    /**
788     * This view is enabled. Interpretation varies by subclass.
789     * Use with ENABLED_MASK when calling setFlags.
790     * {@hide}
791     */
792    static final int ENABLED = 0x00000000;
793
794    /**
795     * This view is disabled. Interpretation varies by subclass.
796     * Use with ENABLED_MASK when calling setFlags.
797     * {@hide}
798     */
799    static final int DISABLED = 0x00000020;
800
801   /**
802    * Mask for use with setFlags indicating bits used for indicating whether
803    * this view is enabled
804    * {@hide}
805    */
806    static final int ENABLED_MASK = 0x00000020;
807
808    /**
809     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
810     * called and further optimizations will be performed. It is okay to have
811     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
812     * {@hide}
813     */
814    static final int WILL_NOT_DRAW = 0x00000080;
815
816    /**
817     * Mask for use with setFlags indicating bits used for indicating whether
818     * this view is will draw
819     * {@hide}
820     */
821    static final int DRAW_MASK = 0x00000080;
822
823    /**
824     * <p>This view doesn't show scrollbars.</p>
825     * {@hide}
826     */
827    static final int SCROLLBARS_NONE = 0x00000000;
828
829    /**
830     * <p>This view shows horizontal scrollbars.</p>
831     * {@hide}
832     */
833    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
834
835    /**
836     * <p>This view shows vertical scrollbars.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_VERTICAL = 0x00000200;
840
841    /**
842     * <p>Mask for use with setFlags indicating bits used for indicating which
843     * scrollbars are enabled.</p>
844     * {@hide}
845     */
846    static final int SCROLLBARS_MASK = 0x00000300;
847
848    /**
849     * Indicates that the view should filter touches when its window is obscured.
850     * Refer to the class comments for more information about this security feature.
851     * {@hide}
852     */
853    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
854
855    /**
856     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
857     * that they are optional and should be skipped if the window has
858     * requested system UI flags that ignore those insets for layout.
859     */
860    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
861
862    /**
863     * <p>This view doesn't show fading edges.</p>
864     * {@hide}
865     */
866    static final int FADING_EDGE_NONE = 0x00000000;
867
868    /**
869     * <p>This view shows horizontal fading edges.</p>
870     * {@hide}
871     */
872    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
873
874    /**
875     * <p>This view shows vertical fading edges.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_VERTICAL = 0x00002000;
879
880    /**
881     * <p>Mask for use with setFlags indicating bits used for indicating which
882     * fading edges are enabled.</p>
883     * {@hide}
884     */
885    static final int FADING_EDGE_MASK = 0x00003000;
886
887    /**
888     * <p>Indicates this view can be clicked. When clickable, a View reacts
889     * to clicks by notifying the OnClickListener.<p>
890     * {@hide}
891     */
892    static final int CLICKABLE = 0x00004000;
893
894    /**
895     * <p>Indicates this view is caching its drawing into a bitmap.</p>
896     * {@hide}
897     */
898    static final int DRAWING_CACHE_ENABLED = 0x00008000;
899
900    /**
901     * <p>Indicates that no icicle should be saved for this view.<p>
902     * {@hide}
903     */
904    static final int SAVE_DISABLED = 0x000010000;
905
906    /**
907     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
908     * property.</p>
909     * {@hide}
910     */
911    static final int SAVE_DISABLED_MASK = 0x000010000;
912
913    /**
914     * <p>Indicates that no drawing cache should ever be created for this view.<p>
915     * {@hide}
916     */
917    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
918
919    /**
920     * <p>Indicates this view can take / keep focus when int touch mode.</p>
921     * {@hide}
922     */
923    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
924
925    /** @hide */
926    @Retention(RetentionPolicy.SOURCE)
927    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
928    public @interface DrawingCacheQuality {}
929
930    /**
931     * <p>Enables low quality mode for the drawing cache.</p>
932     */
933    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
934
935    /**
936     * <p>Enables high quality mode for the drawing cache.</p>
937     */
938    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
939
940    /**
941     * <p>Enables automatic quality mode for the drawing cache.</p>
942     */
943    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
944
945    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
946            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
947    };
948
949    /**
950     * <p>Mask for use with setFlags indicating bits used for the cache
951     * quality property.</p>
952     * {@hide}
953     */
954    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
955
956    /**
957     * <p>
958     * Indicates this view can be long clicked. When long clickable, a View
959     * reacts to long clicks by notifying the OnLongClickListener or showing a
960     * context menu.
961     * </p>
962     * {@hide}
963     */
964    static final int LONG_CLICKABLE = 0x00200000;
965
966    /**
967     * <p>Indicates that this view gets its drawable states from its direct parent
968     * and ignores its original internal states.</p>
969     *
970     * @hide
971     */
972    static final int DUPLICATE_PARENT_STATE = 0x00400000;
973
974    /** @hide */
975    @IntDef({
976        SCROLLBARS_INSIDE_OVERLAY,
977        SCROLLBARS_INSIDE_INSET,
978        SCROLLBARS_OUTSIDE_OVERLAY,
979        SCROLLBARS_OUTSIDE_INSET
980    })
981    @Retention(RetentionPolicy.SOURCE)
982    public @interface ScrollBarStyle {}
983
984    /**
985     * The scrollbar style to display the scrollbars inside the content area,
986     * without increasing the padding. The scrollbars will be overlaid with
987     * translucency on the view's content.
988     */
989    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
990
991    /**
992     * The scrollbar style to display the scrollbars inside the padded area,
993     * increasing the padding of the view. The scrollbars will not overlap the
994     * content area of the view.
995     */
996    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
997
998    /**
999     * The scrollbar style to display the scrollbars at the edge of the view,
1000     * without increasing the padding. The scrollbars will be overlaid with
1001     * translucency.
1002     */
1003    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1004
1005    /**
1006     * The scrollbar style to display the scrollbars at the edge of the view,
1007     * increasing the padding of the view. The scrollbars will only overlap the
1008     * background, if any.
1009     */
1010    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1011
1012    /**
1013     * Mask to check if the scrollbar style is overlay or inset.
1014     * {@hide}
1015     */
1016    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1017
1018    /**
1019     * Mask to check if the scrollbar style is inside or outside.
1020     * {@hide}
1021     */
1022    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1023
1024    /**
1025     * Mask for scrollbar style.
1026     * {@hide}
1027     */
1028    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1029
1030    /**
1031     * View flag indicating that the screen should remain on while the
1032     * window containing this view is visible to the user.  This effectively
1033     * takes care of automatically setting the WindowManager's
1034     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1035     */
1036    public static final int KEEP_SCREEN_ON = 0x04000000;
1037
1038    /**
1039     * View flag indicating whether this view should have sound effects enabled
1040     * for events such as clicking and touching.
1041     */
1042    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1043
1044    /**
1045     * View flag indicating whether this view should have haptic feedback
1046     * enabled for events such as long presses.
1047     */
1048    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1049
1050    /**
1051     * <p>Indicates that the view hierarchy should stop saving state when
1052     * it reaches this view.  If state saving is initiated immediately at
1053     * the view, it will be allowed.
1054     * {@hide}
1055     */
1056    static final int PARENT_SAVE_DISABLED = 0x20000000;
1057
1058    /**
1059     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1060     * {@hide}
1061     */
1062    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1063
1064    /** @hide */
1065    @IntDef(flag = true,
1066            value = {
1067                FOCUSABLES_ALL,
1068                FOCUSABLES_TOUCH_MODE
1069            })
1070    @Retention(RetentionPolicy.SOURCE)
1071    public @interface FocusableMode {}
1072
1073    /**
1074     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1075     * should add all focusable Views regardless if they are focusable in touch mode.
1076     */
1077    public static final int FOCUSABLES_ALL = 0x00000000;
1078
1079    /**
1080     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1081     * should add only Views focusable in touch mode.
1082     */
1083    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1084
1085    /** @hide */
1086    @IntDef({
1087            FOCUS_BACKWARD,
1088            FOCUS_FORWARD,
1089            FOCUS_LEFT,
1090            FOCUS_UP,
1091            FOCUS_RIGHT,
1092            FOCUS_DOWN
1093    })
1094    @Retention(RetentionPolicy.SOURCE)
1095    public @interface FocusDirection {}
1096
1097    /** @hide */
1098    @IntDef({
1099            FOCUS_LEFT,
1100            FOCUS_UP,
1101            FOCUS_RIGHT,
1102            FOCUS_DOWN
1103    })
1104    @Retention(RetentionPolicy.SOURCE)
1105    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1106
1107    /**
1108     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1109     * item.
1110     */
1111    public static final int FOCUS_BACKWARD = 0x00000001;
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1115     * item.
1116     */
1117    public static final int FOCUS_FORWARD = 0x00000002;
1118
1119    /**
1120     * Use with {@link #focusSearch(int)}. Move focus to the left.
1121     */
1122    public static final int FOCUS_LEFT = 0x00000011;
1123
1124    /**
1125     * Use with {@link #focusSearch(int)}. Move focus up.
1126     */
1127    public static final int FOCUS_UP = 0x00000021;
1128
1129    /**
1130     * Use with {@link #focusSearch(int)}. Move focus to the right.
1131     */
1132    public static final int FOCUS_RIGHT = 0x00000042;
1133
1134    /**
1135     * Use with {@link #focusSearch(int)}. Move focus down.
1136     */
1137    public static final int FOCUS_DOWN = 0x00000082;
1138
1139    /**
1140     * Bits of {@link #getMeasuredWidthAndState()} and
1141     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1142     */
1143    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1144
1145    /**
1146     * Bits of {@link #getMeasuredWidthAndState()} and
1147     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1148     */
1149    public static final int MEASURED_STATE_MASK = 0xff000000;
1150
1151    /**
1152     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1153     * for functions that combine both width and height into a single int,
1154     * such as {@link #getMeasuredState()} and the childState argument of
1155     * {@link #resolveSizeAndState(int, int, int)}.
1156     */
1157    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1158
1159    /**
1160     * Bit of {@link #getMeasuredWidthAndState()} and
1161     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1162     * is smaller that the space the view would like to have.
1163     */
1164    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1165
1166    /**
1167     * Base View state sets
1168     */
1169    // Singles
1170    /**
1171     * Indicates the view has no states set. States are used with
1172     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1173     * view depending on its state.
1174     *
1175     * @see android.graphics.drawable.Drawable
1176     * @see #getDrawableState()
1177     */
1178    protected static final int[] EMPTY_STATE_SET;
1179    /**
1180     * Indicates the view is enabled. States are used with
1181     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1182     * view depending on its state.
1183     *
1184     * @see android.graphics.drawable.Drawable
1185     * @see #getDrawableState()
1186     */
1187    protected static final int[] ENABLED_STATE_SET;
1188    /**
1189     * Indicates the view is focused. States are used with
1190     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1191     * view depending on its state.
1192     *
1193     * @see android.graphics.drawable.Drawable
1194     * @see #getDrawableState()
1195     */
1196    protected static final int[] FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is selected. States are used with
1199     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1200     * view depending on its state.
1201     *
1202     * @see android.graphics.drawable.Drawable
1203     * @see #getDrawableState()
1204     */
1205    protected static final int[] SELECTED_STATE_SET;
1206    /**
1207     * Indicates the view is pressed. States are used with
1208     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1209     * view depending on its state.
1210     *
1211     * @see android.graphics.drawable.Drawable
1212     * @see #getDrawableState()
1213     */
1214    protected static final int[] PRESSED_STATE_SET;
1215    /**
1216     * Indicates the view's window has focus. States are used with
1217     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1218     * view depending on its state.
1219     *
1220     * @see android.graphics.drawable.Drawable
1221     * @see #getDrawableState()
1222     */
1223    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1224    // Doubles
1225    /**
1226     * Indicates the view is enabled and has the focus.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #FOCUSED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1232    /**
1233     * Indicates the view is enabled and selected.
1234     *
1235     * @see #ENABLED_STATE_SET
1236     * @see #SELECTED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_SELECTED_STATE_SET;
1239    /**
1240     * Indicates the view is enabled and that its window has focus.
1241     *
1242     * @see #ENABLED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is focused and selected.
1248     *
1249     * @see #FOCUSED_STATE_SET
1250     * @see #SELECTED_STATE_SET
1251     */
1252    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1253    /**
1254     * Indicates the view has the focus and that its window has the focus.
1255     *
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is selected and that its window has the focus.
1262     *
1263     * @see #SELECTED_STATE_SET
1264     * @see #WINDOW_FOCUSED_STATE_SET
1265     */
1266    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1267    // Triples
1268    /**
1269     * Indicates the view is enabled, focused and selected.
1270     *
1271     * @see #ENABLED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     */
1275    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1276    /**
1277     * Indicates the view is enabled, focused and its window has the focus.
1278     *
1279     * @see #ENABLED_STATE_SET
1280     * @see #FOCUSED_STATE_SET
1281     * @see #WINDOW_FOCUSED_STATE_SET
1282     */
1283    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is enabled, selected and its window has the focus.
1286     *
1287     * @see #ENABLED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is focused, selected and its window has the focus.
1294     *
1295     * @see #FOCUSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #WINDOW_FOCUSED_STATE_SET
1298     */
1299    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1300    /**
1301     * Indicates the view is enabled, focused, selected and its window
1302     * has the focus.
1303     *
1304     * @see #ENABLED_STATE_SET
1305     * @see #FOCUSED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and its window has the focus.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #WINDOW_FOCUSED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed and selected.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_SELECTED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, selected and its window has the focus.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #SELECTED_STATE_SET
1329     * @see #WINDOW_FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed and focused.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, focused and its window has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #FOCUSED_STATE_SET
1344     * @see #WINDOW_FOCUSED_STATE_SET
1345     */
1346    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1347    /**
1348     * Indicates the view is pressed, focused and selected.
1349     *
1350     * @see #PRESSED_STATE_SET
1351     * @see #SELECTED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     */
1354    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view is pressed, focused, selected and its window has the focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #FOCUSED_STATE_SET
1360     * @see #SELECTED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed and enabled.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     */
1370    protected static final int[] PRESSED_ENABLED_STATE_SET;
1371    /**
1372     * Indicates the view is pressed, enabled and its window has the focus.
1373     *
1374     * @see #PRESSED_STATE_SET
1375     * @see #ENABLED_STATE_SET
1376     * @see #WINDOW_FOCUSED_STATE_SET
1377     */
1378    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1379    /**
1380     * Indicates the view is pressed, enabled and selected.
1381     *
1382     * @see #PRESSED_STATE_SET
1383     * @see #ENABLED_STATE_SET
1384     * @see #SELECTED_STATE_SET
1385     */
1386    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1387    /**
1388     * Indicates the view is pressed, enabled, selected and its window has the
1389     * focus.
1390     *
1391     * @see #PRESSED_STATE_SET
1392     * @see #ENABLED_STATE_SET
1393     * @see #SELECTED_STATE_SET
1394     * @see #WINDOW_FOCUSED_STATE_SET
1395     */
1396    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1397    /**
1398     * Indicates the view is pressed, enabled and focused.
1399     *
1400     * @see #PRESSED_STATE_SET
1401     * @see #ENABLED_STATE_SET
1402     * @see #FOCUSED_STATE_SET
1403     */
1404    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1405    /**
1406     * Indicates the view is pressed, enabled, focused and its window has the
1407     * focus.
1408     *
1409     * @see #PRESSED_STATE_SET
1410     * @see #ENABLED_STATE_SET
1411     * @see #FOCUSED_STATE_SET
1412     * @see #WINDOW_FOCUSED_STATE_SET
1413     */
1414    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1415    /**
1416     * Indicates the view is pressed, enabled, focused and selected.
1417     *
1418     * @see #PRESSED_STATE_SET
1419     * @see #ENABLED_STATE_SET
1420     * @see #SELECTED_STATE_SET
1421     * @see #FOCUSED_STATE_SET
1422     */
1423    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1424    /**
1425     * Indicates the view is pressed, enabled, focused, selected and its window
1426     * has the focus.
1427     *
1428     * @see #PRESSED_STATE_SET
1429     * @see #ENABLED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #FOCUSED_STATE_SET
1432     * @see #WINDOW_FOCUSED_STATE_SET
1433     */
1434    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1435
1436    /**
1437     * The order here is very important to {@link #getDrawableState()}
1438     */
1439    private static final int[][] VIEW_STATE_SETS;
1440
1441    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1442    static final int VIEW_STATE_SELECTED = 1 << 1;
1443    static final int VIEW_STATE_FOCUSED = 1 << 2;
1444    static final int VIEW_STATE_ENABLED = 1 << 3;
1445    static final int VIEW_STATE_PRESSED = 1 << 4;
1446    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1447    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1448    static final int VIEW_STATE_HOVERED = 1 << 7;
1449    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1450    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1451
1452    static final int[] VIEW_STATE_IDS = new int[] {
1453        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1454        R.attr.state_selected,          VIEW_STATE_SELECTED,
1455        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1456        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1457        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1458        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1459        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1460        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1461        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1462        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1463    };
1464
1465    static {
1466        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1467            throw new IllegalStateException(
1468                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1469        }
1470        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1471        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1472            int viewState = R.styleable.ViewDrawableStates[i];
1473            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1474                if (VIEW_STATE_IDS[j] == viewState) {
1475                    orderedIds[i * 2] = viewState;
1476                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1477                }
1478            }
1479        }
1480        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1481        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1482        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1483            int numBits = Integer.bitCount(i);
1484            int[] set = new int[numBits];
1485            int pos = 0;
1486            for (int j = 0; j < orderedIds.length; j += 2) {
1487                if ((i & orderedIds[j+1]) != 0) {
1488                    set[pos++] = orderedIds[j];
1489                }
1490            }
1491            VIEW_STATE_SETS[i] = set;
1492        }
1493
1494        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1495        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1496        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1497        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1499        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1500        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1502        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1504        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1506                | VIEW_STATE_FOCUSED];
1507        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1508        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1510        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1512        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1514                | VIEW_STATE_ENABLED];
1515        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1517        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1518                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1519                | VIEW_STATE_ENABLED];
1520        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1521                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1522                | VIEW_STATE_ENABLED];
1523        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1525                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1526
1527        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1528        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1532        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1534                | VIEW_STATE_PRESSED];
1535        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1537        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1538                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1539                | VIEW_STATE_PRESSED];
1540        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1541                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1542                | VIEW_STATE_PRESSED];
1543        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1544                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1545                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1546        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1547                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1548        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1549                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1550                | VIEW_STATE_PRESSED];
1551        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1552                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1553                | VIEW_STATE_PRESSED];
1554        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1555                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1556                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1557        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1558                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1559                | VIEW_STATE_PRESSED];
1560        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1561                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1562                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1563        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1564                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1565                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1566        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1567                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1568                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1569                | VIEW_STATE_PRESSED];
1570    }
1571
1572    /**
1573     * Accessibility event types that are dispatched for text population.
1574     */
1575    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1576            AccessibilityEvent.TYPE_VIEW_CLICKED
1577            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1578            | AccessibilityEvent.TYPE_VIEW_SELECTED
1579            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1580            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1581            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1582            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1583            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1584            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1585            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1586            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1587
1588    /**
1589     * Temporary Rect currently for use in setBackground().  This will probably
1590     * be extended in the future to hold our own class with more than just
1591     * a Rect. :)
1592     */
1593    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1594
1595    /**
1596     * Map used to store views' tags.
1597     */
1598    private SparseArray<Object> mKeyedTags;
1599
1600    /**
1601     * The next available accessibility id.
1602     */
1603    private static int sNextAccessibilityViewId;
1604
1605    /**
1606     * The animation currently associated with this view.
1607     * @hide
1608     */
1609    protected Animation mCurrentAnimation = null;
1610
1611    /**
1612     * Width as measured during measure pass.
1613     * {@hide}
1614     */
1615    @ViewDebug.ExportedProperty(category = "measurement")
1616    int mMeasuredWidth;
1617
1618    /**
1619     * Height as measured during measure pass.
1620     * {@hide}
1621     */
1622    @ViewDebug.ExportedProperty(category = "measurement")
1623    int mMeasuredHeight;
1624
1625    /**
1626     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1627     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1628     * its display list. This flag, used only when hw accelerated, allows us to clear the
1629     * flag while retaining this information until it's needed (at getDisplayList() time and
1630     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1631     *
1632     * {@hide}
1633     */
1634    boolean mRecreateDisplayList = false;
1635
1636    /**
1637     * The view's identifier.
1638     * {@hide}
1639     *
1640     * @see #setId(int)
1641     * @see #getId()
1642     */
1643    @ViewDebug.ExportedProperty(resolveId = true)
1644    int mID = NO_ID;
1645
1646    /**
1647     * The stable ID of this view for accessibility purposes.
1648     */
1649    int mAccessibilityViewId = NO_ID;
1650
1651    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1652
1653    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1654
1655    /**
1656     * The view's tag.
1657     * {@hide}
1658     *
1659     * @see #setTag(Object)
1660     * @see #getTag()
1661     */
1662    protected Object mTag = null;
1663
1664    // for mPrivateFlags:
1665    /** {@hide} */
1666    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1667    /** {@hide} */
1668    static final int PFLAG_FOCUSED                     = 0x00000002;
1669    /** {@hide} */
1670    static final int PFLAG_SELECTED                    = 0x00000004;
1671    /** {@hide} */
1672    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1673    /** {@hide} */
1674    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1675    /** {@hide} */
1676    static final int PFLAG_DRAWN                       = 0x00000020;
1677    /**
1678     * When this flag is set, this view is running an animation on behalf of its
1679     * children and should therefore not cancel invalidate requests, even if they
1680     * lie outside of this view's bounds.
1681     *
1682     * {@hide}
1683     */
1684    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1685    /** {@hide} */
1686    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1687    /** {@hide} */
1688    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1689    /** {@hide} */
1690    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1691    /** {@hide} */
1692    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1693    /** {@hide} */
1694    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1695    /** {@hide} */
1696    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1697    /** {@hide} */
1698    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1699
1700    private static final int PFLAG_PRESSED             = 0x00004000;
1701
1702    /** {@hide} */
1703    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1704    /**
1705     * Flag used to indicate that this view should be drawn once more (and only once
1706     * more) after its animation has completed.
1707     * {@hide}
1708     */
1709    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1710
1711    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1712
1713    /**
1714     * Indicates that the View returned true when onSetAlpha() was called and that
1715     * the alpha must be restored.
1716     * {@hide}
1717     */
1718    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1719
1720    /**
1721     * Set by {@link #setScrollContainer(boolean)}.
1722     */
1723    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1724
1725    /**
1726     * Set by {@link #setScrollContainer(boolean)}.
1727     */
1728    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1729
1730    /**
1731     * View flag indicating whether this view was invalidated (fully or partially.)
1732     *
1733     * @hide
1734     */
1735    static final int PFLAG_DIRTY                       = 0x00200000;
1736
1737    /**
1738     * View flag indicating whether this view was invalidated by an opaque
1739     * invalidate request.
1740     *
1741     * @hide
1742     */
1743    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1744
1745    /**
1746     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1751
1752    /**
1753     * Indicates whether the background is opaque.
1754     *
1755     * @hide
1756     */
1757    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1758
1759    /**
1760     * Indicates whether the scrollbars are opaque.
1761     *
1762     * @hide
1763     */
1764    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1765
1766    /**
1767     * Indicates whether the view is opaque.
1768     *
1769     * @hide
1770     */
1771    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1772
1773    /**
1774     * Indicates a prepressed state;
1775     * the short time between ACTION_DOWN and recognizing
1776     * a 'real' press. Prepressed is used to recognize quick taps
1777     * even when they are shorter than ViewConfiguration.getTapTimeout().
1778     *
1779     * @hide
1780     */
1781    private static final int PFLAG_PREPRESSED          = 0x02000000;
1782
1783    /**
1784     * Indicates whether the view is temporarily detached.
1785     *
1786     * @hide
1787     */
1788    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1789
1790    /**
1791     * Indicates that we should awaken scroll bars once attached
1792     *
1793     * @hide
1794     */
1795    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1796
1797    /**
1798     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1799     * @hide
1800     */
1801    private static final int PFLAG_HOVERED             = 0x10000000;
1802
1803    /**
1804     * no longer needed, should be reused
1805     */
1806    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1807
1808    /** {@hide} */
1809    static final int PFLAG_ACTIVATED                   = 0x40000000;
1810
1811    /**
1812     * Indicates that this view was specifically invalidated, not just dirtied because some
1813     * child view was invalidated. The flag is used to determine when we need to recreate
1814     * a view's display list (as opposed to just returning a reference to its existing
1815     * display list).
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_INVALIDATED                 = 0x80000000;
1820
1821    /**
1822     * Masks for mPrivateFlags2, as generated by dumpFlags():
1823     *
1824     * |-------|-------|-------|-------|
1825     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1826     *                                1  PFLAG2_DRAG_HOVERED
1827     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1828     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1829     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1830     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1831     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1832     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1833     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1834     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1835     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1836     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1837     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1838     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1839     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1840     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1841     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1842     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1843     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1844     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1845     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1846     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1847     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1848     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1849     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1850     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1851     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1852     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1853     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1854     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1855     *    1                              PFLAG2_PADDING_RESOLVED
1856     *   1                               PFLAG2_DRAWABLE_RESOLVED
1857     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1858     * |-------|-------|-------|-------|
1859     */
1860
1861    /**
1862     * Indicates that this view has reported that it can accept the current drag's content.
1863     * Cleared when the drag operation concludes.
1864     * @hide
1865     */
1866    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1867
1868    /**
1869     * Indicates that this view is currently directly under the drag location in a
1870     * drag-and-drop operation involving content that it can accept.  Cleared when
1871     * the drag exits the view, or when the drag operation concludes.
1872     * @hide
1873     */
1874    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1875
1876    /** @hide */
1877    @IntDef({
1878        LAYOUT_DIRECTION_LTR,
1879        LAYOUT_DIRECTION_RTL,
1880        LAYOUT_DIRECTION_INHERIT,
1881        LAYOUT_DIRECTION_LOCALE
1882    })
1883    @Retention(RetentionPolicy.SOURCE)
1884    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1885    public @interface LayoutDir {}
1886
1887    /** @hide */
1888    @IntDef({
1889        LAYOUT_DIRECTION_LTR,
1890        LAYOUT_DIRECTION_RTL
1891    })
1892    @Retention(RetentionPolicy.SOURCE)
1893    public @interface ResolvedLayoutDir {}
1894
1895    /**
1896     * Horizontal layout direction of this view is from Left to Right.
1897     * Use with {@link #setLayoutDirection}.
1898     */
1899    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1900
1901    /**
1902     * Horizontal layout direction of this view is from Right to Left.
1903     * Use with {@link #setLayoutDirection}.
1904     */
1905    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1906
1907    /**
1908     * Horizontal layout direction of this view is inherited from its parent.
1909     * Use with {@link #setLayoutDirection}.
1910     */
1911    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1912
1913    /**
1914     * Horizontal layout direction of this view is from deduced from the default language
1915     * script for the locale. Use with {@link #setLayoutDirection}.
1916     */
1917    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1918
1919    /**
1920     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1921     * @hide
1922     */
1923    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1924
1925    /**
1926     * Mask for use with private flags indicating bits used for horizontal layout direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1933     * right-to-left direction.
1934     * @hide
1935     */
1936    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1937
1938    /**
1939     * Indicates whether the view horizontal layout direction has been resolved.
1940     * @hide
1941     */
1942    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /**
1945     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1946     * @hide
1947     */
1948    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1949            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1950
1951    /*
1952     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1953     * flag value.
1954     * @hide
1955     */
1956    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1957            LAYOUT_DIRECTION_LTR,
1958            LAYOUT_DIRECTION_RTL,
1959            LAYOUT_DIRECTION_INHERIT,
1960            LAYOUT_DIRECTION_LOCALE
1961    };
1962
1963    /**
1964     * Default horizontal layout direction.
1965     */
1966    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1967
1968    /**
1969     * Default horizontal layout direction.
1970     * @hide
1971     */
1972    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1973
1974    /**
1975     * Text direction is inherited thru {@link ViewGroup}
1976     */
1977    public static final int TEXT_DIRECTION_INHERIT = 0;
1978
1979    /**
1980     * Text direction is using "first strong algorithm". The first strong directional character
1981     * determines the paragraph direction. If there is no strong directional character, the
1982     * paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1985
1986    /**
1987     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1988     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1989     * If there are neither, the paragraph direction is the view's resolved layout direction.
1990     */
1991    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1992
1993    /**
1994     * Text direction is forced to LTR.
1995     */
1996    public static final int TEXT_DIRECTION_LTR = 3;
1997
1998    /**
1999     * Text direction is forced to RTL.
2000     */
2001    public static final int TEXT_DIRECTION_RTL = 4;
2002
2003    /**
2004     * Text direction is coming from the system Locale.
2005     */
2006    public static final int TEXT_DIRECTION_LOCALE = 5;
2007
2008    /**
2009     * Default text direction is inherited
2010     */
2011    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2012
2013    /**
2014     * Default resolved text direction
2015     * @hide
2016     */
2017    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2018
2019    /**
2020     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2021     * @hide
2022     */
2023    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2024
2025    /**
2026     * Mask for use with private flags indicating bits used for text direction.
2027     * @hide
2028     */
2029    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2030            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2031
2032    /**
2033     * Array of text direction flags for mapping attribute "textDirection" to correct
2034     * flag value.
2035     * @hide
2036     */
2037    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2038            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2039            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2040            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2041            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2042            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2043            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2044    };
2045
2046    /**
2047     * Indicates whether the view text direction has been resolved.
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2051            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2052
2053    /**
2054     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2055     * @hide
2056     */
2057    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2058
2059    /**
2060     * Mask for use with private flags indicating bits used for resolved text direction.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2064            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /**
2067     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2068     * @hide
2069     */
2070    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2071            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2072
2073    /** @hide */
2074    @IntDef({
2075        TEXT_ALIGNMENT_INHERIT,
2076        TEXT_ALIGNMENT_GRAVITY,
2077        TEXT_ALIGNMENT_CENTER,
2078        TEXT_ALIGNMENT_TEXT_START,
2079        TEXT_ALIGNMENT_TEXT_END,
2080        TEXT_ALIGNMENT_VIEW_START,
2081        TEXT_ALIGNMENT_VIEW_END
2082    })
2083    @Retention(RetentionPolicy.SOURCE)
2084    public @interface TextAlignment {}
2085
2086    /**
2087     * Default text alignment. The text alignment of this View is inherited from its parent.
2088     * Use with {@link #setTextAlignment(int)}
2089     */
2090    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2091
2092    /**
2093     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2094     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2099
2100    /**
2101     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2106
2107    /**
2108     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2113
2114    /**
2115     * Center the paragraph, e.g. ALIGN_CENTER.
2116     *
2117     * Use with {@link #setTextAlignment(int)}
2118     */
2119    public static final int TEXT_ALIGNMENT_CENTER = 4;
2120
2121    /**
2122     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2123     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2124     *
2125     * Use with {@link #setTextAlignment(int)}
2126     */
2127    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2128
2129    /**
2130     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2131     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2132     *
2133     * Use with {@link #setTextAlignment(int)}
2134     */
2135    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2136
2137    /**
2138     * Default text alignment is inherited
2139     */
2140    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2141
2142    /**
2143     * Default resolved text alignment
2144     * @hide
2145     */
2146    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2147
2148    /**
2149      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2150      * @hide
2151      */
2152    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2153
2154    /**
2155      * Mask for use with private flags indicating bits used for text alignment.
2156      * @hide
2157      */
2158    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2159
2160    /**
2161     * Array of text direction flags for mapping attribute "textAlignment" to correct
2162     * flag value.
2163     * @hide
2164     */
2165    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2166            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2168            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2169            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2170            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2171            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2172            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2173    };
2174
2175    /**
2176     * Indicates whether the view text alignment has been resolved.
2177     * @hide
2178     */
2179    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2180
2181    /**
2182     * Bit shift to get the resolved text alignment.
2183     * @hide
2184     */
2185    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2186
2187    /**
2188     * Mask for use with private flags indicating bits used for text alignment.
2189     * @hide
2190     */
2191    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2192            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2193
2194    /**
2195     * Indicates whether if the view text alignment has been resolved to gravity
2196     */
2197    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2198            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2199
2200    // Accessiblity constants for mPrivateFlags2
2201
2202    /**
2203     * Shift for the bits in {@link #mPrivateFlags2} related to the
2204     * "importantForAccessibility" attribute.
2205     */
2206    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2207
2208    /**
2209     * Automatically determine whether a view is important for accessibility.
2210     */
2211    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2212
2213    /**
2214     * The view is important for accessibility.
2215     */
2216    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2217
2218    /**
2219     * The view is not important for accessibility.
2220     */
2221    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2222
2223    /**
2224     * The view is not important for accessibility, nor are any of its
2225     * descendant views.
2226     */
2227    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2228
2229    /**
2230     * The default whether the view is important for accessibility.
2231     */
2232    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2233
2234    /**
2235     * Mask for obtainig the bits which specify how to determine
2236     * whether a view is important for accessibility.
2237     */
2238    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2239        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2240        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2241        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2242
2243    /**
2244     * Shift for the bits in {@link #mPrivateFlags2} related to the
2245     * "accessibilityLiveRegion" attribute.
2246     */
2247    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2248
2249    /**
2250     * Live region mode specifying that accessibility services should not
2251     * automatically announce changes to this view. This is the default live
2252     * region mode for most views.
2253     * <p>
2254     * Use with {@link #setAccessibilityLiveRegion(int)}.
2255     */
2256    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2257
2258    /**
2259     * Live region mode specifying that accessibility services should announce
2260     * changes to this view.
2261     * <p>
2262     * Use with {@link #setAccessibilityLiveRegion(int)}.
2263     */
2264    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2265
2266    /**
2267     * Live region mode specifying that accessibility services should interrupt
2268     * ongoing speech to immediately announce changes to this view.
2269     * <p>
2270     * Use with {@link #setAccessibilityLiveRegion(int)}.
2271     */
2272    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2273
2274    /**
2275     * The default whether the view is important for accessibility.
2276     */
2277    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2278
2279    /**
2280     * Mask for obtaining the bits which specify a view's accessibility live
2281     * region mode.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2284            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2285            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2286
2287    /**
2288     * Flag indicating whether a view has accessibility focus.
2289     */
2290    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2291
2292    /**
2293     * Flag whether the accessibility state of the subtree rooted at this view changed.
2294     */
2295    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2296
2297    /**
2298     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2299     * is used to check whether later changes to the view's transform should invalidate the
2300     * view to force the quickReject test to run again.
2301     */
2302    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2303
2304    /**
2305     * Flag indicating that start/end padding has been resolved into left/right padding
2306     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2307     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2308     * during measurement. In some special cases this is required such as when an adapter-based
2309     * view measures prospective children without attaching them to a window.
2310     */
2311    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2312
2313    /**
2314     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2315     */
2316    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2317
2318    /**
2319     * Indicates that the view is tracking some sort of transient state
2320     * that the app should not need to be aware of, but that the framework
2321     * should take special care to preserve.
2322     */
2323    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2324
2325    /**
2326     * Group of bits indicating that RTL properties resolution is done.
2327     */
2328    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2329            PFLAG2_TEXT_DIRECTION_RESOLVED |
2330            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2331            PFLAG2_PADDING_RESOLVED |
2332            PFLAG2_DRAWABLE_RESOLVED;
2333
2334    // There are a couple of flags left in mPrivateFlags2
2335
2336    /* End of masks for mPrivateFlags2 */
2337
2338    /**
2339     * Masks for mPrivateFlags3, as generated by dumpFlags():
2340     *
2341     * |-------|-------|-------|-------|
2342     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2343     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2344     *                               1   PFLAG3_IS_LAID_OUT
2345     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2346     *                             1     PFLAG3_CALLED_SUPER
2347     * |-------|-------|-------|-------|
2348     */
2349
2350    /**
2351     * Flag indicating that view has a transform animation set on it. This is used to track whether
2352     * an animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to clear its animation matrix.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2356
2357    /**
2358     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2359     * animation is cleared between successive frames, in order to tell the associated
2360     * DisplayList to restore its alpha value.
2361     */
2362    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2363
2364    /**
2365     * Flag indicating that the view has been through at least one layout since it
2366     * was last attached to a window.
2367     */
2368    static final int PFLAG3_IS_LAID_OUT = 0x4;
2369
2370    /**
2371     * Flag indicating that a call to measure() was skipped and should be done
2372     * instead when layout() is invoked.
2373     */
2374    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2375
2376    /**
2377     * Flag indicating that an overridden method correctly  called down to
2378     * the superclass implementation as required by the API spec.
2379     */
2380    static final int PFLAG3_CALLED_SUPER = 0x10;
2381
2382    /**
2383     * Flag indicating that a view's outline has been specifically defined.
2384     */
2385    static final int PFLAG3_OUTLINE_DEFINED = 0x20;
2386
2387    /**
2388     * Flag indicating that we're in the process of applying window insets.
2389     */
2390    static final int PFLAG3_APPLYING_INSETS = 0x40;
2391
2392    /**
2393     * Flag indicating that we're in the process of fitting system windows using the old method.
2394     */
2395    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2396
2397    /**
2398     * Flag indicating that nested scrolling is enabled for this view.
2399     * The view will optionally cooperate with views up its parent chain to allow for
2400     * integrated nested scrolling along the same axis.
2401     */
2402    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200;
2403
2404    /* End of masks for mPrivateFlags3 */
2405
2406    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2407
2408    /**
2409     * Always allow a user to over-scroll this view, provided it is a
2410     * view that can scroll.
2411     *
2412     * @see #getOverScrollMode()
2413     * @see #setOverScrollMode(int)
2414     */
2415    public static final int OVER_SCROLL_ALWAYS = 0;
2416
2417    /**
2418     * Allow a user to over-scroll this view only if the content is large
2419     * enough to meaningfully scroll, provided it is a view that can scroll.
2420     *
2421     * @see #getOverScrollMode()
2422     * @see #setOverScrollMode(int)
2423     */
2424    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2425
2426    /**
2427     * Never allow a user to over-scroll this view.
2428     *
2429     * @see #getOverScrollMode()
2430     * @see #setOverScrollMode(int)
2431     */
2432    public static final int OVER_SCROLL_NEVER = 2;
2433
2434    /**
2435     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2436     * requested the system UI (status bar) to be visible (the default).
2437     *
2438     * @see #setSystemUiVisibility(int)
2439     */
2440    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2441
2442    /**
2443     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2444     * system UI to enter an unobtrusive "low profile" mode.
2445     *
2446     * <p>This is for use in games, book readers, video players, or any other
2447     * "immersive" application where the usual system chrome is deemed too distracting.
2448     *
2449     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2450     *
2451     * @see #setSystemUiVisibility(int)
2452     */
2453    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2454
2455    /**
2456     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2457     * system navigation be temporarily hidden.
2458     *
2459     * <p>This is an even less obtrusive state than that called for by
2460     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2461     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2462     * those to disappear. This is useful (in conjunction with the
2463     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2464     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2465     * window flags) for displaying content using every last pixel on the display.
2466     *
2467     * <p>There is a limitation: because navigation controls are so important, the least user
2468     * interaction will cause them to reappear immediately.  When this happens, both
2469     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2470     * so that both elements reappear at the same time.
2471     *
2472     * @see #setSystemUiVisibility(int)
2473     */
2474    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2475
2476    /**
2477     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2478     * into the normal fullscreen mode so that its content can take over the screen
2479     * while still allowing the user to interact with the application.
2480     *
2481     * <p>This has the same visual effect as
2482     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2483     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2484     * meaning that non-critical screen decorations (such as the status bar) will be
2485     * hidden while the user is in the View's window, focusing the experience on
2486     * that content.  Unlike the window flag, if you are using ActionBar in
2487     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2488     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2489     * hide the action bar.
2490     *
2491     * <p>This approach to going fullscreen is best used over the window flag when
2492     * it is a transient state -- that is, the application does this at certain
2493     * points in its user interaction where it wants to allow the user to focus
2494     * on content, but not as a continuous state.  For situations where the application
2495     * would like to simply stay full screen the entire time (such as a game that
2496     * wants to take over the screen), the
2497     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2498     * is usually a better approach.  The state set here will be removed by the system
2499     * in various situations (such as the user moving to another application) like
2500     * the other system UI states.
2501     *
2502     * <p>When using this flag, the application should provide some easy facility
2503     * for the user to go out of it.  A common example would be in an e-book
2504     * reader, where tapping on the screen brings back whatever screen and UI
2505     * decorations that had been hidden while the user was immersed in reading
2506     * the book.
2507     *
2508     * @see #setSystemUiVisibility(int)
2509     */
2510    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2511
2512    /**
2513     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2514     * flags, we would like a stable view of the content insets given to
2515     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2516     * will always represent the worst case that the application can expect
2517     * as a continuous state.  In the stock Android UI this is the space for
2518     * the system bar, nav bar, and status bar, but not more transient elements
2519     * such as an input method.
2520     *
2521     * The stable layout your UI sees is based on the system UI modes you can
2522     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2523     * then you will get a stable layout for changes of the
2524     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2526     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2527     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2528     * with a stable layout.  (Note that you should avoid using
2529     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2530     *
2531     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2532     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2533     * then a hidden status bar will be considered a "stable" state for purposes
2534     * here.  This allows your UI to continually hide the status bar, while still
2535     * using the system UI flags to hide the action bar while still retaining
2536     * a stable layout.  Note that changing the window fullscreen flag will never
2537     * provide a stable layout for a clean transition.
2538     *
2539     * <p>If you are using ActionBar in
2540     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2541     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2542     * insets it adds to those given to the application.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2545
2546    /**
2547     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2548     * to be layed out as if it has requested
2549     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2550     * allows it to avoid artifacts when switching in and out of that mode, at
2551     * the expense that some of its user interface may be covered by screen
2552     * decorations when they are shown.  You can perform layout of your inner
2553     * UI elements to account for the navigation system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2560     * to be layed out as if it has requested
2561     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2562     * allows it to avoid artifacts when switching in and out of that mode, at
2563     * the expense that some of its user interface may be covered by screen
2564     * decorations when they are shown.  You can perform layout of your inner
2565     * UI elements to account for non-fullscreen system UI through the
2566     * {@link #fitSystemWindows(Rect)} method.
2567     */
2568    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2569
2570    /**
2571     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2572     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2573     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2574     * user interaction.
2575     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2576     * has an effect when used in combination with that flag.</p>
2577     */
2578    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2579
2580    /**
2581     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2582     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2583     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2584     * experience while also hiding the system bars.  If this flag is not set,
2585     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2586     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2587     * if the user swipes from the top of the screen.
2588     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2589     * system gestures, such as swiping from the top of the screen.  These transient system bars
2590     * will overlay app’s content, may have some degree of transparency, and will automatically
2591     * hide after a short timeout.
2592     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2593     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2594     * with one or both of those flags.</p>
2595     */
2596    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2597
2598    /**
2599     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2600     */
2601    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2602
2603    /**
2604     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2605     */
2606    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2607
2608    /**
2609     * @hide
2610     *
2611     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2612     * out of the public fields to keep the undefined bits out of the developer's way.
2613     *
2614     * Flag to make the status bar not expandable.  Unless you also
2615     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2616     */
2617    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2618
2619    /**
2620     * @hide
2621     *
2622     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2623     * out of the public fields to keep the undefined bits out of the developer's way.
2624     *
2625     * Flag to hide notification icons and scrolling ticker text.
2626     */
2627    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2628
2629    /**
2630     * @hide
2631     *
2632     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2633     * out of the public fields to keep the undefined bits out of the developer's way.
2634     *
2635     * Flag to disable incoming notification alerts.  This will not block
2636     * icons, but it will block sound, vibrating and other visual or aural notifications.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2639
2640    /**
2641     * @hide
2642     *
2643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2644     * out of the public fields to keep the undefined bits out of the developer's way.
2645     *
2646     * Flag to hide only the scrolling ticker.  Note that
2647     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2648     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2649     */
2650    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2651
2652    /**
2653     * @hide
2654     *
2655     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2656     * out of the public fields to keep the undefined bits out of the developer's way.
2657     *
2658     * Flag to hide the center system info area.
2659     */
2660    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2661
2662    /**
2663     * @hide
2664     *
2665     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2666     * out of the public fields to keep the undefined bits out of the developer's way.
2667     *
2668     * Flag to hide only the home button.  Don't use this
2669     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2670     */
2671    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2672
2673    /**
2674     * @hide
2675     *
2676     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2677     * out of the public fields to keep the undefined bits out of the developer's way.
2678     *
2679     * Flag to hide only the back button. Don't use this
2680     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2681     */
2682    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2683
2684    /**
2685     * @hide
2686     *
2687     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2688     * out of the public fields to keep the undefined bits out of the developer's way.
2689     *
2690     * Flag to hide only the clock.  You might use this if your activity has
2691     * its own clock making the status bar's clock redundant.
2692     */
2693    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2694
2695    /**
2696     * @hide
2697     *
2698     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2699     * out of the public fields to keep the undefined bits out of the developer's way.
2700     *
2701     * Flag to hide only the recent apps button. Don't use this
2702     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2703     */
2704    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2705
2706    /**
2707     * @hide
2708     *
2709     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2710     * out of the public fields to keep the undefined bits out of the developer's way.
2711     *
2712     * Flag to disable the global search gesture. Don't use this
2713     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2714     */
2715    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2716
2717    /**
2718     * @hide
2719     *
2720     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2721     * out of the public fields to keep the undefined bits out of the developer's way.
2722     *
2723     * Flag to specify that the status bar is displayed in transient mode.
2724     */
2725    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2726
2727    /**
2728     * @hide
2729     *
2730     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2731     * out of the public fields to keep the undefined bits out of the developer's way.
2732     *
2733     * Flag to specify that the navigation bar is displayed in transient mode.
2734     */
2735    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2736
2737    /**
2738     * @hide
2739     *
2740     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2741     * out of the public fields to keep the undefined bits out of the developer's way.
2742     *
2743     * Flag to specify that the hidden status bar would like to be shown.
2744     */
2745    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2746
2747    /**
2748     * @hide
2749     *
2750     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2751     * out of the public fields to keep the undefined bits out of the developer's way.
2752     *
2753     * Flag to specify that the hidden navigation bar would like to be shown.
2754     */
2755    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2756
2757    /**
2758     * @hide
2759     *
2760     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2761     * out of the public fields to keep the undefined bits out of the developer's way.
2762     *
2763     * Flag to specify that the status bar is displayed in translucent mode.
2764     */
2765    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2766
2767    /**
2768     * @hide
2769     *
2770     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2771     * out of the public fields to keep the undefined bits out of the developer's way.
2772     *
2773     * Flag to specify that the navigation bar is displayed in translucent mode.
2774     */
2775    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2776
2777    /**
2778     * @hide
2779     *
2780     * Whether Recents is visible or not.
2781     */
2782    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2783
2784    /**
2785     * @hide
2786     *
2787     * Makes system ui transparent.
2788     */
2789    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2790
2791    /**
2792     * @hide
2793     */
2794    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2795
2796    /**
2797     * These are the system UI flags that can be cleared by events outside
2798     * of an application.  Currently this is just the ability to tap on the
2799     * screen while hiding the navigation bar to have it return.
2800     * @hide
2801     */
2802    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2803            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2804            | SYSTEM_UI_FLAG_FULLSCREEN;
2805
2806    /**
2807     * Flags that can impact the layout in relation to system UI.
2808     */
2809    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2810            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2811            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2812
2813    /** @hide */
2814    @IntDef(flag = true,
2815            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2816    @Retention(RetentionPolicy.SOURCE)
2817    public @interface FindViewFlags {}
2818
2819    /**
2820     * Find views that render the specified text.
2821     *
2822     * @see #findViewsWithText(ArrayList, CharSequence, int)
2823     */
2824    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2825
2826    /**
2827     * Find find views that contain the specified content description.
2828     *
2829     * @see #findViewsWithText(ArrayList, CharSequence, int)
2830     */
2831    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2832
2833    /**
2834     * Find views that contain {@link AccessibilityNodeProvider}. Such
2835     * a View is a root of virtual view hierarchy and may contain the searched
2836     * text. If this flag is set Views with providers are automatically
2837     * added and it is a responsibility of the client to call the APIs of
2838     * the provider to determine whether the virtual tree rooted at this View
2839     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2840     * representing the virtual views with this text.
2841     *
2842     * @see #findViewsWithText(ArrayList, CharSequence, int)
2843     *
2844     * @hide
2845     */
2846    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2847
2848    /**
2849     * The undefined cursor position.
2850     *
2851     * @hide
2852     */
2853    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2854
2855    /**
2856     * Indicates that the screen has changed state and is now off.
2857     *
2858     * @see #onScreenStateChanged(int)
2859     */
2860    public static final int SCREEN_STATE_OFF = 0x0;
2861
2862    /**
2863     * Indicates that the screen has changed state and is now on.
2864     *
2865     * @see #onScreenStateChanged(int)
2866     */
2867    public static final int SCREEN_STATE_ON = 0x1;
2868
2869    /**
2870     * Indicates no axis of view scrolling.
2871     */
2872    public static final int SCROLL_AXIS_NONE = 0;
2873
2874    /**
2875     * Indicates scrolling along the horizontal axis.
2876     */
2877    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2878
2879    /**
2880     * Indicates scrolling along the vertical axis.
2881     */
2882    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2883
2884    /**
2885     * Controls the over-scroll mode for this view.
2886     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2887     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2888     * and {@link #OVER_SCROLL_NEVER}.
2889     */
2890    private int mOverScrollMode;
2891
2892    /**
2893     * The parent this view is attached to.
2894     * {@hide}
2895     *
2896     * @see #getParent()
2897     */
2898    protected ViewParent mParent;
2899
2900    /**
2901     * {@hide}
2902     */
2903    AttachInfo mAttachInfo;
2904
2905    /**
2906     * {@hide}
2907     */
2908    @ViewDebug.ExportedProperty(flagMapping = {
2909        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2910                name = "FORCE_LAYOUT"),
2911        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2912                name = "LAYOUT_REQUIRED"),
2913        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2914            name = "DRAWING_CACHE_INVALID", outputIf = false),
2915        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2916        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2917        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2918        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2919    })
2920    int mPrivateFlags;
2921    int mPrivateFlags2;
2922    int mPrivateFlags3;
2923
2924    /**
2925     * This view's request for the visibility of the status bar.
2926     * @hide
2927     */
2928    @ViewDebug.ExportedProperty(flagMapping = {
2929        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2930                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2931                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2932        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2933                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2934                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2935        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2936                                equals = SYSTEM_UI_FLAG_VISIBLE,
2937                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2938    })
2939    int mSystemUiVisibility;
2940
2941    /**
2942     * Reference count for transient state.
2943     * @see #setHasTransientState(boolean)
2944     */
2945    int mTransientStateCount = 0;
2946
2947    /**
2948     * Count of how many windows this view has been attached to.
2949     */
2950    int mWindowAttachCount;
2951
2952    /**
2953     * The layout parameters associated with this view and used by the parent
2954     * {@link android.view.ViewGroup} to determine how this view should be
2955     * laid out.
2956     * {@hide}
2957     */
2958    protected ViewGroup.LayoutParams mLayoutParams;
2959
2960    /**
2961     * The view flags hold various views states.
2962     * {@hide}
2963     */
2964    @ViewDebug.ExportedProperty
2965    int mViewFlags;
2966
2967    static class TransformationInfo {
2968        /**
2969         * The transform matrix for the View. This transform is calculated internally
2970         * based on the translation, rotation, and scale properties.
2971         *
2972         * Do *not* use this variable directly; instead call getMatrix(), which will
2973         * load the value from the View's RenderNode.
2974         */
2975        private final Matrix mMatrix = new Matrix();
2976
2977        /**
2978         * The inverse transform matrix for the View. This transform is calculated
2979         * internally based on the translation, rotation, and scale properties.
2980         *
2981         * Do *not* use this variable directly; instead call getInverseMatrix(),
2982         * which will load the value from the View's RenderNode.
2983         */
2984        private Matrix mInverseMatrix;
2985
2986        /**
2987         * The opacity of the View. This is a value from 0 to 1, where 0 means
2988         * completely transparent and 1 means completely opaque.
2989         */
2990        @ViewDebug.ExportedProperty
2991        float mAlpha = 1f;
2992
2993        /**
2994         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2995         * property only used by transitions, which is composited with the other alpha
2996         * values to calculate the final visual alpha value.
2997         */
2998        float mTransitionAlpha = 1f;
2999    }
3000
3001    TransformationInfo mTransformationInfo;
3002
3003    /**
3004     * Current clip bounds. to which all drawing of this view are constrained.
3005     */
3006    Rect mClipBounds = null;
3007
3008    private boolean mLastIsOpaque;
3009
3010    /**
3011     * The distance in pixels from the left edge of this view's parent
3012     * to the left edge of this view.
3013     * {@hide}
3014     */
3015    @ViewDebug.ExportedProperty(category = "layout")
3016    protected int mLeft;
3017    /**
3018     * The distance in pixels from the left edge of this view's parent
3019     * to the right edge of this view.
3020     * {@hide}
3021     */
3022    @ViewDebug.ExportedProperty(category = "layout")
3023    protected int mRight;
3024    /**
3025     * The distance in pixels from the top edge of this view's parent
3026     * to the top edge of this view.
3027     * {@hide}
3028     */
3029    @ViewDebug.ExportedProperty(category = "layout")
3030    protected int mTop;
3031    /**
3032     * The distance in pixels from the top edge of this view's parent
3033     * to the bottom edge of this view.
3034     * {@hide}
3035     */
3036    @ViewDebug.ExportedProperty(category = "layout")
3037    protected int mBottom;
3038
3039    /**
3040     * The offset, in pixels, by which the content of this view is scrolled
3041     * horizontally.
3042     * {@hide}
3043     */
3044    @ViewDebug.ExportedProperty(category = "scrolling")
3045    protected int mScrollX;
3046    /**
3047     * The offset, in pixels, by which the content of this view is scrolled
3048     * vertically.
3049     * {@hide}
3050     */
3051    @ViewDebug.ExportedProperty(category = "scrolling")
3052    protected int mScrollY;
3053
3054    /**
3055     * The left padding in pixels, that is the distance in pixels between the
3056     * left edge of this view and the left edge of its content.
3057     * {@hide}
3058     */
3059    @ViewDebug.ExportedProperty(category = "padding")
3060    protected int mPaddingLeft = 0;
3061    /**
3062     * The right padding in pixels, that is the distance in pixels between the
3063     * right edge of this view and the right edge of its content.
3064     * {@hide}
3065     */
3066    @ViewDebug.ExportedProperty(category = "padding")
3067    protected int mPaddingRight = 0;
3068    /**
3069     * The top padding in pixels, that is the distance in pixels between the
3070     * top edge of this view and the top edge of its content.
3071     * {@hide}
3072     */
3073    @ViewDebug.ExportedProperty(category = "padding")
3074    protected int mPaddingTop;
3075    /**
3076     * The bottom padding in pixels, that is the distance in pixels between the
3077     * bottom edge of this view and the bottom edge of its content.
3078     * {@hide}
3079     */
3080    @ViewDebug.ExportedProperty(category = "padding")
3081    protected int mPaddingBottom;
3082
3083    /**
3084     * The layout insets in pixels, that is the distance in pixels between the
3085     * visible edges of this view its bounds.
3086     */
3087    private Insets mLayoutInsets;
3088
3089    /**
3090     * Briefly describes the view and is primarily used for accessibility support.
3091     */
3092    private CharSequence mContentDescription;
3093
3094    /**
3095     * Specifies the id of a view for which this view serves as a label for
3096     * accessibility purposes.
3097     */
3098    private int mLabelForId = View.NO_ID;
3099
3100    /**
3101     * Predicate for matching labeled view id with its label for
3102     * accessibility purposes.
3103     */
3104    private MatchLabelForPredicate mMatchLabelForPredicate;
3105
3106    /**
3107     * Predicate for matching a view by its id.
3108     */
3109    private MatchIdPredicate mMatchIdPredicate;
3110
3111    /**
3112     * Cache the paddingRight set by the user to append to the scrollbar's size.
3113     *
3114     * @hide
3115     */
3116    @ViewDebug.ExportedProperty(category = "padding")
3117    protected int mUserPaddingRight;
3118
3119    /**
3120     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3121     *
3122     * @hide
3123     */
3124    @ViewDebug.ExportedProperty(category = "padding")
3125    protected int mUserPaddingBottom;
3126
3127    /**
3128     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3129     *
3130     * @hide
3131     */
3132    @ViewDebug.ExportedProperty(category = "padding")
3133    protected int mUserPaddingLeft;
3134
3135    /**
3136     * Cache the paddingStart set by the user to append to the scrollbar's size.
3137     *
3138     */
3139    @ViewDebug.ExportedProperty(category = "padding")
3140    int mUserPaddingStart;
3141
3142    /**
3143     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3144     *
3145     */
3146    @ViewDebug.ExportedProperty(category = "padding")
3147    int mUserPaddingEnd;
3148
3149    /**
3150     * Cache initial left padding.
3151     *
3152     * @hide
3153     */
3154    int mUserPaddingLeftInitial;
3155
3156    /**
3157     * Cache initial right padding.
3158     *
3159     * @hide
3160     */
3161    int mUserPaddingRightInitial;
3162
3163    /**
3164     * Default undefined padding
3165     */
3166    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3167
3168    /**
3169     * Cache if a left padding has been defined
3170     */
3171    private boolean mLeftPaddingDefined = false;
3172
3173    /**
3174     * Cache if a right padding has been defined
3175     */
3176    private boolean mRightPaddingDefined = false;
3177
3178    /**
3179     * @hide
3180     */
3181    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3182    /**
3183     * @hide
3184     */
3185    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3186
3187    private LongSparseLongArray mMeasureCache;
3188
3189    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3190    private Drawable mBackground;
3191    private ColorStateList mBackgroundTint = null;
3192    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3193    private boolean mHasBackgroundTint = false;
3194
3195    /**
3196     * Display list used for backgrounds.
3197     * <p>
3198     * When non-null and valid, this is expected to contain an up-to-date copy
3199     * of the background drawable. It is cleared on temporary detach and reset
3200     * on cleanup.
3201     */
3202    private RenderNode mBackgroundDisplayList;
3203
3204    private int mBackgroundResource;
3205    private boolean mBackgroundSizeChanged;
3206
3207    private String mViewName;
3208
3209    static class ListenerInfo {
3210        /**
3211         * Listener used to dispatch focus change events.
3212         * This field should be made private, so it is hidden from the SDK.
3213         * {@hide}
3214         */
3215        protected OnFocusChangeListener mOnFocusChangeListener;
3216
3217        /**
3218         * Listeners for layout change events.
3219         */
3220        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3221
3222        /**
3223         * Listeners for attach events.
3224         */
3225        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3226
3227        /**
3228         * Listener used to dispatch click events.
3229         * This field should be made private, so it is hidden from the SDK.
3230         * {@hide}
3231         */
3232        public OnClickListener mOnClickListener;
3233
3234        /**
3235         * Listener used to dispatch long click events.
3236         * This field should be made private, so it is hidden from the SDK.
3237         * {@hide}
3238         */
3239        protected OnLongClickListener mOnLongClickListener;
3240
3241        /**
3242         * Listener used to build the context menu.
3243         * This field should be made private, so it is hidden from the SDK.
3244         * {@hide}
3245         */
3246        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3247
3248        private OnKeyListener mOnKeyListener;
3249
3250        private OnTouchListener mOnTouchListener;
3251
3252        private OnHoverListener mOnHoverListener;
3253
3254        private OnGenericMotionListener mOnGenericMotionListener;
3255
3256        private OnDragListener mOnDragListener;
3257
3258        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3259
3260        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3261    }
3262
3263    ListenerInfo mListenerInfo;
3264
3265    /**
3266     * The application environment this view lives in.
3267     * This field should be made private, so it is hidden from the SDK.
3268     * {@hide}
3269     */
3270    protected Context mContext;
3271
3272    private final Resources mResources;
3273
3274    private ScrollabilityCache mScrollCache;
3275
3276    private int[] mDrawableState = null;
3277
3278    /**
3279     * Stores the outline of the view, passed down to the DisplayList level for
3280     * defining shadow shape.
3281     */
3282    private Outline mOutline;
3283
3284    /**
3285     * Animator that automatically runs based on state changes.
3286     */
3287    private StateListAnimator mStateListAnimator;
3288
3289    /**
3290     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3291     * the user may specify which view to go to next.
3292     */
3293    private int mNextFocusLeftId = View.NO_ID;
3294
3295    /**
3296     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3297     * the user may specify which view to go to next.
3298     */
3299    private int mNextFocusRightId = View.NO_ID;
3300
3301    /**
3302     * When this view has focus and the next focus is {@link #FOCUS_UP},
3303     * the user may specify which view to go to next.
3304     */
3305    private int mNextFocusUpId = View.NO_ID;
3306
3307    /**
3308     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3309     * the user may specify which view to go to next.
3310     */
3311    private int mNextFocusDownId = View.NO_ID;
3312
3313    /**
3314     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3315     * the user may specify which view to go to next.
3316     */
3317    int mNextFocusForwardId = View.NO_ID;
3318
3319    private CheckForLongPress mPendingCheckForLongPress;
3320    private CheckForTap mPendingCheckForTap = null;
3321    private PerformClick mPerformClick;
3322    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3323
3324    private UnsetPressedState mUnsetPressedState;
3325
3326    /**
3327     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3328     * up event while a long press is invoked as soon as the long press duration is reached, so
3329     * a long press could be performed before the tap is checked, in which case the tap's action
3330     * should not be invoked.
3331     */
3332    private boolean mHasPerformedLongPress;
3333
3334    /**
3335     * The minimum height of the view. We'll try our best to have the height
3336     * of this view to at least this amount.
3337     */
3338    @ViewDebug.ExportedProperty(category = "measurement")
3339    private int mMinHeight;
3340
3341    /**
3342     * The minimum width of the view. We'll try our best to have the width
3343     * of this view to at least this amount.
3344     */
3345    @ViewDebug.ExportedProperty(category = "measurement")
3346    private int mMinWidth;
3347
3348    /**
3349     * The delegate to handle touch events that are physically in this view
3350     * but should be handled by another view.
3351     */
3352    private TouchDelegate mTouchDelegate = null;
3353
3354    /**
3355     * Solid color to use as a background when creating the drawing cache. Enables
3356     * the cache to use 16 bit bitmaps instead of 32 bit.
3357     */
3358    private int mDrawingCacheBackgroundColor = 0;
3359
3360    /**
3361     * Special tree observer used when mAttachInfo is null.
3362     */
3363    private ViewTreeObserver mFloatingTreeObserver;
3364
3365    /**
3366     * Cache the touch slop from the context that created the view.
3367     */
3368    private int mTouchSlop;
3369
3370    /**
3371     * Object that handles automatic animation of view properties.
3372     */
3373    private ViewPropertyAnimator mAnimator = null;
3374
3375    /**
3376     * Flag indicating that a drag can cross window boundaries.  When
3377     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3378     * with this flag set, all visible applications will be able to participate
3379     * in the drag operation and receive the dragged content.
3380     *
3381     * @hide
3382     */
3383    public static final int DRAG_FLAG_GLOBAL = 1;
3384
3385    /**
3386     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3387     */
3388    private float mVerticalScrollFactor;
3389
3390    /**
3391     * Position of the vertical scroll bar.
3392     */
3393    private int mVerticalScrollbarPosition;
3394
3395    /**
3396     * Position the scroll bar at the default position as determined by the system.
3397     */
3398    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3399
3400    /**
3401     * Position the scroll bar along the left edge.
3402     */
3403    public static final int SCROLLBAR_POSITION_LEFT = 1;
3404
3405    /**
3406     * Position the scroll bar along the right edge.
3407     */
3408    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3409
3410    /**
3411     * Indicates that the view does not have a layer.
3412     *
3413     * @see #getLayerType()
3414     * @see #setLayerType(int, android.graphics.Paint)
3415     * @see #LAYER_TYPE_SOFTWARE
3416     * @see #LAYER_TYPE_HARDWARE
3417     */
3418    public static final int LAYER_TYPE_NONE = 0;
3419
3420    /**
3421     * <p>Indicates that the view has a software layer. A software layer is backed
3422     * by a bitmap and causes the view to be rendered using Android's software
3423     * rendering pipeline, even if hardware acceleration is enabled.</p>
3424     *
3425     * <p>Software layers have various usages:</p>
3426     * <p>When the application is not using hardware acceleration, a software layer
3427     * is useful to apply a specific color filter and/or blending mode and/or
3428     * translucency to a view and all its children.</p>
3429     * <p>When the application is using hardware acceleration, a software layer
3430     * is useful to render drawing primitives not supported by the hardware
3431     * accelerated pipeline. It can also be used to cache a complex view tree
3432     * into a texture and reduce the complexity of drawing operations. For instance,
3433     * when animating a complex view tree with a translation, a software layer can
3434     * be used to render the view tree only once.</p>
3435     * <p>Software layers should be avoided when the affected view tree updates
3436     * often. Every update will require to re-render the software layer, which can
3437     * potentially be slow (particularly when hardware acceleration is turned on
3438     * since the layer will have to be uploaded into a hardware texture after every
3439     * update.)</p>
3440     *
3441     * @see #getLayerType()
3442     * @see #setLayerType(int, android.graphics.Paint)
3443     * @see #LAYER_TYPE_NONE
3444     * @see #LAYER_TYPE_HARDWARE
3445     */
3446    public static final int LAYER_TYPE_SOFTWARE = 1;
3447
3448    /**
3449     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3450     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3451     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3452     * rendering pipeline, but only if hardware acceleration is turned on for the
3453     * view hierarchy. When hardware acceleration is turned off, hardware layers
3454     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3455     *
3456     * <p>A hardware layer is useful to apply a specific color filter and/or
3457     * blending mode and/or translucency to a view and all its children.</p>
3458     * <p>A hardware layer can be used to cache a complex view tree into a
3459     * texture and reduce the complexity of drawing operations. For instance,
3460     * when animating a complex view tree with a translation, a hardware layer can
3461     * be used to render the view tree only once.</p>
3462     * <p>A hardware layer can also be used to increase the rendering quality when
3463     * rotation transformations are applied on a view. It can also be used to
3464     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3465     *
3466     * @see #getLayerType()
3467     * @see #setLayerType(int, android.graphics.Paint)
3468     * @see #LAYER_TYPE_NONE
3469     * @see #LAYER_TYPE_SOFTWARE
3470     */
3471    public static final int LAYER_TYPE_HARDWARE = 2;
3472
3473    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3474            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3475            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3476            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3477    })
3478    int mLayerType = LAYER_TYPE_NONE;
3479    Paint mLayerPaint;
3480
3481    /**
3482     * Set to true when drawing cache is enabled and cannot be created.
3483     *
3484     * @hide
3485     */
3486    public boolean mCachingFailed;
3487    private Bitmap mDrawingCache;
3488    private Bitmap mUnscaledDrawingCache;
3489
3490    /**
3491     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3492     * <p>
3493     * When non-null and valid, this is expected to contain an up-to-date copy
3494     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3495     * cleanup.
3496     */
3497    final RenderNode mRenderNode;
3498
3499    /**
3500     * Set to true when the view is sending hover accessibility events because it
3501     * is the innermost hovered view.
3502     */
3503    private boolean mSendingHoverAccessibilityEvents;
3504
3505    /**
3506     * Delegate for injecting accessibility functionality.
3507     */
3508    AccessibilityDelegate mAccessibilityDelegate;
3509
3510    /**
3511     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3512     * and add/remove objects to/from the overlay directly through the Overlay methods.
3513     */
3514    ViewOverlay mOverlay;
3515
3516    /**
3517     * The currently active parent view for receiving delegated nested scrolling events.
3518     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3519     * by {@link #stopNestedScroll()} at the same point where we clear
3520     * requestDisallowInterceptTouchEvent.
3521     */
3522    private ViewParent mNestedScrollingParent;
3523
3524    /**
3525     * Consistency verifier for debugging purposes.
3526     * @hide
3527     */
3528    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3529            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3530                    new InputEventConsistencyVerifier(this, 0) : null;
3531
3532    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3533
3534    private int[] mTempNestedScrollConsumed;
3535
3536    /**
3537     * Simple constructor to use when creating a view from code.
3538     *
3539     * @param context The Context the view is running in, through which it can
3540     *        access the current theme, resources, etc.
3541     */
3542    public View(Context context) {
3543        mContext = context;
3544        mResources = context != null ? context.getResources() : null;
3545        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3546        // Set some flags defaults
3547        mPrivateFlags2 =
3548                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3549                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3550                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3551                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3552                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3553                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3554        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3555        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3556        mUserPaddingStart = UNDEFINED_PADDING;
3557        mUserPaddingEnd = UNDEFINED_PADDING;
3558        mRenderNode = RenderNode.create(getClass().getName());
3559
3560        if (!sCompatibilityDone && context != null) {
3561            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3562
3563            // Older apps may need this compatibility hack for measurement.
3564            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3565
3566            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3567            // of whether a layout was requested on that View.
3568            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3569
3570            // Older apps may need this to ignore the clip bounds
3571            sIgnoreClipBoundsForChildren = targetSdkVersion < L;
3572
3573            sCompatibilityDone = true;
3574        }
3575    }
3576
3577    /**
3578     * Constructor that is called when inflating a view from XML. This is called
3579     * when a view is being constructed from an XML file, supplying attributes
3580     * that were specified in the XML file. This version uses a default style of
3581     * 0, so the only attribute values applied are those in the Context's Theme
3582     * and the given AttributeSet.
3583     *
3584     * <p>
3585     * The method onFinishInflate() will be called after all children have been
3586     * added.
3587     *
3588     * @param context The Context the view is running in, through which it can
3589     *        access the current theme, resources, etc.
3590     * @param attrs The attributes of the XML tag that is inflating the view.
3591     * @see #View(Context, AttributeSet, int)
3592     */
3593    public View(Context context, AttributeSet attrs) {
3594        this(context, attrs, 0);
3595    }
3596
3597    /**
3598     * Perform inflation from XML and apply a class-specific base style from a
3599     * theme attribute. This constructor of View allows subclasses to use their
3600     * own base style when they are inflating. For example, a Button class's
3601     * constructor would call this version of the super class constructor and
3602     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3603     * allows the theme's button style to modify all of the base view attributes
3604     * (in particular its background) as well as the Button class's attributes.
3605     *
3606     * @param context The Context the view is running in, through which it can
3607     *        access the current theme, resources, etc.
3608     * @param attrs The attributes of the XML tag that is inflating the view.
3609     * @param defStyleAttr An attribute in the current theme that contains a
3610     *        reference to a style resource that supplies default values for
3611     *        the view. Can be 0 to not look for defaults.
3612     * @see #View(Context, AttributeSet)
3613     */
3614    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3615        this(context, attrs, defStyleAttr, 0);
3616    }
3617
3618    /**
3619     * Perform inflation from XML and apply a class-specific base style from a
3620     * theme attribute or style resource. This constructor of View allows
3621     * subclasses to use their own base style when they are inflating.
3622     * <p>
3623     * When determining the final value of a particular attribute, there are
3624     * four inputs that come into play:
3625     * <ol>
3626     * <li>Any attribute values in the given AttributeSet.
3627     * <li>The style resource specified in the AttributeSet (named "style").
3628     * <li>The default style specified by <var>defStyleAttr</var>.
3629     * <li>The default style specified by <var>defStyleRes</var>.
3630     * <li>The base values in this theme.
3631     * </ol>
3632     * <p>
3633     * Each of these inputs is considered in-order, with the first listed taking
3634     * precedence over the following ones. In other words, if in the
3635     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3636     * , then the button's text will <em>always</em> be black, regardless of
3637     * what is specified in any of the styles.
3638     *
3639     * @param context The Context the view is running in, through which it can
3640     *        access the current theme, resources, etc.
3641     * @param attrs The attributes of the XML tag that is inflating the view.
3642     * @param defStyleAttr An attribute in the current theme that contains a
3643     *        reference to a style resource that supplies default values for
3644     *        the view. Can be 0 to not look for defaults.
3645     * @param defStyleRes A resource identifier of a style resource that
3646     *        supplies default values for the view, used only if
3647     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3648     *        to not look for defaults.
3649     * @see #View(Context, AttributeSet, int)
3650     */
3651    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3652        this(context);
3653
3654        final TypedArray a = context.obtainStyledAttributes(
3655                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3656
3657        Drawable background = null;
3658
3659        int leftPadding = -1;
3660        int topPadding = -1;
3661        int rightPadding = -1;
3662        int bottomPadding = -1;
3663        int startPadding = UNDEFINED_PADDING;
3664        int endPadding = UNDEFINED_PADDING;
3665
3666        int padding = -1;
3667
3668        int viewFlagValues = 0;
3669        int viewFlagMasks = 0;
3670
3671        boolean setScrollContainer = false;
3672
3673        int x = 0;
3674        int y = 0;
3675
3676        float tx = 0;
3677        float ty = 0;
3678        float tz = 0;
3679        float elevation = 0;
3680        float rotation = 0;
3681        float rotationX = 0;
3682        float rotationY = 0;
3683        float sx = 1f;
3684        float sy = 1f;
3685        boolean transformSet = false;
3686
3687        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3688        int overScrollMode = mOverScrollMode;
3689        boolean initializeScrollbars = false;
3690
3691        boolean startPaddingDefined = false;
3692        boolean endPaddingDefined = false;
3693        boolean leftPaddingDefined = false;
3694        boolean rightPaddingDefined = false;
3695
3696        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3697
3698        final int N = a.getIndexCount();
3699        for (int i = 0; i < N; i++) {
3700            int attr = a.getIndex(i);
3701            switch (attr) {
3702                case com.android.internal.R.styleable.View_background:
3703                    background = a.getDrawable(attr);
3704                    break;
3705                case com.android.internal.R.styleable.View_padding:
3706                    padding = a.getDimensionPixelSize(attr, -1);
3707                    mUserPaddingLeftInitial = padding;
3708                    mUserPaddingRightInitial = padding;
3709                    leftPaddingDefined = true;
3710                    rightPaddingDefined = true;
3711                    break;
3712                 case com.android.internal.R.styleable.View_paddingLeft:
3713                    leftPadding = a.getDimensionPixelSize(attr, -1);
3714                    mUserPaddingLeftInitial = leftPadding;
3715                    leftPaddingDefined = true;
3716                    break;
3717                case com.android.internal.R.styleable.View_paddingTop:
3718                    topPadding = a.getDimensionPixelSize(attr, -1);
3719                    break;
3720                case com.android.internal.R.styleable.View_paddingRight:
3721                    rightPadding = a.getDimensionPixelSize(attr, -1);
3722                    mUserPaddingRightInitial = rightPadding;
3723                    rightPaddingDefined = true;
3724                    break;
3725                case com.android.internal.R.styleable.View_paddingBottom:
3726                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3727                    break;
3728                case com.android.internal.R.styleable.View_paddingStart:
3729                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3730                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3731                    break;
3732                case com.android.internal.R.styleable.View_paddingEnd:
3733                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3734                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3735                    break;
3736                case com.android.internal.R.styleable.View_scrollX:
3737                    x = a.getDimensionPixelOffset(attr, 0);
3738                    break;
3739                case com.android.internal.R.styleable.View_scrollY:
3740                    y = a.getDimensionPixelOffset(attr, 0);
3741                    break;
3742                case com.android.internal.R.styleable.View_alpha:
3743                    setAlpha(a.getFloat(attr, 1f));
3744                    break;
3745                case com.android.internal.R.styleable.View_transformPivotX:
3746                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3747                    break;
3748                case com.android.internal.R.styleable.View_transformPivotY:
3749                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3750                    break;
3751                case com.android.internal.R.styleable.View_translationX:
3752                    tx = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_translationY:
3756                    ty = a.getDimensionPixelOffset(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_translationZ:
3760                    tz = a.getDimensionPixelOffset(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_elevation:
3764                    elevation = a.getDimensionPixelOffset(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_rotation:
3768                    rotation = a.getFloat(attr, 0);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_rotationX:
3772                    rotationX = a.getFloat(attr, 0);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_rotationY:
3776                    rotationY = a.getFloat(attr, 0);
3777                    transformSet = true;
3778                    break;
3779                case com.android.internal.R.styleable.View_scaleX:
3780                    sx = a.getFloat(attr, 1f);
3781                    transformSet = true;
3782                    break;
3783                case com.android.internal.R.styleable.View_scaleY:
3784                    sy = a.getFloat(attr, 1f);
3785                    transformSet = true;
3786                    break;
3787                case com.android.internal.R.styleable.View_id:
3788                    mID = a.getResourceId(attr, NO_ID);
3789                    break;
3790                case com.android.internal.R.styleable.View_tag:
3791                    mTag = a.getText(attr);
3792                    break;
3793                case com.android.internal.R.styleable.View_fitsSystemWindows:
3794                    if (a.getBoolean(attr, false)) {
3795                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3796                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3797                    }
3798                    break;
3799                case com.android.internal.R.styleable.View_focusable:
3800                    if (a.getBoolean(attr, false)) {
3801                        viewFlagValues |= FOCUSABLE;
3802                        viewFlagMasks |= FOCUSABLE_MASK;
3803                    }
3804                    break;
3805                case com.android.internal.R.styleable.View_focusableInTouchMode:
3806                    if (a.getBoolean(attr, false)) {
3807                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3808                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3809                    }
3810                    break;
3811                case com.android.internal.R.styleable.View_clickable:
3812                    if (a.getBoolean(attr, false)) {
3813                        viewFlagValues |= CLICKABLE;
3814                        viewFlagMasks |= CLICKABLE;
3815                    }
3816                    break;
3817                case com.android.internal.R.styleable.View_longClickable:
3818                    if (a.getBoolean(attr, false)) {
3819                        viewFlagValues |= LONG_CLICKABLE;
3820                        viewFlagMasks |= LONG_CLICKABLE;
3821                    }
3822                    break;
3823                case com.android.internal.R.styleable.View_saveEnabled:
3824                    if (!a.getBoolean(attr, true)) {
3825                        viewFlagValues |= SAVE_DISABLED;
3826                        viewFlagMasks |= SAVE_DISABLED_MASK;
3827                    }
3828                    break;
3829                case com.android.internal.R.styleable.View_duplicateParentState:
3830                    if (a.getBoolean(attr, false)) {
3831                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3832                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3833                    }
3834                    break;
3835                case com.android.internal.R.styleable.View_visibility:
3836                    final int visibility = a.getInt(attr, 0);
3837                    if (visibility != 0) {
3838                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3839                        viewFlagMasks |= VISIBILITY_MASK;
3840                    }
3841                    break;
3842                case com.android.internal.R.styleable.View_layoutDirection:
3843                    // Clear any layout direction flags (included resolved bits) already set
3844                    mPrivateFlags2 &=
3845                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3846                    // Set the layout direction flags depending on the value of the attribute
3847                    final int layoutDirection = a.getInt(attr, -1);
3848                    final int value = (layoutDirection != -1) ?
3849                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3850                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3851                    break;
3852                case com.android.internal.R.styleable.View_drawingCacheQuality:
3853                    final int cacheQuality = a.getInt(attr, 0);
3854                    if (cacheQuality != 0) {
3855                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3856                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_contentDescription:
3860                    setContentDescription(a.getString(attr));
3861                    break;
3862                case com.android.internal.R.styleable.View_labelFor:
3863                    setLabelFor(a.getResourceId(attr, NO_ID));
3864                    break;
3865                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3866                    if (!a.getBoolean(attr, true)) {
3867                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3868                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3869                    }
3870                    break;
3871                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3872                    if (!a.getBoolean(attr, true)) {
3873                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3874                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3875                    }
3876                    break;
3877                case R.styleable.View_scrollbars:
3878                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3879                    if (scrollbars != SCROLLBARS_NONE) {
3880                        viewFlagValues |= scrollbars;
3881                        viewFlagMasks |= SCROLLBARS_MASK;
3882                        initializeScrollbars = true;
3883                    }
3884                    break;
3885                //noinspection deprecation
3886                case R.styleable.View_fadingEdge:
3887                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3888                        // Ignore the attribute starting with ICS
3889                        break;
3890                    }
3891                    // With builds < ICS, fall through and apply fading edges
3892                case R.styleable.View_requiresFadingEdge:
3893                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3894                    if (fadingEdge != FADING_EDGE_NONE) {
3895                        viewFlagValues |= fadingEdge;
3896                        viewFlagMasks |= FADING_EDGE_MASK;
3897                        initializeFadingEdge(a);
3898                    }
3899                    break;
3900                case R.styleable.View_scrollbarStyle:
3901                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3902                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3903                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3904                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3905                    }
3906                    break;
3907                case R.styleable.View_isScrollContainer:
3908                    setScrollContainer = true;
3909                    if (a.getBoolean(attr, false)) {
3910                        setScrollContainer(true);
3911                    }
3912                    break;
3913                case com.android.internal.R.styleable.View_keepScreenOn:
3914                    if (a.getBoolean(attr, false)) {
3915                        viewFlagValues |= KEEP_SCREEN_ON;
3916                        viewFlagMasks |= KEEP_SCREEN_ON;
3917                    }
3918                    break;
3919                case R.styleable.View_filterTouchesWhenObscured:
3920                    if (a.getBoolean(attr, false)) {
3921                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3922                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3923                    }
3924                    break;
3925                case R.styleable.View_nextFocusLeft:
3926                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3927                    break;
3928                case R.styleable.View_nextFocusRight:
3929                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3930                    break;
3931                case R.styleable.View_nextFocusUp:
3932                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3933                    break;
3934                case R.styleable.View_nextFocusDown:
3935                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3936                    break;
3937                case R.styleable.View_nextFocusForward:
3938                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3939                    break;
3940                case R.styleable.View_minWidth:
3941                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3942                    break;
3943                case R.styleable.View_minHeight:
3944                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3945                    break;
3946                case R.styleable.View_onClick:
3947                    if (context.isRestricted()) {
3948                        throw new IllegalStateException("The android:onClick attribute cannot "
3949                                + "be used within a restricted context");
3950                    }
3951
3952                    final String handlerName = a.getString(attr);
3953                    if (handlerName != null) {
3954                        setOnClickListener(new OnClickListener() {
3955                            private Method mHandler;
3956
3957                            public void onClick(View v) {
3958                                if (mHandler == null) {
3959                                    try {
3960                                        mHandler = getContext().getClass().getMethod(handlerName,
3961                                                View.class);
3962                                    } catch (NoSuchMethodException e) {
3963                                        int id = getId();
3964                                        String idText = id == NO_ID ? "" : " with id '"
3965                                                + getContext().getResources().getResourceEntryName(
3966                                                    id) + "'";
3967                                        throw new IllegalStateException("Could not find a method " +
3968                                                handlerName + "(View) in the activity "
3969                                                + getContext().getClass() + " for onClick handler"
3970                                                + " on view " + View.this.getClass() + idText, e);
3971                                    }
3972                                }
3973
3974                                try {
3975                                    mHandler.invoke(getContext(), View.this);
3976                                } catch (IllegalAccessException e) {
3977                                    throw new IllegalStateException("Could not execute non "
3978                                            + "public method of the activity", e);
3979                                } catch (InvocationTargetException e) {
3980                                    throw new IllegalStateException("Could not execute "
3981                                            + "method of the activity", e);
3982                                }
3983                            }
3984                        });
3985                    }
3986                    break;
3987                case R.styleable.View_overScrollMode:
3988                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3989                    break;
3990                case R.styleable.View_verticalScrollbarPosition:
3991                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3992                    break;
3993                case R.styleable.View_layerType:
3994                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3995                    break;
3996                case R.styleable.View_textDirection:
3997                    // Clear any text direction flag already set
3998                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3999                    // Set the text direction flags depending on the value of the attribute
4000                    final int textDirection = a.getInt(attr, -1);
4001                    if (textDirection != -1) {
4002                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4003                    }
4004                    break;
4005                case R.styleable.View_textAlignment:
4006                    // Clear any text alignment flag already set
4007                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4008                    // Set the text alignment flag depending on the value of the attribute
4009                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4010                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4011                    break;
4012                case R.styleable.View_importantForAccessibility:
4013                    setImportantForAccessibility(a.getInt(attr,
4014                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4015                    break;
4016                case R.styleable.View_accessibilityLiveRegion:
4017                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4018                    break;
4019                case R.styleable.View_viewName:
4020                    setViewName(a.getString(attr));
4021                    break;
4022                case R.styleable.View_nestedScrollingEnabled:
4023                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4024                    break;
4025                case R.styleable.View_stateListAnimator:
4026                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4027                            a.getResourceId(attr, 0)));
4028                    break;
4029                case R.styleable.View_backgroundTint:
4030                    // This will get applied later during setBackground().
4031                    mBackgroundTint = a.getColorStateList(R.styleable.View_backgroundTint);
4032                    mHasBackgroundTint = true;
4033                    break;
4034                case R.styleable.View_backgroundTintMode:
4035                    // This will get applied later during setBackground().
4036                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4037                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4038                    break;
4039            }
4040        }
4041
4042        setOverScrollMode(overScrollMode);
4043
4044        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4045        // the resolved layout direction). Those cached values will be used later during padding
4046        // resolution.
4047        mUserPaddingStart = startPadding;
4048        mUserPaddingEnd = endPadding;
4049
4050        if (background != null) {
4051            setBackground(background);
4052        }
4053
4054        // setBackground above will record that padding is currently provided by the background.
4055        // If we have padding specified via xml, record that here instead and use it.
4056        mLeftPaddingDefined = leftPaddingDefined;
4057        mRightPaddingDefined = rightPaddingDefined;
4058
4059        if (padding >= 0) {
4060            leftPadding = padding;
4061            topPadding = padding;
4062            rightPadding = padding;
4063            bottomPadding = padding;
4064            mUserPaddingLeftInitial = padding;
4065            mUserPaddingRightInitial = padding;
4066        }
4067
4068        if (isRtlCompatibilityMode()) {
4069            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4070            // left / right padding are used if defined (meaning here nothing to do). If they are not
4071            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4072            // start / end and resolve them as left / right (layout direction is not taken into account).
4073            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4074            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4075            // defined.
4076            if (!mLeftPaddingDefined && startPaddingDefined) {
4077                leftPadding = startPadding;
4078            }
4079            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4080            if (!mRightPaddingDefined && endPaddingDefined) {
4081                rightPadding = endPadding;
4082            }
4083            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4084        } else {
4085            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4086            // values defined. Otherwise, left /right values are used.
4087            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4088            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4089            // defined.
4090            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4091
4092            if (mLeftPaddingDefined && !hasRelativePadding) {
4093                mUserPaddingLeftInitial = leftPadding;
4094            }
4095            if (mRightPaddingDefined && !hasRelativePadding) {
4096                mUserPaddingRightInitial = rightPadding;
4097            }
4098        }
4099
4100        internalSetPadding(
4101                mUserPaddingLeftInitial,
4102                topPadding >= 0 ? topPadding : mPaddingTop,
4103                mUserPaddingRightInitial,
4104                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4105
4106        if (viewFlagMasks != 0) {
4107            setFlags(viewFlagValues, viewFlagMasks);
4108        }
4109
4110        if (initializeScrollbars) {
4111            initializeScrollbars(a);
4112        }
4113
4114        a.recycle();
4115
4116        // Needs to be called after mViewFlags is set
4117        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4118            recomputePadding();
4119        }
4120
4121        if (x != 0 || y != 0) {
4122            scrollTo(x, y);
4123        }
4124
4125        if (transformSet) {
4126            setTranslationX(tx);
4127            setTranslationY(ty);
4128            setTranslationZ(tz);
4129            setElevation(elevation);
4130            setRotation(rotation);
4131            setRotationX(rotationX);
4132            setRotationY(rotationY);
4133            setScaleX(sx);
4134            setScaleY(sy);
4135        }
4136
4137        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4138            setScrollContainer(true);
4139        }
4140
4141        computeOpaqueFlags();
4142    }
4143
4144    /**
4145     * Non-public constructor for use in testing
4146     */
4147    View() {
4148        mResources = null;
4149        mRenderNode = RenderNode.create(getClass().getName());
4150    }
4151
4152    public String toString() {
4153        StringBuilder out = new StringBuilder(128);
4154        out.append(getClass().getName());
4155        out.append('{');
4156        out.append(Integer.toHexString(System.identityHashCode(this)));
4157        out.append(' ');
4158        switch (mViewFlags&VISIBILITY_MASK) {
4159            case VISIBLE: out.append('V'); break;
4160            case INVISIBLE: out.append('I'); break;
4161            case GONE: out.append('G'); break;
4162            default: out.append('.'); break;
4163        }
4164        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4165        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4166        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4167        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4168        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4169        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4170        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4171        out.append(' ');
4172        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4173        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4174        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4175        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4176            out.append('p');
4177        } else {
4178            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4179        }
4180        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4181        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4182        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4183        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4184        out.append(' ');
4185        out.append(mLeft);
4186        out.append(',');
4187        out.append(mTop);
4188        out.append('-');
4189        out.append(mRight);
4190        out.append(',');
4191        out.append(mBottom);
4192        final int id = getId();
4193        if (id != NO_ID) {
4194            out.append(" #");
4195            out.append(Integer.toHexString(id));
4196            final Resources r = mResources;
4197            if (Resources.resourceHasPackage(id) && r != null) {
4198                try {
4199                    String pkgname;
4200                    switch (id&0xff000000) {
4201                        case 0x7f000000:
4202                            pkgname="app";
4203                            break;
4204                        case 0x01000000:
4205                            pkgname="android";
4206                            break;
4207                        default:
4208                            pkgname = r.getResourcePackageName(id);
4209                            break;
4210                    }
4211                    String typename = r.getResourceTypeName(id);
4212                    String entryname = r.getResourceEntryName(id);
4213                    out.append(" ");
4214                    out.append(pkgname);
4215                    out.append(":");
4216                    out.append(typename);
4217                    out.append("/");
4218                    out.append(entryname);
4219                } catch (Resources.NotFoundException e) {
4220                }
4221            }
4222        }
4223        out.append("}");
4224        return out.toString();
4225    }
4226
4227    /**
4228     * <p>
4229     * Initializes the fading edges from a given set of styled attributes. This
4230     * method should be called by subclasses that need fading edges and when an
4231     * instance of these subclasses is created programmatically rather than
4232     * being inflated from XML. This method is automatically called when the XML
4233     * is inflated.
4234     * </p>
4235     *
4236     * @param a the styled attributes set to initialize the fading edges from
4237     */
4238    protected void initializeFadingEdge(TypedArray a) {
4239        initScrollCache();
4240
4241        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4242                R.styleable.View_fadingEdgeLength,
4243                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4244    }
4245
4246    /**
4247     * Returns the size of the vertical faded edges used to indicate that more
4248     * content in this view is visible.
4249     *
4250     * @return The size in pixels of the vertical faded edge or 0 if vertical
4251     *         faded edges are not enabled for this view.
4252     * @attr ref android.R.styleable#View_fadingEdgeLength
4253     */
4254    public int getVerticalFadingEdgeLength() {
4255        if (isVerticalFadingEdgeEnabled()) {
4256            ScrollabilityCache cache = mScrollCache;
4257            if (cache != null) {
4258                return cache.fadingEdgeLength;
4259            }
4260        }
4261        return 0;
4262    }
4263
4264    /**
4265     * Set the size of the faded edge used to indicate that more content in this
4266     * view is available.  Will not change whether the fading edge is enabled; use
4267     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4268     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4269     * for the vertical or horizontal fading edges.
4270     *
4271     * @param length The size in pixels of the faded edge used to indicate that more
4272     *        content in this view is visible.
4273     */
4274    public void setFadingEdgeLength(int length) {
4275        initScrollCache();
4276        mScrollCache.fadingEdgeLength = length;
4277    }
4278
4279    /**
4280     * Returns the size of the horizontal faded edges used to indicate that more
4281     * content in this view is visible.
4282     *
4283     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4284     *         faded edges are not enabled for this view.
4285     * @attr ref android.R.styleable#View_fadingEdgeLength
4286     */
4287    public int getHorizontalFadingEdgeLength() {
4288        if (isHorizontalFadingEdgeEnabled()) {
4289            ScrollabilityCache cache = mScrollCache;
4290            if (cache != null) {
4291                return cache.fadingEdgeLength;
4292            }
4293        }
4294        return 0;
4295    }
4296
4297    /**
4298     * Returns the width of the vertical scrollbar.
4299     *
4300     * @return The width in pixels of the vertical scrollbar or 0 if there
4301     *         is no vertical scrollbar.
4302     */
4303    public int getVerticalScrollbarWidth() {
4304        ScrollabilityCache cache = mScrollCache;
4305        if (cache != null) {
4306            ScrollBarDrawable scrollBar = cache.scrollBar;
4307            if (scrollBar != null) {
4308                int size = scrollBar.getSize(true);
4309                if (size <= 0) {
4310                    size = cache.scrollBarSize;
4311                }
4312                return size;
4313            }
4314            return 0;
4315        }
4316        return 0;
4317    }
4318
4319    /**
4320     * Returns the height of the horizontal scrollbar.
4321     *
4322     * @return The height in pixels of the horizontal scrollbar or 0 if
4323     *         there is no horizontal scrollbar.
4324     */
4325    protected int getHorizontalScrollbarHeight() {
4326        ScrollabilityCache cache = mScrollCache;
4327        if (cache != null) {
4328            ScrollBarDrawable scrollBar = cache.scrollBar;
4329            if (scrollBar != null) {
4330                int size = scrollBar.getSize(false);
4331                if (size <= 0) {
4332                    size = cache.scrollBarSize;
4333                }
4334                return size;
4335            }
4336            return 0;
4337        }
4338        return 0;
4339    }
4340
4341    /**
4342     * <p>
4343     * Initializes the scrollbars from a given set of styled attributes. This
4344     * method should be called by subclasses that need scrollbars and when an
4345     * instance of these subclasses is created programmatically rather than
4346     * being inflated from XML. This method is automatically called when the XML
4347     * is inflated.
4348     * </p>
4349     *
4350     * @param a the styled attributes set to initialize the scrollbars from
4351     */
4352    protected void initializeScrollbars(TypedArray a) {
4353        initScrollCache();
4354
4355        final ScrollabilityCache scrollabilityCache = mScrollCache;
4356
4357        if (scrollabilityCache.scrollBar == null) {
4358            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4359        }
4360
4361        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4362
4363        if (!fadeScrollbars) {
4364            scrollabilityCache.state = ScrollabilityCache.ON;
4365        }
4366        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4367
4368
4369        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4370                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4371                        .getScrollBarFadeDuration());
4372        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4373                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4374                ViewConfiguration.getScrollDefaultDelay());
4375
4376
4377        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4378                com.android.internal.R.styleable.View_scrollbarSize,
4379                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4380
4381        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4382        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4383
4384        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4385        if (thumb != null) {
4386            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4387        }
4388
4389        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4390                false);
4391        if (alwaysDraw) {
4392            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4393        }
4394
4395        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4396        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4397
4398        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4399        if (thumb != null) {
4400            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4401        }
4402
4403        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4404                false);
4405        if (alwaysDraw) {
4406            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4407        }
4408
4409        // Apply layout direction to the new Drawables if needed
4410        final int layoutDirection = getLayoutDirection();
4411        if (track != null) {
4412            track.setLayoutDirection(layoutDirection);
4413        }
4414        if (thumb != null) {
4415            thumb.setLayoutDirection(layoutDirection);
4416        }
4417
4418        // Re-apply user/background padding so that scrollbar(s) get added
4419        resolvePadding();
4420    }
4421
4422    /**
4423     * <p>
4424     * Initalizes the scrollability cache if necessary.
4425     * </p>
4426     */
4427    private void initScrollCache() {
4428        if (mScrollCache == null) {
4429            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4430        }
4431    }
4432
4433    private ScrollabilityCache getScrollCache() {
4434        initScrollCache();
4435        return mScrollCache;
4436    }
4437
4438    /**
4439     * Set the position of the vertical scroll bar. Should be one of
4440     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4441     * {@link #SCROLLBAR_POSITION_RIGHT}.
4442     *
4443     * @param position Where the vertical scroll bar should be positioned.
4444     */
4445    public void setVerticalScrollbarPosition(int position) {
4446        if (mVerticalScrollbarPosition != position) {
4447            mVerticalScrollbarPosition = position;
4448            computeOpaqueFlags();
4449            resolvePadding();
4450        }
4451    }
4452
4453    /**
4454     * @return The position where the vertical scroll bar will show, if applicable.
4455     * @see #setVerticalScrollbarPosition(int)
4456     */
4457    public int getVerticalScrollbarPosition() {
4458        return mVerticalScrollbarPosition;
4459    }
4460
4461    ListenerInfo getListenerInfo() {
4462        if (mListenerInfo != null) {
4463            return mListenerInfo;
4464        }
4465        mListenerInfo = new ListenerInfo();
4466        return mListenerInfo;
4467    }
4468
4469    /**
4470     * Register a callback to be invoked when focus of this view changed.
4471     *
4472     * @param l The callback that will run.
4473     */
4474    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4475        getListenerInfo().mOnFocusChangeListener = l;
4476    }
4477
4478    /**
4479     * Add a listener that will be called when the bounds of the view change due to
4480     * layout processing.
4481     *
4482     * @param listener The listener that will be called when layout bounds change.
4483     */
4484    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4485        ListenerInfo li = getListenerInfo();
4486        if (li.mOnLayoutChangeListeners == null) {
4487            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4488        }
4489        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4490            li.mOnLayoutChangeListeners.add(listener);
4491        }
4492    }
4493
4494    /**
4495     * Remove a listener for layout changes.
4496     *
4497     * @param listener The listener for layout bounds change.
4498     */
4499    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4500        ListenerInfo li = mListenerInfo;
4501        if (li == null || li.mOnLayoutChangeListeners == null) {
4502            return;
4503        }
4504        li.mOnLayoutChangeListeners.remove(listener);
4505    }
4506
4507    /**
4508     * Add a listener for attach state changes.
4509     *
4510     * This listener will be called whenever this view is attached or detached
4511     * from a window. Remove the listener using
4512     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4513     *
4514     * @param listener Listener to attach
4515     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4516     */
4517    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4518        ListenerInfo li = getListenerInfo();
4519        if (li.mOnAttachStateChangeListeners == null) {
4520            li.mOnAttachStateChangeListeners
4521                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4522        }
4523        li.mOnAttachStateChangeListeners.add(listener);
4524    }
4525
4526    /**
4527     * Remove a listener for attach state changes. The listener will receive no further
4528     * notification of window attach/detach events.
4529     *
4530     * @param listener Listener to remove
4531     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4532     */
4533    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4534        ListenerInfo li = mListenerInfo;
4535        if (li == null || li.mOnAttachStateChangeListeners == null) {
4536            return;
4537        }
4538        li.mOnAttachStateChangeListeners.remove(listener);
4539    }
4540
4541    /**
4542     * Returns the focus-change callback registered for this view.
4543     *
4544     * @return The callback, or null if one is not registered.
4545     */
4546    public OnFocusChangeListener getOnFocusChangeListener() {
4547        ListenerInfo li = mListenerInfo;
4548        return li != null ? li.mOnFocusChangeListener : null;
4549    }
4550
4551    /**
4552     * Register a callback to be invoked when this view is clicked. If this view is not
4553     * clickable, it becomes clickable.
4554     *
4555     * @param l The callback that will run
4556     *
4557     * @see #setClickable(boolean)
4558     */
4559    public void setOnClickListener(OnClickListener l) {
4560        if (!isClickable()) {
4561            setClickable(true);
4562        }
4563        getListenerInfo().mOnClickListener = l;
4564    }
4565
4566    /**
4567     * Return whether this view has an attached OnClickListener.  Returns
4568     * true if there is a listener, false if there is none.
4569     */
4570    public boolean hasOnClickListeners() {
4571        ListenerInfo li = mListenerInfo;
4572        return (li != null && li.mOnClickListener != null);
4573    }
4574
4575    /**
4576     * Register a callback to be invoked when this view is clicked and held. If this view is not
4577     * long clickable, it becomes long clickable.
4578     *
4579     * @param l The callback that will run
4580     *
4581     * @see #setLongClickable(boolean)
4582     */
4583    public void setOnLongClickListener(OnLongClickListener l) {
4584        if (!isLongClickable()) {
4585            setLongClickable(true);
4586        }
4587        getListenerInfo().mOnLongClickListener = l;
4588    }
4589
4590    /**
4591     * Register a callback to be invoked when the context menu for this view is
4592     * being built. If this view is not long clickable, it becomes long clickable.
4593     *
4594     * @param l The callback that will run
4595     *
4596     */
4597    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4598        if (!isLongClickable()) {
4599            setLongClickable(true);
4600        }
4601        getListenerInfo().mOnCreateContextMenuListener = l;
4602    }
4603
4604    /**
4605     * Call this view's OnClickListener, if it is defined.  Performs all normal
4606     * actions associated with clicking: reporting accessibility event, playing
4607     * a sound, etc.
4608     *
4609     * @return True there was an assigned OnClickListener that was called, false
4610     *         otherwise is returned.
4611     */
4612    public boolean performClick() {
4613        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4614
4615        ListenerInfo li = mListenerInfo;
4616        if (li != null && li.mOnClickListener != null) {
4617            playSoundEffect(SoundEffectConstants.CLICK);
4618            li.mOnClickListener.onClick(this);
4619            return true;
4620        }
4621
4622        return false;
4623    }
4624
4625    /**
4626     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4627     * this only calls the listener, and does not do any associated clicking
4628     * actions like reporting an accessibility event.
4629     *
4630     * @return True there was an assigned OnClickListener that was called, false
4631     *         otherwise is returned.
4632     */
4633    public boolean callOnClick() {
4634        ListenerInfo li = mListenerInfo;
4635        if (li != null && li.mOnClickListener != null) {
4636            li.mOnClickListener.onClick(this);
4637            return true;
4638        }
4639        return false;
4640    }
4641
4642    /**
4643     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4644     * OnLongClickListener did not consume the event.
4645     *
4646     * @return True if one of the above receivers consumed the event, false otherwise.
4647     */
4648    public boolean performLongClick() {
4649        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4650
4651        boolean handled = false;
4652        ListenerInfo li = mListenerInfo;
4653        if (li != null && li.mOnLongClickListener != null) {
4654            handled = li.mOnLongClickListener.onLongClick(View.this);
4655        }
4656        if (!handled) {
4657            handled = showContextMenu();
4658        }
4659        if (handled) {
4660            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4661        }
4662        return handled;
4663    }
4664
4665    /**
4666     * Performs button-related actions during a touch down event.
4667     *
4668     * @param event The event.
4669     * @return True if the down was consumed.
4670     *
4671     * @hide
4672     */
4673    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4674        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4675            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4676                return true;
4677            }
4678        }
4679        return false;
4680    }
4681
4682    /**
4683     * Bring up the context menu for this view.
4684     *
4685     * @return Whether a context menu was displayed.
4686     */
4687    public boolean showContextMenu() {
4688        return getParent().showContextMenuForChild(this);
4689    }
4690
4691    /**
4692     * Bring up the context menu for this view, referring to the item under the specified point.
4693     *
4694     * @param x The referenced x coordinate.
4695     * @param y The referenced y coordinate.
4696     * @param metaState The keyboard modifiers that were pressed.
4697     * @return Whether a context menu was displayed.
4698     *
4699     * @hide
4700     */
4701    public boolean showContextMenu(float x, float y, int metaState) {
4702        return showContextMenu();
4703    }
4704
4705    /**
4706     * Start an action mode.
4707     *
4708     * @param callback Callback that will control the lifecycle of the action mode
4709     * @return The new action mode if it is started, null otherwise
4710     *
4711     * @see ActionMode
4712     */
4713    public ActionMode startActionMode(ActionMode.Callback callback) {
4714        ViewParent parent = getParent();
4715        if (parent == null) return null;
4716        return parent.startActionModeForChild(this, callback);
4717    }
4718
4719    /**
4720     * Register a callback to be invoked when a hardware key is pressed in this view.
4721     * Key presses in software input methods will generally not trigger the methods of
4722     * this listener.
4723     * @param l the key listener to attach to this view
4724     */
4725    public void setOnKeyListener(OnKeyListener l) {
4726        getListenerInfo().mOnKeyListener = l;
4727    }
4728
4729    /**
4730     * Register a callback to be invoked when a touch event is sent to this view.
4731     * @param l the touch listener to attach to this view
4732     */
4733    public void setOnTouchListener(OnTouchListener l) {
4734        getListenerInfo().mOnTouchListener = l;
4735    }
4736
4737    /**
4738     * Register a callback to be invoked when a generic motion event is sent to this view.
4739     * @param l the generic motion listener to attach to this view
4740     */
4741    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4742        getListenerInfo().mOnGenericMotionListener = l;
4743    }
4744
4745    /**
4746     * Register a callback to be invoked when a hover event is sent to this view.
4747     * @param l the hover listener to attach to this view
4748     */
4749    public void setOnHoverListener(OnHoverListener l) {
4750        getListenerInfo().mOnHoverListener = l;
4751    }
4752
4753    /**
4754     * Register a drag event listener callback object for this View. The parameter is
4755     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4756     * View, the system calls the
4757     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4758     * @param l An implementation of {@link android.view.View.OnDragListener}.
4759     */
4760    public void setOnDragListener(OnDragListener l) {
4761        getListenerInfo().mOnDragListener = l;
4762    }
4763
4764    /**
4765     * Give this view focus. This will cause
4766     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4767     *
4768     * Note: this does not check whether this {@link View} should get focus, it just
4769     * gives it focus no matter what.  It should only be called internally by framework
4770     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4771     *
4772     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4773     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4774     *        focus moved when requestFocus() is called. It may not always
4775     *        apply, in which case use the default View.FOCUS_DOWN.
4776     * @param previouslyFocusedRect The rectangle of the view that had focus
4777     *        prior in this View's coordinate system.
4778     */
4779    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4780        if (DBG) {
4781            System.out.println(this + " requestFocus()");
4782        }
4783
4784        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4785            mPrivateFlags |= PFLAG_FOCUSED;
4786
4787            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4788
4789            if (mParent != null) {
4790                mParent.requestChildFocus(this, this);
4791            }
4792
4793            if (mAttachInfo != null) {
4794                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4795            }
4796
4797            onFocusChanged(true, direction, previouslyFocusedRect);
4798            manageFocusHotspot(true, oldFocus);
4799            refreshDrawableState();
4800        }
4801    }
4802
4803    /**
4804     * Forwards focus information to the background drawable, if necessary. When
4805     * the view is gaining focus, <code>v</code> is the previous focus holder.
4806     * When the view is losing focus, <code>v</code> is the next focus holder.
4807     *
4808     * @param focused whether this view is focused
4809     * @param v previous or the next focus holder, or null if none
4810     */
4811    private void manageFocusHotspot(boolean focused, View v) {
4812        final Rect r = new Rect();
4813        if (!focused && v != null && mAttachInfo != null) {
4814            v.getBoundsOnScreen(r);
4815            final int[] location = mAttachInfo.mTmpLocation;
4816            getLocationOnScreen(location);
4817            r.offset(-location[0], -location[1]);
4818        } else {
4819            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4820        }
4821
4822        final float x = r.exactCenterX();
4823        final float y = r.exactCenterY();
4824        drawableHotspotChanged(x, y);
4825    }
4826
4827    /**
4828     * Request that a rectangle of this view be visible on the screen,
4829     * scrolling if necessary just enough.
4830     *
4831     * <p>A View should call this if it maintains some notion of which part
4832     * of its content is interesting.  For example, a text editing view
4833     * should call this when its cursor moves.
4834     *
4835     * @param rectangle The rectangle.
4836     * @return Whether any parent scrolled.
4837     */
4838    public boolean requestRectangleOnScreen(Rect rectangle) {
4839        return requestRectangleOnScreen(rectangle, false);
4840    }
4841
4842    /**
4843     * Request that a rectangle of this view be visible on the screen,
4844     * scrolling if necessary just enough.
4845     *
4846     * <p>A View should call this if it maintains some notion of which part
4847     * of its content is interesting.  For example, a text editing view
4848     * should call this when its cursor moves.
4849     *
4850     * <p>When <code>immediate</code> is set to true, scrolling will not be
4851     * animated.
4852     *
4853     * @param rectangle The rectangle.
4854     * @param immediate True to forbid animated scrolling, false otherwise
4855     * @return Whether any parent scrolled.
4856     */
4857    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4858        if (mParent == null) {
4859            return false;
4860        }
4861
4862        View child = this;
4863
4864        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4865        position.set(rectangle);
4866
4867        ViewParent parent = mParent;
4868        boolean scrolled = false;
4869        while (parent != null) {
4870            rectangle.set((int) position.left, (int) position.top,
4871                    (int) position.right, (int) position.bottom);
4872
4873            scrolled |= parent.requestChildRectangleOnScreen(child,
4874                    rectangle, immediate);
4875
4876            if (!child.hasIdentityMatrix()) {
4877                child.getMatrix().mapRect(position);
4878            }
4879
4880            position.offset(child.mLeft, child.mTop);
4881
4882            if (!(parent instanceof View)) {
4883                break;
4884            }
4885
4886            View parentView = (View) parent;
4887
4888            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4889
4890            child = parentView;
4891            parent = child.getParent();
4892        }
4893
4894        return scrolled;
4895    }
4896
4897    /**
4898     * Called when this view wants to give up focus. If focus is cleared
4899     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4900     * <p>
4901     * <strong>Note:</strong> When a View clears focus the framework is trying
4902     * to give focus to the first focusable View from the top. Hence, if this
4903     * View is the first from the top that can take focus, then all callbacks
4904     * related to clearing focus will be invoked after wich the framework will
4905     * give focus to this view.
4906     * </p>
4907     */
4908    public void clearFocus() {
4909        if (DBG) {
4910            System.out.println(this + " clearFocus()");
4911        }
4912
4913        clearFocusInternal(null, true, true);
4914    }
4915
4916    /**
4917     * Clears focus from the view, optionally propagating the change up through
4918     * the parent hierarchy and requesting that the root view place new focus.
4919     *
4920     * @param propagate whether to propagate the change up through the parent
4921     *            hierarchy
4922     * @param refocus when propagate is true, specifies whether to request the
4923     *            root view place new focus
4924     */
4925    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4926        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4927            mPrivateFlags &= ~PFLAG_FOCUSED;
4928
4929            if (propagate && mParent != null) {
4930                mParent.clearChildFocus(this);
4931            }
4932
4933            onFocusChanged(false, 0, null);
4934
4935            manageFocusHotspot(false, focused);
4936            refreshDrawableState();
4937
4938            if (propagate && (!refocus || !rootViewRequestFocus())) {
4939                notifyGlobalFocusCleared(this);
4940            }
4941        }
4942    }
4943
4944    void notifyGlobalFocusCleared(View oldFocus) {
4945        if (oldFocus != null && mAttachInfo != null) {
4946            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4947        }
4948    }
4949
4950    boolean rootViewRequestFocus() {
4951        final View root = getRootView();
4952        return root != null && root.requestFocus();
4953    }
4954
4955    /**
4956     * Called internally by the view system when a new view is getting focus.
4957     * This is what clears the old focus.
4958     * <p>
4959     * <b>NOTE:</b> The parent view's focused child must be updated manually
4960     * after calling this method. Otherwise, the view hierarchy may be left in
4961     * an inconstent state.
4962     */
4963    void unFocus(View focused) {
4964        if (DBG) {
4965            System.out.println(this + " unFocus()");
4966        }
4967
4968        clearFocusInternal(focused, false, false);
4969    }
4970
4971    /**
4972     * Returns true if this view has focus iteself, or is the ancestor of the
4973     * view that has focus.
4974     *
4975     * @return True if this view has or contains focus, false otherwise.
4976     */
4977    @ViewDebug.ExportedProperty(category = "focus")
4978    public boolean hasFocus() {
4979        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4980    }
4981
4982    /**
4983     * Returns true if this view is focusable or if it contains a reachable View
4984     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4985     * is a View whose parents do not block descendants focus.
4986     *
4987     * Only {@link #VISIBLE} views are considered focusable.
4988     *
4989     * @return True if the view is focusable or if the view contains a focusable
4990     *         View, false otherwise.
4991     *
4992     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4993     */
4994    public boolean hasFocusable() {
4995        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4996    }
4997
4998    /**
4999     * Called by the view system when the focus state of this view changes.
5000     * When the focus change event is caused by directional navigation, direction
5001     * and previouslyFocusedRect provide insight into where the focus is coming from.
5002     * When overriding, be sure to call up through to the super class so that
5003     * the standard focus handling will occur.
5004     *
5005     * @param gainFocus True if the View has focus; false otherwise.
5006     * @param direction The direction focus has moved when requestFocus()
5007     *                  is called to give this view focus. Values are
5008     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5009     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5010     *                  It may not always apply, in which case use the default.
5011     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5012     *        system, of the previously focused view.  If applicable, this will be
5013     *        passed in as finer grained information about where the focus is coming
5014     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5015     */
5016    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5017            @Nullable Rect previouslyFocusedRect) {
5018        if (gainFocus) {
5019            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5020        } else {
5021            notifyViewAccessibilityStateChangedIfNeeded(
5022                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5023        }
5024
5025        InputMethodManager imm = InputMethodManager.peekInstance();
5026        if (!gainFocus) {
5027            if (isPressed()) {
5028                setPressed(false);
5029            }
5030            if (imm != null && mAttachInfo != null
5031                    && mAttachInfo.mHasWindowFocus) {
5032                imm.focusOut(this);
5033            }
5034            onFocusLost();
5035        } else if (imm != null && mAttachInfo != null
5036                && mAttachInfo.mHasWindowFocus) {
5037            imm.focusIn(this);
5038        }
5039
5040        invalidate(true);
5041        ListenerInfo li = mListenerInfo;
5042        if (li != null && li.mOnFocusChangeListener != null) {
5043            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5044        }
5045
5046        if (mAttachInfo != null) {
5047            mAttachInfo.mKeyDispatchState.reset(this);
5048        }
5049    }
5050
5051    /**
5052     * Sends an accessibility event of the given type. If accessibility is
5053     * not enabled this method has no effect. The default implementation calls
5054     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5055     * to populate information about the event source (this View), then calls
5056     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5057     * populate the text content of the event source including its descendants,
5058     * and last calls
5059     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5060     * on its parent to resuest sending of the event to interested parties.
5061     * <p>
5062     * If an {@link AccessibilityDelegate} has been specified via calling
5063     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5064     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5065     * responsible for handling this call.
5066     * </p>
5067     *
5068     * @param eventType The type of the event to send, as defined by several types from
5069     * {@link android.view.accessibility.AccessibilityEvent}, such as
5070     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5071     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5072     *
5073     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5074     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5075     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5076     * @see AccessibilityDelegate
5077     */
5078    public void sendAccessibilityEvent(int eventType) {
5079        if (mAccessibilityDelegate != null) {
5080            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5081        } else {
5082            sendAccessibilityEventInternal(eventType);
5083        }
5084    }
5085
5086    /**
5087     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5088     * {@link AccessibilityEvent} to make an announcement which is related to some
5089     * sort of a context change for which none of the events representing UI transitions
5090     * is a good fit. For example, announcing a new page in a book. If accessibility
5091     * is not enabled this method does nothing.
5092     *
5093     * @param text The announcement text.
5094     */
5095    public void announceForAccessibility(CharSequence text) {
5096        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5097            AccessibilityEvent event = AccessibilityEvent.obtain(
5098                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5099            onInitializeAccessibilityEvent(event);
5100            event.getText().add(text);
5101            event.setContentDescription(null);
5102            mParent.requestSendAccessibilityEvent(this, event);
5103        }
5104    }
5105
5106    /**
5107     * @see #sendAccessibilityEvent(int)
5108     *
5109     * Note: Called from the default {@link AccessibilityDelegate}.
5110     */
5111    void sendAccessibilityEventInternal(int eventType) {
5112        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5113            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5114        }
5115    }
5116
5117    /**
5118     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5119     * takes as an argument an empty {@link AccessibilityEvent} and does not
5120     * perform a check whether accessibility is enabled.
5121     * <p>
5122     * If an {@link AccessibilityDelegate} has been specified via calling
5123     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5124     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5125     * is responsible for handling this call.
5126     * </p>
5127     *
5128     * @param event The event to send.
5129     *
5130     * @see #sendAccessibilityEvent(int)
5131     */
5132    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5133        if (mAccessibilityDelegate != null) {
5134            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5135        } else {
5136            sendAccessibilityEventUncheckedInternal(event);
5137        }
5138    }
5139
5140    /**
5141     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5142     *
5143     * Note: Called from the default {@link AccessibilityDelegate}.
5144     */
5145    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5146        if (!isShown()) {
5147            return;
5148        }
5149        onInitializeAccessibilityEvent(event);
5150        // Only a subset of accessibility events populates text content.
5151        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5152            dispatchPopulateAccessibilityEvent(event);
5153        }
5154        // In the beginning we called #isShown(), so we know that getParent() is not null.
5155        getParent().requestSendAccessibilityEvent(this, event);
5156    }
5157
5158    /**
5159     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5160     * to its children for adding their text content to the event. Note that the
5161     * event text is populated in a separate dispatch path since we add to the
5162     * event not only the text of the source but also the text of all its descendants.
5163     * A typical implementation will call
5164     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5165     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5166     * on each child. Override this method if custom population of the event text
5167     * content is required.
5168     * <p>
5169     * If an {@link AccessibilityDelegate} has been specified via calling
5170     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5171     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5172     * is responsible for handling this call.
5173     * </p>
5174     * <p>
5175     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5176     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5177     * </p>
5178     *
5179     * @param event The event.
5180     *
5181     * @return True if the event population was completed.
5182     */
5183    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5184        if (mAccessibilityDelegate != null) {
5185            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5186        } else {
5187            return dispatchPopulateAccessibilityEventInternal(event);
5188        }
5189    }
5190
5191    /**
5192     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5193     *
5194     * Note: Called from the default {@link AccessibilityDelegate}.
5195     */
5196    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5197        onPopulateAccessibilityEvent(event);
5198        return false;
5199    }
5200
5201    /**
5202     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5203     * giving a chance to this View to populate the accessibility event with its
5204     * text content. While this method is free to modify event
5205     * attributes other than text content, doing so should normally be performed in
5206     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5207     * <p>
5208     * Example: Adding formatted date string to an accessibility event in addition
5209     *          to the text added by the super implementation:
5210     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5211     *     super.onPopulateAccessibilityEvent(event);
5212     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5213     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5214     *         mCurrentDate.getTimeInMillis(), flags);
5215     *     event.getText().add(selectedDateUtterance);
5216     * }</pre>
5217     * <p>
5218     * If an {@link AccessibilityDelegate} has been specified via calling
5219     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5220     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5221     * is responsible for handling this call.
5222     * </p>
5223     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5224     * information to the event, in case the default implementation has basic information to add.
5225     * </p>
5226     *
5227     * @param event The accessibility event which to populate.
5228     *
5229     * @see #sendAccessibilityEvent(int)
5230     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5231     */
5232    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5233        if (mAccessibilityDelegate != null) {
5234            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5235        } else {
5236            onPopulateAccessibilityEventInternal(event);
5237        }
5238    }
5239
5240    /**
5241     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5242     *
5243     * Note: Called from the default {@link AccessibilityDelegate}.
5244     */
5245    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5246    }
5247
5248    /**
5249     * Initializes an {@link AccessibilityEvent} with information about
5250     * this View which is the event source. In other words, the source of
5251     * an accessibility event is the view whose state change triggered firing
5252     * the event.
5253     * <p>
5254     * Example: Setting the password property of an event in addition
5255     *          to properties set by the super implementation:
5256     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5257     *     super.onInitializeAccessibilityEvent(event);
5258     *     event.setPassword(true);
5259     * }</pre>
5260     * <p>
5261     * If an {@link AccessibilityDelegate} has been specified via calling
5262     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5263     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5264     * is responsible for handling this call.
5265     * </p>
5266     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5267     * information to the event, in case the default implementation has basic information to add.
5268     * </p>
5269     * @param event The event to initialize.
5270     *
5271     * @see #sendAccessibilityEvent(int)
5272     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5273     */
5274    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5275        if (mAccessibilityDelegate != null) {
5276            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5277        } else {
5278            onInitializeAccessibilityEventInternal(event);
5279        }
5280    }
5281
5282    /**
5283     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5284     *
5285     * Note: Called from the default {@link AccessibilityDelegate}.
5286     */
5287    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5288        event.setSource(this);
5289        event.setClassName(View.class.getName());
5290        event.setPackageName(getContext().getPackageName());
5291        event.setEnabled(isEnabled());
5292        event.setContentDescription(mContentDescription);
5293
5294        switch (event.getEventType()) {
5295            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5296                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5297                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5298                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5299                event.setItemCount(focusablesTempList.size());
5300                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5301                if (mAttachInfo != null) {
5302                    focusablesTempList.clear();
5303                }
5304            } break;
5305            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5306                CharSequence text = getIterableTextForAccessibility();
5307                if (text != null && text.length() > 0) {
5308                    event.setFromIndex(getAccessibilitySelectionStart());
5309                    event.setToIndex(getAccessibilitySelectionEnd());
5310                    event.setItemCount(text.length());
5311                }
5312            } break;
5313        }
5314    }
5315
5316    /**
5317     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5318     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5319     * This method is responsible for obtaining an accessibility node info from a
5320     * pool of reusable instances and calling
5321     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5322     * initialize the former.
5323     * <p>
5324     * Note: The client is responsible for recycling the obtained instance by calling
5325     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5326     * </p>
5327     *
5328     * @return A populated {@link AccessibilityNodeInfo}.
5329     *
5330     * @see AccessibilityNodeInfo
5331     */
5332    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5333        if (mAccessibilityDelegate != null) {
5334            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5335        } else {
5336            return createAccessibilityNodeInfoInternal();
5337        }
5338    }
5339
5340    /**
5341     * @see #createAccessibilityNodeInfo()
5342     */
5343    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5344        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5345        if (provider != null) {
5346            return provider.createAccessibilityNodeInfo(View.NO_ID);
5347        } else {
5348            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5349            onInitializeAccessibilityNodeInfo(info);
5350            return info;
5351        }
5352    }
5353
5354    /**
5355     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5356     * The base implementation sets:
5357     * <ul>
5358     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5359     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5360     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5361     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5362     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5363     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5364     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5365     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5366     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5367     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5368     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5369     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5370     * </ul>
5371     * <p>
5372     * Subclasses should override this method, call the super implementation,
5373     * and set additional attributes.
5374     * </p>
5375     * <p>
5376     * If an {@link AccessibilityDelegate} has been specified via calling
5377     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5378     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5379     * is responsible for handling this call.
5380     * </p>
5381     *
5382     * @param info The instance to initialize.
5383     */
5384    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5385        if (mAccessibilityDelegate != null) {
5386            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5387        } else {
5388            onInitializeAccessibilityNodeInfoInternal(info);
5389        }
5390    }
5391
5392    /**
5393     * Gets the location of this view in screen coordintates.
5394     *
5395     * @param outRect The output location
5396     * @hide
5397     */
5398    public void getBoundsOnScreen(Rect outRect) {
5399        if (mAttachInfo == null) {
5400            return;
5401        }
5402
5403        RectF position = mAttachInfo.mTmpTransformRect;
5404        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5405
5406        if (!hasIdentityMatrix()) {
5407            getMatrix().mapRect(position);
5408        }
5409
5410        position.offset(mLeft, mTop);
5411
5412        ViewParent parent = mParent;
5413        while (parent instanceof View) {
5414            View parentView = (View) parent;
5415
5416            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5417
5418            if (!parentView.hasIdentityMatrix()) {
5419                parentView.getMatrix().mapRect(position);
5420            }
5421
5422            position.offset(parentView.mLeft, parentView.mTop);
5423
5424            parent = parentView.mParent;
5425        }
5426
5427        if (parent instanceof ViewRootImpl) {
5428            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5429            position.offset(0, -viewRootImpl.mCurScrollY);
5430        }
5431
5432        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5433
5434        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5435                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5436    }
5437
5438    /**
5439     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5440     *
5441     * Note: Called from the default {@link AccessibilityDelegate}.
5442     */
5443    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5444        Rect bounds = mAttachInfo.mTmpInvalRect;
5445
5446        getDrawingRect(bounds);
5447        info.setBoundsInParent(bounds);
5448
5449        getBoundsOnScreen(bounds);
5450        info.setBoundsInScreen(bounds);
5451
5452        ViewParent parent = getParentForAccessibility();
5453        if (parent instanceof View) {
5454            info.setParent((View) parent);
5455        }
5456
5457        if (mID != View.NO_ID) {
5458            View rootView = getRootView();
5459            if (rootView == null) {
5460                rootView = this;
5461            }
5462            View label = rootView.findLabelForView(this, mID);
5463            if (label != null) {
5464                info.setLabeledBy(label);
5465            }
5466
5467            if ((mAttachInfo.mAccessibilityFetchFlags
5468                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5469                    && Resources.resourceHasPackage(mID)) {
5470                try {
5471                    String viewId = getResources().getResourceName(mID);
5472                    info.setViewIdResourceName(viewId);
5473                } catch (Resources.NotFoundException nfe) {
5474                    /* ignore */
5475                }
5476            }
5477        }
5478
5479        if (mLabelForId != View.NO_ID) {
5480            View rootView = getRootView();
5481            if (rootView == null) {
5482                rootView = this;
5483            }
5484            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5485            if (labeled != null) {
5486                info.setLabelFor(labeled);
5487            }
5488        }
5489
5490        info.setVisibleToUser(isVisibleToUser());
5491
5492        info.setPackageName(mContext.getPackageName());
5493        info.setClassName(View.class.getName());
5494        info.setContentDescription(getContentDescription());
5495
5496        info.setEnabled(isEnabled());
5497        info.setClickable(isClickable());
5498        info.setFocusable(isFocusable());
5499        info.setFocused(isFocused());
5500        info.setAccessibilityFocused(isAccessibilityFocused());
5501        info.setSelected(isSelected());
5502        info.setLongClickable(isLongClickable());
5503        info.setLiveRegion(getAccessibilityLiveRegion());
5504
5505        // TODO: These make sense only if we are in an AdapterView but all
5506        // views can be selected. Maybe from accessibility perspective
5507        // we should report as selectable view in an AdapterView.
5508        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5509        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5510
5511        if (isFocusable()) {
5512            if (isFocused()) {
5513                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5514            } else {
5515                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5516            }
5517        }
5518
5519        if (!isAccessibilityFocused()) {
5520            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5521        } else {
5522            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5523        }
5524
5525        if (isClickable() && isEnabled()) {
5526            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5527        }
5528
5529        if (isLongClickable() && isEnabled()) {
5530            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5531        }
5532
5533        CharSequence text = getIterableTextForAccessibility();
5534        if (text != null && text.length() > 0) {
5535            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5536
5537            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5538            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5539            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5540            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5541                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5542                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5543        }
5544    }
5545
5546    private View findLabelForView(View view, int labeledId) {
5547        if (mMatchLabelForPredicate == null) {
5548            mMatchLabelForPredicate = new MatchLabelForPredicate();
5549        }
5550        mMatchLabelForPredicate.mLabeledId = labeledId;
5551        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5552    }
5553
5554    /**
5555     * Computes whether this view is visible to the user. Such a view is
5556     * attached, visible, all its predecessors are visible, it is not clipped
5557     * entirely by its predecessors, and has an alpha greater than zero.
5558     *
5559     * @return Whether the view is visible on the screen.
5560     *
5561     * @hide
5562     */
5563    protected boolean isVisibleToUser() {
5564        return isVisibleToUser(null);
5565    }
5566
5567    /**
5568     * Computes whether the given portion of this view is visible to the user.
5569     * Such a view is attached, visible, all its predecessors are visible,
5570     * has an alpha greater than zero, and the specified portion is not
5571     * clipped entirely by its predecessors.
5572     *
5573     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5574     *                    <code>null</code>, and the entire view will be tested in this case.
5575     *                    When <code>true</code> is returned by the function, the actual visible
5576     *                    region will be stored in this parameter; that is, if boundInView is fully
5577     *                    contained within the view, no modification will be made, otherwise regions
5578     *                    outside of the visible area of the view will be clipped.
5579     *
5580     * @return Whether the specified portion of the view is visible on the screen.
5581     *
5582     * @hide
5583     */
5584    protected boolean isVisibleToUser(Rect boundInView) {
5585        if (mAttachInfo != null) {
5586            // Attached to invisible window means this view is not visible.
5587            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5588                return false;
5589            }
5590            // An invisible predecessor or one with alpha zero means
5591            // that this view is not visible to the user.
5592            Object current = this;
5593            while (current instanceof View) {
5594                View view = (View) current;
5595                // We have attach info so this view is attached and there is no
5596                // need to check whether we reach to ViewRootImpl on the way up.
5597                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5598                        view.getVisibility() != VISIBLE) {
5599                    return false;
5600                }
5601                current = view.mParent;
5602            }
5603            // Check if the view is entirely covered by its predecessors.
5604            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5605            Point offset = mAttachInfo.mPoint;
5606            if (!getGlobalVisibleRect(visibleRect, offset)) {
5607                return false;
5608            }
5609            // Check if the visible portion intersects the rectangle of interest.
5610            if (boundInView != null) {
5611                visibleRect.offset(-offset.x, -offset.y);
5612                return boundInView.intersect(visibleRect);
5613            }
5614            return true;
5615        }
5616        return false;
5617    }
5618
5619    /**
5620     * Returns the delegate for implementing accessibility support via
5621     * composition. For more details see {@link AccessibilityDelegate}.
5622     *
5623     * @return The delegate, or null if none set.
5624     *
5625     * @hide
5626     */
5627    public AccessibilityDelegate getAccessibilityDelegate() {
5628        return mAccessibilityDelegate;
5629    }
5630
5631    /**
5632     * Sets a delegate for implementing accessibility support via composition as
5633     * opposed to inheritance. The delegate's primary use is for implementing
5634     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5635     *
5636     * @param delegate The delegate instance.
5637     *
5638     * @see AccessibilityDelegate
5639     */
5640    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5641        mAccessibilityDelegate = delegate;
5642    }
5643
5644    /**
5645     * Gets the provider for managing a virtual view hierarchy rooted at this View
5646     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5647     * that explore the window content.
5648     * <p>
5649     * If this method returns an instance, this instance is responsible for managing
5650     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5651     * View including the one representing the View itself. Similarly the returned
5652     * instance is responsible for performing accessibility actions on any virtual
5653     * view or the root view itself.
5654     * </p>
5655     * <p>
5656     * If an {@link AccessibilityDelegate} has been specified via calling
5657     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5658     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5659     * is responsible for handling this call.
5660     * </p>
5661     *
5662     * @return The provider.
5663     *
5664     * @see AccessibilityNodeProvider
5665     */
5666    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5667        if (mAccessibilityDelegate != null) {
5668            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5669        } else {
5670            return null;
5671        }
5672    }
5673
5674    /**
5675     * Gets the unique identifier of this view on the screen for accessibility purposes.
5676     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5677     *
5678     * @return The view accessibility id.
5679     *
5680     * @hide
5681     */
5682    public int getAccessibilityViewId() {
5683        if (mAccessibilityViewId == NO_ID) {
5684            mAccessibilityViewId = sNextAccessibilityViewId++;
5685        }
5686        return mAccessibilityViewId;
5687    }
5688
5689    /**
5690     * Gets the unique identifier of the window in which this View reseides.
5691     *
5692     * @return The window accessibility id.
5693     *
5694     * @hide
5695     */
5696    public int getAccessibilityWindowId() {
5697        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5698                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5699    }
5700
5701    /**
5702     * Gets the {@link View} description. It briefly describes the view and is
5703     * primarily used for accessibility support. Set this property to enable
5704     * better accessibility support for your application. This is especially
5705     * true for views that do not have textual representation (For example,
5706     * ImageButton).
5707     *
5708     * @return The content description.
5709     *
5710     * @attr ref android.R.styleable#View_contentDescription
5711     */
5712    @ViewDebug.ExportedProperty(category = "accessibility")
5713    public CharSequence getContentDescription() {
5714        return mContentDescription;
5715    }
5716
5717    /**
5718     * Sets the {@link View} description. It briefly describes the view and is
5719     * primarily used for accessibility support. Set this property to enable
5720     * better accessibility support for your application. This is especially
5721     * true for views that do not have textual representation (For example,
5722     * ImageButton).
5723     *
5724     * @param contentDescription The content description.
5725     *
5726     * @attr ref android.R.styleable#View_contentDescription
5727     */
5728    @RemotableViewMethod
5729    public void setContentDescription(CharSequence contentDescription) {
5730        if (mContentDescription == null) {
5731            if (contentDescription == null) {
5732                return;
5733            }
5734        } else if (mContentDescription.equals(contentDescription)) {
5735            return;
5736        }
5737        mContentDescription = contentDescription;
5738        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5739        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5740            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5741            notifySubtreeAccessibilityStateChangedIfNeeded();
5742        } else {
5743            notifyViewAccessibilityStateChangedIfNeeded(
5744                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5745        }
5746    }
5747
5748    /**
5749     * Gets the id of a view for which this view serves as a label for
5750     * accessibility purposes.
5751     *
5752     * @return The labeled view id.
5753     */
5754    @ViewDebug.ExportedProperty(category = "accessibility")
5755    public int getLabelFor() {
5756        return mLabelForId;
5757    }
5758
5759    /**
5760     * Sets the id of a view for which this view serves as a label for
5761     * accessibility purposes.
5762     *
5763     * @param id The labeled view id.
5764     */
5765    @RemotableViewMethod
5766    public void setLabelFor(int id) {
5767        mLabelForId = id;
5768        if (mLabelForId != View.NO_ID
5769                && mID == View.NO_ID) {
5770            mID = generateViewId();
5771        }
5772    }
5773
5774    /**
5775     * Invoked whenever this view loses focus, either by losing window focus or by losing
5776     * focus within its window. This method can be used to clear any state tied to the
5777     * focus. For instance, if a button is held pressed with the trackball and the window
5778     * loses focus, this method can be used to cancel the press.
5779     *
5780     * Subclasses of View overriding this method should always call super.onFocusLost().
5781     *
5782     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5783     * @see #onWindowFocusChanged(boolean)
5784     *
5785     * @hide pending API council approval
5786     */
5787    protected void onFocusLost() {
5788        resetPressedState();
5789    }
5790
5791    private void resetPressedState() {
5792        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5793            return;
5794        }
5795
5796        if (isPressed()) {
5797            setPressed(false);
5798
5799            if (!mHasPerformedLongPress) {
5800                removeLongPressCallback();
5801            }
5802        }
5803    }
5804
5805    /**
5806     * Returns true if this view has focus
5807     *
5808     * @return True if this view has focus, false otherwise.
5809     */
5810    @ViewDebug.ExportedProperty(category = "focus")
5811    public boolean isFocused() {
5812        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5813    }
5814
5815    /**
5816     * Find the view in the hierarchy rooted at this view that currently has
5817     * focus.
5818     *
5819     * @return The view that currently has focus, or null if no focused view can
5820     *         be found.
5821     */
5822    public View findFocus() {
5823        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5824    }
5825
5826    /**
5827     * Indicates whether this view is one of the set of scrollable containers in
5828     * its window.
5829     *
5830     * @return whether this view is one of the set of scrollable containers in
5831     * its window
5832     *
5833     * @attr ref android.R.styleable#View_isScrollContainer
5834     */
5835    public boolean isScrollContainer() {
5836        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5837    }
5838
5839    /**
5840     * Change whether this view is one of the set of scrollable containers in
5841     * its window.  This will be used to determine whether the window can
5842     * resize or must pan when a soft input area is open -- scrollable
5843     * containers allow the window to use resize mode since the container
5844     * will appropriately shrink.
5845     *
5846     * @attr ref android.R.styleable#View_isScrollContainer
5847     */
5848    public void setScrollContainer(boolean isScrollContainer) {
5849        if (isScrollContainer) {
5850            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5851                mAttachInfo.mScrollContainers.add(this);
5852                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5853            }
5854            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5855        } else {
5856            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5857                mAttachInfo.mScrollContainers.remove(this);
5858            }
5859            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5860        }
5861    }
5862
5863    /**
5864     * Returns the quality of the drawing cache.
5865     *
5866     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5867     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5868     *
5869     * @see #setDrawingCacheQuality(int)
5870     * @see #setDrawingCacheEnabled(boolean)
5871     * @see #isDrawingCacheEnabled()
5872     *
5873     * @attr ref android.R.styleable#View_drawingCacheQuality
5874     */
5875    @DrawingCacheQuality
5876    public int getDrawingCacheQuality() {
5877        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5878    }
5879
5880    /**
5881     * Set the drawing cache quality of this view. This value is used only when the
5882     * drawing cache is enabled
5883     *
5884     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5885     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5886     *
5887     * @see #getDrawingCacheQuality()
5888     * @see #setDrawingCacheEnabled(boolean)
5889     * @see #isDrawingCacheEnabled()
5890     *
5891     * @attr ref android.R.styleable#View_drawingCacheQuality
5892     */
5893    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5894        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5895    }
5896
5897    /**
5898     * Returns whether the screen should remain on, corresponding to the current
5899     * value of {@link #KEEP_SCREEN_ON}.
5900     *
5901     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5902     *
5903     * @see #setKeepScreenOn(boolean)
5904     *
5905     * @attr ref android.R.styleable#View_keepScreenOn
5906     */
5907    public boolean getKeepScreenOn() {
5908        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5909    }
5910
5911    /**
5912     * Controls whether the screen should remain on, modifying the
5913     * value of {@link #KEEP_SCREEN_ON}.
5914     *
5915     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5916     *
5917     * @see #getKeepScreenOn()
5918     *
5919     * @attr ref android.R.styleable#View_keepScreenOn
5920     */
5921    public void setKeepScreenOn(boolean keepScreenOn) {
5922        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5923    }
5924
5925    /**
5926     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5927     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5928     *
5929     * @attr ref android.R.styleable#View_nextFocusLeft
5930     */
5931    public int getNextFocusLeftId() {
5932        return mNextFocusLeftId;
5933    }
5934
5935    /**
5936     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5937     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5938     * decide automatically.
5939     *
5940     * @attr ref android.R.styleable#View_nextFocusLeft
5941     */
5942    public void setNextFocusLeftId(int nextFocusLeftId) {
5943        mNextFocusLeftId = nextFocusLeftId;
5944    }
5945
5946    /**
5947     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5948     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5949     *
5950     * @attr ref android.R.styleable#View_nextFocusRight
5951     */
5952    public int getNextFocusRightId() {
5953        return mNextFocusRightId;
5954    }
5955
5956    /**
5957     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5958     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5959     * decide automatically.
5960     *
5961     * @attr ref android.R.styleable#View_nextFocusRight
5962     */
5963    public void setNextFocusRightId(int nextFocusRightId) {
5964        mNextFocusRightId = nextFocusRightId;
5965    }
5966
5967    /**
5968     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5969     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5970     *
5971     * @attr ref android.R.styleable#View_nextFocusUp
5972     */
5973    public int getNextFocusUpId() {
5974        return mNextFocusUpId;
5975    }
5976
5977    /**
5978     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5979     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5980     * decide automatically.
5981     *
5982     * @attr ref android.R.styleable#View_nextFocusUp
5983     */
5984    public void setNextFocusUpId(int nextFocusUpId) {
5985        mNextFocusUpId = nextFocusUpId;
5986    }
5987
5988    /**
5989     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5990     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5991     *
5992     * @attr ref android.R.styleable#View_nextFocusDown
5993     */
5994    public int getNextFocusDownId() {
5995        return mNextFocusDownId;
5996    }
5997
5998    /**
5999     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6000     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6001     * decide automatically.
6002     *
6003     * @attr ref android.R.styleable#View_nextFocusDown
6004     */
6005    public void setNextFocusDownId(int nextFocusDownId) {
6006        mNextFocusDownId = nextFocusDownId;
6007    }
6008
6009    /**
6010     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6011     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6012     *
6013     * @attr ref android.R.styleable#View_nextFocusForward
6014     */
6015    public int getNextFocusForwardId() {
6016        return mNextFocusForwardId;
6017    }
6018
6019    /**
6020     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6021     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6022     * decide automatically.
6023     *
6024     * @attr ref android.R.styleable#View_nextFocusForward
6025     */
6026    public void setNextFocusForwardId(int nextFocusForwardId) {
6027        mNextFocusForwardId = nextFocusForwardId;
6028    }
6029
6030    /**
6031     * Returns the visibility of this view and all of its ancestors
6032     *
6033     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6034     */
6035    public boolean isShown() {
6036        View current = this;
6037        //noinspection ConstantConditions
6038        do {
6039            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6040                return false;
6041            }
6042            ViewParent parent = current.mParent;
6043            if (parent == null) {
6044                return false; // We are not attached to the view root
6045            }
6046            if (!(parent instanceof View)) {
6047                return true;
6048            }
6049            current = (View) parent;
6050        } while (current != null);
6051
6052        return false;
6053    }
6054
6055    /**
6056     * Called by the view hierarchy when the content insets for a window have
6057     * changed, to allow it to adjust its content to fit within those windows.
6058     * The content insets tell you the space that the status bar, input method,
6059     * and other system windows infringe on the application's window.
6060     *
6061     * <p>You do not normally need to deal with this function, since the default
6062     * window decoration given to applications takes care of applying it to the
6063     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6064     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6065     * and your content can be placed under those system elements.  You can then
6066     * use this method within your view hierarchy if you have parts of your UI
6067     * which you would like to ensure are not being covered.
6068     *
6069     * <p>The default implementation of this method simply applies the content
6070     * insets to the view's padding, consuming that content (modifying the
6071     * insets to be 0), and returning true.  This behavior is off by default, but can
6072     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6073     *
6074     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6075     * insets object is propagated down the hierarchy, so any changes made to it will
6076     * be seen by all following views (including potentially ones above in
6077     * the hierarchy since this is a depth-first traversal).  The first view
6078     * that returns true will abort the entire traversal.
6079     *
6080     * <p>The default implementation works well for a situation where it is
6081     * used with a container that covers the entire window, allowing it to
6082     * apply the appropriate insets to its content on all edges.  If you need
6083     * a more complicated layout (such as two different views fitting system
6084     * windows, one on the top of the window, and one on the bottom),
6085     * you can override the method and handle the insets however you would like.
6086     * Note that the insets provided by the framework are always relative to the
6087     * far edges of the window, not accounting for the location of the called view
6088     * within that window.  (In fact when this method is called you do not yet know
6089     * where the layout will place the view, as it is done before layout happens.)
6090     *
6091     * <p>Note: unlike many View methods, there is no dispatch phase to this
6092     * call.  If you are overriding it in a ViewGroup and want to allow the
6093     * call to continue to your children, you must be sure to call the super
6094     * implementation.
6095     *
6096     * <p>Here is a sample layout that makes use of fitting system windows
6097     * to have controls for a video view placed inside of the window decorations
6098     * that it hides and shows.  This can be used with code like the second
6099     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6100     *
6101     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6102     *
6103     * @param insets Current content insets of the window.  Prior to
6104     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6105     * the insets or else you and Android will be unhappy.
6106     *
6107     * @return {@code true} if this view applied the insets and it should not
6108     * continue propagating further down the hierarchy, {@code false} otherwise.
6109     * @see #getFitsSystemWindows()
6110     * @see #setFitsSystemWindows(boolean)
6111     * @see #setSystemUiVisibility(int)
6112     *
6113     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6114     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6115     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6116     * to implement handling their own insets.
6117     */
6118    protected boolean fitSystemWindows(Rect insets) {
6119        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6120            if (insets == null) {
6121                // Null insets by definition have already been consumed.
6122                // This call cannot apply insets since there are none to apply,
6123                // so return false.
6124                return false;
6125            }
6126            // If we're not in the process of dispatching the newer apply insets call,
6127            // that means we're not in the compatibility path. Dispatch into the newer
6128            // apply insets path and take things from there.
6129            try {
6130                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6131                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6132            } finally {
6133                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6134            }
6135        } else {
6136            // We're being called from the newer apply insets path.
6137            // Perform the standard fallback behavior.
6138            return fitSystemWindowsInt(insets);
6139        }
6140    }
6141
6142    private boolean fitSystemWindowsInt(Rect insets) {
6143        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6144            mUserPaddingStart = UNDEFINED_PADDING;
6145            mUserPaddingEnd = UNDEFINED_PADDING;
6146            Rect localInsets = sThreadLocal.get();
6147            if (localInsets == null) {
6148                localInsets = new Rect();
6149                sThreadLocal.set(localInsets);
6150            }
6151            boolean res = computeFitSystemWindows(insets, localInsets);
6152            mUserPaddingLeftInitial = localInsets.left;
6153            mUserPaddingRightInitial = localInsets.right;
6154            internalSetPadding(localInsets.left, localInsets.top,
6155                    localInsets.right, localInsets.bottom);
6156            return res;
6157        }
6158        return false;
6159    }
6160
6161    /**
6162     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6163     *
6164     * <p>This method should be overridden by views that wish to apply a policy different from or
6165     * in addition to the default behavior. Clients that wish to force a view subtree
6166     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6167     *
6168     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6169     * it will be called during dispatch instead of this method. The listener may optionally
6170     * call this method from its own implementation if it wishes to apply the view's default
6171     * insets policy in addition to its own.</p>
6172     *
6173     * <p>Implementations of this method should either return the insets parameter unchanged
6174     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6175     * that this view applied itself. This allows new inset types added in future platform
6176     * versions to pass through existing implementations unchanged without being erroneously
6177     * consumed.</p>
6178     *
6179     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6180     * property is set then the view will consume the system window insets and apply them
6181     * as padding for the view.</p>
6182     *
6183     * @param insets Insets to apply
6184     * @return The supplied insets with any applied insets consumed
6185     */
6186    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6187        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6188            // We weren't called from within a direct call to fitSystemWindows,
6189            // call into it as a fallback in case we're in a class that overrides it
6190            // and has logic to perform.
6191            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6192                return insets.consumeSystemWindowInsets();
6193            }
6194        } else {
6195            // We were called from within a direct call to fitSystemWindows.
6196            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6197                return insets.consumeSystemWindowInsets();
6198            }
6199        }
6200        return insets;
6201    }
6202
6203    /**
6204     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6205     * window insets to this view. The listener's
6206     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6207     * method will be called instead of the view's
6208     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6209     *
6210     * @param listener Listener to set
6211     *
6212     * @see #onApplyWindowInsets(WindowInsets)
6213     */
6214    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6215        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6216    }
6217
6218    /**
6219     * Request to apply the given window insets to this view or another view in its subtree.
6220     *
6221     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6222     * obscured by window decorations or overlays. This can include the status and navigation bars,
6223     * action bars, input methods and more. New inset categories may be added in the future.
6224     * The method returns the insets provided minus any that were applied by this view or its
6225     * children.</p>
6226     *
6227     * <p>Clients wishing to provide custom behavior should override the
6228     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6229     * {@link OnApplyWindowInsetsListener} via the
6230     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6231     * method.</p>
6232     *
6233     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6234     * </p>
6235     *
6236     * @param insets Insets to apply
6237     * @return The provided insets minus the insets that were consumed
6238     */
6239    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6240        try {
6241            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6242            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6243                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6244            } else {
6245                return onApplyWindowInsets(insets);
6246            }
6247        } finally {
6248            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6249        }
6250    }
6251
6252    /**
6253     * @hide Compute the insets that should be consumed by this view and the ones
6254     * that should propagate to those under it.
6255     */
6256    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6257        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6258                || mAttachInfo == null
6259                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6260                        && !mAttachInfo.mOverscanRequested)) {
6261            outLocalInsets.set(inoutInsets);
6262            inoutInsets.set(0, 0, 0, 0);
6263            return true;
6264        } else {
6265            // The application wants to take care of fitting system window for
6266            // the content...  however we still need to take care of any overscan here.
6267            final Rect overscan = mAttachInfo.mOverscanInsets;
6268            outLocalInsets.set(overscan);
6269            inoutInsets.left -= overscan.left;
6270            inoutInsets.top -= overscan.top;
6271            inoutInsets.right -= overscan.right;
6272            inoutInsets.bottom -= overscan.bottom;
6273            return false;
6274        }
6275    }
6276
6277    /**
6278     * Sets whether or not this view should account for system screen decorations
6279     * such as the status bar and inset its content; that is, controlling whether
6280     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6281     * executed.  See that method for more details.
6282     *
6283     * <p>Note that if you are providing your own implementation of
6284     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6285     * flag to true -- your implementation will be overriding the default
6286     * implementation that checks this flag.
6287     *
6288     * @param fitSystemWindows If true, then the default implementation of
6289     * {@link #fitSystemWindows(Rect)} will be executed.
6290     *
6291     * @attr ref android.R.styleable#View_fitsSystemWindows
6292     * @see #getFitsSystemWindows()
6293     * @see #fitSystemWindows(Rect)
6294     * @see #setSystemUiVisibility(int)
6295     */
6296    public void setFitsSystemWindows(boolean fitSystemWindows) {
6297        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6298    }
6299
6300    /**
6301     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6302     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6303     * will be executed.
6304     *
6305     * @return {@code true} if the default implementation of
6306     * {@link #fitSystemWindows(Rect)} will be executed.
6307     *
6308     * @attr ref android.R.styleable#View_fitsSystemWindows
6309     * @see #setFitsSystemWindows(boolean)
6310     * @see #fitSystemWindows(Rect)
6311     * @see #setSystemUiVisibility(int)
6312     */
6313    public boolean getFitsSystemWindows() {
6314        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6315    }
6316
6317    /** @hide */
6318    public boolean fitsSystemWindows() {
6319        return getFitsSystemWindows();
6320    }
6321
6322    /**
6323     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6324     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6325     */
6326    public void requestFitSystemWindows() {
6327        if (mParent != null) {
6328            mParent.requestFitSystemWindows();
6329        }
6330    }
6331
6332    /**
6333     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6334     */
6335    public void requestApplyInsets() {
6336        requestFitSystemWindows();
6337    }
6338
6339    /**
6340     * For use by PhoneWindow to make its own system window fitting optional.
6341     * @hide
6342     */
6343    public void makeOptionalFitsSystemWindows() {
6344        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6345    }
6346
6347    /**
6348     * Returns the visibility status for this view.
6349     *
6350     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6351     * @attr ref android.R.styleable#View_visibility
6352     */
6353    @ViewDebug.ExportedProperty(mapping = {
6354        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6355        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6356        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6357    })
6358    @Visibility
6359    public int getVisibility() {
6360        return mViewFlags & VISIBILITY_MASK;
6361    }
6362
6363    /**
6364     * Set the enabled state of this view.
6365     *
6366     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6367     * @attr ref android.R.styleable#View_visibility
6368     */
6369    @RemotableViewMethod
6370    public void setVisibility(@Visibility int visibility) {
6371        setFlags(visibility, VISIBILITY_MASK);
6372        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6373    }
6374
6375    /**
6376     * Returns the enabled status for this view. The interpretation of the
6377     * enabled state varies by subclass.
6378     *
6379     * @return True if this view is enabled, false otherwise.
6380     */
6381    @ViewDebug.ExportedProperty
6382    public boolean isEnabled() {
6383        return (mViewFlags & ENABLED_MASK) == ENABLED;
6384    }
6385
6386    /**
6387     * Set the enabled state of this view. The interpretation of the enabled
6388     * state varies by subclass.
6389     *
6390     * @param enabled True if this view is enabled, false otherwise.
6391     */
6392    @RemotableViewMethod
6393    public void setEnabled(boolean enabled) {
6394        if (enabled == isEnabled()) return;
6395
6396        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6397
6398        /*
6399         * The View most likely has to change its appearance, so refresh
6400         * the drawable state.
6401         */
6402        refreshDrawableState();
6403
6404        // Invalidate too, since the default behavior for views is to be
6405        // be drawn at 50% alpha rather than to change the drawable.
6406        invalidate(true);
6407
6408        if (!enabled) {
6409            cancelPendingInputEvents();
6410        }
6411    }
6412
6413    /**
6414     * Set whether this view can receive the focus.
6415     *
6416     * Setting this to false will also ensure that this view is not focusable
6417     * in touch mode.
6418     *
6419     * @param focusable If true, this view can receive the focus.
6420     *
6421     * @see #setFocusableInTouchMode(boolean)
6422     * @attr ref android.R.styleable#View_focusable
6423     */
6424    public void setFocusable(boolean focusable) {
6425        if (!focusable) {
6426            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6427        }
6428        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6429    }
6430
6431    /**
6432     * Set whether this view can receive focus while in touch mode.
6433     *
6434     * Setting this to true will also ensure that this view is focusable.
6435     *
6436     * @param focusableInTouchMode If true, this view can receive the focus while
6437     *   in touch mode.
6438     *
6439     * @see #setFocusable(boolean)
6440     * @attr ref android.R.styleable#View_focusableInTouchMode
6441     */
6442    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6443        // Focusable in touch mode should always be set before the focusable flag
6444        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6445        // which, in touch mode, will not successfully request focus on this view
6446        // because the focusable in touch mode flag is not set
6447        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6448        if (focusableInTouchMode) {
6449            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6450        }
6451    }
6452
6453    /**
6454     * Set whether this view should have sound effects enabled for events such as
6455     * clicking and touching.
6456     *
6457     * <p>You may wish to disable sound effects for a view if you already play sounds,
6458     * for instance, a dial key that plays dtmf tones.
6459     *
6460     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6461     * @see #isSoundEffectsEnabled()
6462     * @see #playSoundEffect(int)
6463     * @attr ref android.R.styleable#View_soundEffectsEnabled
6464     */
6465    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6466        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6467    }
6468
6469    /**
6470     * @return whether this view should have sound effects enabled for events such as
6471     *     clicking and touching.
6472     *
6473     * @see #setSoundEffectsEnabled(boolean)
6474     * @see #playSoundEffect(int)
6475     * @attr ref android.R.styleable#View_soundEffectsEnabled
6476     */
6477    @ViewDebug.ExportedProperty
6478    public boolean isSoundEffectsEnabled() {
6479        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6480    }
6481
6482    /**
6483     * Set whether this view should have haptic feedback for events such as
6484     * long presses.
6485     *
6486     * <p>You may wish to disable haptic feedback if your view already controls
6487     * its own haptic feedback.
6488     *
6489     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6490     * @see #isHapticFeedbackEnabled()
6491     * @see #performHapticFeedback(int)
6492     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6493     */
6494    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6495        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6496    }
6497
6498    /**
6499     * @return whether this view should have haptic feedback enabled for events
6500     * long presses.
6501     *
6502     * @see #setHapticFeedbackEnabled(boolean)
6503     * @see #performHapticFeedback(int)
6504     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6505     */
6506    @ViewDebug.ExportedProperty
6507    public boolean isHapticFeedbackEnabled() {
6508        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6509    }
6510
6511    /**
6512     * Returns the layout direction for this view.
6513     *
6514     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6515     *   {@link #LAYOUT_DIRECTION_RTL},
6516     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6517     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6518     *
6519     * @attr ref android.R.styleable#View_layoutDirection
6520     *
6521     * @hide
6522     */
6523    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6524        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6525        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6526        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6527        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6528    })
6529    @LayoutDir
6530    public int getRawLayoutDirection() {
6531        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6532    }
6533
6534    /**
6535     * Set the layout direction for this view. This will propagate a reset of layout direction
6536     * resolution to the view's children and resolve layout direction for this view.
6537     *
6538     * @param layoutDirection the layout direction to set. Should be one of:
6539     *
6540     * {@link #LAYOUT_DIRECTION_LTR},
6541     * {@link #LAYOUT_DIRECTION_RTL},
6542     * {@link #LAYOUT_DIRECTION_INHERIT},
6543     * {@link #LAYOUT_DIRECTION_LOCALE}.
6544     *
6545     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6546     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6547     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6548     *
6549     * @attr ref android.R.styleable#View_layoutDirection
6550     */
6551    @RemotableViewMethod
6552    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6553        if (getRawLayoutDirection() != layoutDirection) {
6554            // Reset the current layout direction and the resolved one
6555            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6556            resetRtlProperties();
6557            // Set the new layout direction (filtered)
6558            mPrivateFlags2 |=
6559                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6560            // We need to resolve all RTL properties as they all depend on layout direction
6561            resolveRtlPropertiesIfNeeded();
6562            requestLayout();
6563            invalidate(true);
6564        }
6565    }
6566
6567    /**
6568     * Returns the resolved layout direction for this view.
6569     *
6570     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6571     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6572     *
6573     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6574     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6575     *
6576     * @attr ref android.R.styleable#View_layoutDirection
6577     */
6578    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6579        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6580        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6581    })
6582    @ResolvedLayoutDir
6583    public int getLayoutDirection() {
6584        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6585        if (targetSdkVersion < JELLY_BEAN_MR1) {
6586            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6587            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6588        }
6589        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6590                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6591    }
6592
6593    /**
6594     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6595     * layout attribute and/or the inherited value from the parent
6596     *
6597     * @return true if the layout is right-to-left.
6598     *
6599     * @hide
6600     */
6601    @ViewDebug.ExportedProperty(category = "layout")
6602    public boolean isLayoutRtl() {
6603        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6604    }
6605
6606    /**
6607     * Indicates whether the view is currently tracking transient state that the
6608     * app should not need to concern itself with saving and restoring, but that
6609     * the framework should take special note to preserve when possible.
6610     *
6611     * <p>A view with transient state cannot be trivially rebound from an external
6612     * data source, such as an adapter binding item views in a list. This may be
6613     * because the view is performing an animation, tracking user selection
6614     * of content, or similar.</p>
6615     *
6616     * @return true if the view has transient state
6617     */
6618    @ViewDebug.ExportedProperty(category = "layout")
6619    public boolean hasTransientState() {
6620        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6621    }
6622
6623    /**
6624     * Set whether this view is currently tracking transient state that the
6625     * framework should attempt to preserve when possible. This flag is reference counted,
6626     * so every call to setHasTransientState(true) should be paired with a later call
6627     * to setHasTransientState(false).
6628     *
6629     * <p>A view with transient state cannot be trivially rebound from an external
6630     * data source, such as an adapter binding item views in a list. This may be
6631     * because the view is performing an animation, tracking user selection
6632     * of content, or similar.</p>
6633     *
6634     * @param hasTransientState true if this view has transient state
6635     */
6636    public void setHasTransientState(boolean hasTransientState) {
6637        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6638                mTransientStateCount - 1;
6639        if (mTransientStateCount < 0) {
6640            mTransientStateCount = 0;
6641            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6642                    "unmatched pair of setHasTransientState calls");
6643        } else if ((hasTransientState && mTransientStateCount == 1) ||
6644                (!hasTransientState && mTransientStateCount == 0)) {
6645            // update flag if we've just incremented up from 0 or decremented down to 0
6646            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6647                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6648            if (mParent != null) {
6649                try {
6650                    mParent.childHasTransientStateChanged(this, hasTransientState);
6651                } catch (AbstractMethodError e) {
6652                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6653                            " does not fully implement ViewParent", e);
6654                }
6655            }
6656        }
6657    }
6658
6659    /**
6660     * Returns true if this view is currently attached to a window.
6661     */
6662    public boolean isAttachedToWindow() {
6663        return mAttachInfo != null;
6664    }
6665
6666    /**
6667     * Returns true if this view has been through at least one layout since it
6668     * was last attached to or detached from a window.
6669     */
6670    public boolean isLaidOut() {
6671        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6672    }
6673
6674    /**
6675     * If this view doesn't do any drawing on its own, set this flag to
6676     * allow further optimizations. By default, this flag is not set on
6677     * View, but could be set on some View subclasses such as ViewGroup.
6678     *
6679     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6680     * you should clear this flag.
6681     *
6682     * @param willNotDraw whether or not this View draw on its own
6683     */
6684    public void setWillNotDraw(boolean willNotDraw) {
6685        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6686    }
6687
6688    /**
6689     * Returns whether or not this View draws on its own.
6690     *
6691     * @return true if this view has nothing to draw, false otherwise
6692     */
6693    @ViewDebug.ExportedProperty(category = "drawing")
6694    public boolean willNotDraw() {
6695        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6696    }
6697
6698    /**
6699     * When a View's drawing cache is enabled, drawing is redirected to an
6700     * offscreen bitmap. Some views, like an ImageView, must be able to
6701     * bypass this mechanism if they already draw a single bitmap, to avoid
6702     * unnecessary usage of the memory.
6703     *
6704     * @param willNotCacheDrawing true if this view does not cache its
6705     *        drawing, false otherwise
6706     */
6707    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6708        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6709    }
6710
6711    /**
6712     * Returns whether or not this View can cache its drawing or not.
6713     *
6714     * @return true if this view does not cache its drawing, false otherwise
6715     */
6716    @ViewDebug.ExportedProperty(category = "drawing")
6717    public boolean willNotCacheDrawing() {
6718        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6719    }
6720
6721    /**
6722     * Indicates whether this view reacts to click events or not.
6723     *
6724     * @return true if the view is clickable, false otherwise
6725     *
6726     * @see #setClickable(boolean)
6727     * @attr ref android.R.styleable#View_clickable
6728     */
6729    @ViewDebug.ExportedProperty
6730    public boolean isClickable() {
6731        return (mViewFlags & CLICKABLE) == CLICKABLE;
6732    }
6733
6734    /**
6735     * Enables or disables click events for this view. When a view
6736     * is clickable it will change its state to "pressed" on every click.
6737     * Subclasses should set the view clickable to visually react to
6738     * user's clicks.
6739     *
6740     * @param clickable true to make the view clickable, false otherwise
6741     *
6742     * @see #isClickable()
6743     * @attr ref android.R.styleable#View_clickable
6744     */
6745    public void setClickable(boolean clickable) {
6746        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6747    }
6748
6749    /**
6750     * Indicates whether this view reacts to long click events or not.
6751     *
6752     * @return true if the view is long clickable, false otherwise
6753     *
6754     * @see #setLongClickable(boolean)
6755     * @attr ref android.R.styleable#View_longClickable
6756     */
6757    public boolean isLongClickable() {
6758        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6759    }
6760
6761    /**
6762     * Enables or disables long click events for this view. When a view is long
6763     * clickable it reacts to the user holding down the button for a longer
6764     * duration than a tap. This event can either launch the listener or a
6765     * context menu.
6766     *
6767     * @param longClickable true to make the view long clickable, false otherwise
6768     * @see #isLongClickable()
6769     * @attr ref android.R.styleable#View_longClickable
6770     */
6771    public void setLongClickable(boolean longClickable) {
6772        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6773    }
6774
6775    /**
6776     * Sets the pressed state for this view and provides a touch coordinate for
6777     * animation hinting.
6778     *
6779     * @param pressed Pass true to set the View's internal state to "pressed",
6780     *            or false to reverts the View's internal state from a
6781     *            previously set "pressed" state.
6782     * @param x The x coordinate of the touch that caused the press
6783     * @param y The y coordinate of the touch that caused the press
6784     */
6785    private void setPressed(boolean pressed, float x, float y) {
6786        if (pressed) {
6787            drawableHotspotChanged(x, y);
6788        }
6789
6790        setPressed(pressed);
6791    }
6792
6793    /**
6794     * Sets the pressed state for this view.
6795     *
6796     * @see #isClickable()
6797     * @see #setClickable(boolean)
6798     *
6799     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6800     *        the View's internal state from a previously set "pressed" state.
6801     */
6802    public void setPressed(boolean pressed) {
6803        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6804
6805        if (pressed) {
6806            mPrivateFlags |= PFLAG_PRESSED;
6807        } else {
6808            mPrivateFlags &= ~PFLAG_PRESSED;
6809        }
6810
6811        if (needsRefresh) {
6812            refreshDrawableState();
6813        }
6814        dispatchSetPressed(pressed);
6815    }
6816
6817    /**
6818     * Dispatch setPressed to all of this View's children.
6819     *
6820     * @see #setPressed(boolean)
6821     *
6822     * @param pressed The new pressed state
6823     */
6824    protected void dispatchSetPressed(boolean pressed) {
6825    }
6826
6827    /**
6828     * Indicates whether the view is currently in pressed state. Unless
6829     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6830     * the pressed state.
6831     *
6832     * @see #setPressed(boolean)
6833     * @see #isClickable()
6834     * @see #setClickable(boolean)
6835     *
6836     * @return true if the view is currently pressed, false otherwise
6837     */
6838    public boolean isPressed() {
6839        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6840    }
6841
6842    /**
6843     * Indicates whether this view will save its state (that is,
6844     * whether its {@link #onSaveInstanceState} method will be called).
6845     *
6846     * @return Returns true if the view state saving is enabled, else false.
6847     *
6848     * @see #setSaveEnabled(boolean)
6849     * @attr ref android.R.styleable#View_saveEnabled
6850     */
6851    public boolean isSaveEnabled() {
6852        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6853    }
6854
6855    /**
6856     * Controls whether the saving of this view's state is
6857     * enabled (that is, whether its {@link #onSaveInstanceState} method
6858     * will be called).  Note that even if freezing is enabled, the
6859     * view still must have an id assigned to it (via {@link #setId(int)})
6860     * for its state to be saved.  This flag can only disable the
6861     * saving of this view; any child views may still have their state saved.
6862     *
6863     * @param enabled Set to false to <em>disable</em> state saving, or true
6864     * (the default) to allow it.
6865     *
6866     * @see #isSaveEnabled()
6867     * @see #setId(int)
6868     * @see #onSaveInstanceState()
6869     * @attr ref android.R.styleable#View_saveEnabled
6870     */
6871    public void setSaveEnabled(boolean enabled) {
6872        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6873    }
6874
6875    /**
6876     * Gets whether the framework should discard touches when the view's
6877     * window is obscured by another visible window.
6878     * Refer to the {@link View} security documentation for more details.
6879     *
6880     * @return True if touch filtering is enabled.
6881     *
6882     * @see #setFilterTouchesWhenObscured(boolean)
6883     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6884     */
6885    @ViewDebug.ExportedProperty
6886    public boolean getFilterTouchesWhenObscured() {
6887        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6888    }
6889
6890    /**
6891     * Sets whether the framework should discard touches when the view's
6892     * window is obscured by another visible window.
6893     * Refer to the {@link View} security documentation for more details.
6894     *
6895     * @param enabled True if touch filtering should be enabled.
6896     *
6897     * @see #getFilterTouchesWhenObscured
6898     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6899     */
6900    public void setFilterTouchesWhenObscured(boolean enabled) {
6901        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6902                FILTER_TOUCHES_WHEN_OBSCURED);
6903    }
6904
6905    /**
6906     * Indicates whether the entire hierarchy under this view will save its
6907     * state when a state saving traversal occurs from its parent.  The default
6908     * is true; if false, these views will not be saved unless
6909     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6910     *
6911     * @return Returns true if the view state saving from parent is enabled, else false.
6912     *
6913     * @see #setSaveFromParentEnabled(boolean)
6914     */
6915    public boolean isSaveFromParentEnabled() {
6916        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6917    }
6918
6919    /**
6920     * Controls whether the entire hierarchy under this view will save its
6921     * state when a state saving traversal occurs from its parent.  The default
6922     * is true; if false, these views will not be saved unless
6923     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6924     *
6925     * @param enabled Set to false to <em>disable</em> state saving, or true
6926     * (the default) to allow it.
6927     *
6928     * @see #isSaveFromParentEnabled()
6929     * @see #setId(int)
6930     * @see #onSaveInstanceState()
6931     */
6932    public void setSaveFromParentEnabled(boolean enabled) {
6933        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6934    }
6935
6936
6937    /**
6938     * Returns whether this View is able to take focus.
6939     *
6940     * @return True if this view can take focus, or false otherwise.
6941     * @attr ref android.R.styleable#View_focusable
6942     */
6943    @ViewDebug.ExportedProperty(category = "focus")
6944    public final boolean isFocusable() {
6945        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6946    }
6947
6948    /**
6949     * When a view is focusable, it may not want to take focus when in touch mode.
6950     * For example, a button would like focus when the user is navigating via a D-pad
6951     * so that the user can click on it, but once the user starts touching the screen,
6952     * the button shouldn't take focus
6953     * @return Whether the view is focusable in touch mode.
6954     * @attr ref android.R.styleable#View_focusableInTouchMode
6955     */
6956    @ViewDebug.ExportedProperty
6957    public final boolean isFocusableInTouchMode() {
6958        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6959    }
6960
6961    /**
6962     * Find the nearest view in the specified direction that can take focus.
6963     * This does not actually give focus to that view.
6964     *
6965     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6966     *
6967     * @return The nearest focusable in the specified direction, or null if none
6968     *         can be found.
6969     */
6970    public View focusSearch(@FocusRealDirection int direction) {
6971        if (mParent != null) {
6972            return mParent.focusSearch(this, direction);
6973        } else {
6974            return null;
6975        }
6976    }
6977
6978    /**
6979     * This method is the last chance for the focused view and its ancestors to
6980     * respond to an arrow key. This is called when the focused view did not
6981     * consume the key internally, nor could the view system find a new view in
6982     * the requested direction to give focus to.
6983     *
6984     * @param focused The currently focused view.
6985     * @param direction The direction focus wants to move. One of FOCUS_UP,
6986     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6987     * @return True if the this view consumed this unhandled move.
6988     */
6989    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6990        return false;
6991    }
6992
6993    /**
6994     * If a user manually specified the next view id for a particular direction,
6995     * use the root to look up the view.
6996     * @param root The root view of the hierarchy containing this view.
6997     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6998     * or FOCUS_BACKWARD.
6999     * @return The user specified next view, or null if there is none.
7000     */
7001    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7002        switch (direction) {
7003            case FOCUS_LEFT:
7004                if (mNextFocusLeftId == View.NO_ID) return null;
7005                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7006            case FOCUS_RIGHT:
7007                if (mNextFocusRightId == View.NO_ID) return null;
7008                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7009            case FOCUS_UP:
7010                if (mNextFocusUpId == View.NO_ID) return null;
7011                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7012            case FOCUS_DOWN:
7013                if (mNextFocusDownId == View.NO_ID) return null;
7014                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7015            case FOCUS_FORWARD:
7016                if (mNextFocusForwardId == View.NO_ID) return null;
7017                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7018            case FOCUS_BACKWARD: {
7019                if (mID == View.NO_ID) return null;
7020                final int id = mID;
7021                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7022                    @Override
7023                    public boolean apply(View t) {
7024                        return t.mNextFocusForwardId == id;
7025                    }
7026                });
7027            }
7028        }
7029        return null;
7030    }
7031
7032    private View findViewInsideOutShouldExist(View root, int id) {
7033        if (mMatchIdPredicate == null) {
7034            mMatchIdPredicate = new MatchIdPredicate();
7035        }
7036        mMatchIdPredicate.mId = id;
7037        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7038        if (result == null) {
7039            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7040        }
7041        return result;
7042    }
7043
7044    /**
7045     * Find and return all focusable views that are descendants of this view,
7046     * possibly including this view if it is focusable itself.
7047     *
7048     * @param direction The direction of the focus
7049     * @return A list of focusable views
7050     */
7051    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7052        ArrayList<View> result = new ArrayList<View>(24);
7053        addFocusables(result, direction);
7054        return result;
7055    }
7056
7057    /**
7058     * Add any focusable views that are descendants of this view (possibly
7059     * including this view if it is focusable itself) to views.  If we are in touch mode,
7060     * only add views that are also focusable in touch mode.
7061     *
7062     * @param views Focusable views found so far
7063     * @param direction The direction of the focus
7064     */
7065    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7066        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7067    }
7068
7069    /**
7070     * Adds any focusable views that are descendants of this view (possibly
7071     * including this view if it is focusable itself) to views. This method
7072     * adds all focusable views regardless if we are in touch mode or
7073     * only views focusable in touch mode if we are in touch mode or
7074     * only views that can take accessibility focus if accessibility is enabeld
7075     * depending on the focusable mode paramater.
7076     *
7077     * @param views Focusable views found so far or null if all we are interested is
7078     *        the number of focusables.
7079     * @param direction The direction of the focus.
7080     * @param focusableMode The type of focusables to be added.
7081     *
7082     * @see #FOCUSABLES_ALL
7083     * @see #FOCUSABLES_TOUCH_MODE
7084     */
7085    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7086            @FocusableMode int focusableMode) {
7087        if (views == null) {
7088            return;
7089        }
7090        if (!isFocusable()) {
7091            return;
7092        }
7093        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7094                && isInTouchMode() && !isFocusableInTouchMode()) {
7095            return;
7096        }
7097        views.add(this);
7098    }
7099
7100    /**
7101     * Finds the Views that contain given text. The containment is case insensitive.
7102     * The search is performed by either the text that the View renders or the content
7103     * description that describes the view for accessibility purposes and the view does
7104     * not render or both. Clients can specify how the search is to be performed via
7105     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7106     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7107     *
7108     * @param outViews The output list of matching Views.
7109     * @param searched The text to match against.
7110     *
7111     * @see #FIND_VIEWS_WITH_TEXT
7112     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7113     * @see #setContentDescription(CharSequence)
7114     */
7115    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7116            @FindViewFlags int flags) {
7117        if (getAccessibilityNodeProvider() != null) {
7118            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7119                outViews.add(this);
7120            }
7121        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7122                && (searched != null && searched.length() > 0)
7123                && (mContentDescription != null && mContentDescription.length() > 0)) {
7124            String searchedLowerCase = searched.toString().toLowerCase();
7125            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7126            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7127                outViews.add(this);
7128            }
7129        }
7130    }
7131
7132    /**
7133     * Find and return all touchable views that are descendants of this view,
7134     * possibly including this view if it is touchable itself.
7135     *
7136     * @return A list of touchable views
7137     */
7138    public ArrayList<View> getTouchables() {
7139        ArrayList<View> result = new ArrayList<View>();
7140        addTouchables(result);
7141        return result;
7142    }
7143
7144    /**
7145     * Add any touchable views that are descendants of this view (possibly
7146     * including this view if it is touchable itself) to views.
7147     *
7148     * @param views Touchable views found so far
7149     */
7150    public void addTouchables(ArrayList<View> views) {
7151        final int viewFlags = mViewFlags;
7152
7153        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7154                && (viewFlags & ENABLED_MASK) == ENABLED) {
7155            views.add(this);
7156        }
7157    }
7158
7159    /**
7160     * Returns whether this View is accessibility focused.
7161     *
7162     * @return True if this View is accessibility focused.
7163     */
7164    public boolean isAccessibilityFocused() {
7165        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7166    }
7167
7168    /**
7169     * Call this to try to give accessibility focus to this view.
7170     *
7171     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7172     * returns false or the view is no visible or the view already has accessibility
7173     * focus.
7174     *
7175     * See also {@link #focusSearch(int)}, which is what you call to say that you
7176     * have focus, and you want your parent to look for the next one.
7177     *
7178     * @return Whether this view actually took accessibility focus.
7179     *
7180     * @hide
7181     */
7182    public boolean requestAccessibilityFocus() {
7183        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7184        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7185            return false;
7186        }
7187        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7188            return false;
7189        }
7190        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7191            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7192            ViewRootImpl viewRootImpl = getViewRootImpl();
7193            if (viewRootImpl != null) {
7194                viewRootImpl.setAccessibilityFocus(this, null);
7195            }
7196            Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect();
7197            getDrawingRect(rect);
7198            requestRectangleOnScreen(rect, false);
7199            invalidate();
7200            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7201            return true;
7202        }
7203        return false;
7204    }
7205
7206    /**
7207     * Call this to try to clear accessibility focus of this view.
7208     *
7209     * See also {@link #focusSearch(int)}, which is what you call to say that you
7210     * have focus, and you want your parent to look for the next one.
7211     *
7212     * @hide
7213     */
7214    public void clearAccessibilityFocus() {
7215        clearAccessibilityFocusNoCallbacks();
7216        // Clear the global reference of accessibility focus if this
7217        // view or any of its descendants had accessibility focus.
7218        ViewRootImpl viewRootImpl = getViewRootImpl();
7219        if (viewRootImpl != null) {
7220            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7221            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7222                viewRootImpl.setAccessibilityFocus(null, null);
7223            }
7224        }
7225    }
7226
7227    private void sendAccessibilityHoverEvent(int eventType) {
7228        // Since we are not delivering to a client accessibility events from not
7229        // important views (unless the clinet request that) we need to fire the
7230        // event from the deepest view exposed to the client. As a consequence if
7231        // the user crosses a not exposed view the client will see enter and exit
7232        // of the exposed predecessor followed by and enter and exit of that same
7233        // predecessor when entering and exiting the not exposed descendant. This
7234        // is fine since the client has a clear idea which view is hovered at the
7235        // price of a couple more events being sent. This is a simple and
7236        // working solution.
7237        View source = this;
7238        while (true) {
7239            if (source.includeForAccessibility()) {
7240                source.sendAccessibilityEvent(eventType);
7241                return;
7242            }
7243            ViewParent parent = source.getParent();
7244            if (parent instanceof View) {
7245                source = (View) parent;
7246            } else {
7247                return;
7248            }
7249        }
7250    }
7251
7252    /**
7253     * Clears accessibility focus without calling any callback methods
7254     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7255     * is used for clearing accessibility focus when giving this focus to
7256     * another view.
7257     */
7258    void clearAccessibilityFocusNoCallbacks() {
7259        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7260            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7261            invalidate();
7262            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7263        }
7264    }
7265
7266    /**
7267     * Call this to try to give focus to a specific view or to one of its
7268     * descendants.
7269     *
7270     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7271     * false), or if it is focusable and it is not focusable in touch mode
7272     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7273     *
7274     * See also {@link #focusSearch(int)}, which is what you call to say that you
7275     * have focus, and you want your parent to look for the next one.
7276     *
7277     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7278     * {@link #FOCUS_DOWN} and <code>null</code>.
7279     *
7280     * @return Whether this view or one of its descendants actually took focus.
7281     */
7282    public final boolean requestFocus() {
7283        return requestFocus(View.FOCUS_DOWN);
7284    }
7285
7286    /**
7287     * Call this to try to give focus to a specific view or to one of its
7288     * descendants and give it a hint about what direction focus is heading.
7289     *
7290     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7291     * false), or if it is focusable and it is not focusable in touch mode
7292     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7293     *
7294     * See also {@link #focusSearch(int)}, which is what you call to say that you
7295     * have focus, and you want your parent to look for the next one.
7296     *
7297     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7298     * <code>null</code> set for the previously focused rectangle.
7299     *
7300     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7301     * @return Whether this view or one of its descendants actually took focus.
7302     */
7303    public final boolean requestFocus(int direction) {
7304        return requestFocus(direction, null);
7305    }
7306
7307    /**
7308     * Call this to try to give focus to a specific view or to one of its descendants
7309     * and give it hints about the direction and a specific rectangle that the focus
7310     * is coming from.  The rectangle can help give larger views a finer grained hint
7311     * about where focus is coming from, and therefore, where to show selection, or
7312     * forward focus change internally.
7313     *
7314     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7315     * false), or if it is focusable and it is not focusable in touch mode
7316     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7317     *
7318     * A View will not take focus if it is not visible.
7319     *
7320     * A View will not take focus if one of its parents has
7321     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7322     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7323     *
7324     * See also {@link #focusSearch(int)}, which is what you call to say that you
7325     * have focus, and you want your parent to look for the next one.
7326     *
7327     * You may wish to override this method if your custom {@link View} has an internal
7328     * {@link View} that it wishes to forward the request to.
7329     *
7330     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7331     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7332     *        to give a finer grained hint about where focus is coming from.  May be null
7333     *        if there is no hint.
7334     * @return Whether this view or one of its descendants actually took focus.
7335     */
7336    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7337        return requestFocusNoSearch(direction, previouslyFocusedRect);
7338    }
7339
7340    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7341        // need to be focusable
7342        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7343                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7344            return false;
7345        }
7346
7347        // need to be focusable in touch mode if in touch mode
7348        if (isInTouchMode() &&
7349            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7350               return false;
7351        }
7352
7353        // need to not have any parents blocking us
7354        if (hasAncestorThatBlocksDescendantFocus()) {
7355            return false;
7356        }
7357
7358        handleFocusGainInternal(direction, previouslyFocusedRect);
7359        return true;
7360    }
7361
7362    /**
7363     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7364     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7365     * touch mode to request focus when they are touched.
7366     *
7367     * @return Whether this view or one of its descendants actually took focus.
7368     *
7369     * @see #isInTouchMode()
7370     *
7371     */
7372    public final boolean requestFocusFromTouch() {
7373        // Leave touch mode if we need to
7374        if (isInTouchMode()) {
7375            ViewRootImpl viewRoot = getViewRootImpl();
7376            if (viewRoot != null) {
7377                viewRoot.ensureTouchMode(false);
7378            }
7379        }
7380        return requestFocus(View.FOCUS_DOWN);
7381    }
7382
7383    /**
7384     * @return Whether any ancestor of this view blocks descendant focus.
7385     */
7386    private boolean hasAncestorThatBlocksDescendantFocus() {
7387        ViewParent ancestor = mParent;
7388        while (ancestor instanceof ViewGroup) {
7389            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7390            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7391                return true;
7392            } else {
7393                ancestor = vgAncestor.getParent();
7394            }
7395        }
7396        return false;
7397    }
7398
7399    /**
7400     * Gets the mode for determining whether this View is important for accessibility
7401     * which is if it fires accessibility events and if it is reported to
7402     * accessibility services that query the screen.
7403     *
7404     * @return The mode for determining whether a View is important for accessibility.
7405     *
7406     * @attr ref android.R.styleable#View_importantForAccessibility
7407     *
7408     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7409     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7410     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7411     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7412     */
7413    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7414            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7415            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7416            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7417            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7418                    to = "noHideDescendants")
7419        })
7420    public int getImportantForAccessibility() {
7421        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7422                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7423    }
7424
7425    /**
7426     * Sets the live region mode for this view. This indicates to accessibility
7427     * services whether they should automatically notify the user about changes
7428     * to the view's content description or text, or to the content descriptions
7429     * or text of the view's children (where applicable).
7430     * <p>
7431     * For example, in a login screen with a TextView that displays an "incorrect
7432     * password" notification, that view should be marked as a live region with
7433     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7434     * <p>
7435     * To disable change notifications for this view, use
7436     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7437     * mode for most views.
7438     * <p>
7439     * To indicate that the user should be notified of changes, use
7440     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7441     * <p>
7442     * If the view's changes should interrupt ongoing speech and notify the user
7443     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7444     *
7445     * @param mode The live region mode for this view, one of:
7446     *        <ul>
7447     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7448     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7449     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7450     *        </ul>
7451     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7452     */
7453    public void setAccessibilityLiveRegion(int mode) {
7454        if (mode != getAccessibilityLiveRegion()) {
7455            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7456            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7457                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7458            notifyViewAccessibilityStateChangedIfNeeded(
7459                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7460        }
7461    }
7462
7463    /**
7464     * Gets the live region mode for this View.
7465     *
7466     * @return The live region mode for the view.
7467     *
7468     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7469     *
7470     * @see #setAccessibilityLiveRegion(int)
7471     */
7472    public int getAccessibilityLiveRegion() {
7473        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7474                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7475    }
7476
7477    /**
7478     * Sets how to determine whether this view is important for accessibility
7479     * which is if it fires accessibility events and if it is reported to
7480     * accessibility services that query the screen.
7481     *
7482     * @param mode How to determine whether this view is important for accessibility.
7483     *
7484     * @attr ref android.R.styleable#View_importantForAccessibility
7485     *
7486     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7487     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7488     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7489     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7490     */
7491    public void setImportantForAccessibility(int mode) {
7492        final int oldMode = getImportantForAccessibility();
7493        if (mode != oldMode) {
7494            // If we're moving between AUTO and another state, we might not need
7495            // to send a subtree changed notification. We'll store the computed
7496            // importance, since we'll need to check it later to make sure.
7497            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7498                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7499            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7500            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7501            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7502                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7503            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7504                notifySubtreeAccessibilityStateChangedIfNeeded();
7505            } else {
7506                notifyViewAccessibilityStateChangedIfNeeded(
7507                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7508            }
7509        }
7510    }
7511
7512    /**
7513     * Computes whether this view should be exposed for accessibility. In
7514     * general, views that are interactive or provide information are exposed
7515     * while views that serve only as containers are hidden.
7516     * <p>
7517     * If an ancestor of this view has importance
7518     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7519     * returns <code>false</code>.
7520     * <p>
7521     * Otherwise, the value is computed according to the view's
7522     * {@link #getImportantForAccessibility()} value:
7523     * <ol>
7524     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7525     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7526     * </code>
7527     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7528     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7529     * view satisfies any of the following:
7530     * <ul>
7531     * <li>Is actionable, e.g. {@link #isClickable()},
7532     * {@link #isLongClickable()}, or {@link #isFocusable()}
7533     * <li>Has an {@link AccessibilityDelegate}
7534     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7535     * {@link OnKeyListener}, etc.
7536     * <li>Is an accessibility live region, e.g.
7537     * {@link #getAccessibilityLiveRegion()} is not
7538     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7539     * </ul>
7540     * </ol>
7541     *
7542     * @return Whether the view is exposed for accessibility.
7543     * @see #setImportantForAccessibility(int)
7544     * @see #getImportantForAccessibility()
7545     */
7546    public boolean isImportantForAccessibility() {
7547        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7548                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7549        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7550                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7551            return false;
7552        }
7553
7554        // Check parent mode to ensure we're not hidden.
7555        ViewParent parent = mParent;
7556        while (parent instanceof View) {
7557            if (((View) parent).getImportantForAccessibility()
7558                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7559                return false;
7560            }
7561            parent = parent.getParent();
7562        }
7563
7564        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7565                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7566                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7567    }
7568
7569    /**
7570     * Gets the parent for accessibility purposes. Note that the parent for
7571     * accessibility is not necessary the immediate parent. It is the first
7572     * predecessor that is important for accessibility.
7573     *
7574     * @return The parent for accessibility purposes.
7575     */
7576    public ViewParent getParentForAccessibility() {
7577        if (mParent instanceof View) {
7578            View parentView = (View) mParent;
7579            if (parentView.includeForAccessibility()) {
7580                return mParent;
7581            } else {
7582                return mParent.getParentForAccessibility();
7583            }
7584        }
7585        return null;
7586    }
7587
7588    /**
7589     * Adds the children of a given View for accessibility. Since some Views are
7590     * not important for accessibility the children for accessibility are not
7591     * necessarily direct children of the view, rather they are the first level of
7592     * descendants important for accessibility.
7593     *
7594     * @param children The list of children for accessibility.
7595     */
7596    public void addChildrenForAccessibility(ArrayList<View> children) {
7597
7598    }
7599
7600    /**
7601     * Whether to regard this view for accessibility. A view is regarded for
7602     * accessibility if it is important for accessibility or the querying
7603     * accessibility service has explicitly requested that view not
7604     * important for accessibility are regarded.
7605     *
7606     * @return Whether to regard the view for accessibility.
7607     *
7608     * @hide
7609     */
7610    public boolean includeForAccessibility() {
7611        if (mAttachInfo != null) {
7612            return (mAttachInfo.mAccessibilityFetchFlags
7613                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7614                    || isImportantForAccessibility();
7615        }
7616        return false;
7617    }
7618
7619    /**
7620     * Returns whether the View is considered actionable from
7621     * accessibility perspective. Such view are important for
7622     * accessibility.
7623     *
7624     * @return True if the view is actionable for accessibility.
7625     *
7626     * @hide
7627     */
7628    public boolean isActionableForAccessibility() {
7629        return (isClickable() || isLongClickable() || isFocusable());
7630    }
7631
7632    /**
7633     * Returns whether the View has registered callbacks which makes it
7634     * important for accessibility.
7635     *
7636     * @return True if the view is actionable for accessibility.
7637     */
7638    private boolean hasListenersForAccessibility() {
7639        ListenerInfo info = getListenerInfo();
7640        return mTouchDelegate != null || info.mOnKeyListener != null
7641                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7642                || info.mOnHoverListener != null || info.mOnDragListener != null;
7643    }
7644
7645    /**
7646     * Notifies that the accessibility state of this view changed. The change
7647     * is local to this view and does not represent structural changes such
7648     * as children and parent. For example, the view became focusable. The
7649     * notification is at at most once every
7650     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7651     * to avoid unnecessary load to the system. Also once a view has a pending
7652     * notification this method is a NOP until the notification has been sent.
7653     *
7654     * @hide
7655     */
7656    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7657        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7658            return;
7659        }
7660        if (mSendViewStateChangedAccessibilityEvent == null) {
7661            mSendViewStateChangedAccessibilityEvent =
7662                    new SendViewStateChangedAccessibilityEvent();
7663        }
7664        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7665    }
7666
7667    /**
7668     * Notifies that the accessibility state of this view changed. The change
7669     * is *not* local to this view and does represent structural changes such
7670     * as children and parent. For example, the view size changed. The
7671     * notification is at at most once every
7672     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7673     * to avoid unnecessary load to the system. Also once a view has a pending
7674     * notification this method is a NOP until the notification has been sent.
7675     *
7676     * @hide
7677     */
7678    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7679        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7680            return;
7681        }
7682        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7683            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7684            if (mParent != null) {
7685                try {
7686                    mParent.notifySubtreeAccessibilityStateChanged(
7687                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7688                } catch (AbstractMethodError e) {
7689                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7690                            " does not fully implement ViewParent", e);
7691                }
7692            }
7693        }
7694    }
7695
7696    /**
7697     * Reset the flag indicating the accessibility state of the subtree rooted
7698     * at this view changed.
7699     */
7700    void resetSubtreeAccessibilityStateChanged() {
7701        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7702    }
7703
7704    /**
7705     * Performs the specified accessibility action on the view. For
7706     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7707     * <p>
7708     * If an {@link AccessibilityDelegate} has been specified via calling
7709     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7710     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7711     * is responsible for handling this call.
7712     * </p>
7713     *
7714     * @param action The action to perform.
7715     * @param arguments Optional action arguments.
7716     * @return Whether the action was performed.
7717     */
7718    public boolean performAccessibilityAction(int action, Bundle arguments) {
7719      if (mAccessibilityDelegate != null) {
7720          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7721      } else {
7722          return performAccessibilityActionInternal(action, arguments);
7723      }
7724    }
7725
7726   /**
7727    * @see #performAccessibilityAction(int, Bundle)
7728    *
7729    * Note: Called from the default {@link AccessibilityDelegate}.
7730    */
7731    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7732        switch (action) {
7733            case AccessibilityNodeInfo.ACTION_CLICK: {
7734                if (isClickable()) {
7735                    performClick();
7736                    return true;
7737                }
7738            } break;
7739            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7740                if (isLongClickable()) {
7741                    performLongClick();
7742                    return true;
7743                }
7744            } break;
7745            case AccessibilityNodeInfo.ACTION_FOCUS: {
7746                if (!hasFocus()) {
7747                    // Get out of touch mode since accessibility
7748                    // wants to move focus around.
7749                    getViewRootImpl().ensureTouchMode(false);
7750                    return requestFocus();
7751                }
7752            } break;
7753            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7754                if (hasFocus()) {
7755                    clearFocus();
7756                    return !isFocused();
7757                }
7758            } break;
7759            case AccessibilityNodeInfo.ACTION_SELECT: {
7760                if (!isSelected()) {
7761                    setSelected(true);
7762                    return isSelected();
7763                }
7764            } break;
7765            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7766                if (isSelected()) {
7767                    setSelected(false);
7768                    return !isSelected();
7769                }
7770            } break;
7771            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7772                if (!isAccessibilityFocused()) {
7773                    return requestAccessibilityFocus();
7774                }
7775            } break;
7776            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7777                if (isAccessibilityFocused()) {
7778                    clearAccessibilityFocus();
7779                    return true;
7780                }
7781            } break;
7782            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7783                if (arguments != null) {
7784                    final int granularity = arguments.getInt(
7785                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7786                    final boolean extendSelection = arguments.getBoolean(
7787                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7788                    return traverseAtGranularity(granularity, true, extendSelection);
7789                }
7790            } break;
7791            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7792                if (arguments != null) {
7793                    final int granularity = arguments.getInt(
7794                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7795                    final boolean extendSelection = arguments.getBoolean(
7796                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7797                    return traverseAtGranularity(granularity, false, extendSelection);
7798                }
7799            } break;
7800            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7801                CharSequence text = getIterableTextForAccessibility();
7802                if (text == null) {
7803                    return false;
7804                }
7805                final int start = (arguments != null) ? arguments.getInt(
7806                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7807                final int end = (arguments != null) ? arguments.getInt(
7808                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7809                // Only cursor position can be specified (selection length == 0)
7810                if ((getAccessibilitySelectionStart() != start
7811                        || getAccessibilitySelectionEnd() != end)
7812                        && (start == end)) {
7813                    setAccessibilitySelection(start, end);
7814                    notifyViewAccessibilityStateChangedIfNeeded(
7815                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7816                    return true;
7817                }
7818            } break;
7819        }
7820        return false;
7821    }
7822
7823    private boolean traverseAtGranularity(int granularity, boolean forward,
7824            boolean extendSelection) {
7825        CharSequence text = getIterableTextForAccessibility();
7826        if (text == null || text.length() == 0) {
7827            return false;
7828        }
7829        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7830        if (iterator == null) {
7831            return false;
7832        }
7833        int current = getAccessibilitySelectionEnd();
7834        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7835            current = forward ? 0 : text.length();
7836        }
7837        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7838        if (range == null) {
7839            return false;
7840        }
7841        final int segmentStart = range[0];
7842        final int segmentEnd = range[1];
7843        int selectionStart;
7844        int selectionEnd;
7845        if (extendSelection && isAccessibilitySelectionExtendable()) {
7846            selectionStart = getAccessibilitySelectionStart();
7847            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7848                selectionStart = forward ? segmentStart : segmentEnd;
7849            }
7850            selectionEnd = forward ? segmentEnd : segmentStart;
7851        } else {
7852            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7853        }
7854        setAccessibilitySelection(selectionStart, selectionEnd);
7855        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7856                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7857        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7858        return true;
7859    }
7860
7861    /**
7862     * Gets the text reported for accessibility purposes.
7863     *
7864     * @return The accessibility text.
7865     *
7866     * @hide
7867     */
7868    public CharSequence getIterableTextForAccessibility() {
7869        return getContentDescription();
7870    }
7871
7872    /**
7873     * Gets whether accessibility selection can be extended.
7874     *
7875     * @return If selection is extensible.
7876     *
7877     * @hide
7878     */
7879    public boolean isAccessibilitySelectionExtendable() {
7880        return false;
7881    }
7882
7883    /**
7884     * @hide
7885     */
7886    public int getAccessibilitySelectionStart() {
7887        return mAccessibilityCursorPosition;
7888    }
7889
7890    /**
7891     * @hide
7892     */
7893    public int getAccessibilitySelectionEnd() {
7894        return getAccessibilitySelectionStart();
7895    }
7896
7897    /**
7898     * @hide
7899     */
7900    public void setAccessibilitySelection(int start, int end) {
7901        if (start ==  end && end == mAccessibilityCursorPosition) {
7902            return;
7903        }
7904        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7905            mAccessibilityCursorPosition = start;
7906        } else {
7907            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7908        }
7909        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7910    }
7911
7912    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7913            int fromIndex, int toIndex) {
7914        if (mParent == null) {
7915            return;
7916        }
7917        AccessibilityEvent event = AccessibilityEvent.obtain(
7918                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7919        onInitializeAccessibilityEvent(event);
7920        onPopulateAccessibilityEvent(event);
7921        event.setFromIndex(fromIndex);
7922        event.setToIndex(toIndex);
7923        event.setAction(action);
7924        event.setMovementGranularity(granularity);
7925        mParent.requestSendAccessibilityEvent(this, event);
7926    }
7927
7928    /**
7929     * @hide
7930     */
7931    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7932        switch (granularity) {
7933            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7934                CharSequence text = getIterableTextForAccessibility();
7935                if (text != null && text.length() > 0) {
7936                    CharacterTextSegmentIterator iterator =
7937                        CharacterTextSegmentIterator.getInstance(
7938                                mContext.getResources().getConfiguration().locale);
7939                    iterator.initialize(text.toString());
7940                    return iterator;
7941                }
7942            } break;
7943            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7944                CharSequence text = getIterableTextForAccessibility();
7945                if (text != null && text.length() > 0) {
7946                    WordTextSegmentIterator iterator =
7947                        WordTextSegmentIterator.getInstance(
7948                                mContext.getResources().getConfiguration().locale);
7949                    iterator.initialize(text.toString());
7950                    return iterator;
7951                }
7952            } break;
7953            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7954                CharSequence text = getIterableTextForAccessibility();
7955                if (text != null && text.length() > 0) {
7956                    ParagraphTextSegmentIterator iterator =
7957                        ParagraphTextSegmentIterator.getInstance();
7958                    iterator.initialize(text.toString());
7959                    return iterator;
7960                }
7961            } break;
7962        }
7963        return null;
7964    }
7965
7966    /**
7967     * @hide
7968     */
7969    public void dispatchStartTemporaryDetach() {
7970        onStartTemporaryDetach();
7971    }
7972
7973    /**
7974     * This is called when a container is going to temporarily detach a child, with
7975     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7976     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7977     * {@link #onDetachedFromWindow()} when the container is done.
7978     */
7979    public void onStartTemporaryDetach() {
7980        removeUnsetPressCallback();
7981        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7982    }
7983
7984    /**
7985     * @hide
7986     */
7987    public void dispatchFinishTemporaryDetach() {
7988        onFinishTemporaryDetach();
7989    }
7990
7991    /**
7992     * Called after {@link #onStartTemporaryDetach} when the container is done
7993     * changing the view.
7994     */
7995    public void onFinishTemporaryDetach() {
7996    }
7997
7998    /**
7999     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8000     * for this view's window.  Returns null if the view is not currently attached
8001     * to the window.  Normally you will not need to use this directly, but
8002     * just use the standard high-level event callbacks like
8003     * {@link #onKeyDown(int, KeyEvent)}.
8004     */
8005    public KeyEvent.DispatcherState getKeyDispatcherState() {
8006        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8007    }
8008
8009    /**
8010     * Dispatch a key event before it is processed by any input method
8011     * associated with the view hierarchy.  This can be used to intercept
8012     * key events in special situations before the IME consumes them; a
8013     * typical example would be handling the BACK key to update the application's
8014     * UI instead of allowing the IME to see it and close itself.
8015     *
8016     * @param event The key event to be dispatched.
8017     * @return True if the event was handled, false otherwise.
8018     */
8019    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8020        return onKeyPreIme(event.getKeyCode(), event);
8021    }
8022
8023    /**
8024     * Dispatch a key event to the next view on the focus path. This path runs
8025     * from the top of the view tree down to the currently focused view. If this
8026     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8027     * the next node down the focus path. This method also fires any key
8028     * listeners.
8029     *
8030     * @param event The key event to be dispatched.
8031     * @return True if the event was handled, false otherwise.
8032     */
8033    public boolean dispatchKeyEvent(KeyEvent event) {
8034        if (mInputEventConsistencyVerifier != null) {
8035            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8036        }
8037
8038        // Give any attached key listener a first crack at the event.
8039        //noinspection SimplifiableIfStatement
8040        ListenerInfo li = mListenerInfo;
8041        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8042                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8043            return true;
8044        }
8045
8046        if (event.dispatch(this, mAttachInfo != null
8047                ? mAttachInfo.mKeyDispatchState : null, this)) {
8048            return true;
8049        }
8050
8051        if (mInputEventConsistencyVerifier != null) {
8052            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8053        }
8054        return false;
8055    }
8056
8057    /**
8058     * Dispatches a key shortcut event.
8059     *
8060     * @param event The key event to be dispatched.
8061     * @return True if the event was handled by the view, false otherwise.
8062     */
8063    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8064        return onKeyShortcut(event.getKeyCode(), event);
8065    }
8066
8067    /**
8068     * Pass the touch screen motion event down to the target view, or this
8069     * view if it is the target.
8070     *
8071     * @param event The motion event to be dispatched.
8072     * @return True if the event was handled by the view, false otherwise.
8073     */
8074    public boolean dispatchTouchEvent(MotionEvent event) {
8075        boolean result = false;
8076
8077        if (mInputEventConsistencyVerifier != null) {
8078            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8079        }
8080
8081        final int actionMasked = event.getActionMasked();
8082        if (actionMasked == MotionEvent.ACTION_DOWN) {
8083            // Defensive cleanup for new gesture
8084            stopNestedScroll();
8085        }
8086
8087        if (onFilterTouchEventForSecurity(event)) {
8088            //noinspection SimplifiableIfStatement
8089            ListenerInfo li = mListenerInfo;
8090            if (li != null && li.mOnTouchListener != null
8091                    && (mViewFlags & ENABLED_MASK) == ENABLED
8092                    && li.mOnTouchListener.onTouch(this, event)) {
8093                result = true;
8094            }
8095
8096            if (!result && onTouchEvent(event)) {
8097                result = true;
8098            }
8099        }
8100
8101        if (!result && mInputEventConsistencyVerifier != null) {
8102            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8103        }
8104
8105        // Clean up after nested scrolls if this is the end of a gesture;
8106        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8107        // of the gesture.
8108        if (actionMasked == MotionEvent.ACTION_UP ||
8109                actionMasked == MotionEvent.ACTION_CANCEL ||
8110                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8111            stopNestedScroll();
8112        }
8113
8114        return result;
8115    }
8116
8117    /**
8118     * Filter the touch event to apply security policies.
8119     *
8120     * @param event The motion event to be filtered.
8121     * @return True if the event should be dispatched, false if the event should be dropped.
8122     *
8123     * @see #getFilterTouchesWhenObscured
8124     */
8125    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8126        //noinspection RedundantIfStatement
8127        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8128                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8129            // Window is obscured, drop this touch.
8130            return false;
8131        }
8132        return true;
8133    }
8134
8135    /**
8136     * Pass a trackball motion event down to the focused view.
8137     *
8138     * @param event The motion event to be dispatched.
8139     * @return True if the event was handled by the view, false otherwise.
8140     */
8141    public boolean dispatchTrackballEvent(MotionEvent event) {
8142        if (mInputEventConsistencyVerifier != null) {
8143            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8144        }
8145
8146        return onTrackballEvent(event);
8147    }
8148
8149    /**
8150     * Dispatch a generic motion event.
8151     * <p>
8152     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8153     * are delivered to the view under the pointer.  All other generic motion events are
8154     * delivered to the focused view.  Hover events are handled specially and are delivered
8155     * to {@link #onHoverEvent(MotionEvent)}.
8156     * </p>
8157     *
8158     * @param event The motion event to be dispatched.
8159     * @return True if the event was handled by the view, false otherwise.
8160     */
8161    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8162        if (mInputEventConsistencyVerifier != null) {
8163            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8164        }
8165
8166        final int source = event.getSource();
8167        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8168            final int action = event.getAction();
8169            if (action == MotionEvent.ACTION_HOVER_ENTER
8170                    || action == MotionEvent.ACTION_HOVER_MOVE
8171                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8172                if (dispatchHoverEvent(event)) {
8173                    return true;
8174                }
8175            } else if (dispatchGenericPointerEvent(event)) {
8176                return true;
8177            }
8178        } else if (dispatchGenericFocusedEvent(event)) {
8179            return true;
8180        }
8181
8182        if (dispatchGenericMotionEventInternal(event)) {
8183            return true;
8184        }
8185
8186        if (mInputEventConsistencyVerifier != null) {
8187            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8188        }
8189        return false;
8190    }
8191
8192    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8193        //noinspection SimplifiableIfStatement
8194        ListenerInfo li = mListenerInfo;
8195        if (li != null && li.mOnGenericMotionListener != null
8196                && (mViewFlags & ENABLED_MASK) == ENABLED
8197                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8198            return true;
8199        }
8200
8201        if (onGenericMotionEvent(event)) {
8202            return true;
8203        }
8204
8205        if (mInputEventConsistencyVerifier != null) {
8206            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8207        }
8208        return false;
8209    }
8210
8211    /**
8212     * Dispatch a hover event.
8213     * <p>
8214     * Do not call this method directly.
8215     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8216     * </p>
8217     *
8218     * @param event The motion event to be dispatched.
8219     * @return True if the event was handled by the view, false otherwise.
8220     */
8221    protected boolean dispatchHoverEvent(MotionEvent event) {
8222        ListenerInfo li = mListenerInfo;
8223        //noinspection SimplifiableIfStatement
8224        if (li != null && li.mOnHoverListener != null
8225                && (mViewFlags & ENABLED_MASK) == ENABLED
8226                && li.mOnHoverListener.onHover(this, event)) {
8227            return true;
8228        }
8229
8230        return onHoverEvent(event);
8231    }
8232
8233    /**
8234     * Returns true if the view has a child to which it has recently sent
8235     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8236     * it does not have a hovered child, then it must be the innermost hovered view.
8237     * @hide
8238     */
8239    protected boolean hasHoveredChild() {
8240        return false;
8241    }
8242
8243    /**
8244     * Dispatch a generic motion event to the view under the first pointer.
8245     * <p>
8246     * Do not call this method directly.
8247     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8248     * </p>
8249     *
8250     * @param event The motion event to be dispatched.
8251     * @return True if the event was handled by the view, false otherwise.
8252     */
8253    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8254        return false;
8255    }
8256
8257    /**
8258     * Dispatch a generic motion event to the currently focused view.
8259     * <p>
8260     * Do not call this method directly.
8261     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8262     * </p>
8263     *
8264     * @param event The motion event to be dispatched.
8265     * @return True if the event was handled by the view, false otherwise.
8266     */
8267    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8268        return false;
8269    }
8270
8271    /**
8272     * Dispatch a pointer event.
8273     * <p>
8274     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8275     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8276     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8277     * and should not be expected to handle other pointing device features.
8278     * </p>
8279     *
8280     * @param event The motion event to be dispatched.
8281     * @return True if the event was handled by the view, false otherwise.
8282     * @hide
8283     */
8284    public final boolean dispatchPointerEvent(MotionEvent event) {
8285        if (event.isTouchEvent()) {
8286            return dispatchTouchEvent(event);
8287        } else {
8288            return dispatchGenericMotionEvent(event);
8289        }
8290    }
8291
8292    /**
8293     * Called when the window containing this view gains or loses window focus.
8294     * ViewGroups should override to route to their children.
8295     *
8296     * @param hasFocus True if the window containing this view now has focus,
8297     *        false otherwise.
8298     */
8299    public void dispatchWindowFocusChanged(boolean hasFocus) {
8300        onWindowFocusChanged(hasFocus);
8301    }
8302
8303    /**
8304     * Called when the window containing this view gains or loses focus.  Note
8305     * that this is separate from view focus: to receive key events, both
8306     * your view and its window must have focus.  If a window is displayed
8307     * on top of yours that takes input focus, then your own window will lose
8308     * focus but the view focus will remain unchanged.
8309     *
8310     * @param hasWindowFocus True if the window containing this view now has
8311     *        focus, false otherwise.
8312     */
8313    public void onWindowFocusChanged(boolean hasWindowFocus) {
8314        InputMethodManager imm = InputMethodManager.peekInstance();
8315        if (!hasWindowFocus) {
8316            if (isPressed()) {
8317                setPressed(false);
8318            }
8319            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8320                imm.focusOut(this);
8321            }
8322            removeLongPressCallback();
8323            removeTapCallback();
8324            onFocusLost();
8325        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8326            imm.focusIn(this);
8327        }
8328        refreshDrawableState();
8329    }
8330
8331    /**
8332     * Returns true if this view is in a window that currently has window focus.
8333     * Note that this is not the same as the view itself having focus.
8334     *
8335     * @return True if this view is in a window that currently has window focus.
8336     */
8337    public boolean hasWindowFocus() {
8338        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8339    }
8340
8341    /**
8342     * Dispatch a view visibility change down the view hierarchy.
8343     * ViewGroups should override to route to their children.
8344     * @param changedView The view whose visibility changed. Could be 'this' or
8345     * an ancestor view.
8346     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8347     * {@link #INVISIBLE} or {@link #GONE}.
8348     */
8349    protected void dispatchVisibilityChanged(@NonNull View changedView,
8350            @Visibility int visibility) {
8351        onVisibilityChanged(changedView, visibility);
8352    }
8353
8354    /**
8355     * Called when the visibility of the view or an ancestor of the view is changed.
8356     * @param changedView The view whose visibility changed. Could be 'this' or
8357     * an ancestor view.
8358     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8359     * {@link #INVISIBLE} or {@link #GONE}.
8360     */
8361    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8362        if (visibility == VISIBLE) {
8363            if (mAttachInfo != null) {
8364                initialAwakenScrollBars();
8365            } else {
8366                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8367            }
8368        }
8369    }
8370
8371    /**
8372     * Dispatch a hint about whether this view is displayed. For instance, when
8373     * a View moves out of the screen, it might receives a display hint indicating
8374     * the view is not displayed. Applications should not <em>rely</em> on this hint
8375     * as there is no guarantee that they will receive one.
8376     *
8377     * @param hint A hint about whether or not this view is displayed:
8378     * {@link #VISIBLE} or {@link #INVISIBLE}.
8379     */
8380    public void dispatchDisplayHint(@Visibility int hint) {
8381        onDisplayHint(hint);
8382    }
8383
8384    /**
8385     * Gives this view a hint about whether is displayed or not. For instance, when
8386     * a View moves out of the screen, it might receives a display hint indicating
8387     * the view is not displayed. Applications should not <em>rely</em> on this hint
8388     * as there is no guarantee that they will receive one.
8389     *
8390     * @param hint A hint about whether or not this view is displayed:
8391     * {@link #VISIBLE} or {@link #INVISIBLE}.
8392     */
8393    protected void onDisplayHint(@Visibility int hint) {
8394    }
8395
8396    /**
8397     * Dispatch a window visibility change down the view hierarchy.
8398     * ViewGroups should override to route to their children.
8399     *
8400     * @param visibility The new visibility of the window.
8401     *
8402     * @see #onWindowVisibilityChanged(int)
8403     */
8404    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8405        onWindowVisibilityChanged(visibility);
8406    }
8407
8408    /**
8409     * Called when the window containing has change its visibility
8410     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8411     * that this tells you whether or not your window is being made visible
8412     * to the window manager; this does <em>not</em> tell you whether or not
8413     * your window is obscured by other windows on the screen, even if it
8414     * is itself visible.
8415     *
8416     * @param visibility The new visibility of the window.
8417     */
8418    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8419        if (visibility == VISIBLE) {
8420            initialAwakenScrollBars();
8421        }
8422    }
8423
8424    /**
8425     * Returns the current visibility of the window this view is attached to
8426     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8427     *
8428     * @return Returns the current visibility of the view's window.
8429     */
8430    @Visibility
8431    public int getWindowVisibility() {
8432        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8433    }
8434
8435    /**
8436     * Retrieve the overall visible display size in which the window this view is
8437     * attached to has been positioned in.  This takes into account screen
8438     * decorations above the window, for both cases where the window itself
8439     * is being position inside of them or the window is being placed under
8440     * then and covered insets are used for the window to position its content
8441     * inside.  In effect, this tells you the available area where content can
8442     * be placed and remain visible to users.
8443     *
8444     * <p>This function requires an IPC back to the window manager to retrieve
8445     * the requested information, so should not be used in performance critical
8446     * code like drawing.
8447     *
8448     * @param outRect Filled in with the visible display frame.  If the view
8449     * is not attached to a window, this is simply the raw display size.
8450     */
8451    public void getWindowVisibleDisplayFrame(Rect outRect) {
8452        if (mAttachInfo != null) {
8453            try {
8454                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8455            } catch (RemoteException e) {
8456                return;
8457            }
8458            // XXX This is really broken, and probably all needs to be done
8459            // in the window manager, and we need to know more about whether
8460            // we want the area behind or in front of the IME.
8461            final Rect insets = mAttachInfo.mVisibleInsets;
8462            outRect.left += insets.left;
8463            outRect.top += insets.top;
8464            outRect.right -= insets.right;
8465            outRect.bottom -= insets.bottom;
8466            return;
8467        }
8468        // The view is not attached to a display so we don't have a context.
8469        // Make a best guess about the display size.
8470        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8471        d.getRectSize(outRect);
8472    }
8473
8474    /**
8475     * Dispatch a notification about a resource configuration change down
8476     * the view hierarchy.
8477     * ViewGroups should override to route to their children.
8478     *
8479     * @param newConfig The new resource configuration.
8480     *
8481     * @see #onConfigurationChanged(android.content.res.Configuration)
8482     */
8483    public void dispatchConfigurationChanged(Configuration newConfig) {
8484        onConfigurationChanged(newConfig);
8485    }
8486
8487    /**
8488     * Called when the current configuration of the resources being used
8489     * by the application have changed.  You can use this to decide when
8490     * to reload resources that can changed based on orientation and other
8491     * configuration characterstics.  You only need to use this if you are
8492     * not relying on the normal {@link android.app.Activity} mechanism of
8493     * recreating the activity instance upon a configuration change.
8494     *
8495     * @param newConfig The new resource configuration.
8496     */
8497    protected void onConfigurationChanged(Configuration newConfig) {
8498    }
8499
8500    /**
8501     * Private function to aggregate all per-view attributes in to the view
8502     * root.
8503     */
8504    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8505        performCollectViewAttributes(attachInfo, visibility);
8506    }
8507
8508    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8509        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8510            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8511                attachInfo.mKeepScreenOn = true;
8512            }
8513            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8514            ListenerInfo li = mListenerInfo;
8515            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8516                attachInfo.mHasSystemUiListeners = true;
8517            }
8518        }
8519    }
8520
8521    void needGlobalAttributesUpdate(boolean force) {
8522        final AttachInfo ai = mAttachInfo;
8523        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8524            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8525                    || ai.mHasSystemUiListeners) {
8526                ai.mRecomputeGlobalAttributes = true;
8527            }
8528        }
8529    }
8530
8531    /**
8532     * Returns whether the device is currently in touch mode.  Touch mode is entered
8533     * once the user begins interacting with the device by touch, and affects various
8534     * things like whether focus is always visible to the user.
8535     *
8536     * @return Whether the device is in touch mode.
8537     */
8538    @ViewDebug.ExportedProperty
8539    public boolean isInTouchMode() {
8540        if (mAttachInfo != null) {
8541            return mAttachInfo.mInTouchMode;
8542        } else {
8543            return ViewRootImpl.isInTouchMode();
8544        }
8545    }
8546
8547    /**
8548     * Returns the context the view is running in, through which it can
8549     * access the current theme, resources, etc.
8550     *
8551     * @return The view's Context.
8552     */
8553    @ViewDebug.CapturedViewProperty
8554    public final Context getContext() {
8555        return mContext;
8556    }
8557
8558    /**
8559     * Handle a key event before it is processed by any input method
8560     * associated with the view hierarchy.  This can be used to intercept
8561     * key events in special situations before the IME consumes them; a
8562     * typical example would be handling the BACK key to update the application's
8563     * UI instead of allowing the IME to see it and close itself.
8564     *
8565     * @param keyCode The value in event.getKeyCode().
8566     * @param event Description of the key event.
8567     * @return If you handled the event, return true. If you want to allow the
8568     *         event to be handled by the next receiver, return false.
8569     */
8570    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8571        return false;
8572    }
8573
8574    /**
8575     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8576     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8577     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8578     * is released, if the view is enabled and clickable.
8579     *
8580     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8581     * although some may elect to do so in some situations. Do not rely on this to
8582     * catch software key presses.
8583     *
8584     * @param keyCode A key code that represents the button pressed, from
8585     *                {@link android.view.KeyEvent}.
8586     * @param event   The KeyEvent object that defines the button action.
8587     */
8588    public boolean onKeyDown(int keyCode, KeyEvent event) {
8589        boolean result = false;
8590
8591        if (KeyEvent.isConfirmKey(keyCode)) {
8592            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8593                return true;
8594            }
8595            // Long clickable items don't necessarily have to be clickable
8596            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8597                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8598                    (event.getRepeatCount() == 0)) {
8599                setPressed(true);
8600                checkForLongClick(0);
8601                return true;
8602            }
8603        }
8604        return result;
8605    }
8606
8607    /**
8608     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8609     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8610     * the event).
8611     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8612     * although some may elect to do so in some situations. Do not rely on this to
8613     * catch software key presses.
8614     */
8615    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8616        return false;
8617    }
8618
8619    /**
8620     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8621     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8622     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8623     * {@link KeyEvent#KEYCODE_ENTER} is released.
8624     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8625     * although some may elect to do so in some situations. Do not rely on this to
8626     * catch software key presses.
8627     *
8628     * @param keyCode A key code that represents the button pressed, from
8629     *                {@link android.view.KeyEvent}.
8630     * @param event   The KeyEvent object that defines the button action.
8631     */
8632    public boolean onKeyUp(int keyCode, KeyEvent event) {
8633        if (KeyEvent.isConfirmKey(keyCode)) {
8634            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8635                return true;
8636            }
8637            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8638                setPressed(false);
8639
8640                if (!mHasPerformedLongPress) {
8641                    // This is a tap, so remove the longpress check
8642                    removeLongPressCallback();
8643                    return performClick();
8644                }
8645            }
8646        }
8647        return false;
8648    }
8649
8650    /**
8651     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8652     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8653     * the event).
8654     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8655     * although some may elect to do so in some situations. Do not rely on this to
8656     * catch software key presses.
8657     *
8658     * @param keyCode     A key code that represents the button pressed, from
8659     *                    {@link android.view.KeyEvent}.
8660     * @param repeatCount The number of times the action was made.
8661     * @param event       The KeyEvent object that defines the button action.
8662     */
8663    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8664        return false;
8665    }
8666
8667    /**
8668     * Called on the focused view when a key shortcut event is not handled.
8669     * Override this method to implement local key shortcuts for the View.
8670     * Key shortcuts can also be implemented by setting the
8671     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8672     *
8673     * @param keyCode The value in event.getKeyCode().
8674     * @param event Description of the key event.
8675     * @return If you handled the event, return true. If you want to allow the
8676     *         event to be handled by the next receiver, return false.
8677     */
8678    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8679        return false;
8680    }
8681
8682    /**
8683     * Check whether the called view is a text editor, in which case it
8684     * would make sense to automatically display a soft input window for
8685     * it.  Subclasses should override this if they implement
8686     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8687     * a call on that method would return a non-null InputConnection, and
8688     * they are really a first-class editor that the user would normally
8689     * start typing on when the go into a window containing your view.
8690     *
8691     * <p>The default implementation always returns false.  This does
8692     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8693     * will not be called or the user can not otherwise perform edits on your
8694     * view; it is just a hint to the system that this is not the primary
8695     * purpose of this view.
8696     *
8697     * @return Returns true if this view is a text editor, else false.
8698     */
8699    public boolean onCheckIsTextEditor() {
8700        return false;
8701    }
8702
8703    /**
8704     * Create a new InputConnection for an InputMethod to interact
8705     * with the view.  The default implementation returns null, since it doesn't
8706     * support input methods.  You can override this to implement such support.
8707     * This is only needed for views that take focus and text input.
8708     *
8709     * <p>When implementing this, you probably also want to implement
8710     * {@link #onCheckIsTextEditor()} to indicate you will return a
8711     * non-null InputConnection.</p>
8712     *
8713     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8714     * object correctly and in its entirety, so that the connected IME can rely
8715     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8716     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8717     * must be filled in with the correct cursor position for IMEs to work correctly
8718     * with your application.</p>
8719     *
8720     * @param outAttrs Fill in with attribute information about the connection.
8721     */
8722    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8723        return null;
8724    }
8725
8726    /**
8727     * Called by the {@link android.view.inputmethod.InputMethodManager}
8728     * when a view who is not the current
8729     * input connection target is trying to make a call on the manager.  The
8730     * default implementation returns false; you can override this to return
8731     * true for certain views if you are performing InputConnection proxying
8732     * to them.
8733     * @param view The View that is making the InputMethodManager call.
8734     * @return Return true to allow the call, false to reject.
8735     */
8736    public boolean checkInputConnectionProxy(View view) {
8737        return false;
8738    }
8739
8740    /**
8741     * Show the context menu for this view. It is not safe to hold on to the
8742     * menu after returning from this method.
8743     *
8744     * You should normally not overload this method. Overload
8745     * {@link #onCreateContextMenu(ContextMenu)} or define an
8746     * {@link OnCreateContextMenuListener} to add items to the context menu.
8747     *
8748     * @param menu The context menu to populate
8749     */
8750    public void createContextMenu(ContextMenu menu) {
8751        ContextMenuInfo menuInfo = getContextMenuInfo();
8752
8753        // Sets the current menu info so all items added to menu will have
8754        // my extra info set.
8755        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8756
8757        onCreateContextMenu(menu);
8758        ListenerInfo li = mListenerInfo;
8759        if (li != null && li.mOnCreateContextMenuListener != null) {
8760            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8761        }
8762
8763        // Clear the extra information so subsequent items that aren't mine don't
8764        // have my extra info.
8765        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8766
8767        if (mParent != null) {
8768            mParent.createContextMenu(menu);
8769        }
8770    }
8771
8772    /**
8773     * Views should implement this if they have extra information to associate
8774     * with the context menu. The return result is supplied as a parameter to
8775     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8776     * callback.
8777     *
8778     * @return Extra information about the item for which the context menu
8779     *         should be shown. This information will vary across different
8780     *         subclasses of View.
8781     */
8782    protected ContextMenuInfo getContextMenuInfo() {
8783        return null;
8784    }
8785
8786    /**
8787     * Views should implement this if the view itself is going to add items to
8788     * the context menu.
8789     *
8790     * @param menu the context menu to populate
8791     */
8792    protected void onCreateContextMenu(ContextMenu menu) {
8793    }
8794
8795    /**
8796     * Implement this method to handle trackball motion events.  The
8797     * <em>relative</em> movement of the trackball since the last event
8798     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8799     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8800     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8801     * they will often be fractional values, representing the more fine-grained
8802     * movement information available from a trackball).
8803     *
8804     * @param event The motion event.
8805     * @return True if the event was handled, false otherwise.
8806     */
8807    public boolean onTrackballEvent(MotionEvent event) {
8808        return false;
8809    }
8810
8811    /**
8812     * Implement this method to handle generic motion events.
8813     * <p>
8814     * Generic motion events describe joystick movements, mouse hovers, track pad
8815     * touches, scroll wheel movements and other input events.  The
8816     * {@link MotionEvent#getSource() source} of the motion event specifies
8817     * the class of input that was received.  Implementations of this method
8818     * must examine the bits in the source before processing the event.
8819     * The following code example shows how this is done.
8820     * </p><p>
8821     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8822     * are delivered to the view under the pointer.  All other generic motion events are
8823     * delivered to the focused view.
8824     * </p>
8825     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8826     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8827     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8828     *             // process the joystick movement...
8829     *             return true;
8830     *         }
8831     *     }
8832     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8833     *         switch (event.getAction()) {
8834     *             case MotionEvent.ACTION_HOVER_MOVE:
8835     *                 // process the mouse hover movement...
8836     *                 return true;
8837     *             case MotionEvent.ACTION_SCROLL:
8838     *                 // process the scroll wheel movement...
8839     *                 return true;
8840     *         }
8841     *     }
8842     *     return super.onGenericMotionEvent(event);
8843     * }</pre>
8844     *
8845     * @param event The generic motion event being processed.
8846     * @return True if the event was handled, false otherwise.
8847     */
8848    public boolean onGenericMotionEvent(MotionEvent event) {
8849        return false;
8850    }
8851
8852    /**
8853     * Implement this method to handle hover events.
8854     * <p>
8855     * This method is called whenever a pointer is hovering into, over, or out of the
8856     * bounds of a view and the view is not currently being touched.
8857     * Hover events are represented as pointer events with action
8858     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8859     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8860     * </p>
8861     * <ul>
8862     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8863     * when the pointer enters the bounds of the view.</li>
8864     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8865     * when the pointer has already entered the bounds of the view and has moved.</li>
8866     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8867     * when the pointer has exited the bounds of the view or when the pointer is
8868     * about to go down due to a button click, tap, or similar user action that
8869     * causes the view to be touched.</li>
8870     * </ul>
8871     * <p>
8872     * The view should implement this method to return true to indicate that it is
8873     * handling the hover event, such as by changing its drawable state.
8874     * </p><p>
8875     * The default implementation calls {@link #setHovered} to update the hovered state
8876     * of the view when a hover enter or hover exit event is received, if the view
8877     * is enabled and is clickable.  The default implementation also sends hover
8878     * accessibility events.
8879     * </p>
8880     *
8881     * @param event The motion event that describes the hover.
8882     * @return True if the view handled the hover event.
8883     *
8884     * @see #isHovered
8885     * @see #setHovered
8886     * @see #onHoverChanged
8887     */
8888    public boolean onHoverEvent(MotionEvent event) {
8889        // The root view may receive hover (or touch) events that are outside the bounds of
8890        // the window.  This code ensures that we only send accessibility events for
8891        // hovers that are actually within the bounds of the root view.
8892        final int action = event.getActionMasked();
8893        if (!mSendingHoverAccessibilityEvents) {
8894            if ((action == MotionEvent.ACTION_HOVER_ENTER
8895                    || action == MotionEvent.ACTION_HOVER_MOVE)
8896                    && !hasHoveredChild()
8897                    && pointInView(event.getX(), event.getY())) {
8898                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8899                mSendingHoverAccessibilityEvents = true;
8900            }
8901        } else {
8902            if (action == MotionEvent.ACTION_HOVER_EXIT
8903                    || (action == MotionEvent.ACTION_MOVE
8904                            && !pointInView(event.getX(), event.getY()))) {
8905                mSendingHoverAccessibilityEvents = false;
8906                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8907            }
8908        }
8909
8910        if (isHoverable()) {
8911            switch (action) {
8912                case MotionEvent.ACTION_HOVER_ENTER:
8913                    setHovered(true);
8914                    break;
8915                case MotionEvent.ACTION_HOVER_EXIT:
8916                    setHovered(false);
8917                    break;
8918            }
8919
8920            // Dispatch the event to onGenericMotionEvent before returning true.
8921            // This is to provide compatibility with existing applications that
8922            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8923            // break because of the new default handling for hoverable views
8924            // in onHoverEvent.
8925            // Note that onGenericMotionEvent will be called by default when
8926            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8927            dispatchGenericMotionEventInternal(event);
8928            // The event was already handled by calling setHovered(), so always
8929            // return true.
8930            return true;
8931        }
8932
8933        return false;
8934    }
8935
8936    /**
8937     * Returns true if the view should handle {@link #onHoverEvent}
8938     * by calling {@link #setHovered} to change its hovered state.
8939     *
8940     * @return True if the view is hoverable.
8941     */
8942    private boolean isHoverable() {
8943        final int viewFlags = mViewFlags;
8944        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8945            return false;
8946        }
8947
8948        return (viewFlags & CLICKABLE) == CLICKABLE
8949                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8950    }
8951
8952    /**
8953     * Returns true if the view is currently hovered.
8954     *
8955     * @return True if the view is currently hovered.
8956     *
8957     * @see #setHovered
8958     * @see #onHoverChanged
8959     */
8960    @ViewDebug.ExportedProperty
8961    public boolean isHovered() {
8962        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8963    }
8964
8965    /**
8966     * Sets whether the view is currently hovered.
8967     * <p>
8968     * Calling this method also changes the drawable state of the view.  This
8969     * enables the view to react to hover by using different drawable resources
8970     * to change its appearance.
8971     * </p><p>
8972     * The {@link #onHoverChanged} method is called when the hovered state changes.
8973     * </p>
8974     *
8975     * @param hovered True if the view is hovered.
8976     *
8977     * @see #isHovered
8978     * @see #onHoverChanged
8979     */
8980    public void setHovered(boolean hovered) {
8981        if (hovered) {
8982            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8983                mPrivateFlags |= PFLAG_HOVERED;
8984                refreshDrawableState();
8985                onHoverChanged(true);
8986            }
8987        } else {
8988            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8989                mPrivateFlags &= ~PFLAG_HOVERED;
8990                refreshDrawableState();
8991                onHoverChanged(false);
8992            }
8993        }
8994    }
8995
8996    /**
8997     * Implement this method to handle hover state changes.
8998     * <p>
8999     * This method is called whenever the hover state changes as a result of a
9000     * call to {@link #setHovered}.
9001     * </p>
9002     *
9003     * @param hovered The current hover state, as returned by {@link #isHovered}.
9004     *
9005     * @see #isHovered
9006     * @see #setHovered
9007     */
9008    public void onHoverChanged(boolean hovered) {
9009    }
9010
9011    /**
9012     * Implement this method to handle touch screen motion events.
9013     * <p>
9014     * If this method is used to detect click actions, it is recommended that
9015     * the actions be performed by implementing and calling
9016     * {@link #performClick()}. This will ensure consistent system behavior,
9017     * including:
9018     * <ul>
9019     * <li>obeying click sound preferences
9020     * <li>dispatching OnClickListener calls
9021     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9022     * accessibility features are enabled
9023     * </ul>
9024     *
9025     * @param event The motion event.
9026     * @return True if the event was handled, false otherwise.
9027     */
9028    public boolean onTouchEvent(MotionEvent event) {
9029        final float x = event.getX();
9030        final float y = event.getY();
9031        final int viewFlags = mViewFlags;
9032
9033        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9034            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9035                setPressed(false);
9036            }
9037            // A disabled view that is clickable still consumes the touch
9038            // events, it just doesn't respond to them.
9039            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9040                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9041        }
9042
9043        if (mTouchDelegate != null) {
9044            if (mTouchDelegate.onTouchEvent(event)) {
9045                return true;
9046            }
9047        }
9048
9049        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9050                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9051            switch (event.getAction()) {
9052                case MotionEvent.ACTION_UP:
9053                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9054                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9055                        // take focus if we don't have it already and we should in
9056                        // touch mode.
9057                        boolean focusTaken = false;
9058                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9059                            focusTaken = requestFocus();
9060                        }
9061
9062                        if (prepressed) {
9063                            // The button is being released before we actually
9064                            // showed it as pressed.  Make it show the pressed
9065                            // state now (before scheduling the click) to ensure
9066                            // the user sees it.
9067                            setPressed(true, x, y);
9068                       }
9069
9070                        if (!mHasPerformedLongPress) {
9071                            // This is a tap, so remove the longpress check
9072                            removeLongPressCallback();
9073
9074                            // Only perform take click actions if we were in the pressed state
9075                            if (!focusTaken) {
9076                                // Use a Runnable and post this rather than calling
9077                                // performClick directly. This lets other visual state
9078                                // of the view update before click actions start.
9079                                if (mPerformClick == null) {
9080                                    mPerformClick = new PerformClick();
9081                                }
9082                                if (!post(mPerformClick)) {
9083                                    performClick();
9084                                }
9085                            }
9086                        }
9087
9088                        if (mUnsetPressedState == null) {
9089                            mUnsetPressedState = new UnsetPressedState();
9090                        }
9091
9092                        if (prepressed) {
9093                            postDelayed(mUnsetPressedState,
9094                                    ViewConfiguration.getPressedStateDuration());
9095                        } else if (!post(mUnsetPressedState)) {
9096                            // If the post failed, unpress right now
9097                            mUnsetPressedState.run();
9098                        }
9099
9100                        removeTapCallback();
9101                    }
9102                    break;
9103
9104                case MotionEvent.ACTION_DOWN:
9105                    mHasPerformedLongPress = false;
9106
9107                    if (performButtonActionOnTouchDown(event)) {
9108                        break;
9109                    }
9110
9111                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9112                    boolean isInScrollingContainer = isInScrollingContainer();
9113
9114                    // For views inside a scrolling container, delay the pressed feedback for
9115                    // a short period in case this is a scroll.
9116                    if (isInScrollingContainer) {
9117                        mPrivateFlags |= PFLAG_PREPRESSED;
9118                        if (mPendingCheckForTap == null) {
9119                            mPendingCheckForTap = new CheckForTap();
9120                        }
9121                        mPendingCheckForTap.x = event.getX();
9122                        mPendingCheckForTap.y = event.getY();
9123                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9124                    } else {
9125                        // Not inside a scrolling container, so show the feedback right away
9126                        setPressed(true, x, y);
9127                        checkForLongClick(0);
9128                    }
9129                    break;
9130
9131                case MotionEvent.ACTION_CANCEL:
9132                    setPressed(false);
9133                    removeTapCallback();
9134                    removeLongPressCallback();
9135                    break;
9136
9137                case MotionEvent.ACTION_MOVE:
9138                    drawableHotspotChanged(x, y);
9139
9140                    // Be lenient about moving outside of buttons
9141                    if (!pointInView(x, y, mTouchSlop)) {
9142                        // Outside button
9143                        removeTapCallback();
9144                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9145                            // Remove any future long press/tap checks
9146                            removeLongPressCallback();
9147
9148                            setPressed(false);
9149                        }
9150                    }
9151                    break;
9152            }
9153
9154            return true;
9155        }
9156
9157        return false;
9158    }
9159
9160    /**
9161     * @hide
9162     */
9163    public boolean isInScrollingContainer() {
9164        ViewParent p = getParent();
9165        while (p != null && p instanceof ViewGroup) {
9166            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9167                return true;
9168            }
9169            p = p.getParent();
9170        }
9171        return false;
9172    }
9173
9174    /**
9175     * Remove the longpress detection timer.
9176     */
9177    private void removeLongPressCallback() {
9178        if (mPendingCheckForLongPress != null) {
9179          removeCallbacks(mPendingCheckForLongPress);
9180        }
9181    }
9182
9183    /**
9184     * Remove the pending click action
9185     */
9186    private void removePerformClickCallback() {
9187        if (mPerformClick != null) {
9188            removeCallbacks(mPerformClick);
9189        }
9190    }
9191
9192    /**
9193     * Remove the prepress detection timer.
9194     */
9195    private void removeUnsetPressCallback() {
9196        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9197            setPressed(false);
9198            removeCallbacks(mUnsetPressedState);
9199        }
9200    }
9201
9202    /**
9203     * Remove the tap detection timer.
9204     */
9205    private void removeTapCallback() {
9206        if (mPendingCheckForTap != null) {
9207            mPrivateFlags &= ~PFLAG_PREPRESSED;
9208            removeCallbacks(mPendingCheckForTap);
9209        }
9210    }
9211
9212    /**
9213     * Cancels a pending long press.  Your subclass can use this if you
9214     * want the context menu to come up if the user presses and holds
9215     * at the same place, but you don't want it to come up if they press
9216     * and then move around enough to cause scrolling.
9217     */
9218    public void cancelLongPress() {
9219        removeLongPressCallback();
9220
9221        /*
9222         * The prepressed state handled by the tap callback is a display
9223         * construct, but the tap callback will post a long press callback
9224         * less its own timeout. Remove it here.
9225         */
9226        removeTapCallback();
9227    }
9228
9229    /**
9230     * Remove the pending callback for sending a
9231     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9232     */
9233    private void removeSendViewScrolledAccessibilityEventCallback() {
9234        if (mSendViewScrolledAccessibilityEvent != null) {
9235            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9236            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9237        }
9238    }
9239
9240    /**
9241     * Sets the TouchDelegate for this View.
9242     */
9243    public void setTouchDelegate(TouchDelegate delegate) {
9244        mTouchDelegate = delegate;
9245    }
9246
9247    /**
9248     * Gets the TouchDelegate for this View.
9249     */
9250    public TouchDelegate getTouchDelegate() {
9251        return mTouchDelegate;
9252    }
9253
9254    /**
9255     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9256     *
9257     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9258     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9259     * available. This method should only be called for touch events.
9260     *
9261     * <p class="note">This api is not intended for most applications. Buffered dispatch
9262     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9263     * streams will not improve your input latency. Side effects include: increased latency,
9264     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9265     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9266     * you.</p>
9267     */
9268    public final void requestUnbufferedDispatch(MotionEvent event) {
9269        final int action = event.getAction();
9270        if (mAttachInfo == null
9271                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9272                || !event.isTouchEvent()) {
9273            return;
9274        }
9275        mAttachInfo.mUnbufferedDispatchRequested = true;
9276    }
9277
9278    /**
9279     * Set flags controlling behavior of this view.
9280     *
9281     * @param flags Constant indicating the value which should be set
9282     * @param mask Constant indicating the bit range that should be changed
9283     */
9284    void setFlags(int flags, int mask) {
9285        final boolean accessibilityEnabled =
9286                AccessibilityManager.getInstance(mContext).isEnabled();
9287        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9288
9289        int old = mViewFlags;
9290        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9291
9292        int changed = mViewFlags ^ old;
9293        if (changed == 0) {
9294            return;
9295        }
9296        int privateFlags = mPrivateFlags;
9297
9298        /* Check if the FOCUSABLE bit has changed */
9299        if (((changed & FOCUSABLE_MASK) != 0) &&
9300                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9301            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9302                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9303                /* Give up focus if we are no longer focusable */
9304                clearFocus();
9305            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9306                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9307                /*
9308                 * Tell the view system that we are now available to take focus
9309                 * if no one else already has it.
9310                 */
9311                if (mParent != null) mParent.focusableViewAvailable(this);
9312            }
9313        }
9314
9315        final int newVisibility = flags & VISIBILITY_MASK;
9316        if (newVisibility == VISIBLE) {
9317            if ((changed & VISIBILITY_MASK) != 0) {
9318                /*
9319                 * If this view is becoming visible, invalidate it in case it changed while
9320                 * it was not visible. Marking it drawn ensures that the invalidation will
9321                 * go through.
9322                 */
9323                mPrivateFlags |= PFLAG_DRAWN;
9324                invalidate(true);
9325
9326                needGlobalAttributesUpdate(true);
9327
9328                // a view becoming visible is worth notifying the parent
9329                // about in case nothing has focus.  even if this specific view
9330                // isn't focusable, it may contain something that is, so let
9331                // the root view try to give this focus if nothing else does.
9332                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9333                    mParent.focusableViewAvailable(this);
9334                }
9335            }
9336        }
9337
9338        /* Check if the GONE bit has changed */
9339        if ((changed & GONE) != 0) {
9340            needGlobalAttributesUpdate(false);
9341            requestLayout();
9342
9343            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9344                if (hasFocus()) clearFocus();
9345                clearAccessibilityFocus();
9346                destroyDrawingCache();
9347                if (mParent instanceof View) {
9348                    // GONE views noop invalidation, so invalidate the parent
9349                    ((View) mParent).invalidate(true);
9350                }
9351                // Mark the view drawn to ensure that it gets invalidated properly the next
9352                // time it is visible and gets invalidated
9353                mPrivateFlags |= PFLAG_DRAWN;
9354            }
9355            if (mAttachInfo != null) {
9356                mAttachInfo.mViewVisibilityChanged = true;
9357            }
9358        }
9359
9360        /* Check if the VISIBLE bit has changed */
9361        if ((changed & INVISIBLE) != 0) {
9362            needGlobalAttributesUpdate(false);
9363            /*
9364             * If this view is becoming invisible, set the DRAWN flag so that
9365             * the next invalidate() will not be skipped.
9366             */
9367            mPrivateFlags |= PFLAG_DRAWN;
9368
9369            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9370                // root view becoming invisible shouldn't clear focus and accessibility focus
9371                if (getRootView() != this) {
9372                    if (hasFocus()) clearFocus();
9373                    clearAccessibilityFocus();
9374                }
9375            }
9376            if (mAttachInfo != null) {
9377                mAttachInfo.mViewVisibilityChanged = true;
9378            }
9379        }
9380
9381        if ((changed & VISIBILITY_MASK) != 0) {
9382            // If the view is invisible, cleanup its display list to free up resources
9383            if (newVisibility != VISIBLE && mAttachInfo != null) {
9384                cleanupDraw();
9385            }
9386
9387            if (mParent instanceof ViewGroup) {
9388                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9389                        (changed & VISIBILITY_MASK), newVisibility);
9390                ((View) mParent).invalidate(true);
9391            } else if (mParent != null) {
9392                mParent.invalidateChild(this, null);
9393            }
9394            dispatchVisibilityChanged(this, newVisibility);
9395
9396            notifySubtreeAccessibilityStateChangedIfNeeded();
9397        }
9398
9399        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9400            destroyDrawingCache();
9401        }
9402
9403        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9404            destroyDrawingCache();
9405            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9406            invalidateParentCaches();
9407        }
9408
9409        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9410            destroyDrawingCache();
9411            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9412        }
9413
9414        if ((changed & DRAW_MASK) != 0) {
9415            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9416                if (mBackground != null) {
9417                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9418                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9419                } else {
9420                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9421                }
9422            } else {
9423                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9424            }
9425            requestLayout();
9426            invalidate(true);
9427        }
9428
9429        if ((changed & KEEP_SCREEN_ON) != 0) {
9430            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9431                mParent.recomputeViewAttributes(this);
9432            }
9433        }
9434
9435        if (accessibilityEnabled) {
9436            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9437                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9438                if (oldIncludeForAccessibility != includeForAccessibility()) {
9439                    notifySubtreeAccessibilityStateChangedIfNeeded();
9440                } else {
9441                    notifyViewAccessibilityStateChangedIfNeeded(
9442                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9443                }
9444            } else if ((changed & ENABLED_MASK) != 0) {
9445                notifyViewAccessibilityStateChangedIfNeeded(
9446                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9447            }
9448        }
9449    }
9450
9451    /**
9452     * Change the view's z order in the tree, so it's on top of other sibling
9453     * views. This ordering change may affect layout, if the parent container
9454     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9455     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9456     * method should be followed by calls to {@link #requestLayout()} and
9457     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9458     * with the new child ordering.
9459     *
9460     * @see ViewGroup#bringChildToFront(View)
9461     */
9462    public void bringToFront() {
9463        if (mParent != null) {
9464            mParent.bringChildToFront(this);
9465        }
9466    }
9467
9468    /**
9469     * This is called in response to an internal scroll in this view (i.e., the
9470     * view scrolled its own contents). This is typically as a result of
9471     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9472     * called.
9473     *
9474     * @param l Current horizontal scroll origin.
9475     * @param t Current vertical scroll origin.
9476     * @param oldl Previous horizontal scroll origin.
9477     * @param oldt Previous vertical scroll origin.
9478     */
9479    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9480        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9481            postSendViewScrolledAccessibilityEventCallback();
9482        }
9483
9484        mBackgroundSizeChanged = true;
9485
9486        final AttachInfo ai = mAttachInfo;
9487        if (ai != null) {
9488            ai.mViewScrollChanged = true;
9489        }
9490    }
9491
9492    /**
9493     * Interface definition for a callback to be invoked when the layout bounds of a view
9494     * changes due to layout processing.
9495     */
9496    public interface OnLayoutChangeListener {
9497        /**
9498         * Called when the layout bounds of a view changes due to layout processing.
9499         *
9500         * @param v The view whose bounds have changed.
9501         * @param left The new value of the view's left property.
9502         * @param top The new value of the view's top property.
9503         * @param right The new value of the view's right property.
9504         * @param bottom The new value of the view's bottom property.
9505         * @param oldLeft The previous value of the view's left property.
9506         * @param oldTop The previous value of the view's top property.
9507         * @param oldRight The previous value of the view's right property.
9508         * @param oldBottom The previous value of the view's bottom property.
9509         */
9510        void onLayoutChange(View v, int left, int top, int right, int bottom,
9511            int oldLeft, int oldTop, int oldRight, int oldBottom);
9512    }
9513
9514    /**
9515     * This is called during layout when the size of this view has changed. If
9516     * you were just added to the view hierarchy, you're called with the old
9517     * values of 0.
9518     *
9519     * @param w Current width of this view.
9520     * @param h Current height of this view.
9521     * @param oldw Old width of this view.
9522     * @param oldh Old height of this view.
9523     */
9524    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9525    }
9526
9527    /**
9528     * Called by draw to draw the child views. This may be overridden
9529     * by derived classes to gain control just before its children are drawn
9530     * (but after its own view has been drawn).
9531     * @param canvas the canvas on which to draw the view
9532     */
9533    protected void dispatchDraw(Canvas canvas) {
9534
9535    }
9536
9537    /**
9538     * Gets the parent of this view. Note that the parent is a
9539     * ViewParent and not necessarily a View.
9540     *
9541     * @return Parent of this view.
9542     */
9543    public final ViewParent getParent() {
9544        return mParent;
9545    }
9546
9547    /**
9548     * Set the horizontal scrolled position of your view. This will cause a call to
9549     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9550     * invalidated.
9551     * @param value the x position to scroll to
9552     */
9553    public void setScrollX(int value) {
9554        scrollTo(value, mScrollY);
9555    }
9556
9557    /**
9558     * Set the vertical scrolled position of your view. This will cause a call to
9559     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9560     * invalidated.
9561     * @param value the y position to scroll to
9562     */
9563    public void setScrollY(int value) {
9564        scrollTo(mScrollX, value);
9565    }
9566
9567    /**
9568     * Return the scrolled left position of this view. This is the left edge of
9569     * the displayed part of your view. You do not need to draw any pixels
9570     * farther left, since those are outside of the frame of your view on
9571     * screen.
9572     *
9573     * @return The left edge of the displayed part of your view, in pixels.
9574     */
9575    public final int getScrollX() {
9576        return mScrollX;
9577    }
9578
9579    /**
9580     * Return the scrolled top position of this view. This is the top edge of
9581     * the displayed part of your view. You do not need to draw any pixels above
9582     * it, since those are outside of the frame of your view on screen.
9583     *
9584     * @return The top edge of the displayed part of your view, in pixels.
9585     */
9586    public final int getScrollY() {
9587        return mScrollY;
9588    }
9589
9590    /**
9591     * Return the width of the your view.
9592     *
9593     * @return The width of your view, in pixels.
9594     */
9595    @ViewDebug.ExportedProperty(category = "layout")
9596    public final int getWidth() {
9597        return mRight - mLeft;
9598    }
9599
9600    /**
9601     * Return the height of your view.
9602     *
9603     * @return The height of your view, in pixels.
9604     */
9605    @ViewDebug.ExportedProperty(category = "layout")
9606    public final int getHeight() {
9607        return mBottom - mTop;
9608    }
9609
9610    /**
9611     * Return the visible drawing bounds of your view. Fills in the output
9612     * rectangle with the values from getScrollX(), getScrollY(),
9613     * getWidth(), and getHeight(). These bounds do not account for any
9614     * transformation properties currently set on the view, such as
9615     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9616     *
9617     * @param outRect The (scrolled) drawing bounds of the view.
9618     */
9619    public void getDrawingRect(Rect outRect) {
9620        outRect.left = mScrollX;
9621        outRect.top = mScrollY;
9622        outRect.right = mScrollX + (mRight - mLeft);
9623        outRect.bottom = mScrollY + (mBottom - mTop);
9624    }
9625
9626    /**
9627     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9628     * raw width component (that is the result is masked by
9629     * {@link #MEASURED_SIZE_MASK}).
9630     *
9631     * @return The raw measured width of this view.
9632     */
9633    public final int getMeasuredWidth() {
9634        return mMeasuredWidth & MEASURED_SIZE_MASK;
9635    }
9636
9637    /**
9638     * Return the full width measurement information for this view as computed
9639     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9640     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9641     * This should be used during measurement and layout calculations only. Use
9642     * {@link #getWidth()} to see how wide a view is after layout.
9643     *
9644     * @return The measured width of this view as a bit mask.
9645     */
9646    public final int getMeasuredWidthAndState() {
9647        return mMeasuredWidth;
9648    }
9649
9650    /**
9651     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9652     * raw width component (that is the result is masked by
9653     * {@link #MEASURED_SIZE_MASK}).
9654     *
9655     * @return The raw measured height of this view.
9656     */
9657    public final int getMeasuredHeight() {
9658        return mMeasuredHeight & MEASURED_SIZE_MASK;
9659    }
9660
9661    /**
9662     * Return the full height measurement information for this view as computed
9663     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9664     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9665     * This should be used during measurement and layout calculations only. Use
9666     * {@link #getHeight()} to see how wide a view is after layout.
9667     *
9668     * @return The measured width of this view as a bit mask.
9669     */
9670    public final int getMeasuredHeightAndState() {
9671        return mMeasuredHeight;
9672    }
9673
9674    /**
9675     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9676     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9677     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9678     * and the height component is at the shifted bits
9679     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9680     */
9681    public final int getMeasuredState() {
9682        return (mMeasuredWidth&MEASURED_STATE_MASK)
9683                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9684                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9685    }
9686
9687    /**
9688     * The transform matrix of this view, which is calculated based on the current
9689     * rotation, scale, and pivot properties.
9690     *
9691     * @see #getRotation()
9692     * @see #getScaleX()
9693     * @see #getScaleY()
9694     * @see #getPivotX()
9695     * @see #getPivotY()
9696     * @return The current transform matrix for the view
9697     */
9698    public Matrix getMatrix() {
9699        ensureTransformationInfo();
9700        final Matrix matrix = mTransformationInfo.mMatrix;
9701        mRenderNode.getMatrix(matrix);
9702        return matrix;
9703    }
9704
9705    /**
9706     * Returns true if the transform matrix is the identity matrix.
9707     * Recomputes the matrix if necessary.
9708     *
9709     * @return True if the transform matrix is the identity matrix, false otherwise.
9710     */
9711    final boolean hasIdentityMatrix() {
9712        return mRenderNode.hasIdentityMatrix();
9713    }
9714
9715    void ensureTransformationInfo() {
9716        if (mTransformationInfo == null) {
9717            mTransformationInfo = new TransformationInfo();
9718        }
9719    }
9720
9721   /**
9722     * Utility method to retrieve the inverse of the current mMatrix property.
9723     * We cache the matrix to avoid recalculating it when transform properties
9724     * have not changed.
9725     *
9726     * @return The inverse of the current matrix of this view.
9727     */
9728    final Matrix getInverseMatrix() {
9729        ensureTransformationInfo();
9730        if (mTransformationInfo.mInverseMatrix == null) {
9731            mTransformationInfo.mInverseMatrix = new Matrix();
9732        }
9733        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9734        mRenderNode.getInverseMatrix(matrix);
9735        return matrix;
9736    }
9737
9738    /**
9739     * Gets the distance along the Z axis from the camera to this view.
9740     *
9741     * @see #setCameraDistance(float)
9742     *
9743     * @return The distance along the Z axis.
9744     */
9745    public float getCameraDistance() {
9746        final float dpi = mResources.getDisplayMetrics().densityDpi;
9747        return -(mRenderNode.getCameraDistance() * dpi);
9748    }
9749
9750    /**
9751     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9752     * views are drawn) from the camera to this view. The camera's distance
9753     * affects 3D transformations, for instance rotations around the X and Y
9754     * axis. If the rotationX or rotationY properties are changed and this view is
9755     * large (more than half the size of the screen), it is recommended to always
9756     * use a camera distance that's greater than the height (X axis rotation) or
9757     * the width (Y axis rotation) of this view.</p>
9758     *
9759     * <p>The distance of the camera from the view plane can have an affect on the
9760     * perspective distortion of the view when it is rotated around the x or y axis.
9761     * For example, a large distance will result in a large viewing angle, and there
9762     * will not be much perspective distortion of the view as it rotates. A short
9763     * distance may cause much more perspective distortion upon rotation, and can
9764     * also result in some drawing artifacts if the rotated view ends up partially
9765     * behind the camera (which is why the recommendation is to use a distance at
9766     * least as far as the size of the view, if the view is to be rotated.)</p>
9767     *
9768     * <p>The distance is expressed in "depth pixels." The default distance depends
9769     * on the screen density. For instance, on a medium density display, the
9770     * default distance is 1280. On a high density display, the default distance
9771     * is 1920.</p>
9772     *
9773     * <p>If you want to specify a distance that leads to visually consistent
9774     * results across various densities, use the following formula:</p>
9775     * <pre>
9776     * float scale = context.getResources().getDisplayMetrics().density;
9777     * view.setCameraDistance(distance * scale);
9778     * </pre>
9779     *
9780     * <p>The density scale factor of a high density display is 1.5,
9781     * and 1920 = 1280 * 1.5.</p>
9782     *
9783     * @param distance The distance in "depth pixels", if negative the opposite
9784     *        value is used
9785     *
9786     * @see #setRotationX(float)
9787     * @see #setRotationY(float)
9788     */
9789    public void setCameraDistance(float distance) {
9790        final float dpi = mResources.getDisplayMetrics().densityDpi;
9791
9792        invalidateViewProperty(true, false);
9793        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9794        invalidateViewProperty(false, false);
9795
9796        invalidateParentIfNeededAndWasQuickRejected();
9797    }
9798
9799    /**
9800     * The degrees that the view is rotated around the pivot point.
9801     *
9802     * @see #setRotation(float)
9803     * @see #getPivotX()
9804     * @see #getPivotY()
9805     *
9806     * @return The degrees of rotation.
9807     */
9808    @ViewDebug.ExportedProperty(category = "drawing")
9809    public float getRotation() {
9810        return mRenderNode.getRotation();
9811    }
9812
9813    /**
9814     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9815     * result in clockwise rotation.
9816     *
9817     * @param rotation The degrees of rotation.
9818     *
9819     * @see #getRotation()
9820     * @see #getPivotX()
9821     * @see #getPivotY()
9822     * @see #setRotationX(float)
9823     * @see #setRotationY(float)
9824     *
9825     * @attr ref android.R.styleable#View_rotation
9826     */
9827    public void setRotation(float rotation) {
9828        if (rotation != getRotation()) {
9829            // Double-invalidation is necessary to capture view's old and new areas
9830            invalidateViewProperty(true, false);
9831            mRenderNode.setRotation(rotation);
9832            invalidateViewProperty(false, true);
9833
9834            invalidateParentIfNeededAndWasQuickRejected();
9835            notifySubtreeAccessibilityStateChangedIfNeeded();
9836        }
9837    }
9838
9839    /**
9840     * The degrees that the view is rotated around the vertical axis through the pivot point.
9841     *
9842     * @see #getPivotX()
9843     * @see #getPivotY()
9844     * @see #setRotationY(float)
9845     *
9846     * @return The degrees of Y rotation.
9847     */
9848    @ViewDebug.ExportedProperty(category = "drawing")
9849    public float getRotationY() {
9850        return mRenderNode.getRotationY();
9851    }
9852
9853    /**
9854     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9855     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9856     * down the y axis.
9857     *
9858     * When rotating large views, it is recommended to adjust the camera distance
9859     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9860     *
9861     * @param rotationY The degrees of Y rotation.
9862     *
9863     * @see #getRotationY()
9864     * @see #getPivotX()
9865     * @see #getPivotY()
9866     * @see #setRotation(float)
9867     * @see #setRotationX(float)
9868     * @see #setCameraDistance(float)
9869     *
9870     * @attr ref android.R.styleable#View_rotationY
9871     */
9872    public void setRotationY(float rotationY) {
9873        if (rotationY != getRotationY()) {
9874            invalidateViewProperty(true, false);
9875            mRenderNode.setRotationY(rotationY);
9876            invalidateViewProperty(false, true);
9877
9878            invalidateParentIfNeededAndWasQuickRejected();
9879            notifySubtreeAccessibilityStateChangedIfNeeded();
9880        }
9881    }
9882
9883    /**
9884     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9885     *
9886     * @see #getPivotX()
9887     * @see #getPivotY()
9888     * @see #setRotationX(float)
9889     *
9890     * @return The degrees of X rotation.
9891     */
9892    @ViewDebug.ExportedProperty(category = "drawing")
9893    public float getRotationX() {
9894        return mRenderNode.getRotationX();
9895    }
9896
9897    /**
9898     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9899     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9900     * x axis.
9901     *
9902     * When rotating large views, it is recommended to adjust the camera distance
9903     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9904     *
9905     * @param rotationX The degrees of X rotation.
9906     *
9907     * @see #getRotationX()
9908     * @see #getPivotX()
9909     * @see #getPivotY()
9910     * @see #setRotation(float)
9911     * @see #setRotationY(float)
9912     * @see #setCameraDistance(float)
9913     *
9914     * @attr ref android.R.styleable#View_rotationX
9915     */
9916    public void setRotationX(float rotationX) {
9917        if (rotationX != getRotationX()) {
9918            invalidateViewProperty(true, false);
9919            mRenderNode.setRotationX(rotationX);
9920            invalidateViewProperty(false, true);
9921
9922            invalidateParentIfNeededAndWasQuickRejected();
9923            notifySubtreeAccessibilityStateChangedIfNeeded();
9924        }
9925    }
9926
9927    /**
9928     * The amount that the view is scaled in x around the pivot point, as a proportion of
9929     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9930     *
9931     * <p>By default, this is 1.0f.
9932     *
9933     * @see #getPivotX()
9934     * @see #getPivotY()
9935     * @return The scaling factor.
9936     */
9937    @ViewDebug.ExportedProperty(category = "drawing")
9938    public float getScaleX() {
9939        return mRenderNode.getScaleX();
9940    }
9941
9942    /**
9943     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9944     * the view's unscaled width. A value of 1 means that no scaling is applied.
9945     *
9946     * @param scaleX The scaling factor.
9947     * @see #getPivotX()
9948     * @see #getPivotY()
9949     *
9950     * @attr ref android.R.styleable#View_scaleX
9951     */
9952    public void setScaleX(float scaleX) {
9953        if (scaleX != getScaleX()) {
9954            invalidateViewProperty(true, false);
9955            mRenderNode.setScaleX(scaleX);
9956            invalidateViewProperty(false, true);
9957
9958            invalidateParentIfNeededAndWasQuickRejected();
9959            notifySubtreeAccessibilityStateChangedIfNeeded();
9960        }
9961    }
9962
9963    /**
9964     * The amount that the view is scaled in y around the pivot point, as a proportion of
9965     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9966     *
9967     * <p>By default, this is 1.0f.
9968     *
9969     * @see #getPivotX()
9970     * @see #getPivotY()
9971     * @return The scaling factor.
9972     */
9973    @ViewDebug.ExportedProperty(category = "drawing")
9974    public float getScaleY() {
9975        return mRenderNode.getScaleY();
9976    }
9977
9978    /**
9979     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9980     * the view's unscaled width. A value of 1 means that no scaling is applied.
9981     *
9982     * @param scaleY The scaling factor.
9983     * @see #getPivotX()
9984     * @see #getPivotY()
9985     *
9986     * @attr ref android.R.styleable#View_scaleY
9987     */
9988    public void setScaleY(float scaleY) {
9989        if (scaleY != getScaleY()) {
9990            invalidateViewProperty(true, false);
9991            mRenderNode.setScaleY(scaleY);
9992            invalidateViewProperty(false, true);
9993
9994            invalidateParentIfNeededAndWasQuickRejected();
9995            notifySubtreeAccessibilityStateChangedIfNeeded();
9996        }
9997    }
9998
9999    /**
10000     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10001     * and {@link #setScaleX(float) scaled}.
10002     *
10003     * @see #getRotation()
10004     * @see #getScaleX()
10005     * @see #getScaleY()
10006     * @see #getPivotY()
10007     * @return The x location of the pivot point.
10008     *
10009     * @attr ref android.R.styleable#View_transformPivotX
10010     */
10011    @ViewDebug.ExportedProperty(category = "drawing")
10012    public float getPivotX() {
10013        return mRenderNode.getPivotX();
10014    }
10015
10016    /**
10017     * Sets the x location of the point around which the view is
10018     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10019     * By default, the pivot point is centered on the object.
10020     * Setting this property disables this behavior and causes the view to use only the
10021     * explicitly set pivotX and pivotY values.
10022     *
10023     * @param pivotX The x location of the pivot point.
10024     * @see #getRotation()
10025     * @see #getScaleX()
10026     * @see #getScaleY()
10027     * @see #getPivotY()
10028     *
10029     * @attr ref android.R.styleable#View_transformPivotX
10030     */
10031    public void setPivotX(float pivotX) {
10032        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10033            invalidateViewProperty(true, false);
10034            mRenderNode.setPivotX(pivotX);
10035            invalidateViewProperty(false, true);
10036
10037            invalidateParentIfNeededAndWasQuickRejected();
10038        }
10039    }
10040
10041    /**
10042     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10043     * and {@link #setScaleY(float) scaled}.
10044     *
10045     * @see #getRotation()
10046     * @see #getScaleX()
10047     * @see #getScaleY()
10048     * @see #getPivotY()
10049     * @return The y location of the pivot point.
10050     *
10051     * @attr ref android.R.styleable#View_transformPivotY
10052     */
10053    @ViewDebug.ExportedProperty(category = "drawing")
10054    public float getPivotY() {
10055        return mRenderNode.getPivotY();
10056    }
10057
10058    /**
10059     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10060     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10061     * Setting this property disables this behavior and causes the view to use only the
10062     * explicitly set pivotX and pivotY values.
10063     *
10064     * @param pivotY The y location of the pivot point.
10065     * @see #getRotation()
10066     * @see #getScaleX()
10067     * @see #getScaleY()
10068     * @see #getPivotY()
10069     *
10070     * @attr ref android.R.styleable#View_transformPivotY
10071     */
10072    public void setPivotY(float pivotY) {
10073        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10074            invalidateViewProperty(true, false);
10075            mRenderNode.setPivotY(pivotY);
10076            invalidateViewProperty(false, true);
10077
10078            invalidateParentIfNeededAndWasQuickRejected();
10079        }
10080    }
10081
10082    /**
10083     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10084     * completely transparent and 1 means the view is completely opaque.
10085     *
10086     * <p>By default this is 1.0f.
10087     * @return The opacity of the view.
10088     */
10089    @ViewDebug.ExportedProperty(category = "drawing")
10090    public float getAlpha() {
10091        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10092    }
10093
10094    /**
10095     * Returns whether this View has content which overlaps.
10096     *
10097     * <p>This function, intended to be overridden by specific View types, is an optimization when
10098     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10099     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10100     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10101     * directly. An example of overlapping rendering is a TextView with a background image, such as
10102     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10103     * ImageView with only the foreground image. The default implementation returns true; subclasses
10104     * should override if they have cases which can be optimized.</p>
10105     *
10106     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10107     * necessitates that a View return true if it uses the methods internally without passing the
10108     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10109     *
10110     * @return true if the content in this view might overlap, false otherwise.
10111     */
10112    public boolean hasOverlappingRendering() {
10113        return true;
10114    }
10115
10116    /**
10117     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10118     * completely transparent and 1 means the view is completely opaque.</p>
10119     *
10120     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10121     * performance implications, especially for large views. It is best to use the alpha property
10122     * sparingly and transiently, as in the case of fading animations.</p>
10123     *
10124     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10125     * strongly recommended for performance reasons to either override
10126     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10127     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10128     *
10129     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10130     * responsible for applying the opacity itself.</p>
10131     *
10132     * <p>Note that if the view is backed by a
10133     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10134     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10135     * 1.0 will supercede the alpha of the layer paint.</p>
10136     *
10137     * @param alpha The opacity of the view.
10138     *
10139     * @see #hasOverlappingRendering()
10140     * @see #setLayerType(int, android.graphics.Paint)
10141     *
10142     * @attr ref android.R.styleable#View_alpha
10143     */
10144    public void setAlpha(float alpha) {
10145        ensureTransformationInfo();
10146        if (mTransformationInfo.mAlpha != alpha) {
10147            mTransformationInfo.mAlpha = alpha;
10148            if (onSetAlpha((int) (alpha * 255))) {
10149                mPrivateFlags |= PFLAG_ALPHA_SET;
10150                // subclass is handling alpha - don't optimize rendering cache invalidation
10151                invalidateParentCaches();
10152                invalidate(true);
10153            } else {
10154                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10155                invalidateViewProperty(true, false);
10156                mRenderNode.setAlpha(getFinalAlpha());
10157                notifyViewAccessibilityStateChangedIfNeeded(
10158                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10159            }
10160        }
10161    }
10162
10163    /**
10164     * Faster version of setAlpha() which performs the same steps except there are
10165     * no calls to invalidate(). The caller of this function should perform proper invalidation
10166     * on the parent and this object. The return value indicates whether the subclass handles
10167     * alpha (the return value for onSetAlpha()).
10168     *
10169     * @param alpha The new value for the alpha property
10170     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10171     *         the new value for the alpha property is different from the old value
10172     */
10173    boolean setAlphaNoInvalidation(float alpha) {
10174        ensureTransformationInfo();
10175        if (mTransformationInfo.mAlpha != alpha) {
10176            mTransformationInfo.mAlpha = alpha;
10177            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10178            if (subclassHandlesAlpha) {
10179                mPrivateFlags |= PFLAG_ALPHA_SET;
10180                return true;
10181            } else {
10182                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10183                mRenderNode.setAlpha(getFinalAlpha());
10184            }
10185        }
10186        return false;
10187    }
10188
10189    /**
10190     * This property is hidden and intended only for use by the Fade transition, which
10191     * animates it to produce a visual translucency that does not side-effect (or get
10192     * affected by) the real alpha property. This value is composited with the other
10193     * alpha value (and the AlphaAnimation value, when that is present) to produce
10194     * a final visual translucency result, which is what is passed into the DisplayList.
10195     *
10196     * @hide
10197     */
10198    public void setTransitionAlpha(float alpha) {
10199        ensureTransformationInfo();
10200        if (mTransformationInfo.mTransitionAlpha != alpha) {
10201            mTransformationInfo.mTransitionAlpha = alpha;
10202            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10203            invalidateViewProperty(true, false);
10204            mRenderNode.setAlpha(getFinalAlpha());
10205        }
10206    }
10207
10208    /**
10209     * Calculates the visual alpha of this view, which is a combination of the actual
10210     * alpha value and the transitionAlpha value (if set).
10211     */
10212    private float getFinalAlpha() {
10213        if (mTransformationInfo != null) {
10214            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10215        }
10216        return 1;
10217    }
10218
10219    /**
10220     * This property is hidden and intended only for use by the Fade transition, which
10221     * animates it to produce a visual translucency that does not side-effect (or get
10222     * affected by) the real alpha property. This value is composited with the other
10223     * alpha value (and the AlphaAnimation value, when that is present) to produce
10224     * a final visual translucency result, which is what is passed into the DisplayList.
10225     *
10226     * @hide
10227     */
10228    public float getTransitionAlpha() {
10229        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10230    }
10231
10232    /**
10233     * Top position of this view relative to its parent.
10234     *
10235     * @return The top of this view, in pixels.
10236     */
10237    @ViewDebug.CapturedViewProperty
10238    public final int getTop() {
10239        return mTop;
10240    }
10241
10242    /**
10243     * Sets the top position of this view relative to its parent. This method is meant to be called
10244     * by the layout system and should not generally be called otherwise, because the property
10245     * may be changed at any time by the layout.
10246     *
10247     * @param top The top of this view, in pixels.
10248     */
10249    public final void setTop(int top) {
10250        if (top != mTop) {
10251            final boolean matrixIsIdentity = hasIdentityMatrix();
10252            if (matrixIsIdentity) {
10253                if (mAttachInfo != null) {
10254                    int minTop;
10255                    int yLoc;
10256                    if (top < mTop) {
10257                        minTop = top;
10258                        yLoc = top - mTop;
10259                    } else {
10260                        minTop = mTop;
10261                        yLoc = 0;
10262                    }
10263                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10264                }
10265            } else {
10266                // Double-invalidation is necessary to capture view's old and new areas
10267                invalidate(true);
10268            }
10269
10270            int width = mRight - mLeft;
10271            int oldHeight = mBottom - mTop;
10272
10273            mTop = top;
10274            mRenderNode.setTop(mTop);
10275
10276            sizeChange(width, mBottom - mTop, width, oldHeight);
10277
10278            if (!matrixIsIdentity) {
10279                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10280                invalidate(true);
10281            }
10282            mBackgroundSizeChanged = true;
10283            invalidateParentIfNeeded();
10284            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10285                // View was rejected last time it was drawn by its parent; this may have changed
10286                invalidateParentIfNeeded();
10287            }
10288        }
10289    }
10290
10291    /**
10292     * Bottom position of this view relative to its parent.
10293     *
10294     * @return The bottom of this view, in pixels.
10295     */
10296    @ViewDebug.CapturedViewProperty
10297    public final int getBottom() {
10298        return mBottom;
10299    }
10300
10301    /**
10302     * True if this view has changed since the last time being drawn.
10303     *
10304     * @return The dirty state of this view.
10305     */
10306    public boolean isDirty() {
10307        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10308    }
10309
10310    /**
10311     * Sets the bottom position of this view relative to its parent. This method is meant to be
10312     * called by the layout system and should not generally be called otherwise, because the
10313     * property may be changed at any time by the layout.
10314     *
10315     * @param bottom The bottom of this view, in pixels.
10316     */
10317    public final void setBottom(int bottom) {
10318        if (bottom != mBottom) {
10319            final boolean matrixIsIdentity = hasIdentityMatrix();
10320            if (matrixIsIdentity) {
10321                if (mAttachInfo != null) {
10322                    int maxBottom;
10323                    if (bottom < mBottom) {
10324                        maxBottom = mBottom;
10325                    } else {
10326                        maxBottom = bottom;
10327                    }
10328                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10329                }
10330            } else {
10331                // Double-invalidation is necessary to capture view's old and new areas
10332                invalidate(true);
10333            }
10334
10335            int width = mRight - mLeft;
10336            int oldHeight = mBottom - mTop;
10337
10338            mBottom = bottom;
10339            mRenderNode.setBottom(mBottom);
10340
10341            sizeChange(width, mBottom - mTop, width, oldHeight);
10342
10343            if (!matrixIsIdentity) {
10344                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10345                invalidate(true);
10346            }
10347            mBackgroundSizeChanged = true;
10348            invalidateParentIfNeeded();
10349            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10350                // View was rejected last time it was drawn by its parent; this may have changed
10351                invalidateParentIfNeeded();
10352            }
10353        }
10354    }
10355
10356    /**
10357     * Left position of this view relative to its parent.
10358     *
10359     * @return The left edge of this view, in pixels.
10360     */
10361    @ViewDebug.CapturedViewProperty
10362    public final int getLeft() {
10363        return mLeft;
10364    }
10365
10366    /**
10367     * Sets the left position of this view relative to its parent. This method is meant to be called
10368     * by the layout system and should not generally be called otherwise, because the property
10369     * may be changed at any time by the layout.
10370     *
10371     * @param left The left of this view, in pixels.
10372     */
10373    public final void setLeft(int left) {
10374        if (left != mLeft) {
10375            final boolean matrixIsIdentity = hasIdentityMatrix();
10376            if (matrixIsIdentity) {
10377                if (mAttachInfo != null) {
10378                    int minLeft;
10379                    int xLoc;
10380                    if (left < mLeft) {
10381                        minLeft = left;
10382                        xLoc = left - mLeft;
10383                    } else {
10384                        minLeft = mLeft;
10385                        xLoc = 0;
10386                    }
10387                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10388                }
10389            } else {
10390                // Double-invalidation is necessary to capture view's old and new areas
10391                invalidate(true);
10392            }
10393
10394            int oldWidth = mRight - mLeft;
10395            int height = mBottom - mTop;
10396
10397            mLeft = left;
10398            mRenderNode.setLeft(left);
10399
10400            sizeChange(mRight - mLeft, height, oldWidth, height);
10401
10402            if (!matrixIsIdentity) {
10403                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10404                invalidate(true);
10405            }
10406            mBackgroundSizeChanged = true;
10407            invalidateParentIfNeeded();
10408            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10409                // View was rejected last time it was drawn by its parent; this may have changed
10410                invalidateParentIfNeeded();
10411            }
10412        }
10413    }
10414
10415    /**
10416     * Right position of this view relative to its parent.
10417     *
10418     * @return The right edge of this view, in pixels.
10419     */
10420    @ViewDebug.CapturedViewProperty
10421    public final int getRight() {
10422        return mRight;
10423    }
10424
10425    /**
10426     * Sets the right position of this view relative to its parent. This method is meant to be called
10427     * by the layout system and should not generally be called otherwise, because the property
10428     * may be changed at any time by the layout.
10429     *
10430     * @param right The right of this view, in pixels.
10431     */
10432    public final void setRight(int right) {
10433        if (right != mRight) {
10434            final boolean matrixIsIdentity = hasIdentityMatrix();
10435            if (matrixIsIdentity) {
10436                if (mAttachInfo != null) {
10437                    int maxRight;
10438                    if (right < mRight) {
10439                        maxRight = mRight;
10440                    } else {
10441                        maxRight = right;
10442                    }
10443                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10444                }
10445            } else {
10446                // Double-invalidation is necessary to capture view's old and new areas
10447                invalidate(true);
10448            }
10449
10450            int oldWidth = mRight - mLeft;
10451            int height = mBottom - mTop;
10452
10453            mRight = right;
10454            mRenderNode.setRight(mRight);
10455
10456            sizeChange(mRight - mLeft, height, oldWidth, height);
10457
10458            if (!matrixIsIdentity) {
10459                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10460                invalidate(true);
10461            }
10462            mBackgroundSizeChanged = true;
10463            invalidateParentIfNeeded();
10464            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10465                // View was rejected last time it was drawn by its parent; this may have changed
10466                invalidateParentIfNeeded();
10467            }
10468        }
10469    }
10470
10471    /**
10472     * The visual x position of this view, in pixels. This is equivalent to the
10473     * {@link #setTranslationX(float) translationX} property plus the current
10474     * {@link #getLeft() left} property.
10475     *
10476     * @return The visual x position of this view, in pixels.
10477     */
10478    @ViewDebug.ExportedProperty(category = "drawing")
10479    public float getX() {
10480        return mLeft + getTranslationX();
10481    }
10482
10483    /**
10484     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10485     * {@link #setTranslationX(float) translationX} property to be the difference between
10486     * the x value passed in and the current {@link #getLeft() left} property.
10487     *
10488     * @param x The visual x position of this view, in pixels.
10489     */
10490    public void setX(float x) {
10491        setTranslationX(x - mLeft);
10492    }
10493
10494    /**
10495     * The visual y position of this view, in pixels. This is equivalent to the
10496     * {@link #setTranslationY(float) translationY} property plus the current
10497     * {@link #getTop() top} property.
10498     *
10499     * @return The visual y position of this view, in pixels.
10500     */
10501    @ViewDebug.ExportedProperty(category = "drawing")
10502    public float getY() {
10503        return mTop + getTranslationY();
10504    }
10505
10506    /**
10507     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10508     * {@link #setTranslationY(float) translationY} property to be the difference between
10509     * the y value passed in and the current {@link #getTop() top} property.
10510     *
10511     * @param y The visual y position of this view, in pixels.
10512     */
10513    public void setY(float y) {
10514        setTranslationY(y - mTop);
10515    }
10516
10517    /**
10518     * The visual z position of this view, in pixels. This is equivalent to the
10519     * {@link #setTranslationZ(float) translationZ} property plus the current
10520     * {@link #getElevation() elevation} property.
10521     *
10522     * @return The visual z position of this view, in pixels.
10523     */
10524    @ViewDebug.ExportedProperty(category = "drawing")
10525    public float getZ() {
10526        return getElevation() + getTranslationZ();
10527    }
10528
10529    /**
10530     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10531     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10532     * the x value passed in and the current {@link #getElevation() elevation} property.
10533     *
10534     * @param z The visual z position of this view, in pixels.
10535     */
10536    public void setZ(float z) {
10537        setTranslationZ(z - getElevation());
10538    }
10539
10540    /**
10541     * The base elevation of this view relative to its parent, in pixels.
10542     *
10543     * @return The base depth position of the view, in pixels.
10544     */
10545    @ViewDebug.ExportedProperty(category = "drawing")
10546    public float getElevation() {
10547        return mRenderNode.getElevation();
10548    }
10549
10550    /**
10551     * Sets the base elevation of this view, in pixels.
10552     *
10553     * @attr ref android.R.styleable#View_elevation
10554     */
10555    public void setElevation(float elevation) {
10556        if (elevation != getElevation()) {
10557            invalidateViewProperty(true, false);
10558            mRenderNode.setElevation(elevation);
10559            invalidateViewProperty(false, true);
10560
10561            invalidateParentIfNeededAndWasQuickRejected();
10562        }
10563    }
10564
10565    /**
10566     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10567     * This position is post-layout, in addition to wherever the object's
10568     * layout placed it.
10569     *
10570     * @return The horizontal position of this view relative to its left position, in pixels.
10571     */
10572    @ViewDebug.ExportedProperty(category = "drawing")
10573    public float getTranslationX() {
10574        return mRenderNode.getTranslationX();
10575    }
10576
10577    /**
10578     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10579     * This effectively positions the object post-layout, in addition to wherever the object's
10580     * layout placed it.
10581     *
10582     * @param translationX The horizontal position of this view relative to its left position,
10583     * in pixels.
10584     *
10585     * @attr ref android.R.styleable#View_translationX
10586     */
10587    public void setTranslationX(float translationX) {
10588        if (translationX != getTranslationX()) {
10589            invalidateViewProperty(true, false);
10590            mRenderNode.setTranslationX(translationX);
10591            invalidateViewProperty(false, true);
10592
10593            invalidateParentIfNeededAndWasQuickRejected();
10594            notifySubtreeAccessibilityStateChangedIfNeeded();
10595        }
10596    }
10597
10598    /**
10599     * The vertical location of this view relative to its {@link #getTop() top} position.
10600     * This position is post-layout, in addition to wherever the object's
10601     * layout placed it.
10602     *
10603     * @return The vertical position of this view relative to its top position,
10604     * in pixels.
10605     */
10606    @ViewDebug.ExportedProperty(category = "drawing")
10607    public float getTranslationY() {
10608        return mRenderNode.getTranslationY();
10609    }
10610
10611    /**
10612     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10613     * This effectively positions the object post-layout, in addition to wherever the object's
10614     * layout placed it.
10615     *
10616     * @param translationY The vertical position of this view relative to its top position,
10617     * in pixels.
10618     *
10619     * @attr ref android.R.styleable#View_translationY
10620     */
10621    public void setTranslationY(float translationY) {
10622        if (translationY != getTranslationY()) {
10623            invalidateViewProperty(true, false);
10624            mRenderNode.setTranslationY(translationY);
10625            invalidateViewProperty(false, true);
10626
10627            invalidateParentIfNeededAndWasQuickRejected();
10628        }
10629    }
10630
10631    /**
10632     * The depth location of this view relative to its {@link #getElevation() elevation}.
10633     *
10634     * @return The depth of this view relative to its elevation.
10635     */
10636    @ViewDebug.ExportedProperty(category = "drawing")
10637    public float getTranslationZ() {
10638        return mRenderNode.getTranslationZ();
10639    }
10640
10641    /**
10642     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10643     *
10644     * @attr ref android.R.styleable#View_translationZ
10645     */
10646    public void setTranslationZ(float translationZ) {
10647        if (translationZ != getTranslationZ()) {
10648            invalidateViewProperty(true, false);
10649            mRenderNode.setTranslationZ(translationZ);
10650            invalidateViewProperty(false, true);
10651
10652            invalidateParentIfNeededAndWasQuickRejected();
10653        }
10654    }
10655
10656    /**
10657     * Returns a ValueAnimator which can animate a clearing circle.
10658     * <p>
10659     * The View is prevented from drawing within the circle, so the content
10660     * behind the View shows through.
10661     *
10662     * @param centerX The x coordinate of the center of the animating circle.
10663     * @param centerY The y coordinate of the center of the animating circle.
10664     * @param startRadius The starting radius of the animating circle.
10665     * @param endRadius The ending radius of the animating circle.
10666     *
10667     * @hide
10668     */
10669    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10670            float startRadius, float endRadius) {
10671        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10672                startRadius, endRadius, true);
10673    }
10674
10675    /**
10676     * Returns the current StateListAnimator if exists.
10677     *
10678     * @return StateListAnimator or null if it does not exists
10679     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10680     */
10681    public StateListAnimator getStateListAnimator() {
10682        return mStateListAnimator;
10683    }
10684
10685    /**
10686     * Attaches the provided StateListAnimator to this View.
10687     * <p>
10688     * Any previously attached StateListAnimator will be detached.
10689     *
10690     * @param stateListAnimator The StateListAnimator to update the view
10691     * @see {@link android.animation.StateListAnimator}
10692     */
10693    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10694        if (mStateListAnimator == stateListAnimator) {
10695            return;
10696        }
10697        if (mStateListAnimator != null) {
10698            mStateListAnimator.setTarget(null);
10699        }
10700        mStateListAnimator = stateListAnimator;
10701        if (stateListAnimator != null) {
10702            stateListAnimator.setTarget(this);
10703            if (isAttachedToWindow()) {
10704                stateListAnimator.setState(getDrawableState());
10705            }
10706        }
10707    }
10708
10709    /**
10710     * Sets the {@link Outline} of the view, which defines the shape of the shadow it
10711     * casts, and enables outline clipping.
10712     * <p>
10713     * By default, a View queries its Outline from its background drawable, via
10714     * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows
10715     * this behavior to be overridden.
10716     * <p>
10717     * If the outline is {@link Outline#isEmpty()} or is <code>null</code>,
10718     * shadows will not be cast.
10719     * <p>
10720     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10721     *
10722     * @param outline The new outline of the view.
10723     *
10724     * @see #setClipToOutline(boolean)
10725     * @see #getClipToOutline()
10726     */
10727    public void setOutline(@Nullable Outline outline) {
10728        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10729
10730        if (outline == null || outline.isEmpty()) {
10731            if (mOutline != null) {
10732                mOutline.setEmpty();
10733            }
10734        } else {
10735            // always copy the path since caller may reuse
10736            if (mOutline == null) {
10737                mOutline = new Outline();
10738            }
10739            mOutline.set(outline);
10740        }
10741        mRenderNode.setOutline(mOutline);
10742    }
10743
10744    /**
10745     * Returns whether the Outline should be used to clip the contents of the View.
10746     * <p>
10747     * Note that this flag will only be respected if the View's Outline returns true from
10748     * {@link Outline#canClip()}.
10749     *
10750     * @see #setOutline(Outline)
10751     * @see #setClipToOutline(boolean)
10752     */
10753    public final boolean getClipToOutline() {
10754        return mRenderNode.getClipToOutline();
10755    }
10756
10757    /**
10758     * Sets whether the View's Outline should be used to clip the contents of the View.
10759     * <p>
10760     * Note that this flag will only be respected if the View's Outline returns true from
10761     * {@link Outline#canClip()}.
10762     *
10763     * @see #setOutline(Outline)
10764     * @see #getClipToOutline()
10765     */
10766    public void setClipToOutline(boolean clipToOutline) {
10767        damageInParent();
10768        if (getClipToOutline() != clipToOutline) {
10769            mRenderNode.setClipToOutline(clipToOutline);
10770        }
10771    }
10772
10773    private void queryOutlineFromBackgroundIfUndefined() {
10774        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
10775            // Outline not currently defined, query from background
10776            if (mOutline == null) {
10777                mOutline = new Outline();
10778            } else {
10779                //invalidate outline, to ensure background calculates it
10780                mOutline.setEmpty();
10781            }
10782            if (mBackground.getOutline(mOutline)) {
10783                if (mOutline.isEmpty()) {
10784                    throw new IllegalStateException("Background drawable failed to build outline");
10785                }
10786                mRenderNode.setOutline(mOutline);
10787            } else {
10788                mRenderNode.setOutline(null);
10789            }
10790            notifySubtreeAccessibilityStateChangedIfNeeded();
10791        }
10792    }
10793
10794    /**
10795     * Private API to be used for reveal animation
10796     *
10797     * @hide
10798     */
10799    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10800            float x, float y, float radius) {
10801        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10802        // TODO: Handle this invalidate in a better way, or purely in native.
10803        invalidate();
10804    }
10805
10806    /**
10807     * Hit rectangle in parent's coordinates
10808     *
10809     * @param outRect The hit rectangle of the view.
10810     */
10811    public void getHitRect(Rect outRect) {
10812        if (hasIdentityMatrix() || mAttachInfo == null) {
10813            outRect.set(mLeft, mTop, mRight, mBottom);
10814        } else {
10815            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10816            tmpRect.set(0, 0, getWidth(), getHeight());
10817            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10818            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10819                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10820        }
10821    }
10822
10823    /**
10824     * Determines whether the given point, in local coordinates is inside the view.
10825     */
10826    /*package*/ final boolean pointInView(float localX, float localY) {
10827        return localX >= 0 && localX < (mRight - mLeft)
10828                && localY >= 0 && localY < (mBottom - mTop);
10829    }
10830
10831    /**
10832     * Utility method to determine whether the given point, in local coordinates,
10833     * is inside the view, where the area of the view is expanded by the slop factor.
10834     * This method is called while processing touch-move events to determine if the event
10835     * is still within the view.
10836     *
10837     * @hide
10838     */
10839    public boolean pointInView(float localX, float localY, float slop) {
10840        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10841                localY < ((mBottom - mTop) + slop);
10842    }
10843
10844    /**
10845     * When a view has focus and the user navigates away from it, the next view is searched for
10846     * starting from the rectangle filled in by this method.
10847     *
10848     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10849     * of the view.  However, if your view maintains some idea of internal selection,
10850     * such as a cursor, or a selected row or column, you should override this method and
10851     * fill in a more specific rectangle.
10852     *
10853     * @param r The rectangle to fill in, in this view's coordinates.
10854     */
10855    public void getFocusedRect(Rect r) {
10856        getDrawingRect(r);
10857    }
10858
10859    /**
10860     * If some part of this view is not clipped by any of its parents, then
10861     * return that area in r in global (root) coordinates. To convert r to local
10862     * coordinates (without taking possible View rotations into account), offset
10863     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10864     * If the view is completely clipped or translated out, return false.
10865     *
10866     * @param r If true is returned, r holds the global coordinates of the
10867     *        visible portion of this view.
10868     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10869     *        between this view and its root. globalOffet may be null.
10870     * @return true if r is non-empty (i.e. part of the view is visible at the
10871     *         root level.
10872     */
10873    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10874        int width = mRight - mLeft;
10875        int height = mBottom - mTop;
10876        if (width > 0 && height > 0) {
10877            r.set(0, 0, width, height);
10878            if (globalOffset != null) {
10879                globalOffset.set(-mScrollX, -mScrollY);
10880            }
10881            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10882        }
10883        return false;
10884    }
10885
10886    public final boolean getGlobalVisibleRect(Rect r) {
10887        return getGlobalVisibleRect(r, null);
10888    }
10889
10890    public final boolean getLocalVisibleRect(Rect r) {
10891        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10892        if (getGlobalVisibleRect(r, offset)) {
10893            r.offset(-offset.x, -offset.y); // make r local
10894            return true;
10895        }
10896        return false;
10897    }
10898
10899    /**
10900     * Offset this view's vertical location by the specified number of pixels.
10901     *
10902     * @param offset the number of pixels to offset the view by
10903     */
10904    public void offsetTopAndBottom(int offset) {
10905        if (offset != 0) {
10906            final boolean matrixIsIdentity = hasIdentityMatrix();
10907            if (matrixIsIdentity) {
10908                if (isHardwareAccelerated()) {
10909                    invalidateViewProperty(false, false);
10910                } else {
10911                    final ViewParent p = mParent;
10912                    if (p != null && mAttachInfo != null) {
10913                        final Rect r = mAttachInfo.mTmpInvalRect;
10914                        int minTop;
10915                        int maxBottom;
10916                        int yLoc;
10917                        if (offset < 0) {
10918                            minTop = mTop + offset;
10919                            maxBottom = mBottom;
10920                            yLoc = offset;
10921                        } else {
10922                            minTop = mTop;
10923                            maxBottom = mBottom + offset;
10924                            yLoc = 0;
10925                        }
10926                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10927                        p.invalidateChild(this, r);
10928                    }
10929                }
10930            } else {
10931                invalidateViewProperty(false, false);
10932            }
10933
10934            mTop += offset;
10935            mBottom += offset;
10936            mRenderNode.offsetTopAndBottom(offset);
10937            if (isHardwareAccelerated()) {
10938                invalidateViewProperty(false, false);
10939            } else {
10940                if (!matrixIsIdentity) {
10941                    invalidateViewProperty(false, true);
10942                }
10943                invalidateParentIfNeeded();
10944            }
10945            notifySubtreeAccessibilityStateChangedIfNeeded();
10946        }
10947    }
10948
10949    /**
10950     * Offset this view's horizontal location by the specified amount of pixels.
10951     *
10952     * @param offset the number of pixels to offset the view by
10953     */
10954    public void offsetLeftAndRight(int offset) {
10955        if (offset != 0) {
10956            final boolean matrixIsIdentity = hasIdentityMatrix();
10957            if (matrixIsIdentity) {
10958                if (isHardwareAccelerated()) {
10959                    invalidateViewProperty(false, false);
10960                } else {
10961                    final ViewParent p = mParent;
10962                    if (p != null && mAttachInfo != null) {
10963                        final Rect r = mAttachInfo.mTmpInvalRect;
10964                        int minLeft;
10965                        int maxRight;
10966                        if (offset < 0) {
10967                            minLeft = mLeft + offset;
10968                            maxRight = mRight;
10969                        } else {
10970                            minLeft = mLeft;
10971                            maxRight = mRight + offset;
10972                        }
10973                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10974                        p.invalidateChild(this, r);
10975                    }
10976                }
10977            } else {
10978                invalidateViewProperty(false, false);
10979            }
10980
10981            mLeft += offset;
10982            mRight += offset;
10983            mRenderNode.offsetLeftAndRight(offset);
10984            if (isHardwareAccelerated()) {
10985                invalidateViewProperty(false, false);
10986            } else {
10987                if (!matrixIsIdentity) {
10988                    invalidateViewProperty(false, true);
10989                }
10990                invalidateParentIfNeeded();
10991            }
10992            notifySubtreeAccessibilityStateChangedIfNeeded();
10993        }
10994    }
10995
10996    /**
10997     * Get the LayoutParams associated with this view. All views should have
10998     * layout parameters. These supply parameters to the <i>parent</i> of this
10999     * view specifying how it should be arranged. There are many subclasses of
11000     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11001     * of ViewGroup that are responsible for arranging their children.
11002     *
11003     * This method may return null if this View is not attached to a parent
11004     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11005     * was not invoked successfully. When a View is attached to a parent
11006     * ViewGroup, this method must not return null.
11007     *
11008     * @return The LayoutParams associated with this view, or null if no
11009     *         parameters have been set yet
11010     */
11011    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11012    public ViewGroup.LayoutParams getLayoutParams() {
11013        return mLayoutParams;
11014    }
11015
11016    /**
11017     * Set the layout parameters associated with this view. These supply
11018     * parameters to the <i>parent</i> of this view specifying how it should be
11019     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11020     * correspond to the different subclasses of ViewGroup that are responsible
11021     * for arranging their children.
11022     *
11023     * @param params The layout parameters for this view, cannot be null
11024     */
11025    public void setLayoutParams(ViewGroup.LayoutParams params) {
11026        if (params == null) {
11027            throw new NullPointerException("Layout parameters cannot be null");
11028        }
11029        mLayoutParams = params;
11030        resolveLayoutParams();
11031        if (mParent instanceof ViewGroup) {
11032            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11033        }
11034        requestLayout();
11035    }
11036
11037    /**
11038     * Resolve the layout parameters depending on the resolved layout direction
11039     *
11040     * @hide
11041     */
11042    public void resolveLayoutParams() {
11043        if (mLayoutParams != null) {
11044            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11045        }
11046    }
11047
11048    /**
11049     * Set the scrolled position of your view. This will cause a call to
11050     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11051     * invalidated.
11052     * @param x the x position to scroll to
11053     * @param y the y position to scroll to
11054     */
11055    public void scrollTo(int x, int y) {
11056        if (mScrollX != x || mScrollY != y) {
11057            int oldX = mScrollX;
11058            int oldY = mScrollY;
11059            mScrollX = x;
11060            mScrollY = y;
11061            invalidateParentCaches();
11062            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11063            if (!awakenScrollBars()) {
11064                postInvalidateOnAnimation();
11065            }
11066        }
11067    }
11068
11069    /**
11070     * Move the scrolled position of your view. This will cause a call to
11071     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11072     * invalidated.
11073     * @param x the amount of pixels to scroll by horizontally
11074     * @param y the amount of pixels to scroll by vertically
11075     */
11076    public void scrollBy(int x, int y) {
11077        scrollTo(mScrollX + x, mScrollY + y);
11078    }
11079
11080    /**
11081     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11082     * animation to fade the scrollbars out after a default delay. If a subclass
11083     * provides animated scrolling, the start delay should equal the duration
11084     * of the scrolling animation.</p>
11085     *
11086     * <p>The animation starts only if at least one of the scrollbars is
11087     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11088     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11089     * this method returns true, and false otherwise. If the animation is
11090     * started, this method calls {@link #invalidate()}; in that case the
11091     * caller should not call {@link #invalidate()}.</p>
11092     *
11093     * <p>This method should be invoked every time a subclass directly updates
11094     * the scroll parameters.</p>
11095     *
11096     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11097     * and {@link #scrollTo(int, int)}.</p>
11098     *
11099     * @return true if the animation is played, false otherwise
11100     *
11101     * @see #awakenScrollBars(int)
11102     * @see #scrollBy(int, int)
11103     * @see #scrollTo(int, int)
11104     * @see #isHorizontalScrollBarEnabled()
11105     * @see #isVerticalScrollBarEnabled()
11106     * @see #setHorizontalScrollBarEnabled(boolean)
11107     * @see #setVerticalScrollBarEnabled(boolean)
11108     */
11109    protected boolean awakenScrollBars() {
11110        return mScrollCache != null &&
11111                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11112    }
11113
11114    /**
11115     * Trigger the scrollbars to draw.
11116     * This method differs from awakenScrollBars() only in its default duration.
11117     * initialAwakenScrollBars() will show the scroll bars for longer than
11118     * usual to give the user more of a chance to notice them.
11119     *
11120     * @return true if the animation is played, false otherwise.
11121     */
11122    private boolean initialAwakenScrollBars() {
11123        return mScrollCache != null &&
11124                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11125    }
11126
11127    /**
11128     * <p>
11129     * Trigger the scrollbars to draw. When invoked this method starts an
11130     * animation to fade the scrollbars out after a fixed delay. If a subclass
11131     * provides animated scrolling, the start delay should equal the duration of
11132     * the scrolling animation.
11133     * </p>
11134     *
11135     * <p>
11136     * The animation starts only if at least one of the scrollbars is enabled,
11137     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11138     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11139     * this method returns true, and false otherwise. If the animation is
11140     * started, this method calls {@link #invalidate()}; in that case the caller
11141     * should not call {@link #invalidate()}.
11142     * </p>
11143     *
11144     * <p>
11145     * This method should be invoked everytime a subclass directly updates the
11146     * scroll parameters.
11147     * </p>
11148     *
11149     * @param startDelay the delay, in milliseconds, after which the animation
11150     *        should start; when the delay is 0, the animation starts
11151     *        immediately
11152     * @return true if the animation is played, false otherwise
11153     *
11154     * @see #scrollBy(int, int)
11155     * @see #scrollTo(int, int)
11156     * @see #isHorizontalScrollBarEnabled()
11157     * @see #isVerticalScrollBarEnabled()
11158     * @see #setHorizontalScrollBarEnabled(boolean)
11159     * @see #setVerticalScrollBarEnabled(boolean)
11160     */
11161    protected boolean awakenScrollBars(int startDelay) {
11162        return awakenScrollBars(startDelay, true);
11163    }
11164
11165    /**
11166     * <p>
11167     * Trigger the scrollbars to draw. When invoked this method starts an
11168     * animation to fade the scrollbars out after a fixed delay. If a subclass
11169     * provides animated scrolling, the start delay should equal the duration of
11170     * the scrolling animation.
11171     * </p>
11172     *
11173     * <p>
11174     * The animation starts only if at least one of the scrollbars is enabled,
11175     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11176     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11177     * this method returns true, and false otherwise. If the animation is
11178     * started, this method calls {@link #invalidate()} if the invalidate parameter
11179     * is set to true; in that case the caller
11180     * should not call {@link #invalidate()}.
11181     * </p>
11182     *
11183     * <p>
11184     * This method should be invoked everytime a subclass directly updates the
11185     * scroll parameters.
11186     * </p>
11187     *
11188     * @param startDelay the delay, in milliseconds, after which the animation
11189     *        should start; when the delay is 0, the animation starts
11190     *        immediately
11191     *
11192     * @param invalidate Wheter this method should call invalidate
11193     *
11194     * @return true if the animation is played, false otherwise
11195     *
11196     * @see #scrollBy(int, int)
11197     * @see #scrollTo(int, int)
11198     * @see #isHorizontalScrollBarEnabled()
11199     * @see #isVerticalScrollBarEnabled()
11200     * @see #setHorizontalScrollBarEnabled(boolean)
11201     * @see #setVerticalScrollBarEnabled(boolean)
11202     */
11203    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11204        final ScrollabilityCache scrollCache = mScrollCache;
11205
11206        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11207            return false;
11208        }
11209
11210        if (scrollCache.scrollBar == null) {
11211            scrollCache.scrollBar = new ScrollBarDrawable();
11212        }
11213
11214        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11215
11216            if (invalidate) {
11217                // Invalidate to show the scrollbars
11218                postInvalidateOnAnimation();
11219            }
11220
11221            if (scrollCache.state == ScrollabilityCache.OFF) {
11222                // FIXME: this is copied from WindowManagerService.
11223                // We should get this value from the system when it
11224                // is possible to do so.
11225                final int KEY_REPEAT_FIRST_DELAY = 750;
11226                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11227            }
11228
11229            // Tell mScrollCache when we should start fading. This may
11230            // extend the fade start time if one was already scheduled
11231            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11232            scrollCache.fadeStartTime = fadeStartTime;
11233            scrollCache.state = ScrollabilityCache.ON;
11234
11235            // Schedule our fader to run, unscheduling any old ones first
11236            if (mAttachInfo != null) {
11237                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11238                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11239            }
11240
11241            return true;
11242        }
11243
11244        return false;
11245    }
11246
11247    /**
11248     * Do not invalidate views which are not visible and which are not running an animation. They
11249     * will not get drawn and they should not set dirty flags as if they will be drawn
11250     */
11251    private boolean skipInvalidate() {
11252        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11253                (!(mParent instanceof ViewGroup) ||
11254                        !((ViewGroup) mParent).isViewTransitioning(this));
11255    }
11256
11257    /**
11258     * Mark the area defined by dirty as needing to be drawn. If the view is
11259     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11260     * point in the future.
11261     * <p>
11262     * This must be called from a UI thread. To call from a non-UI thread, call
11263     * {@link #postInvalidate()}.
11264     * <p>
11265     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11266     * {@code dirty}.
11267     *
11268     * @param dirty the rectangle representing the bounds of the dirty region
11269     */
11270    public void invalidate(Rect dirty) {
11271        final int scrollX = mScrollX;
11272        final int scrollY = mScrollY;
11273        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11274                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11275    }
11276
11277    /**
11278     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11279     * coordinates of the dirty rect are relative to the view. If the view is
11280     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11281     * point in the future.
11282     * <p>
11283     * This must be called from a UI thread. To call from a non-UI thread, call
11284     * {@link #postInvalidate()}.
11285     *
11286     * @param l the left position of the dirty region
11287     * @param t the top position of the dirty region
11288     * @param r the right position of the dirty region
11289     * @param b the bottom position of the dirty region
11290     */
11291    public void invalidate(int l, int t, int r, int b) {
11292        final int scrollX = mScrollX;
11293        final int scrollY = mScrollY;
11294        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11295    }
11296
11297    /**
11298     * Invalidate the whole view. If the view is visible,
11299     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11300     * the future.
11301     * <p>
11302     * This must be called from a UI thread. To call from a non-UI thread, call
11303     * {@link #postInvalidate()}.
11304     */
11305    public void invalidate() {
11306        invalidate(true);
11307    }
11308
11309    /**
11310     * This is where the invalidate() work actually happens. A full invalidate()
11311     * causes the drawing cache to be invalidated, but this function can be
11312     * called with invalidateCache set to false to skip that invalidation step
11313     * for cases that do not need it (for example, a component that remains at
11314     * the same dimensions with the same content).
11315     *
11316     * @param invalidateCache Whether the drawing cache for this view should be
11317     *            invalidated as well. This is usually true for a full
11318     *            invalidate, but may be set to false if the View's contents or
11319     *            dimensions have not changed.
11320     */
11321    void invalidate(boolean invalidateCache) {
11322        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11323    }
11324
11325    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11326            boolean fullInvalidate) {
11327        if (skipInvalidate()) {
11328            return;
11329        }
11330
11331        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11332                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11333                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11334                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11335            if (fullInvalidate) {
11336                mLastIsOpaque = isOpaque();
11337                mPrivateFlags &= ~PFLAG_DRAWN;
11338            }
11339
11340            mPrivateFlags |= PFLAG_DIRTY;
11341
11342            if (invalidateCache) {
11343                mPrivateFlags |= PFLAG_INVALIDATED;
11344                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11345            }
11346
11347            // Propagate the damage rectangle to the parent view.
11348            final AttachInfo ai = mAttachInfo;
11349            final ViewParent p = mParent;
11350            if (p != null && ai != null && l < r && t < b) {
11351                final Rect damage = ai.mTmpInvalRect;
11352                damage.set(l, t, r, b);
11353                p.invalidateChild(this, damage);
11354            }
11355
11356            // Damage the entire projection receiver, if necessary.
11357            if (mBackground != null && mBackground.isProjected()) {
11358                final View receiver = getProjectionReceiver();
11359                if (receiver != null) {
11360                    receiver.damageInParent();
11361                }
11362            }
11363
11364            // Damage the entire IsolatedZVolume recieving this view's shadow.
11365            if (isHardwareAccelerated() && getZ() != 0) {
11366                damageShadowReceiver();
11367            }
11368        }
11369    }
11370
11371    /**
11372     * @return this view's projection receiver, or {@code null} if none exists
11373     */
11374    private View getProjectionReceiver() {
11375        ViewParent p = getParent();
11376        while (p != null && p instanceof View) {
11377            final View v = (View) p;
11378            if (v.isProjectionReceiver()) {
11379                return v;
11380            }
11381            p = p.getParent();
11382        }
11383
11384        return null;
11385    }
11386
11387    /**
11388     * @return whether the view is a projection receiver
11389     */
11390    private boolean isProjectionReceiver() {
11391        return mBackground != null;
11392    }
11393
11394    /**
11395     * Damage area of the screen that can be covered by this View's shadow.
11396     *
11397     * This method will guarantee that any changes to shadows cast by a View
11398     * are damaged on the screen for future redraw.
11399     */
11400    private void damageShadowReceiver() {
11401        final AttachInfo ai = mAttachInfo;
11402        if (ai != null) {
11403            ViewParent p = getParent();
11404            if (p != null && p instanceof ViewGroup) {
11405                final ViewGroup vg = (ViewGroup) p;
11406                vg.damageInParent();
11407            }
11408        }
11409    }
11410
11411    /**
11412     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11413     * set any flags or handle all of the cases handled by the default invalidation methods.
11414     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11415     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11416     * walk up the hierarchy, transforming the dirty rect as necessary.
11417     *
11418     * The method also handles normal invalidation logic if display list properties are not
11419     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11420     * backup approach, to handle these cases used in the various property-setting methods.
11421     *
11422     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11423     * are not being used in this view
11424     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11425     * list properties are not being used in this view
11426     */
11427    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11428        if (!isHardwareAccelerated()
11429                || !mRenderNode.isValid()
11430                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11431            if (invalidateParent) {
11432                invalidateParentCaches();
11433            }
11434            if (forceRedraw) {
11435                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11436            }
11437            invalidate(false);
11438        } else {
11439            damageInParent();
11440        }
11441        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11442            damageShadowReceiver();
11443        }
11444    }
11445
11446    /**
11447     * Tells the parent view to damage this view's bounds.
11448     *
11449     * @hide
11450     */
11451    protected void damageInParent() {
11452        final AttachInfo ai = mAttachInfo;
11453        final ViewParent p = mParent;
11454        if (p != null && ai != null) {
11455            final Rect r = ai.mTmpInvalRect;
11456            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11457            if (mParent instanceof ViewGroup) {
11458                ((ViewGroup) mParent).damageChild(this, r);
11459            } else {
11460                mParent.invalidateChild(this, r);
11461            }
11462        }
11463    }
11464
11465    /**
11466     * Utility method to transform a given Rect by the current matrix of this view.
11467     */
11468    void transformRect(final Rect rect) {
11469        if (!getMatrix().isIdentity()) {
11470            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11471            boundingRect.set(rect);
11472            getMatrix().mapRect(boundingRect);
11473            rect.set((int) Math.floor(boundingRect.left),
11474                    (int) Math.floor(boundingRect.top),
11475                    (int) Math.ceil(boundingRect.right),
11476                    (int) Math.ceil(boundingRect.bottom));
11477        }
11478    }
11479
11480    /**
11481     * Used to indicate that the parent of this view should clear its caches. This functionality
11482     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11483     * which is necessary when various parent-managed properties of the view change, such as
11484     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11485     * clears the parent caches and does not causes an invalidate event.
11486     *
11487     * @hide
11488     */
11489    protected void invalidateParentCaches() {
11490        if (mParent instanceof View) {
11491            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11492        }
11493    }
11494
11495    /**
11496     * Used to indicate that the parent of this view should be invalidated. This functionality
11497     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11498     * which is necessary when various parent-managed properties of the view change, such as
11499     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11500     * an invalidation event to the parent.
11501     *
11502     * @hide
11503     */
11504    protected void invalidateParentIfNeeded() {
11505        if (isHardwareAccelerated() && mParent instanceof View) {
11506            ((View) mParent).invalidate(true);
11507        }
11508    }
11509
11510    /**
11511     * @hide
11512     */
11513    protected void invalidateParentIfNeededAndWasQuickRejected() {
11514        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11515            // View was rejected last time it was drawn by its parent; this may have changed
11516            invalidateParentIfNeeded();
11517        }
11518    }
11519
11520    /**
11521     * Indicates whether this View is opaque. An opaque View guarantees that it will
11522     * draw all the pixels overlapping its bounds using a fully opaque color.
11523     *
11524     * Subclasses of View should override this method whenever possible to indicate
11525     * whether an instance is opaque. Opaque Views are treated in a special way by
11526     * the View hierarchy, possibly allowing it to perform optimizations during
11527     * invalidate/draw passes.
11528     *
11529     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11530     */
11531    @ViewDebug.ExportedProperty(category = "drawing")
11532    public boolean isOpaque() {
11533        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11534                getFinalAlpha() >= 1.0f;
11535    }
11536
11537    /**
11538     * @hide
11539     */
11540    protected void computeOpaqueFlags() {
11541        // Opaque if:
11542        //   - Has a background
11543        //   - Background is opaque
11544        //   - Doesn't have scrollbars or scrollbars overlay
11545
11546        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11547            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11548        } else {
11549            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11550        }
11551
11552        final int flags = mViewFlags;
11553        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11554                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11555                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11556            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11557        } else {
11558            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11559        }
11560    }
11561
11562    /**
11563     * @hide
11564     */
11565    protected boolean hasOpaqueScrollbars() {
11566        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11567    }
11568
11569    /**
11570     * @return A handler associated with the thread running the View. This
11571     * handler can be used to pump events in the UI events queue.
11572     */
11573    public Handler getHandler() {
11574        final AttachInfo attachInfo = mAttachInfo;
11575        if (attachInfo != null) {
11576            return attachInfo.mHandler;
11577        }
11578        return null;
11579    }
11580
11581    /**
11582     * Gets the view root associated with the View.
11583     * @return The view root, or null if none.
11584     * @hide
11585     */
11586    public ViewRootImpl getViewRootImpl() {
11587        if (mAttachInfo != null) {
11588            return mAttachInfo.mViewRootImpl;
11589        }
11590        return null;
11591    }
11592
11593    /**
11594     * @hide
11595     */
11596    public HardwareRenderer getHardwareRenderer() {
11597        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11598    }
11599
11600    /**
11601     * <p>Causes the Runnable to be added to the message queue.
11602     * The runnable will be run on the user interface thread.</p>
11603     *
11604     * @param action The Runnable that will be executed.
11605     *
11606     * @return Returns true if the Runnable was successfully placed in to the
11607     *         message queue.  Returns false on failure, usually because the
11608     *         looper processing the message queue is exiting.
11609     *
11610     * @see #postDelayed
11611     * @see #removeCallbacks
11612     */
11613    public boolean post(Runnable action) {
11614        final AttachInfo attachInfo = mAttachInfo;
11615        if (attachInfo != null) {
11616            return attachInfo.mHandler.post(action);
11617        }
11618        // Assume that post will succeed later
11619        ViewRootImpl.getRunQueue().post(action);
11620        return true;
11621    }
11622
11623    /**
11624     * <p>Causes the Runnable to be added to the message queue, to be run
11625     * after the specified amount of time elapses.
11626     * The runnable will be run on the user interface thread.</p>
11627     *
11628     * @param action The Runnable that will be executed.
11629     * @param delayMillis The delay (in milliseconds) until the Runnable
11630     *        will be executed.
11631     *
11632     * @return true if the Runnable was successfully placed in to the
11633     *         message queue.  Returns false on failure, usually because the
11634     *         looper processing the message queue is exiting.  Note that a
11635     *         result of true does not mean the Runnable will be processed --
11636     *         if the looper is quit before the delivery time of the message
11637     *         occurs then the message will be dropped.
11638     *
11639     * @see #post
11640     * @see #removeCallbacks
11641     */
11642    public boolean postDelayed(Runnable action, long delayMillis) {
11643        final AttachInfo attachInfo = mAttachInfo;
11644        if (attachInfo != null) {
11645            return attachInfo.mHandler.postDelayed(action, delayMillis);
11646        }
11647        // Assume that post will succeed later
11648        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11649        return true;
11650    }
11651
11652    /**
11653     * <p>Causes the Runnable to execute on the next animation time step.
11654     * The runnable will be run on the user interface thread.</p>
11655     *
11656     * @param action The Runnable that will be executed.
11657     *
11658     * @see #postOnAnimationDelayed
11659     * @see #removeCallbacks
11660     */
11661    public void postOnAnimation(Runnable action) {
11662        final AttachInfo attachInfo = mAttachInfo;
11663        if (attachInfo != null) {
11664            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11665                    Choreographer.CALLBACK_ANIMATION, action, null);
11666        } else {
11667            // Assume that post will succeed later
11668            ViewRootImpl.getRunQueue().post(action);
11669        }
11670    }
11671
11672    /**
11673     * <p>Causes the Runnable to execute on the next animation time step,
11674     * after the specified amount of time elapses.
11675     * The runnable will be run on the user interface thread.</p>
11676     *
11677     * @param action The Runnable that will be executed.
11678     * @param delayMillis The delay (in milliseconds) until the Runnable
11679     *        will be executed.
11680     *
11681     * @see #postOnAnimation
11682     * @see #removeCallbacks
11683     */
11684    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11685        final AttachInfo attachInfo = mAttachInfo;
11686        if (attachInfo != null) {
11687            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11688                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11689        } else {
11690            // Assume that post will succeed later
11691            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11692        }
11693    }
11694
11695    /**
11696     * <p>Removes the specified Runnable from the message queue.</p>
11697     *
11698     * @param action The Runnable to remove from the message handling queue
11699     *
11700     * @return true if this view could ask the Handler to remove the Runnable,
11701     *         false otherwise. When the returned value is true, the Runnable
11702     *         may or may not have been actually removed from the message queue
11703     *         (for instance, if the Runnable was not in the queue already.)
11704     *
11705     * @see #post
11706     * @see #postDelayed
11707     * @see #postOnAnimation
11708     * @see #postOnAnimationDelayed
11709     */
11710    public boolean removeCallbacks(Runnable action) {
11711        if (action != null) {
11712            final AttachInfo attachInfo = mAttachInfo;
11713            if (attachInfo != null) {
11714                attachInfo.mHandler.removeCallbacks(action);
11715                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11716                        Choreographer.CALLBACK_ANIMATION, action, null);
11717            }
11718            // Assume that post will succeed later
11719            ViewRootImpl.getRunQueue().removeCallbacks(action);
11720        }
11721        return true;
11722    }
11723
11724    /**
11725     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11726     * Use this to invalidate the View from a non-UI thread.</p>
11727     *
11728     * <p>This method can be invoked from outside of the UI thread
11729     * only when this View is attached to a window.</p>
11730     *
11731     * @see #invalidate()
11732     * @see #postInvalidateDelayed(long)
11733     */
11734    public void postInvalidate() {
11735        postInvalidateDelayed(0);
11736    }
11737
11738    /**
11739     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11740     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11741     *
11742     * <p>This method can be invoked from outside of the UI thread
11743     * only when this View is attached to a window.</p>
11744     *
11745     * @param left The left coordinate of the rectangle to invalidate.
11746     * @param top The top coordinate of the rectangle to invalidate.
11747     * @param right The right coordinate of the rectangle to invalidate.
11748     * @param bottom The bottom coordinate of the rectangle to invalidate.
11749     *
11750     * @see #invalidate(int, int, int, int)
11751     * @see #invalidate(Rect)
11752     * @see #postInvalidateDelayed(long, int, int, int, int)
11753     */
11754    public void postInvalidate(int left, int top, int right, int bottom) {
11755        postInvalidateDelayed(0, left, top, right, bottom);
11756    }
11757
11758    /**
11759     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11760     * loop. Waits for the specified amount of time.</p>
11761     *
11762     * <p>This method can be invoked from outside of the UI thread
11763     * only when this View is attached to a window.</p>
11764     *
11765     * @param delayMilliseconds the duration in milliseconds to delay the
11766     *         invalidation by
11767     *
11768     * @see #invalidate()
11769     * @see #postInvalidate()
11770     */
11771    public void postInvalidateDelayed(long delayMilliseconds) {
11772        // We try only with the AttachInfo because there's no point in invalidating
11773        // if we are not attached to our window
11774        final AttachInfo attachInfo = mAttachInfo;
11775        if (attachInfo != null) {
11776            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11777        }
11778    }
11779
11780    /**
11781     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11782     * through the event loop. Waits for the specified amount of time.</p>
11783     *
11784     * <p>This method can be invoked from outside of the UI thread
11785     * only when this View is attached to a window.</p>
11786     *
11787     * @param delayMilliseconds the duration in milliseconds to delay the
11788     *         invalidation by
11789     * @param left The left coordinate of the rectangle to invalidate.
11790     * @param top The top coordinate of the rectangle to invalidate.
11791     * @param right The right coordinate of the rectangle to invalidate.
11792     * @param bottom The bottom coordinate of the rectangle to invalidate.
11793     *
11794     * @see #invalidate(int, int, int, int)
11795     * @see #invalidate(Rect)
11796     * @see #postInvalidate(int, int, int, int)
11797     */
11798    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11799            int right, int bottom) {
11800
11801        // We try only with the AttachInfo because there's no point in invalidating
11802        // if we are not attached to our window
11803        final AttachInfo attachInfo = mAttachInfo;
11804        if (attachInfo != null) {
11805            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11806            info.target = this;
11807            info.left = left;
11808            info.top = top;
11809            info.right = right;
11810            info.bottom = bottom;
11811
11812            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11813        }
11814    }
11815
11816    /**
11817     * <p>Cause an invalidate to happen on the next animation time step, typically the
11818     * next display frame.</p>
11819     *
11820     * <p>This method can be invoked from outside of the UI thread
11821     * only when this View is attached to a window.</p>
11822     *
11823     * @see #invalidate()
11824     */
11825    public void postInvalidateOnAnimation() {
11826        // We try only with the AttachInfo because there's no point in invalidating
11827        // if we are not attached to our window
11828        final AttachInfo attachInfo = mAttachInfo;
11829        if (attachInfo != null) {
11830            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11831        }
11832    }
11833
11834    /**
11835     * <p>Cause an invalidate of the specified area to happen on the next animation
11836     * time step, typically the next display frame.</p>
11837     *
11838     * <p>This method can be invoked from outside of the UI thread
11839     * only when this View is attached to a window.</p>
11840     *
11841     * @param left The left coordinate of the rectangle to invalidate.
11842     * @param top The top coordinate of the rectangle to invalidate.
11843     * @param right The right coordinate of the rectangle to invalidate.
11844     * @param bottom The bottom coordinate of the rectangle to invalidate.
11845     *
11846     * @see #invalidate(int, int, int, int)
11847     * @see #invalidate(Rect)
11848     */
11849    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11850        // We try only with the AttachInfo because there's no point in invalidating
11851        // if we are not attached to our window
11852        final AttachInfo attachInfo = mAttachInfo;
11853        if (attachInfo != null) {
11854            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11855            info.target = this;
11856            info.left = left;
11857            info.top = top;
11858            info.right = right;
11859            info.bottom = bottom;
11860
11861            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11862        }
11863    }
11864
11865    /**
11866     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11867     * This event is sent at most once every
11868     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11869     */
11870    private void postSendViewScrolledAccessibilityEventCallback() {
11871        if (mSendViewScrolledAccessibilityEvent == null) {
11872            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11873        }
11874        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11875            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11876            postDelayed(mSendViewScrolledAccessibilityEvent,
11877                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11878        }
11879    }
11880
11881    /**
11882     * Called by a parent to request that a child update its values for mScrollX
11883     * and mScrollY if necessary. This will typically be done if the child is
11884     * animating a scroll using a {@link android.widget.Scroller Scroller}
11885     * object.
11886     */
11887    public void computeScroll() {
11888    }
11889
11890    /**
11891     * <p>Indicate whether the horizontal edges are faded when the view is
11892     * scrolled horizontally.</p>
11893     *
11894     * @return true if the horizontal edges should are faded on scroll, false
11895     *         otherwise
11896     *
11897     * @see #setHorizontalFadingEdgeEnabled(boolean)
11898     *
11899     * @attr ref android.R.styleable#View_requiresFadingEdge
11900     */
11901    public boolean isHorizontalFadingEdgeEnabled() {
11902        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11903    }
11904
11905    /**
11906     * <p>Define whether the horizontal edges should be faded when this view
11907     * is scrolled horizontally.</p>
11908     *
11909     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11910     *                                    be faded when the view is scrolled
11911     *                                    horizontally
11912     *
11913     * @see #isHorizontalFadingEdgeEnabled()
11914     *
11915     * @attr ref android.R.styleable#View_requiresFadingEdge
11916     */
11917    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11918        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11919            if (horizontalFadingEdgeEnabled) {
11920                initScrollCache();
11921            }
11922
11923            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11924        }
11925    }
11926
11927    /**
11928     * <p>Indicate whether the vertical edges are faded when the view is
11929     * scrolled horizontally.</p>
11930     *
11931     * @return true if the vertical edges should are faded on scroll, false
11932     *         otherwise
11933     *
11934     * @see #setVerticalFadingEdgeEnabled(boolean)
11935     *
11936     * @attr ref android.R.styleable#View_requiresFadingEdge
11937     */
11938    public boolean isVerticalFadingEdgeEnabled() {
11939        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11940    }
11941
11942    /**
11943     * <p>Define whether the vertical edges should be faded when this view
11944     * is scrolled vertically.</p>
11945     *
11946     * @param verticalFadingEdgeEnabled true if the vertical edges should
11947     *                                  be faded when the view is scrolled
11948     *                                  vertically
11949     *
11950     * @see #isVerticalFadingEdgeEnabled()
11951     *
11952     * @attr ref android.R.styleable#View_requiresFadingEdge
11953     */
11954    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11955        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11956            if (verticalFadingEdgeEnabled) {
11957                initScrollCache();
11958            }
11959
11960            mViewFlags ^= FADING_EDGE_VERTICAL;
11961        }
11962    }
11963
11964    /**
11965     * Returns the strength, or intensity, of the top faded edge. The strength is
11966     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11967     * returns 0.0 or 1.0 but no value in between.
11968     *
11969     * Subclasses should override this method to provide a smoother fade transition
11970     * when scrolling occurs.
11971     *
11972     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11973     */
11974    protected float getTopFadingEdgeStrength() {
11975        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11976    }
11977
11978    /**
11979     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11980     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11981     * returns 0.0 or 1.0 but no value in between.
11982     *
11983     * Subclasses should override this method to provide a smoother fade transition
11984     * when scrolling occurs.
11985     *
11986     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11987     */
11988    protected float getBottomFadingEdgeStrength() {
11989        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11990                computeVerticalScrollRange() ? 1.0f : 0.0f;
11991    }
11992
11993    /**
11994     * Returns the strength, or intensity, of the left faded edge. The strength is
11995     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11996     * returns 0.0 or 1.0 but no value in between.
11997     *
11998     * Subclasses should override this method to provide a smoother fade transition
11999     * when scrolling occurs.
12000     *
12001     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12002     */
12003    protected float getLeftFadingEdgeStrength() {
12004        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12005    }
12006
12007    /**
12008     * Returns the strength, or intensity, of the right faded edge. The strength is
12009     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12010     * returns 0.0 or 1.0 but no value in between.
12011     *
12012     * Subclasses should override this method to provide a smoother fade transition
12013     * when scrolling occurs.
12014     *
12015     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12016     */
12017    protected float getRightFadingEdgeStrength() {
12018        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12019                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12020    }
12021
12022    /**
12023     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12024     * scrollbar is not drawn by default.</p>
12025     *
12026     * @return true if the horizontal scrollbar should be painted, false
12027     *         otherwise
12028     *
12029     * @see #setHorizontalScrollBarEnabled(boolean)
12030     */
12031    public boolean isHorizontalScrollBarEnabled() {
12032        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12033    }
12034
12035    /**
12036     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12037     * scrollbar is not drawn by default.</p>
12038     *
12039     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12040     *                                   be painted
12041     *
12042     * @see #isHorizontalScrollBarEnabled()
12043     */
12044    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12045        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12046            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12047            computeOpaqueFlags();
12048            resolvePadding();
12049        }
12050    }
12051
12052    /**
12053     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12054     * scrollbar is not drawn by default.</p>
12055     *
12056     * @return true if the vertical scrollbar should be painted, false
12057     *         otherwise
12058     *
12059     * @see #setVerticalScrollBarEnabled(boolean)
12060     */
12061    public boolean isVerticalScrollBarEnabled() {
12062        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12063    }
12064
12065    /**
12066     * <p>Define whether the vertical scrollbar should be drawn or not. The
12067     * scrollbar is not drawn by default.</p>
12068     *
12069     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12070     *                                 be painted
12071     *
12072     * @see #isVerticalScrollBarEnabled()
12073     */
12074    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12075        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12076            mViewFlags ^= SCROLLBARS_VERTICAL;
12077            computeOpaqueFlags();
12078            resolvePadding();
12079        }
12080    }
12081
12082    /**
12083     * @hide
12084     */
12085    protected void recomputePadding() {
12086        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12087    }
12088
12089    /**
12090     * Define whether scrollbars will fade when the view is not scrolling.
12091     *
12092     * @param fadeScrollbars wheter to enable fading
12093     *
12094     * @attr ref android.R.styleable#View_fadeScrollbars
12095     */
12096    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12097        initScrollCache();
12098        final ScrollabilityCache scrollabilityCache = mScrollCache;
12099        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12100        if (fadeScrollbars) {
12101            scrollabilityCache.state = ScrollabilityCache.OFF;
12102        } else {
12103            scrollabilityCache.state = ScrollabilityCache.ON;
12104        }
12105    }
12106
12107    /**
12108     *
12109     * Returns true if scrollbars will fade when this view is not scrolling
12110     *
12111     * @return true if scrollbar fading is enabled
12112     *
12113     * @attr ref android.R.styleable#View_fadeScrollbars
12114     */
12115    public boolean isScrollbarFadingEnabled() {
12116        return mScrollCache != null && mScrollCache.fadeScrollBars;
12117    }
12118
12119    /**
12120     *
12121     * Returns the delay before scrollbars fade.
12122     *
12123     * @return the delay before scrollbars fade
12124     *
12125     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12126     */
12127    public int getScrollBarDefaultDelayBeforeFade() {
12128        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12129                mScrollCache.scrollBarDefaultDelayBeforeFade;
12130    }
12131
12132    /**
12133     * Define the delay before scrollbars fade.
12134     *
12135     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12136     *
12137     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12138     */
12139    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12140        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12141    }
12142
12143    /**
12144     *
12145     * Returns the scrollbar fade duration.
12146     *
12147     * @return the scrollbar fade duration
12148     *
12149     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12150     */
12151    public int getScrollBarFadeDuration() {
12152        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12153                mScrollCache.scrollBarFadeDuration;
12154    }
12155
12156    /**
12157     * Define the scrollbar fade duration.
12158     *
12159     * @param scrollBarFadeDuration - the scrollbar fade duration
12160     *
12161     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12162     */
12163    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12164        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12165    }
12166
12167    /**
12168     *
12169     * Returns the scrollbar size.
12170     *
12171     * @return the scrollbar size
12172     *
12173     * @attr ref android.R.styleable#View_scrollbarSize
12174     */
12175    public int getScrollBarSize() {
12176        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12177                mScrollCache.scrollBarSize;
12178    }
12179
12180    /**
12181     * Define the scrollbar size.
12182     *
12183     * @param scrollBarSize - the scrollbar size
12184     *
12185     * @attr ref android.R.styleable#View_scrollbarSize
12186     */
12187    public void setScrollBarSize(int scrollBarSize) {
12188        getScrollCache().scrollBarSize = scrollBarSize;
12189    }
12190
12191    /**
12192     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12193     * inset. When inset, they add to the padding of the view. And the scrollbars
12194     * can be drawn inside the padding area or on the edge of the view. For example,
12195     * if a view has a background drawable and you want to draw the scrollbars
12196     * inside the padding specified by the drawable, you can use
12197     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12198     * appear at the edge of the view, ignoring the padding, then you can use
12199     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12200     * @param style the style of the scrollbars. Should be one of
12201     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12202     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12203     * @see #SCROLLBARS_INSIDE_OVERLAY
12204     * @see #SCROLLBARS_INSIDE_INSET
12205     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12206     * @see #SCROLLBARS_OUTSIDE_INSET
12207     *
12208     * @attr ref android.R.styleable#View_scrollbarStyle
12209     */
12210    public void setScrollBarStyle(@ScrollBarStyle int style) {
12211        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12212            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12213            computeOpaqueFlags();
12214            resolvePadding();
12215        }
12216    }
12217
12218    /**
12219     * <p>Returns the current scrollbar style.</p>
12220     * @return the current scrollbar style
12221     * @see #SCROLLBARS_INSIDE_OVERLAY
12222     * @see #SCROLLBARS_INSIDE_INSET
12223     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12224     * @see #SCROLLBARS_OUTSIDE_INSET
12225     *
12226     * @attr ref android.R.styleable#View_scrollbarStyle
12227     */
12228    @ViewDebug.ExportedProperty(mapping = {
12229            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12230            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12231            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12232            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12233    })
12234    @ScrollBarStyle
12235    public int getScrollBarStyle() {
12236        return mViewFlags & SCROLLBARS_STYLE_MASK;
12237    }
12238
12239    /**
12240     * <p>Compute the horizontal range that the horizontal scrollbar
12241     * represents.</p>
12242     *
12243     * <p>The range is expressed in arbitrary units that must be the same as the
12244     * units used by {@link #computeHorizontalScrollExtent()} and
12245     * {@link #computeHorizontalScrollOffset()}.</p>
12246     *
12247     * <p>The default range is the drawing width of this view.</p>
12248     *
12249     * @return the total horizontal range represented by the horizontal
12250     *         scrollbar
12251     *
12252     * @see #computeHorizontalScrollExtent()
12253     * @see #computeHorizontalScrollOffset()
12254     * @see android.widget.ScrollBarDrawable
12255     */
12256    protected int computeHorizontalScrollRange() {
12257        return getWidth();
12258    }
12259
12260    /**
12261     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12262     * within the horizontal range. This value is used to compute the position
12263     * of the thumb within the scrollbar's track.</p>
12264     *
12265     * <p>The range is expressed in arbitrary units that must be the same as the
12266     * units used by {@link #computeHorizontalScrollRange()} and
12267     * {@link #computeHorizontalScrollExtent()}.</p>
12268     *
12269     * <p>The default offset is the scroll offset of this view.</p>
12270     *
12271     * @return the horizontal offset of the scrollbar's thumb
12272     *
12273     * @see #computeHorizontalScrollRange()
12274     * @see #computeHorizontalScrollExtent()
12275     * @see android.widget.ScrollBarDrawable
12276     */
12277    protected int computeHorizontalScrollOffset() {
12278        return mScrollX;
12279    }
12280
12281    /**
12282     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12283     * within the horizontal range. This value is used to compute the length
12284     * of the thumb within the scrollbar's track.</p>
12285     *
12286     * <p>The range is expressed in arbitrary units that must be the same as the
12287     * units used by {@link #computeHorizontalScrollRange()} and
12288     * {@link #computeHorizontalScrollOffset()}.</p>
12289     *
12290     * <p>The default extent is the drawing width of this view.</p>
12291     *
12292     * @return the horizontal extent of the scrollbar's thumb
12293     *
12294     * @see #computeHorizontalScrollRange()
12295     * @see #computeHorizontalScrollOffset()
12296     * @see android.widget.ScrollBarDrawable
12297     */
12298    protected int computeHorizontalScrollExtent() {
12299        return getWidth();
12300    }
12301
12302    /**
12303     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12304     *
12305     * <p>The range is expressed in arbitrary units that must be the same as the
12306     * units used by {@link #computeVerticalScrollExtent()} and
12307     * {@link #computeVerticalScrollOffset()}.</p>
12308     *
12309     * @return the total vertical range represented by the vertical scrollbar
12310     *
12311     * <p>The default range is the drawing height of this view.</p>
12312     *
12313     * @see #computeVerticalScrollExtent()
12314     * @see #computeVerticalScrollOffset()
12315     * @see android.widget.ScrollBarDrawable
12316     */
12317    protected int computeVerticalScrollRange() {
12318        return getHeight();
12319    }
12320
12321    /**
12322     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12323     * within the horizontal range. This value is used to compute the position
12324     * of the thumb within the scrollbar's track.</p>
12325     *
12326     * <p>The range is expressed in arbitrary units that must be the same as the
12327     * units used by {@link #computeVerticalScrollRange()} and
12328     * {@link #computeVerticalScrollExtent()}.</p>
12329     *
12330     * <p>The default offset is the scroll offset of this view.</p>
12331     *
12332     * @return the vertical offset of the scrollbar's thumb
12333     *
12334     * @see #computeVerticalScrollRange()
12335     * @see #computeVerticalScrollExtent()
12336     * @see android.widget.ScrollBarDrawable
12337     */
12338    protected int computeVerticalScrollOffset() {
12339        return mScrollY;
12340    }
12341
12342    /**
12343     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12344     * within the vertical range. This value is used to compute the length
12345     * of the thumb within the scrollbar's track.</p>
12346     *
12347     * <p>The range is expressed in arbitrary units that must be the same as the
12348     * units used by {@link #computeVerticalScrollRange()} and
12349     * {@link #computeVerticalScrollOffset()}.</p>
12350     *
12351     * <p>The default extent is the drawing height of this view.</p>
12352     *
12353     * @return the vertical extent of the scrollbar's thumb
12354     *
12355     * @see #computeVerticalScrollRange()
12356     * @see #computeVerticalScrollOffset()
12357     * @see android.widget.ScrollBarDrawable
12358     */
12359    protected int computeVerticalScrollExtent() {
12360        return getHeight();
12361    }
12362
12363    /**
12364     * Check if this view can be scrolled horizontally in a certain direction.
12365     *
12366     * @param direction Negative to check scrolling left, positive to check scrolling right.
12367     * @return true if this view can be scrolled in the specified direction, false otherwise.
12368     */
12369    public boolean canScrollHorizontally(int direction) {
12370        final int offset = computeHorizontalScrollOffset();
12371        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12372        if (range == 0) return false;
12373        if (direction < 0) {
12374            return offset > 0;
12375        } else {
12376            return offset < range - 1;
12377        }
12378    }
12379
12380    /**
12381     * Check if this view can be scrolled vertically in a certain direction.
12382     *
12383     * @param direction Negative to check scrolling up, positive to check scrolling down.
12384     * @return true if this view can be scrolled in the specified direction, false otherwise.
12385     */
12386    public boolean canScrollVertically(int direction) {
12387        final int offset = computeVerticalScrollOffset();
12388        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12389        if (range == 0) return false;
12390        if (direction < 0) {
12391            return offset > 0;
12392        } else {
12393            return offset < range - 1;
12394        }
12395    }
12396
12397    /**
12398     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12399     * scrollbars are painted only if they have been awakened first.</p>
12400     *
12401     * @param canvas the canvas on which to draw the scrollbars
12402     *
12403     * @see #awakenScrollBars(int)
12404     */
12405    protected final void onDrawScrollBars(Canvas canvas) {
12406        // scrollbars are drawn only when the animation is running
12407        final ScrollabilityCache cache = mScrollCache;
12408        if (cache != null) {
12409
12410            int state = cache.state;
12411
12412            if (state == ScrollabilityCache.OFF) {
12413                return;
12414            }
12415
12416            boolean invalidate = false;
12417
12418            if (state == ScrollabilityCache.FADING) {
12419                // We're fading -- get our fade interpolation
12420                if (cache.interpolatorValues == null) {
12421                    cache.interpolatorValues = new float[1];
12422                }
12423
12424                float[] values = cache.interpolatorValues;
12425
12426                // Stops the animation if we're done
12427                if (cache.scrollBarInterpolator.timeToValues(values) ==
12428                        Interpolator.Result.FREEZE_END) {
12429                    cache.state = ScrollabilityCache.OFF;
12430                } else {
12431                    cache.scrollBar.setAlpha(Math.round(values[0]));
12432                }
12433
12434                // This will make the scroll bars inval themselves after
12435                // drawing. We only want this when we're fading so that
12436                // we prevent excessive redraws
12437                invalidate = true;
12438            } else {
12439                // We're just on -- but we may have been fading before so
12440                // reset alpha
12441                cache.scrollBar.setAlpha(255);
12442            }
12443
12444
12445            final int viewFlags = mViewFlags;
12446
12447            final boolean drawHorizontalScrollBar =
12448                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12449            final boolean drawVerticalScrollBar =
12450                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12451                && !isVerticalScrollBarHidden();
12452
12453            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12454                final int width = mRight - mLeft;
12455                final int height = mBottom - mTop;
12456
12457                final ScrollBarDrawable scrollBar = cache.scrollBar;
12458
12459                final int scrollX = mScrollX;
12460                final int scrollY = mScrollY;
12461                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12462
12463                int left;
12464                int top;
12465                int right;
12466                int bottom;
12467
12468                if (drawHorizontalScrollBar) {
12469                    int size = scrollBar.getSize(false);
12470                    if (size <= 0) {
12471                        size = cache.scrollBarSize;
12472                    }
12473
12474                    scrollBar.setParameters(computeHorizontalScrollRange(),
12475                                            computeHorizontalScrollOffset(),
12476                                            computeHorizontalScrollExtent(), false);
12477                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12478                            getVerticalScrollbarWidth() : 0;
12479                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12480                    left = scrollX + (mPaddingLeft & inside);
12481                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12482                    bottom = top + size;
12483                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12484                    if (invalidate) {
12485                        invalidate(left, top, right, bottom);
12486                    }
12487                }
12488
12489                if (drawVerticalScrollBar) {
12490                    int size = scrollBar.getSize(true);
12491                    if (size <= 0) {
12492                        size = cache.scrollBarSize;
12493                    }
12494
12495                    scrollBar.setParameters(computeVerticalScrollRange(),
12496                                            computeVerticalScrollOffset(),
12497                                            computeVerticalScrollExtent(), true);
12498                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12499                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12500                        verticalScrollbarPosition = isLayoutRtl() ?
12501                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12502                    }
12503                    switch (verticalScrollbarPosition) {
12504                        default:
12505                        case SCROLLBAR_POSITION_RIGHT:
12506                            left = scrollX + width - size - (mUserPaddingRight & inside);
12507                            break;
12508                        case SCROLLBAR_POSITION_LEFT:
12509                            left = scrollX + (mUserPaddingLeft & inside);
12510                            break;
12511                    }
12512                    top = scrollY + (mPaddingTop & inside);
12513                    right = left + size;
12514                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12515                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12516                    if (invalidate) {
12517                        invalidate(left, top, right, bottom);
12518                    }
12519                }
12520            }
12521        }
12522    }
12523
12524    /**
12525     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12526     * FastScroller is visible.
12527     * @return whether to temporarily hide the vertical scrollbar
12528     * @hide
12529     */
12530    protected boolean isVerticalScrollBarHidden() {
12531        return false;
12532    }
12533
12534    /**
12535     * <p>Draw the horizontal scrollbar if
12536     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12537     *
12538     * @param canvas the canvas on which to draw the scrollbar
12539     * @param scrollBar the scrollbar's drawable
12540     *
12541     * @see #isHorizontalScrollBarEnabled()
12542     * @see #computeHorizontalScrollRange()
12543     * @see #computeHorizontalScrollExtent()
12544     * @see #computeHorizontalScrollOffset()
12545     * @see android.widget.ScrollBarDrawable
12546     * @hide
12547     */
12548    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12549            int l, int t, int r, int b) {
12550        scrollBar.setBounds(l, t, r, b);
12551        scrollBar.draw(canvas);
12552    }
12553
12554    /**
12555     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12556     * returns true.</p>
12557     *
12558     * @param canvas the canvas on which to draw the scrollbar
12559     * @param scrollBar the scrollbar's drawable
12560     *
12561     * @see #isVerticalScrollBarEnabled()
12562     * @see #computeVerticalScrollRange()
12563     * @see #computeVerticalScrollExtent()
12564     * @see #computeVerticalScrollOffset()
12565     * @see android.widget.ScrollBarDrawable
12566     * @hide
12567     */
12568    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12569            int l, int t, int r, int b) {
12570        scrollBar.setBounds(l, t, r, b);
12571        scrollBar.draw(canvas);
12572    }
12573
12574    /**
12575     * Implement this to do your drawing.
12576     *
12577     * @param canvas the canvas on which the background will be drawn
12578     */
12579    protected void onDraw(Canvas canvas) {
12580    }
12581
12582    /*
12583     * Caller is responsible for calling requestLayout if necessary.
12584     * (This allows addViewInLayout to not request a new layout.)
12585     */
12586    void assignParent(ViewParent parent) {
12587        if (mParent == null) {
12588            mParent = parent;
12589        } else if (parent == null) {
12590            mParent = null;
12591        } else {
12592            throw new RuntimeException("view " + this + " being added, but"
12593                    + " it already has a parent");
12594        }
12595    }
12596
12597    /**
12598     * This is called when the view is attached to a window.  At this point it
12599     * has a Surface and will start drawing.  Note that this function is
12600     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12601     * however it may be called any time before the first onDraw -- including
12602     * before or after {@link #onMeasure(int, int)}.
12603     *
12604     * @see #onDetachedFromWindow()
12605     */
12606    protected void onAttachedToWindow() {
12607        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12608            mParent.requestTransparentRegion(this);
12609        }
12610
12611        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12612            initialAwakenScrollBars();
12613            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12614        }
12615
12616        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12617
12618        jumpDrawablesToCurrentState();
12619
12620        resetSubtreeAccessibilityStateChanged();
12621
12622        if (isFocused()) {
12623            InputMethodManager imm = InputMethodManager.peekInstance();
12624            imm.focusIn(this);
12625        }
12626    }
12627
12628    /**
12629     * Resolve all RTL related properties.
12630     *
12631     * @return true if resolution of RTL properties has been done
12632     *
12633     * @hide
12634     */
12635    public boolean resolveRtlPropertiesIfNeeded() {
12636        if (!needRtlPropertiesResolution()) return false;
12637
12638        // Order is important here: LayoutDirection MUST be resolved first
12639        if (!isLayoutDirectionResolved()) {
12640            resolveLayoutDirection();
12641            resolveLayoutParams();
12642        }
12643        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12644        if (!isTextDirectionResolved()) {
12645            resolveTextDirection();
12646        }
12647        if (!isTextAlignmentResolved()) {
12648            resolveTextAlignment();
12649        }
12650        // Should resolve Drawables before Padding because we need the layout direction of the
12651        // Drawable to correctly resolve Padding.
12652        if (!isDrawablesResolved()) {
12653            resolveDrawables();
12654        }
12655        if (!isPaddingResolved()) {
12656            resolvePadding();
12657        }
12658        onRtlPropertiesChanged(getLayoutDirection());
12659        return true;
12660    }
12661
12662    /**
12663     * Reset resolution of all RTL related properties.
12664     *
12665     * @hide
12666     */
12667    public void resetRtlProperties() {
12668        resetResolvedLayoutDirection();
12669        resetResolvedTextDirection();
12670        resetResolvedTextAlignment();
12671        resetResolvedPadding();
12672        resetResolvedDrawables();
12673    }
12674
12675    /**
12676     * @see #onScreenStateChanged(int)
12677     */
12678    void dispatchScreenStateChanged(int screenState) {
12679        onScreenStateChanged(screenState);
12680    }
12681
12682    /**
12683     * This method is called whenever the state of the screen this view is
12684     * attached to changes. A state change will usually occurs when the screen
12685     * turns on or off (whether it happens automatically or the user does it
12686     * manually.)
12687     *
12688     * @param screenState The new state of the screen. Can be either
12689     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12690     */
12691    public void onScreenStateChanged(int screenState) {
12692    }
12693
12694    /**
12695     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12696     */
12697    private boolean hasRtlSupport() {
12698        return mContext.getApplicationInfo().hasRtlSupport();
12699    }
12700
12701    /**
12702     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12703     * RTL not supported)
12704     */
12705    private boolean isRtlCompatibilityMode() {
12706        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12707        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12708    }
12709
12710    /**
12711     * @return true if RTL properties need resolution.
12712     *
12713     */
12714    private boolean needRtlPropertiesResolution() {
12715        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12716    }
12717
12718    /**
12719     * Called when any RTL property (layout direction or text direction or text alignment) has
12720     * been changed.
12721     *
12722     * Subclasses need to override this method to take care of cached information that depends on the
12723     * resolved layout direction, or to inform child views that inherit their layout direction.
12724     *
12725     * The default implementation does nothing.
12726     *
12727     * @param layoutDirection the direction of the layout
12728     *
12729     * @see #LAYOUT_DIRECTION_LTR
12730     * @see #LAYOUT_DIRECTION_RTL
12731     */
12732    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12733    }
12734
12735    /**
12736     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12737     * that the parent directionality can and will be resolved before its children.
12738     *
12739     * @return true if resolution has been done, false otherwise.
12740     *
12741     * @hide
12742     */
12743    public boolean resolveLayoutDirection() {
12744        // Clear any previous layout direction resolution
12745        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12746
12747        if (hasRtlSupport()) {
12748            // Set resolved depending on layout direction
12749            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12750                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12751                case LAYOUT_DIRECTION_INHERIT:
12752                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12753                    // later to get the correct resolved value
12754                    if (!canResolveLayoutDirection()) return false;
12755
12756                    // Parent has not yet resolved, LTR is still the default
12757                    try {
12758                        if (!mParent.isLayoutDirectionResolved()) return false;
12759
12760                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12761                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12762                        }
12763                    } catch (AbstractMethodError e) {
12764                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12765                                " does not fully implement ViewParent", e);
12766                    }
12767                    break;
12768                case LAYOUT_DIRECTION_RTL:
12769                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12770                    break;
12771                case LAYOUT_DIRECTION_LOCALE:
12772                    if((LAYOUT_DIRECTION_RTL ==
12773                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12774                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12775                    }
12776                    break;
12777                default:
12778                    // Nothing to do, LTR by default
12779            }
12780        }
12781
12782        // Set to resolved
12783        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12784        return true;
12785    }
12786
12787    /**
12788     * Check if layout direction resolution can be done.
12789     *
12790     * @return true if layout direction resolution can be done otherwise return false.
12791     */
12792    public boolean canResolveLayoutDirection() {
12793        switch (getRawLayoutDirection()) {
12794            case LAYOUT_DIRECTION_INHERIT:
12795                if (mParent != null) {
12796                    try {
12797                        return mParent.canResolveLayoutDirection();
12798                    } catch (AbstractMethodError e) {
12799                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12800                                " does not fully implement ViewParent", e);
12801                    }
12802                }
12803                return false;
12804
12805            default:
12806                return true;
12807        }
12808    }
12809
12810    /**
12811     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12812     * {@link #onMeasure(int, int)}.
12813     *
12814     * @hide
12815     */
12816    public void resetResolvedLayoutDirection() {
12817        // Reset the current resolved bits
12818        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12819    }
12820
12821    /**
12822     * @return true if the layout direction is inherited.
12823     *
12824     * @hide
12825     */
12826    public boolean isLayoutDirectionInherited() {
12827        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12828    }
12829
12830    /**
12831     * @return true if layout direction has been resolved.
12832     */
12833    public boolean isLayoutDirectionResolved() {
12834        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12835    }
12836
12837    /**
12838     * Return if padding has been resolved
12839     *
12840     * @hide
12841     */
12842    boolean isPaddingResolved() {
12843        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12844    }
12845
12846    /**
12847     * Resolves padding depending on layout direction, if applicable, and
12848     * recomputes internal padding values to adjust for scroll bars.
12849     *
12850     * @hide
12851     */
12852    public void resolvePadding() {
12853        final int resolvedLayoutDirection = getLayoutDirection();
12854
12855        if (!isRtlCompatibilityMode()) {
12856            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12857            // If start / end padding are defined, they will be resolved (hence overriding) to
12858            // left / right or right / left depending on the resolved layout direction.
12859            // If start / end padding are not defined, use the left / right ones.
12860            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12861                Rect padding = sThreadLocal.get();
12862                if (padding == null) {
12863                    padding = new Rect();
12864                    sThreadLocal.set(padding);
12865                }
12866                mBackground.getPadding(padding);
12867                if (!mLeftPaddingDefined) {
12868                    mUserPaddingLeftInitial = padding.left;
12869                }
12870                if (!mRightPaddingDefined) {
12871                    mUserPaddingRightInitial = padding.right;
12872                }
12873            }
12874            switch (resolvedLayoutDirection) {
12875                case LAYOUT_DIRECTION_RTL:
12876                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12877                        mUserPaddingRight = mUserPaddingStart;
12878                    } else {
12879                        mUserPaddingRight = mUserPaddingRightInitial;
12880                    }
12881                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12882                        mUserPaddingLeft = mUserPaddingEnd;
12883                    } else {
12884                        mUserPaddingLeft = mUserPaddingLeftInitial;
12885                    }
12886                    break;
12887                case LAYOUT_DIRECTION_LTR:
12888                default:
12889                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12890                        mUserPaddingLeft = mUserPaddingStart;
12891                    } else {
12892                        mUserPaddingLeft = mUserPaddingLeftInitial;
12893                    }
12894                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12895                        mUserPaddingRight = mUserPaddingEnd;
12896                    } else {
12897                        mUserPaddingRight = mUserPaddingRightInitial;
12898                    }
12899            }
12900
12901            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12902        }
12903
12904        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12905        onRtlPropertiesChanged(resolvedLayoutDirection);
12906
12907        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12908    }
12909
12910    /**
12911     * Reset the resolved layout direction.
12912     *
12913     * @hide
12914     */
12915    public void resetResolvedPadding() {
12916        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12917    }
12918
12919    /**
12920     * This is called when the view is detached from a window.  At this point it
12921     * no longer has a surface for drawing.
12922     *
12923     * @see #onAttachedToWindow()
12924     */
12925    protected void onDetachedFromWindow() {
12926    }
12927
12928    /**
12929     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12930     * after onDetachedFromWindow().
12931     *
12932     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12933     * The super method should be called at the end of the overriden method to ensure
12934     * subclasses are destroyed first
12935     *
12936     * @hide
12937     */
12938    protected void onDetachedFromWindowInternal() {
12939        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12940        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12941
12942        removeUnsetPressCallback();
12943        removeLongPressCallback();
12944        removePerformClickCallback();
12945        removeSendViewScrolledAccessibilityEventCallback();
12946        stopNestedScroll();
12947
12948        destroyDrawingCache();
12949
12950        cleanupDraw();
12951        mCurrentAnimation = null;
12952    }
12953
12954    private void cleanupDraw() {
12955        resetDisplayList();
12956        if (mAttachInfo != null) {
12957            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12958        }
12959    }
12960
12961    /**
12962     * This method ensures the hardware renderer is in a valid state
12963     * before executing the specified action.
12964     *
12965     * This method will attempt to set a valid state even if the window
12966     * the renderer is attached to was destroyed.
12967     *
12968     * This method is not guaranteed to work. If the hardware renderer
12969     * does not exist or cannot be put in a valid state, this method
12970     * will not executed the specified action.
12971     *
12972     * The specified action is executed synchronously.
12973     *
12974     * @param action The action to execute after the renderer is in a valid state
12975     *
12976     * @return True if the specified Runnable was executed, false otherwise
12977     *
12978     * @hide
12979     */
12980    public boolean executeHardwareAction(Runnable action) {
12981        //noinspection SimplifiableIfStatement
12982        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12983            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12984        }
12985        return false;
12986    }
12987
12988    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12989    }
12990
12991    /**
12992     * @return The number of times this view has been attached to a window
12993     */
12994    protected int getWindowAttachCount() {
12995        return mWindowAttachCount;
12996    }
12997
12998    /**
12999     * Retrieve a unique token identifying the window this view is attached to.
13000     * @return Return the window's token for use in
13001     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13002     */
13003    public IBinder getWindowToken() {
13004        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13005    }
13006
13007    /**
13008     * Retrieve the {@link WindowId} for the window this view is
13009     * currently attached to.
13010     */
13011    public WindowId getWindowId() {
13012        if (mAttachInfo == null) {
13013            return null;
13014        }
13015        if (mAttachInfo.mWindowId == null) {
13016            try {
13017                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13018                        mAttachInfo.mWindowToken);
13019                mAttachInfo.mWindowId = new WindowId(
13020                        mAttachInfo.mIWindowId);
13021            } catch (RemoteException e) {
13022            }
13023        }
13024        return mAttachInfo.mWindowId;
13025    }
13026
13027    /**
13028     * Retrieve a unique token identifying the top-level "real" window of
13029     * the window that this view is attached to.  That is, this is like
13030     * {@link #getWindowToken}, except if the window this view in is a panel
13031     * window (attached to another containing window), then the token of
13032     * the containing window is returned instead.
13033     *
13034     * @return Returns the associated window token, either
13035     * {@link #getWindowToken()} or the containing window's token.
13036     */
13037    public IBinder getApplicationWindowToken() {
13038        AttachInfo ai = mAttachInfo;
13039        if (ai != null) {
13040            IBinder appWindowToken = ai.mPanelParentWindowToken;
13041            if (appWindowToken == null) {
13042                appWindowToken = ai.mWindowToken;
13043            }
13044            return appWindowToken;
13045        }
13046        return null;
13047    }
13048
13049    /**
13050     * Gets the logical display to which the view's window has been attached.
13051     *
13052     * @return The logical display, or null if the view is not currently attached to a window.
13053     */
13054    public Display getDisplay() {
13055        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13056    }
13057
13058    /**
13059     * Retrieve private session object this view hierarchy is using to
13060     * communicate with the window manager.
13061     * @return the session object to communicate with the window manager
13062     */
13063    /*package*/ IWindowSession getWindowSession() {
13064        return mAttachInfo != null ? mAttachInfo.mSession : null;
13065    }
13066
13067    /**
13068     * @param info the {@link android.view.View.AttachInfo} to associated with
13069     *        this view
13070     */
13071    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13072        //System.out.println("Attached! " + this);
13073        mAttachInfo = info;
13074        if (mOverlay != null) {
13075            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13076        }
13077        mWindowAttachCount++;
13078        // We will need to evaluate the drawable state at least once.
13079        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13080        if (mFloatingTreeObserver != null) {
13081            info.mTreeObserver.merge(mFloatingTreeObserver);
13082            mFloatingTreeObserver = null;
13083        }
13084        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13085            mAttachInfo.mScrollContainers.add(this);
13086            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13087        }
13088        performCollectViewAttributes(mAttachInfo, visibility);
13089        onAttachedToWindow();
13090
13091        ListenerInfo li = mListenerInfo;
13092        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13093                li != null ? li.mOnAttachStateChangeListeners : null;
13094        if (listeners != null && listeners.size() > 0) {
13095            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13096            // perform the dispatching. The iterator is a safe guard against listeners that
13097            // could mutate the list by calling the various add/remove methods. This prevents
13098            // the array from being modified while we iterate it.
13099            for (OnAttachStateChangeListener listener : listeners) {
13100                listener.onViewAttachedToWindow(this);
13101            }
13102        }
13103
13104        int vis = info.mWindowVisibility;
13105        if (vis != GONE) {
13106            onWindowVisibilityChanged(vis);
13107        }
13108        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13109            // If nobody has evaluated the drawable state yet, then do it now.
13110            refreshDrawableState();
13111        }
13112        needGlobalAttributesUpdate(false);
13113    }
13114
13115    void dispatchDetachedFromWindow() {
13116        AttachInfo info = mAttachInfo;
13117        if (info != null) {
13118            int vis = info.mWindowVisibility;
13119            if (vis != GONE) {
13120                onWindowVisibilityChanged(GONE);
13121            }
13122        }
13123
13124        onDetachedFromWindow();
13125        onDetachedFromWindowInternal();
13126
13127        ListenerInfo li = mListenerInfo;
13128        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13129                li != null ? li.mOnAttachStateChangeListeners : null;
13130        if (listeners != null && listeners.size() > 0) {
13131            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13132            // perform the dispatching. The iterator is a safe guard against listeners that
13133            // could mutate the list by calling the various add/remove methods. This prevents
13134            // the array from being modified while we iterate it.
13135            for (OnAttachStateChangeListener listener : listeners) {
13136                listener.onViewDetachedFromWindow(this);
13137            }
13138        }
13139
13140        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13141            mAttachInfo.mScrollContainers.remove(this);
13142            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13143        }
13144
13145        mAttachInfo = null;
13146        if (mOverlay != null) {
13147            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13148        }
13149    }
13150
13151    /**
13152     * Cancel any deferred high-level input events that were previously posted to the event queue.
13153     *
13154     * <p>Many views post high-level events such as click handlers to the event queue
13155     * to run deferred in order to preserve a desired user experience - clearing visible
13156     * pressed states before executing, etc. This method will abort any events of this nature
13157     * that are currently in flight.</p>
13158     *
13159     * <p>Custom views that generate their own high-level deferred input events should override
13160     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13161     *
13162     * <p>This will also cancel pending input events for any child views.</p>
13163     *
13164     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13165     * This will not impact newer events posted after this call that may occur as a result of
13166     * lower-level input events still waiting in the queue. If you are trying to prevent
13167     * double-submitted  events for the duration of some sort of asynchronous transaction
13168     * you should also take other steps to protect against unexpected double inputs e.g. calling
13169     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13170     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13171     */
13172    public final void cancelPendingInputEvents() {
13173        dispatchCancelPendingInputEvents();
13174    }
13175
13176    /**
13177     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13178     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13179     */
13180    void dispatchCancelPendingInputEvents() {
13181        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13182        onCancelPendingInputEvents();
13183        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13184            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13185                    " did not call through to super.onCancelPendingInputEvents()");
13186        }
13187    }
13188
13189    /**
13190     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13191     * a parent view.
13192     *
13193     * <p>This method is responsible for removing any pending high-level input events that were
13194     * posted to the event queue to run later. Custom view classes that post their own deferred
13195     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13196     * {@link android.os.Handler} should override this method, call
13197     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13198     * </p>
13199     */
13200    public void onCancelPendingInputEvents() {
13201        removePerformClickCallback();
13202        cancelLongPress();
13203        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13204    }
13205
13206    /**
13207     * Store this view hierarchy's frozen state into the given container.
13208     *
13209     * @param container The SparseArray in which to save the view's state.
13210     *
13211     * @see #restoreHierarchyState(android.util.SparseArray)
13212     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13213     * @see #onSaveInstanceState()
13214     */
13215    public void saveHierarchyState(SparseArray<Parcelable> container) {
13216        dispatchSaveInstanceState(container);
13217    }
13218
13219    /**
13220     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13221     * this view and its children. May be overridden to modify how freezing happens to a
13222     * view's children; for example, some views may want to not store state for their children.
13223     *
13224     * @param container The SparseArray in which to save the view's state.
13225     *
13226     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13227     * @see #saveHierarchyState(android.util.SparseArray)
13228     * @see #onSaveInstanceState()
13229     */
13230    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13231        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13232            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13233            Parcelable state = onSaveInstanceState();
13234            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13235                throw new IllegalStateException(
13236                        "Derived class did not call super.onSaveInstanceState()");
13237            }
13238            if (state != null) {
13239                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13240                // + ": " + state);
13241                container.put(mID, state);
13242            }
13243        }
13244    }
13245
13246    /**
13247     * Hook allowing a view to generate a representation of its internal state
13248     * that can later be used to create a new instance with that same state.
13249     * This state should only contain information that is not persistent or can
13250     * not be reconstructed later. For example, you will never store your
13251     * current position on screen because that will be computed again when a
13252     * new instance of the view is placed in its view hierarchy.
13253     * <p>
13254     * Some examples of things you may store here: the current cursor position
13255     * in a text view (but usually not the text itself since that is stored in a
13256     * content provider or other persistent storage), the currently selected
13257     * item in a list view.
13258     *
13259     * @return Returns a Parcelable object containing the view's current dynamic
13260     *         state, or null if there is nothing interesting to save. The
13261     *         default implementation returns null.
13262     * @see #onRestoreInstanceState(android.os.Parcelable)
13263     * @see #saveHierarchyState(android.util.SparseArray)
13264     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13265     * @see #setSaveEnabled(boolean)
13266     */
13267    protected Parcelable onSaveInstanceState() {
13268        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13269        return BaseSavedState.EMPTY_STATE;
13270    }
13271
13272    /**
13273     * Restore this view hierarchy's frozen state from the given container.
13274     *
13275     * @param container The SparseArray which holds previously frozen states.
13276     *
13277     * @see #saveHierarchyState(android.util.SparseArray)
13278     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13279     * @see #onRestoreInstanceState(android.os.Parcelable)
13280     */
13281    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13282        dispatchRestoreInstanceState(container);
13283    }
13284
13285    /**
13286     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13287     * state for this view and its children. May be overridden to modify how restoring
13288     * happens to a view's children; for example, some views may want to not store state
13289     * for their children.
13290     *
13291     * @param container The SparseArray which holds previously saved state.
13292     *
13293     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13294     * @see #restoreHierarchyState(android.util.SparseArray)
13295     * @see #onRestoreInstanceState(android.os.Parcelable)
13296     */
13297    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13298        if (mID != NO_ID) {
13299            Parcelable state = container.get(mID);
13300            if (state != null) {
13301                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13302                // + ": " + state);
13303                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13304                onRestoreInstanceState(state);
13305                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13306                    throw new IllegalStateException(
13307                            "Derived class did not call super.onRestoreInstanceState()");
13308                }
13309            }
13310        }
13311    }
13312
13313    /**
13314     * Hook allowing a view to re-apply a representation of its internal state that had previously
13315     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13316     * null state.
13317     *
13318     * @param state The frozen state that had previously been returned by
13319     *        {@link #onSaveInstanceState}.
13320     *
13321     * @see #onSaveInstanceState()
13322     * @see #restoreHierarchyState(android.util.SparseArray)
13323     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13324     */
13325    protected void onRestoreInstanceState(Parcelable state) {
13326        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13327        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13328            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13329                    + "received " + state.getClass().toString() + " instead. This usually happens "
13330                    + "when two views of different type have the same id in the same hierarchy. "
13331                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13332                    + "other views do not use the same id.");
13333        }
13334    }
13335
13336    /**
13337     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13338     *
13339     * @return the drawing start time in milliseconds
13340     */
13341    public long getDrawingTime() {
13342        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13343    }
13344
13345    /**
13346     * <p>Enables or disables the duplication of the parent's state into this view. When
13347     * duplication is enabled, this view gets its drawable state from its parent rather
13348     * than from its own internal properties.</p>
13349     *
13350     * <p>Note: in the current implementation, setting this property to true after the
13351     * view was added to a ViewGroup might have no effect at all. This property should
13352     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13353     *
13354     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13355     * property is enabled, an exception will be thrown.</p>
13356     *
13357     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13358     * parent, these states should not be affected by this method.</p>
13359     *
13360     * @param enabled True to enable duplication of the parent's drawable state, false
13361     *                to disable it.
13362     *
13363     * @see #getDrawableState()
13364     * @see #isDuplicateParentStateEnabled()
13365     */
13366    public void setDuplicateParentStateEnabled(boolean enabled) {
13367        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13368    }
13369
13370    /**
13371     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13372     *
13373     * @return True if this view's drawable state is duplicated from the parent,
13374     *         false otherwise
13375     *
13376     * @see #getDrawableState()
13377     * @see #setDuplicateParentStateEnabled(boolean)
13378     */
13379    public boolean isDuplicateParentStateEnabled() {
13380        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13381    }
13382
13383    /**
13384     * <p>Specifies the type of layer backing this view. The layer can be
13385     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13386     * {@link #LAYER_TYPE_HARDWARE}.</p>
13387     *
13388     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13389     * instance that controls how the layer is composed on screen. The following
13390     * properties of the paint are taken into account when composing the layer:</p>
13391     * <ul>
13392     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13393     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13394     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13395     * </ul>
13396     *
13397     * <p>If this view has an alpha value set to < 1.0 by calling
13398     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13399     * by this view's alpha value.</p>
13400     *
13401     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13402     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13403     * for more information on when and how to use layers.</p>
13404     *
13405     * @param layerType The type of layer to use with this view, must be one of
13406     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13407     *        {@link #LAYER_TYPE_HARDWARE}
13408     * @param paint The paint used to compose the layer. This argument is optional
13409     *        and can be null. It is ignored when the layer type is
13410     *        {@link #LAYER_TYPE_NONE}
13411     *
13412     * @see #getLayerType()
13413     * @see #LAYER_TYPE_NONE
13414     * @see #LAYER_TYPE_SOFTWARE
13415     * @see #LAYER_TYPE_HARDWARE
13416     * @see #setAlpha(float)
13417     *
13418     * @attr ref android.R.styleable#View_layerType
13419     */
13420    public void setLayerType(int layerType, Paint paint) {
13421        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13422            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13423                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13424        }
13425
13426        boolean typeChanged = mRenderNode.setLayerType(layerType);
13427
13428        if (!typeChanged) {
13429            setLayerPaint(paint);
13430            return;
13431        }
13432
13433        // Destroy any previous software drawing cache if needed
13434        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13435            destroyDrawingCache();
13436        }
13437
13438        mLayerType = layerType;
13439        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13440        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13441        mRenderNode.setLayerPaint(mLayerPaint);
13442
13443        // draw() behaves differently if we are on a layer, so we need to
13444        // invalidate() here
13445        invalidateParentCaches();
13446        invalidate(true);
13447    }
13448
13449    /**
13450     * Updates the {@link Paint} object used with the current layer (used only if the current
13451     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13452     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13453     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13454     * ensure that the view gets redrawn immediately.
13455     *
13456     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13457     * instance that controls how the layer is composed on screen. The following
13458     * properties of the paint are taken into account when composing the layer:</p>
13459     * <ul>
13460     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13461     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13462     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13463     * </ul>
13464     *
13465     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13466     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13467     *
13468     * @param paint The paint used to compose the layer. This argument is optional
13469     *        and can be null. It is ignored when the layer type is
13470     *        {@link #LAYER_TYPE_NONE}
13471     *
13472     * @see #setLayerType(int, android.graphics.Paint)
13473     */
13474    public void setLayerPaint(Paint paint) {
13475        int layerType = getLayerType();
13476        if (layerType != LAYER_TYPE_NONE) {
13477            mLayerPaint = paint == null ? new Paint() : paint;
13478            if (layerType == LAYER_TYPE_HARDWARE) {
13479                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13480                    invalidateViewProperty(false, false);
13481                }
13482            } else {
13483                invalidate();
13484            }
13485        }
13486    }
13487
13488    /**
13489     * Indicates whether this view has a static layer. A view with layer type
13490     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13491     * dynamic.
13492     */
13493    boolean hasStaticLayer() {
13494        return true;
13495    }
13496
13497    /**
13498     * Indicates what type of layer is currently associated with this view. By default
13499     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13500     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13501     * for more information on the different types of layers.
13502     *
13503     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13504     *         {@link #LAYER_TYPE_HARDWARE}
13505     *
13506     * @see #setLayerType(int, android.graphics.Paint)
13507     * @see #buildLayer()
13508     * @see #LAYER_TYPE_NONE
13509     * @see #LAYER_TYPE_SOFTWARE
13510     * @see #LAYER_TYPE_HARDWARE
13511     */
13512    public int getLayerType() {
13513        return mLayerType;
13514    }
13515
13516    /**
13517     * Forces this view's layer to be created and this view to be rendered
13518     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13519     * invoking this method will have no effect.
13520     *
13521     * This method can for instance be used to render a view into its layer before
13522     * starting an animation. If this view is complex, rendering into the layer
13523     * before starting the animation will avoid skipping frames.
13524     *
13525     * @throws IllegalStateException If this view is not attached to a window
13526     *
13527     * @see #setLayerType(int, android.graphics.Paint)
13528     */
13529    public void buildLayer() {
13530        if (mLayerType == LAYER_TYPE_NONE) return;
13531
13532        final AttachInfo attachInfo = mAttachInfo;
13533        if (attachInfo == null) {
13534            throw new IllegalStateException("This view must be attached to a window first");
13535        }
13536
13537        if (getWidth() == 0 || getHeight() == 0) {
13538            return;
13539        }
13540
13541        switch (mLayerType) {
13542            case LAYER_TYPE_HARDWARE:
13543                // The only part of a hardware layer we can build in response to
13544                // this call is to ensure the display list is up to date.
13545                // The actual rendering of the display list into the layer must
13546                // be done at playback time
13547                updateDisplayListIfDirty();
13548                break;
13549            case LAYER_TYPE_SOFTWARE:
13550                buildDrawingCache(true);
13551                break;
13552        }
13553    }
13554
13555    /**
13556     * If this View draws with a HardwareLayer, returns it.
13557     * Otherwise returns null
13558     *
13559     * TODO: Only TextureView uses this, can we eliminate it?
13560     */
13561    HardwareLayer getHardwareLayer() {
13562        return null;
13563    }
13564
13565    /**
13566     * Destroys all hardware rendering resources. This method is invoked
13567     * when the system needs to reclaim resources. Upon execution of this
13568     * method, you should free any OpenGL resources created by the view.
13569     *
13570     * Note: you <strong>must</strong> call
13571     * <code>super.destroyHardwareResources()</code> when overriding
13572     * this method.
13573     *
13574     * @hide
13575     */
13576    protected void destroyHardwareResources() {
13577        resetDisplayList();
13578    }
13579
13580    /**
13581     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13582     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13583     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13584     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13585     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13586     * null.</p>
13587     *
13588     * <p>Enabling the drawing cache is similar to
13589     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13590     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13591     * drawing cache has no effect on rendering because the system uses a different mechanism
13592     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13593     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13594     * for information on how to enable software and hardware layers.</p>
13595     *
13596     * <p>This API can be used to manually generate
13597     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13598     * {@link #getDrawingCache()}.</p>
13599     *
13600     * @param enabled true to enable the drawing cache, false otherwise
13601     *
13602     * @see #isDrawingCacheEnabled()
13603     * @see #getDrawingCache()
13604     * @see #buildDrawingCache()
13605     * @see #setLayerType(int, android.graphics.Paint)
13606     */
13607    public void setDrawingCacheEnabled(boolean enabled) {
13608        mCachingFailed = false;
13609        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13610    }
13611
13612    /**
13613     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13614     *
13615     * @return true if the drawing cache is enabled
13616     *
13617     * @see #setDrawingCacheEnabled(boolean)
13618     * @see #getDrawingCache()
13619     */
13620    @ViewDebug.ExportedProperty(category = "drawing")
13621    public boolean isDrawingCacheEnabled() {
13622        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13623    }
13624
13625    /**
13626     * Debugging utility which recursively outputs the dirty state of a view and its
13627     * descendants.
13628     *
13629     * @hide
13630     */
13631    @SuppressWarnings({"UnusedDeclaration"})
13632    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13633        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13634                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13635                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13636                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13637        if (clear) {
13638            mPrivateFlags &= clearMask;
13639        }
13640        if (this instanceof ViewGroup) {
13641            ViewGroup parent = (ViewGroup) this;
13642            final int count = parent.getChildCount();
13643            for (int i = 0; i < count; i++) {
13644                final View child = parent.getChildAt(i);
13645                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13646            }
13647        }
13648    }
13649
13650    /**
13651     * This method is used by ViewGroup to cause its children to restore or recreate their
13652     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13653     * to recreate its own display list, which would happen if it went through the normal
13654     * draw/dispatchDraw mechanisms.
13655     *
13656     * @hide
13657     */
13658    protected void dispatchGetDisplayList() {}
13659
13660    /**
13661     * A view that is not attached or hardware accelerated cannot create a display list.
13662     * This method checks these conditions and returns the appropriate result.
13663     *
13664     * @return true if view has the ability to create a display list, false otherwise.
13665     *
13666     * @hide
13667     */
13668    public boolean canHaveDisplayList() {
13669        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13670    }
13671
13672    private void updateDisplayListIfDirty() {
13673        final RenderNode renderNode = mRenderNode;
13674        if (!canHaveDisplayList()) {
13675            // can't populate RenderNode, don't try
13676            return;
13677        }
13678
13679        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13680                || !renderNode.isValid()
13681                || (mRecreateDisplayList)) {
13682            // Don't need to recreate the display list, just need to tell our
13683            // children to restore/recreate theirs
13684            if (renderNode.isValid()
13685                    && !mRecreateDisplayList) {
13686                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13687                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13688                dispatchGetDisplayList();
13689
13690                return; // no work needed
13691            }
13692
13693            // If we got here, we're recreating it. Mark it as such to ensure that
13694            // we copy in child display lists into ours in drawChild()
13695            mRecreateDisplayList = true;
13696
13697            int width = mRight - mLeft;
13698            int height = mBottom - mTop;
13699            int layerType = getLayerType();
13700
13701            final HardwareCanvas canvas = renderNode.start(width, height);
13702
13703            try {
13704                final HardwareLayer layer = getHardwareLayer();
13705                if (layer != null && layer.isValid()) {
13706                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13707                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13708                    buildDrawingCache(true);
13709                    Bitmap cache = getDrawingCache(true);
13710                    if (cache != null) {
13711                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13712                    }
13713                } else {
13714                    computeScroll();
13715
13716                    canvas.translate(-mScrollX, -mScrollY);
13717                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13718                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13719
13720                    // Fast path for layouts with no backgrounds
13721                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13722                        dispatchDraw(canvas);
13723                        if (mOverlay != null && !mOverlay.isEmpty()) {
13724                            mOverlay.getOverlayView().draw(canvas);
13725                        }
13726                    } else {
13727                        draw(canvas);
13728                    }
13729                }
13730            } finally {
13731                renderNode.end(canvas);
13732                setDisplayListProperties(renderNode);
13733            }
13734        } else {
13735            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13736            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13737        }
13738    }
13739
13740    /**
13741     * Returns a RenderNode with View draw content recorded, which can be
13742     * used to draw this view again without executing its draw method.
13743     *
13744     * @return A RenderNode ready to replay, or null if caching is not enabled.
13745     *
13746     * @hide
13747     */
13748    public RenderNode getDisplayList() {
13749        updateDisplayListIfDirty();
13750        return mRenderNode;
13751    }
13752
13753    private void resetDisplayList() {
13754        if (mRenderNode.isValid()) {
13755            mRenderNode.destroyDisplayListData();
13756        }
13757
13758        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
13759            mBackgroundDisplayList.destroyDisplayListData();
13760        }
13761    }
13762
13763    /**
13764     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13765     *
13766     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13767     *
13768     * @see #getDrawingCache(boolean)
13769     */
13770    public Bitmap getDrawingCache() {
13771        return getDrawingCache(false);
13772    }
13773
13774    /**
13775     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13776     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13777     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13778     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13779     * request the drawing cache by calling this method and draw it on screen if the
13780     * returned bitmap is not null.</p>
13781     *
13782     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13783     * this method will create a bitmap of the same size as this view. Because this bitmap
13784     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13785     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13786     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13787     * size than the view. This implies that your application must be able to handle this
13788     * size.</p>
13789     *
13790     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13791     *        the current density of the screen when the application is in compatibility
13792     *        mode.
13793     *
13794     * @return A bitmap representing this view or null if cache is disabled.
13795     *
13796     * @see #setDrawingCacheEnabled(boolean)
13797     * @see #isDrawingCacheEnabled()
13798     * @see #buildDrawingCache(boolean)
13799     * @see #destroyDrawingCache()
13800     */
13801    public Bitmap getDrawingCache(boolean autoScale) {
13802        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13803            return null;
13804        }
13805        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13806            buildDrawingCache(autoScale);
13807        }
13808        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13809    }
13810
13811    /**
13812     * <p>Frees the resources used by the drawing cache. If you call
13813     * {@link #buildDrawingCache()} manually without calling
13814     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13815     * should cleanup the cache with this method afterwards.</p>
13816     *
13817     * @see #setDrawingCacheEnabled(boolean)
13818     * @see #buildDrawingCache()
13819     * @see #getDrawingCache()
13820     */
13821    public void destroyDrawingCache() {
13822        if (mDrawingCache != null) {
13823            mDrawingCache.recycle();
13824            mDrawingCache = null;
13825        }
13826        if (mUnscaledDrawingCache != null) {
13827            mUnscaledDrawingCache.recycle();
13828            mUnscaledDrawingCache = null;
13829        }
13830    }
13831
13832    /**
13833     * Setting a solid background color for the drawing cache's bitmaps will improve
13834     * performance and memory usage. Note, though that this should only be used if this
13835     * view will always be drawn on top of a solid color.
13836     *
13837     * @param color The background color to use for the drawing cache's bitmap
13838     *
13839     * @see #setDrawingCacheEnabled(boolean)
13840     * @see #buildDrawingCache()
13841     * @see #getDrawingCache()
13842     */
13843    public void setDrawingCacheBackgroundColor(int color) {
13844        if (color != mDrawingCacheBackgroundColor) {
13845            mDrawingCacheBackgroundColor = color;
13846            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13847        }
13848    }
13849
13850    /**
13851     * @see #setDrawingCacheBackgroundColor(int)
13852     *
13853     * @return The background color to used for the drawing cache's bitmap
13854     */
13855    public int getDrawingCacheBackgroundColor() {
13856        return mDrawingCacheBackgroundColor;
13857    }
13858
13859    /**
13860     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13861     *
13862     * @see #buildDrawingCache(boolean)
13863     */
13864    public void buildDrawingCache() {
13865        buildDrawingCache(false);
13866    }
13867
13868    /**
13869     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13870     *
13871     * <p>If you call {@link #buildDrawingCache()} manually without calling
13872     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13873     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13874     *
13875     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13876     * this method will create a bitmap of the same size as this view. Because this bitmap
13877     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13878     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13879     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13880     * size than the view. This implies that your application must be able to handle this
13881     * size.</p>
13882     *
13883     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13884     * you do not need the drawing cache bitmap, calling this method will increase memory
13885     * usage and cause the view to be rendered in software once, thus negatively impacting
13886     * performance.</p>
13887     *
13888     * @see #getDrawingCache()
13889     * @see #destroyDrawingCache()
13890     */
13891    public void buildDrawingCache(boolean autoScale) {
13892        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13893                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13894            mCachingFailed = false;
13895
13896            int width = mRight - mLeft;
13897            int height = mBottom - mTop;
13898
13899            final AttachInfo attachInfo = mAttachInfo;
13900            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13901
13902            if (autoScale && scalingRequired) {
13903                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13904                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13905            }
13906
13907            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13908            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13909            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13910
13911            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13912            final long drawingCacheSize =
13913                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13914            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13915                if (width > 0 && height > 0) {
13916                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13917                            + projectedBitmapSize + " bytes, only "
13918                            + drawingCacheSize + " available");
13919                }
13920                destroyDrawingCache();
13921                mCachingFailed = true;
13922                return;
13923            }
13924
13925            boolean clear = true;
13926            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13927
13928            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13929                Bitmap.Config quality;
13930                if (!opaque) {
13931                    // Never pick ARGB_4444 because it looks awful
13932                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13933                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13934                        case DRAWING_CACHE_QUALITY_AUTO:
13935                        case DRAWING_CACHE_QUALITY_LOW:
13936                        case DRAWING_CACHE_QUALITY_HIGH:
13937                        default:
13938                            quality = Bitmap.Config.ARGB_8888;
13939                            break;
13940                    }
13941                } else {
13942                    // Optimization for translucent windows
13943                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13944                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13945                }
13946
13947                // Try to cleanup memory
13948                if (bitmap != null) bitmap.recycle();
13949
13950                try {
13951                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13952                            width, height, quality);
13953                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13954                    if (autoScale) {
13955                        mDrawingCache = bitmap;
13956                    } else {
13957                        mUnscaledDrawingCache = bitmap;
13958                    }
13959                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13960                } catch (OutOfMemoryError e) {
13961                    // If there is not enough memory to create the bitmap cache, just
13962                    // ignore the issue as bitmap caches are not required to draw the
13963                    // view hierarchy
13964                    if (autoScale) {
13965                        mDrawingCache = null;
13966                    } else {
13967                        mUnscaledDrawingCache = null;
13968                    }
13969                    mCachingFailed = true;
13970                    return;
13971                }
13972
13973                clear = drawingCacheBackgroundColor != 0;
13974            }
13975
13976            Canvas canvas;
13977            if (attachInfo != null) {
13978                canvas = attachInfo.mCanvas;
13979                if (canvas == null) {
13980                    canvas = new Canvas();
13981                }
13982                canvas.setBitmap(bitmap);
13983                // Temporarily clobber the cached Canvas in case one of our children
13984                // is also using a drawing cache. Without this, the children would
13985                // steal the canvas by attaching their own bitmap to it and bad, bad
13986                // thing would happen (invisible views, corrupted drawings, etc.)
13987                attachInfo.mCanvas = null;
13988            } else {
13989                // This case should hopefully never or seldom happen
13990                canvas = new Canvas(bitmap);
13991            }
13992
13993            if (clear) {
13994                bitmap.eraseColor(drawingCacheBackgroundColor);
13995            }
13996
13997            computeScroll();
13998            final int restoreCount = canvas.save();
13999
14000            if (autoScale && scalingRequired) {
14001                final float scale = attachInfo.mApplicationScale;
14002                canvas.scale(scale, scale);
14003            }
14004
14005            canvas.translate(-mScrollX, -mScrollY);
14006
14007            mPrivateFlags |= PFLAG_DRAWN;
14008            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14009                    mLayerType != LAYER_TYPE_NONE) {
14010                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14011            }
14012
14013            // Fast path for layouts with no backgrounds
14014            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14015                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14016                dispatchDraw(canvas);
14017                if (mOverlay != null && !mOverlay.isEmpty()) {
14018                    mOverlay.getOverlayView().draw(canvas);
14019                }
14020            } else {
14021                draw(canvas);
14022            }
14023
14024            canvas.restoreToCount(restoreCount);
14025            canvas.setBitmap(null);
14026
14027            if (attachInfo != null) {
14028                // Restore the cached Canvas for our siblings
14029                attachInfo.mCanvas = canvas;
14030            }
14031        }
14032    }
14033
14034    /**
14035     * Create a snapshot of the view into a bitmap.  We should probably make
14036     * some form of this public, but should think about the API.
14037     */
14038    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14039        int width = mRight - mLeft;
14040        int height = mBottom - mTop;
14041
14042        final AttachInfo attachInfo = mAttachInfo;
14043        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14044        width = (int) ((width * scale) + 0.5f);
14045        height = (int) ((height * scale) + 0.5f);
14046
14047        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14048                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14049        if (bitmap == null) {
14050            throw new OutOfMemoryError();
14051        }
14052
14053        Resources resources = getResources();
14054        if (resources != null) {
14055            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14056        }
14057
14058        Canvas canvas;
14059        if (attachInfo != null) {
14060            canvas = attachInfo.mCanvas;
14061            if (canvas == null) {
14062                canvas = new Canvas();
14063            }
14064            canvas.setBitmap(bitmap);
14065            // Temporarily clobber the cached Canvas in case one of our children
14066            // is also using a drawing cache. Without this, the children would
14067            // steal the canvas by attaching their own bitmap to it and bad, bad
14068            // things would happen (invisible views, corrupted drawings, etc.)
14069            attachInfo.mCanvas = null;
14070        } else {
14071            // This case should hopefully never or seldom happen
14072            canvas = new Canvas(bitmap);
14073        }
14074
14075        if ((backgroundColor & 0xff000000) != 0) {
14076            bitmap.eraseColor(backgroundColor);
14077        }
14078
14079        computeScroll();
14080        final int restoreCount = canvas.save();
14081        canvas.scale(scale, scale);
14082        canvas.translate(-mScrollX, -mScrollY);
14083
14084        // Temporarily remove the dirty mask
14085        int flags = mPrivateFlags;
14086        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14087
14088        // Fast path for layouts with no backgrounds
14089        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14090            dispatchDraw(canvas);
14091            if (mOverlay != null && !mOverlay.isEmpty()) {
14092                mOverlay.getOverlayView().draw(canvas);
14093            }
14094        } else {
14095            draw(canvas);
14096        }
14097
14098        mPrivateFlags = flags;
14099
14100        canvas.restoreToCount(restoreCount);
14101        canvas.setBitmap(null);
14102
14103        if (attachInfo != null) {
14104            // Restore the cached Canvas for our siblings
14105            attachInfo.mCanvas = canvas;
14106        }
14107
14108        return bitmap;
14109    }
14110
14111    /**
14112     * Indicates whether this View is currently in edit mode. A View is usually
14113     * in edit mode when displayed within a developer tool. For instance, if
14114     * this View is being drawn by a visual user interface builder, this method
14115     * should return true.
14116     *
14117     * Subclasses should check the return value of this method to provide
14118     * different behaviors if their normal behavior might interfere with the
14119     * host environment. For instance: the class spawns a thread in its
14120     * constructor, the drawing code relies on device-specific features, etc.
14121     *
14122     * This method is usually checked in the drawing code of custom widgets.
14123     *
14124     * @return True if this View is in edit mode, false otherwise.
14125     */
14126    public boolean isInEditMode() {
14127        return false;
14128    }
14129
14130    /**
14131     * If the View draws content inside its padding and enables fading edges,
14132     * it needs to support padding offsets. Padding offsets are added to the
14133     * fading edges to extend the length of the fade so that it covers pixels
14134     * drawn inside the padding.
14135     *
14136     * Subclasses of this class should override this method if they need
14137     * to draw content inside the padding.
14138     *
14139     * @return True if padding offset must be applied, false otherwise.
14140     *
14141     * @see #getLeftPaddingOffset()
14142     * @see #getRightPaddingOffset()
14143     * @see #getTopPaddingOffset()
14144     * @see #getBottomPaddingOffset()
14145     *
14146     * @since CURRENT
14147     */
14148    protected boolean isPaddingOffsetRequired() {
14149        return false;
14150    }
14151
14152    /**
14153     * Amount by which to extend the left fading region. Called only when
14154     * {@link #isPaddingOffsetRequired()} returns true.
14155     *
14156     * @return The left padding offset in pixels.
14157     *
14158     * @see #isPaddingOffsetRequired()
14159     *
14160     * @since CURRENT
14161     */
14162    protected int getLeftPaddingOffset() {
14163        return 0;
14164    }
14165
14166    /**
14167     * Amount by which to extend the right fading region. Called only when
14168     * {@link #isPaddingOffsetRequired()} returns true.
14169     *
14170     * @return The right padding offset in pixels.
14171     *
14172     * @see #isPaddingOffsetRequired()
14173     *
14174     * @since CURRENT
14175     */
14176    protected int getRightPaddingOffset() {
14177        return 0;
14178    }
14179
14180    /**
14181     * Amount by which to extend the top fading region. Called only when
14182     * {@link #isPaddingOffsetRequired()} returns true.
14183     *
14184     * @return The top padding offset in pixels.
14185     *
14186     * @see #isPaddingOffsetRequired()
14187     *
14188     * @since CURRENT
14189     */
14190    protected int getTopPaddingOffset() {
14191        return 0;
14192    }
14193
14194    /**
14195     * Amount by which to extend the bottom fading region. Called only when
14196     * {@link #isPaddingOffsetRequired()} returns true.
14197     *
14198     * @return The bottom padding offset in pixels.
14199     *
14200     * @see #isPaddingOffsetRequired()
14201     *
14202     * @since CURRENT
14203     */
14204    protected int getBottomPaddingOffset() {
14205        return 0;
14206    }
14207
14208    /**
14209     * @hide
14210     * @param offsetRequired
14211     */
14212    protected int getFadeTop(boolean offsetRequired) {
14213        int top = mPaddingTop;
14214        if (offsetRequired) top += getTopPaddingOffset();
14215        return top;
14216    }
14217
14218    /**
14219     * @hide
14220     * @param offsetRequired
14221     */
14222    protected int getFadeHeight(boolean offsetRequired) {
14223        int padding = mPaddingTop;
14224        if (offsetRequired) padding += getTopPaddingOffset();
14225        return mBottom - mTop - mPaddingBottom - padding;
14226    }
14227
14228    /**
14229     * <p>Indicates whether this view is attached to a hardware accelerated
14230     * window or not.</p>
14231     *
14232     * <p>Even if this method returns true, it does not mean that every call
14233     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14234     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14235     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14236     * window is hardware accelerated,
14237     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14238     * return false, and this method will return true.</p>
14239     *
14240     * @return True if the view is attached to a window and the window is
14241     *         hardware accelerated; false in any other case.
14242     */
14243    public boolean isHardwareAccelerated() {
14244        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14245    }
14246
14247    /**
14248     * Sets a rectangular area on this view to which the view will be clipped
14249     * when it is drawn. Setting the value to null will remove the clip bounds
14250     * and the view will draw normally, using its full bounds.
14251     *
14252     * @param clipBounds The rectangular area, in the local coordinates of
14253     * this view, to which future drawing operations will be clipped.
14254     */
14255    public void setClipBounds(Rect clipBounds) {
14256        if (clipBounds != null) {
14257            if (clipBounds.equals(mClipBounds)) {
14258                return;
14259            }
14260            if (mClipBounds == null) {
14261                invalidate();
14262                mClipBounds = new Rect(clipBounds);
14263            } else {
14264                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14265                        Math.min(mClipBounds.top, clipBounds.top),
14266                        Math.max(mClipBounds.right, clipBounds.right),
14267                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14268                mClipBounds.set(clipBounds);
14269            }
14270        } else {
14271            if (mClipBounds != null) {
14272                invalidate();
14273                mClipBounds = null;
14274            }
14275        }
14276    }
14277
14278    /**
14279     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14280     *
14281     * @return A copy of the current clip bounds if clip bounds are set,
14282     * otherwise null.
14283     */
14284    public Rect getClipBounds() {
14285        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14286    }
14287
14288    /**
14289     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14290     * case of an active Animation being run on the view.
14291     */
14292    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14293            Animation a, boolean scalingRequired) {
14294        Transformation invalidationTransform;
14295        final int flags = parent.mGroupFlags;
14296        final boolean initialized = a.isInitialized();
14297        if (!initialized) {
14298            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14299            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14300            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14301            onAnimationStart();
14302        }
14303
14304        final Transformation t = parent.getChildTransformation();
14305        boolean more = a.getTransformation(drawingTime, t, 1f);
14306        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14307            if (parent.mInvalidationTransformation == null) {
14308                parent.mInvalidationTransformation = new Transformation();
14309            }
14310            invalidationTransform = parent.mInvalidationTransformation;
14311            a.getTransformation(drawingTime, invalidationTransform, 1f);
14312        } else {
14313            invalidationTransform = t;
14314        }
14315
14316        if (more) {
14317            if (!a.willChangeBounds()) {
14318                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14319                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14320                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14321                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14322                    // The child need to draw an animation, potentially offscreen, so
14323                    // make sure we do not cancel invalidate requests
14324                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14325                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14326                }
14327            } else {
14328                if (parent.mInvalidateRegion == null) {
14329                    parent.mInvalidateRegion = new RectF();
14330                }
14331                final RectF region = parent.mInvalidateRegion;
14332                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14333                        invalidationTransform);
14334
14335                // The child need to draw an animation, potentially offscreen, so
14336                // make sure we do not cancel invalidate requests
14337                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14338
14339                final int left = mLeft + (int) region.left;
14340                final int top = mTop + (int) region.top;
14341                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14342                        top + (int) (region.height() + .5f));
14343            }
14344        }
14345        return more;
14346    }
14347
14348    /**
14349     * This method is called by getDisplayList() when a display list is recorded for a View.
14350     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14351     */
14352    void setDisplayListProperties(RenderNode renderNode) {
14353        if (renderNode != null) {
14354            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14355            if (mParent instanceof ViewGroup) {
14356                renderNode.setClipToBounds(
14357                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14358            }
14359            float alpha = 1;
14360            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14361                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14362                ViewGroup parentVG = (ViewGroup) mParent;
14363                final Transformation t = parentVG.getChildTransformation();
14364                if (parentVG.getChildStaticTransformation(this, t)) {
14365                    final int transformType = t.getTransformationType();
14366                    if (transformType != Transformation.TYPE_IDENTITY) {
14367                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14368                            alpha = t.getAlpha();
14369                        }
14370                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14371                            renderNode.setStaticMatrix(t.getMatrix());
14372                        }
14373                    }
14374                }
14375            }
14376            if (mTransformationInfo != null) {
14377                alpha *= getFinalAlpha();
14378                if (alpha < 1) {
14379                    final int multipliedAlpha = (int) (255 * alpha);
14380                    if (onSetAlpha(multipliedAlpha)) {
14381                        alpha = 1;
14382                    }
14383                }
14384                renderNode.setAlpha(alpha);
14385            } else if (alpha < 1) {
14386                renderNode.setAlpha(alpha);
14387            }
14388        }
14389    }
14390
14391    /**
14392     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14393     * This draw() method is an implementation detail and is not intended to be overridden or
14394     * to be called from anywhere else other than ViewGroup.drawChild().
14395     */
14396    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14397        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14398        boolean more = false;
14399        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14400        final int flags = parent.mGroupFlags;
14401
14402        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14403            parent.getChildTransformation().clear();
14404            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14405        }
14406
14407        Transformation transformToApply = null;
14408        boolean concatMatrix = false;
14409
14410        boolean scalingRequired = false;
14411        boolean caching;
14412        int layerType = getLayerType();
14413
14414        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14415        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14416                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14417            caching = true;
14418            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14419            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14420        } else {
14421            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14422        }
14423
14424        final Animation a = getAnimation();
14425        if (a != null) {
14426            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14427            concatMatrix = a.willChangeTransformationMatrix();
14428            if (concatMatrix) {
14429                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14430            }
14431            transformToApply = parent.getChildTransformation();
14432        } else {
14433            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14434                // No longer animating: clear out old animation matrix
14435                mRenderNode.setAnimationMatrix(null);
14436                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14437            }
14438            if (!useDisplayListProperties &&
14439                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14440                final Transformation t = parent.getChildTransformation();
14441                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14442                if (hasTransform) {
14443                    final int transformType = t.getTransformationType();
14444                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14445                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14446                }
14447            }
14448        }
14449
14450        concatMatrix |= !childHasIdentityMatrix;
14451
14452        // Sets the flag as early as possible to allow draw() implementations
14453        // to call invalidate() successfully when doing animations
14454        mPrivateFlags |= PFLAG_DRAWN;
14455
14456        if (!concatMatrix &&
14457                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14458                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14459                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14460                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14461            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14462            return more;
14463        }
14464        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14465
14466        if (hardwareAccelerated) {
14467            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14468            // retain the flag's value temporarily in the mRecreateDisplayList flag
14469            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14470            mPrivateFlags &= ~PFLAG_INVALIDATED;
14471        }
14472
14473        RenderNode displayList = null;
14474        Bitmap cache = null;
14475        boolean hasDisplayList = false;
14476        if (caching) {
14477            if (!hardwareAccelerated) {
14478                if (layerType != LAYER_TYPE_NONE) {
14479                    layerType = LAYER_TYPE_SOFTWARE;
14480                    buildDrawingCache(true);
14481                }
14482                cache = getDrawingCache(true);
14483            } else {
14484                switch (layerType) {
14485                    case LAYER_TYPE_SOFTWARE:
14486                        if (useDisplayListProperties) {
14487                            hasDisplayList = canHaveDisplayList();
14488                        } else {
14489                            buildDrawingCache(true);
14490                            cache = getDrawingCache(true);
14491                        }
14492                        break;
14493                    case LAYER_TYPE_HARDWARE:
14494                        if (useDisplayListProperties) {
14495                            hasDisplayList = canHaveDisplayList();
14496                        }
14497                        break;
14498                    case LAYER_TYPE_NONE:
14499                        // Delay getting the display list until animation-driven alpha values are
14500                        // set up and possibly passed on to the view
14501                        hasDisplayList = canHaveDisplayList();
14502                        break;
14503                }
14504            }
14505        }
14506        useDisplayListProperties &= hasDisplayList;
14507        if (useDisplayListProperties) {
14508            displayList = getDisplayList();
14509            if (!displayList.isValid()) {
14510                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14511                // to getDisplayList(), the display list will be marked invalid and we should not
14512                // try to use it again.
14513                displayList = null;
14514                hasDisplayList = false;
14515                useDisplayListProperties = false;
14516            }
14517        }
14518
14519        int sx = 0;
14520        int sy = 0;
14521        if (!hasDisplayList) {
14522            computeScroll();
14523            sx = mScrollX;
14524            sy = mScrollY;
14525        }
14526
14527        final boolean hasNoCache = cache == null || hasDisplayList;
14528        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14529                layerType != LAYER_TYPE_HARDWARE;
14530
14531        int restoreTo = -1;
14532        if (!useDisplayListProperties || transformToApply != null) {
14533            restoreTo = canvas.save();
14534        }
14535        if (offsetForScroll) {
14536            canvas.translate(mLeft - sx, mTop - sy);
14537        } else {
14538            if (!useDisplayListProperties) {
14539                canvas.translate(mLeft, mTop);
14540            }
14541            if (scalingRequired) {
14542                if (useDisplayListProperties) {
14543                    // TODO: Might not need this if we put everything inside the DL
14544                    restoreTo = canvas.save();
14545                }
14546                // mAttachInfo cannot be null, otherwise scalingRequired == false
14547                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14548                canvas.scale(scale, scale);
14549            }
14550        }
14551
14552        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14553        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14554                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14555            if (transformToApply != null || !childHasIdentityMatrix) {
14556                int transX = 0;
14557                int transY = 0;
14558
14559                if (offsetForScroll) {
14560                    transX = -sx;
14561                    transY = -sy;
14562                }
14563
14564                if (transformToApply != null) {
14565                    if (concatMatrix) {
14566                        if (useDisplayListProperties) {
14567                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14568                        } else {
14569                            // Undo the scroll translation, apply the transformation matrix,
14570                            // then redo the scroll translate to get the correct result.
14571                            canvas.translate(-transX, -transY);
14572                            canvas.concat(transformToApply.getMatrix());
14573                            canvas.translate(transX, transY);
14574                        }
14575                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14576                    }
14577
14578                    float transformAlpha = transformToApply.getAlpha();
14579                    if (transformAlpha < 1) {
14580                        alpha *= transformAlpha;
14581                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14582                    }
14583                }
14584
14585                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14586                    canvas.translate(-transX, -transY);
14587                    canvas.concat(getMatrix());
14588                    canvas.translate(transX, transY);
14589                }
14590            }
14591
14592            // Deal with alpha if it is or used to be <1
14593            if (alpha < 1 ||
14594                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14595                if (alpha < 1) {
14596                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14597                } else {
14598                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14599                }
14600                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14601                if (hasNoCache) {
14602                    final int multipliedAlpha = (int) (255 * alpha);
14603                    if (!onSetAlpha(multipliedAlpha)) {
14604                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14605                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14606                                layerType != LAYER_TYPE_NONE) {
14607                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14608                        }
14609                        if (useDisplayListProperties) {
14610                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14611                        } else  if (layerType == LAYER_TYPE_NONE) {
14612                            final int scrollX = hasDisplayList ? 0 : sx;
14613                            final int scrollY = hasDisplayList ? 0 : sy;
14614                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14615                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14616                        }
14617                    } else {
14618                        // Alpha is handled by the child directly, clobber the layer's alpha
14619                        mPrivateFlags |= PFLAG_ALPHA_SET;
14620                    }
14621                }
14622            }
14623        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14624            onSetAlpha(255);
14625            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14626        }
14627
14628        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14629                !useDisplayListProperties && cache == null) {
14630            if (offsetForScroll) {
14631                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14632            } else {
14633                if (!scalingRequired || cache == null) {
14634                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14635                } else {
14636                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14637                }
14638            }
14639        }
14640
14641        if (!useDisplayListProperties && hasDisplayList) {
14642            displayList = getDisplayList();
14643            if (!displayList.isValid()) {
14644                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14645                // to getDisplayList(), the display list will be marked invalid and we should not
14646                // try to use it again.
14647                displayList = null;
14648                hasDisplayList = false;
14649            }
14650        }
14651
14652        if (hasNoCache) {
14653            boolean layerRendered = false;
14654            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14655                final HardwareLayer layer = getHardwareLayer();
14656                if (layer != null && layer.isValid()) {
14657                    mLayerPaint.setAlpha((int) (alpha * 255));
14658                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14659                    layerRendered = true;
14660                } else {
14661                    final int scrollX = hasDisplayList ? 0 : sx;
14662                    final int scrollY = hasDisplayList ? 0 : sy;
14663                    canvas.saveLayer(scrollX, scrollY,
14664                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14665                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14666                }
14667            }
14668
14669            if (!layerRendered) {
14670                if (!hasDisplayList) {
14671                    // Fast path for layouts with no backgrounds
14672                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14673                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14674                        dispatchDraw(canvas);
14675                    } else {
14676                        draw(canvas);
14677                    }
14678                } else {
14679                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14680                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14681                }
14682            }
14683        } else if (cache != null) {
14684            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14685            Paint cachePaint;
14686
14687            if (layerType == LAYER_TYPE_NONE) {
14688                cachePaint = parent.mCachePaint;
14689                if (cachePaint == null) {
14690                    cachePaint = new Paint();
14691                    cachePaint.setDither(false);
14692                    parent.mCachePaint = cachePaint;
14693                }
14694                if (alpha < 1) {
14695                    cachePaint.setAlpha((int) (alpha * 255));
14696                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14697                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14698                    cachePaint.setAlpha(255);
14699                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14700                }
14701            } else {
14702                cachePaint = mLayerPaint;
14703                cachePaint.setAlpha((int) (alpha * 255));
14704            }
14705            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14706        }
14707
14708        if (restoreTo >= 0) {
14709            canvas.restoreToCount(restoreTo);
14710        }
14711
14712        if (a != null && !more) {
14713            if (!hardwareAccelerated && !a.getFillAfter()) {
14714                onSetAlpha(255);
14715            }
14716            parent.finishAnimatingView(this, a);
14717        }
14718
14719        if (more && hardwareAccelerated) {
14720            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14721                // alpha animations should cause the child to recreate its display list
14722                invalidate(true);
14723            }
14724        }
14725
14726        mRecreateDisplayList = false;
14727
14728        return more;
14729    }
14730
14731    /**
14732     * Manually render this view (and all of its children) to the given Canvas.
14733     * The view must have already done a full layout before this function is
14734     * called.  When implementing a view, implement
14735     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14736     * If you do need to override this method, call the superclass version.
14737     *
14738     * @param canvas The Canvas to which the View is rendered.
14739     */
14740    public void draw(Canvas canvas) {
14741        if (mClipBounds != null) {
14742            canvas.clipRect(mClipBounds);
14743        }
14744        final int privateFlags = mPrivateFlags;
14745        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14746                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14747        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14748
14749        /*
14750         * Draw traversal performs several drawing steps which must be executed
14751         * in the appropriate order:
14752         *
14753         *      1. Draw the background
14754         *      2. If necessary, save the canvas' layers to prepare for fading
14755         *      3. Draw view's content
14756         *      4. Draw children
14757         *      5. If necessary, draw the fading edges and restore layers
14758         *      6. Draw decorations (scrollbars for instance)
14759         */
14760
14761        // Step 1, draw the background, if needed
14762        int saveCount;
14763
14764        if (!dirtyOpaque) {
14765            drawBackground(canvas);
14766        }
14767
14768        // skip step 2 & 5 if possible (common case)
14769        final int viewFlags = mViewFlags;
14770        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14771        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14772        if (!verticalEdges && !horizontalEdges) {
14773            // Step 3, draw the content
14774            if (!dirtyOpaque) onDraw(canvas);
14775
14776            // Step 4, draw the children
14777            dispatchDraw(canvas);
14778
14779            // Step 6, draw decorations (scrollbars)
14780            onDrawScrollBars(canvas);
14781
14782            if (mOverlay != null && !mOverlay.isEmpty()) {
14783                mOverlay.getOverlayView().dispatchDraw(canvas);
14784            }
14785
14786            // we're done...
14787            return;
14788        }
14789
14790        /*
14791         * Here we do the full fledged routine...
14792         * (this is an uncommon case where speed matters less,
14793         * this is why we repeat some of the tests that have been
14794         * done above)
14795         */
14796
14797        boolean drawTop = false;
14798        boolean drawBottom = false;
14799        boolean drawLeft = false;
14800        boolean drawRight = false;
14801
14802        float topFadeStrength = 0.0f;
14803        float bottomFadeStrength = 0.0f;
14804        float leftFadeStrength = 0.0f;
14805        float rightFadeStrength = 0.0f;
14806
14807        // Step 2, save the canvas' layers
14808        int paddingLeft = mPaddingLeft;
14809
14810        final boolean offsetRequired = isPaddingOffsetRequired();
14811        if (offsetRequired) {
14812            paddingLeft += getLeftPaddingOffset();
14813        }
14814
14815        int left = mScrollX + paddingLeft;
14816        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14817        int top = mScrollY + getFadeTop(offsetRequired);
14818        int bottom = top + getFadeHeight(offsetRequired);
14819
14820        if (offsetRequired) {
14821            right += getRightPaddingOffset();
14822            bottom += getBottomPaddingOffset();
14823        }
14824
14825        final ScrollabilityCache scrollabilityCache = mScrollCache;
14826        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14827        int length = (int) fadeHeight;
14828
14829        // clip the fade length if top and bottom fades overlap
14830        // overlapping fades produce odd-looking artifacts
14831        if (verticalEdges && (top + length > bottom - length)) {
14832            length = (bottom - top) / 2;
14833        }
14834
14835        // also clip horizontal fades if necessary
14836        if (horizontalEdges && (left + length > right - length)) {
14837            length = (right - left) / 2;
14838        }
14839
14840        if (verticalEdges) {
14841            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14842            drawTop = topFadeStrength * fadeHeight > 1.0f;
14843            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14844            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14845        }
14846
14847        if (horizontalEdges) {
14848            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14849            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14850            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14851            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14852        }
14853
14854        saveCount = canvas.getSaveCount();
14855
14856        int solidColor = getSolidColor();
14857        if (solidColor == 0) {
14858            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14859
14860            if (drawTop) {
14861                canvas.saveLayer(left, top, right, top + length, null, flags);
14862            }
14863
14864            if (drawBottom) {
14865                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14866            }
14867
14868            if (drawLeft) {
14869                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14870            }
14871
14872            if (drawRight) {
14873                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14874            }
14875        } else {
14876            scrollabilityCache.setFadeColor(solidColor);
14877        }
14878
14879        // Step 3, draw the content
14880        if (!dirtyOpaque) onDraw(canvas);
14881
14882        // Step 4, draw the children
14883        dispatchDraw(canvas);
14884
14885        // Step 5, draw the fade effect and restore layers
14886        final Paint p = scrollabilityCache.paint;
14887        final Matrix matrix = scrollabilityCache.matrix;
14888        final Shader fade = scrollabilityCache.shader;
14889
14890        if (drawTop) {
14891            matrix.setScale(1, fadeHeight * topFadeStrength);
14892            matrix.postTranslate(left, top);
14893            fade.setLocalMatrix(matrix);
14894            canvas.drawRect(left, top, right, top + length, p);
14895        }
14896
14897        if (drawBottom) {
14898            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14899            matrix.postRotate(180);
14900            matrix.postTranslate(left, bottom);
14901            fade.setLocalMatrix(matrix);
14902            canvas.drawRect(left, bottom - length, right, bottom, p);
14903        }
14904
14905        if (drawLeft) {
14906            matrix.setScale(1, fadeHeight * leftFadeStrength);
14907            matrix.postRotate(-90);
14908            matrix.postTranslate(left, top);
14909            fade.setLocalMatrix(matrix);
14910            canvas.drawRect(left, top, left + length, bottom, p);
14911        }
14912
14913        if (drawRight) {
14914            matrix.setScale(1, fadeHeight * rightFadeStrength);
14915            matrix.postRotate(90);
14916            matrix.postTranslate(right, top);
14917            fade.setLocalMatrix(matrix);
14918            canvas.drawRect(right - length, top, right, bottom, p);
14919        }
14920
14921        canvas.restoreToCount(saveCount);
14922
14923        // Step 6, draw decorations (scrollbars)
14924        onDrawScrollBars(canvas);
14925
14926        if (mOverlay != null && !mOverlay.isEmpty()) {
14927            mOverlay.getOverlayView().dispatchDraw(canvas);
14928        }
14929    }
14930
14931    /**
14932     * Draws the background onto the specified canvas.
14933     *
14934     * @param canvas Canvas on which to draw the background
14935     */
14936    private void drawBackground(Canvas canvas) {
14937        final Drawable background = mBackground;
14938        if (background == null) {
14939            return;
14940        }
14941
14942        if (mBackgroundSizeChanged) {
14943            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14944            mBackgroundSizeChanged = false;
14945            queryOutlineFromBackgroundIfUndefined();
14946        }
14947
14948        // Attempt to use a display list if requested.
14949        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14950                && mAttachInfo.mHardwareRenderer != null) {
14951            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
14952
14953            final RenderNode displayList = mBackgroundDisplayList;
14954            if (displayList != null && displayList.isValid()) {
14955                setBackgroundDisplayListProperties(displayList);
14956                ((HardwareCanvas) canvas).drawDisplayList(displayList);
14957                return;
14958            }
14959        }
14960
14961        final int scrollX = mScrollX;
14962        final int scrollY = mScrollY;
14963        if ((scrollX | scrollY) == 0) {
14964            background.draw(canvas);
14965        } else {
14966            canvas.translate(scrollX, scrollY);
14967            background.draw(canvas);
14968            canvas.translate(-scrollX, -scrollY);
14969        }
14970    }
14971
14972    /**
14973     * Set up background drawable display list properties.
14974     *
14975     * @param displayList Valid display list for the background drawable
14976     */
14977    private void setBackgroundDisplayListProperties(RenderNode displayList) {
14978        displayList.setTranslationX(mScrollX);
14979        displayList.setTranslationY(mScrollY);
14980    }
14981
14982    /**
14983     * Creates a new display list or updates the existing display list for the
14984     * specified Drawable.
14985     *
14986     * @param drawable Drawable for which to create a display list
14987     * @param displayList Existing display list, or {@code null}
14988     * @return A valid display list for the specified drawable
14989     */
14990    private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) {
14991        if (displayList == null) {
14992            displayList = RenderNode.create(drawable.getClass().getName());
14993        }
14994
14995        final Rect bounds = drawable.getBounds();
14996        final int width = bounds.width();
14997        final int height = bounds.height();
14998        final HardwareCanvas canvas = displayList.start(width, height);
14999        try {
15000            drawable.draw(canvas);
15001        } finally {
15002            displayList.end(canvas);
15003        }
15004
15005        // Set up drawable properties that are view-independent.
15006        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15007        displayList.setProjectBackwards(drawable.isProjected());
15008        displayList.setProjectionReceiver(true);
15009        displayList.setClipToBounds(false);
15010        return displayList;
15011    }
15012
15013    /**
15014     * Returns the overlay for this view, creating it if it does not yet exist.
15015     * Adding drawables to the overlay will cause them to be displayed whenever
15016     * the view itself is redrawn. Objects in the overlay should be actively
15017     * managed: remove them when they should not be displayed anymore. The
15018     * overlay will always have the same size as its host view.
15019     *
15020     * <p>Note: Overlays do not currently work correctly with {@link
15021     * SurfaceView} or {@link TextureView}; contents in overlays for these
15022     * types of views may not display correctly.</p>
15023     *
15024     * @return The ViewOverlay object for this view.
15025     * @see ViewOverlay
15026     */
15027    public ViewOverlay getOverlay() {
15028        if (mOverlay == null) {
15029            mOverlay = new ViewOverlay(mContext, this);
15030        }
15031        return mOverlay;
15032    }
15033
15034    /**
15035     * Override this if your view is known to always be drawn on top of a solid color background,
15036     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15037     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15038     * should be set to 0xFF.
15039     *
15040     * @see #setVerticalFadingEdgeEnabled(boolean)
15041     * @see #setHorizontalFadingEdgeEnabled(boolean)
15042     *
15043     * @return The known solid color background for this view, or 0 if the color may vary
15044     */
15045    @ViewDebug.ExportedProperty(category = "drawing")
15046    public int getSolidColor() {
15047        return 0;
15048    }
15049
15050    /**
15051     * Build a human readable string representation of the specified view flags.
15052     *
15053     * @param flags the view flags to convert to a string
15054     * @return a String representing the supplied flags
15055     */
15056    private static String printFlags(int flags) {
15057        String output = "";
15058        int numFlags = 0;
15059        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15060            output += "TAKES_FOCUS";
15061            numFlags++;
15062        }
15063
15064        switch (flags & VISIBILITY_MASK) {
15065        case INVISIBLE:
15066            if (numFlags > 0) {
15067                output += " ";
15068            }
15069            output += "INVISIBLE";
15070            // USELESS HERE numFlags++;
15071            break;
15072        case GONE:
15073            if (numFlags > 0) {
15074                output += " ";
15075            }
15076            output += "GONE";
15077            // USELESS HERE numFlags++;
15078            break;
15079        default:
15080            break;
15081        }
15082        return output;
15083    }
15084
15085    /**
15086     * Build a human readable string representation of the specified private
15087     * view flags.
15088     *
15089     * @param privateFlags the private view flags to convert to a string
15090     * @return a String representing the supplied flags
15091     */
15092    private static String printPrivateFlags(int privateFlags) {
15093        String output = "";
15094        int numFlags = 0;
15095
15096        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15097            output += "WANTS_FOCUS";
15098            numFlags++;
15099        }
15100
15101        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15102            if (numFlags > 0) {
15103                output += " ";
15104            }
15105            output += "FOCUSED";
15106            numFlags++;
15107        }
15108
15109        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15110            if (numFlags > 0) {
15111                output += " ";
15112            }
15113            output += "SELECTED";
15114            numFlags++;
15115        }
15116
15117        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15118            if (numFlags > 0) {
15119                output += " ";
15120            }
15121            output += "IS_ROOT_NAMESPACE";
15122            numFlags++;
15123        }
15124
15125        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15126            if (numFlags > 0) {
15127                output += " ";
15128            }
15129            output += "HAS_BOUNDS";
15130            numFlags++;
15131        }
15132
15133        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15134            if (numFlags > 0) {
15135                output += " ";
15136            }
15137            output += "DRAWN";
15138            // USELESS HERE numFlags++;
15139        }
15140        return output;
15141    }
15142
15143    /**
15144     * <p>Indicates whether or not this view's layout will be requested during
15145     * the next hierarchy layout pass.</p>
15146     *
15147     * @return true if the layout will be forced during next layout pass
15148     */
15149    public boolean isLayoutRequested() {
15150        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15151    }
15152
15153    /**
15154     * Return true if o is a ViewGroup that is laying out using optical bounds.
15155     * @hide
15156     */
15157    public static boolean isLayoutModeOptical(Object o) {
15158        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15159    }
15160
15161    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15162        Insets parentInsets = mParent instanceof View ?
15163                ((View) mParent).getOpticalInsets() : Insets.NONE;
15164        Insets childInsets = getOpticalInsets();
15165        return setFrame(
15166                left   + parentInsets.left - childInsets.left,
15167                top    + parentInsets.top  - childInsets.top,
15168                right  + parentInsets.left + childInsets.right,
15169                bottom + parentInsets.top  + childInsets.bottom);
15170    }
15171
15172    /**
15173     * Assign a size and position to a view and all of its
15174     * descendants
15175     *
15176     * <p>This is the second phase of the layout mechanism.
15177     * (The first is measuring). In this phase, each parent calls
15178     * layout on all of its children to position them.
15179     * This is typically done using the child measurements
15180     * that were stored in the measure pass().</p>
15181     *
15182     * <p>Derived classes should not override this method.
15183     * Derived classes with children should override
15184     * onLayout. In that method, they should
15185     * call layout on each of their children.</p>
15186     *
15187     * @param l Left position, relative to parent
15188     * @param t Top position, relative to parent
15189     * @param r Right position, relative to parent
15190     * @param b Bottom position, relative to parent
15191     */
15192    @SuppressWarnings({"unchecked"})
15193    public void layout(int l, int t, int r, int b) {
15194        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15195            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15196            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15197        }
15198
15199        int oldL = mLeft;
15200        int oldT = mTop;
15201        int oldB = mBottom;
15202        int oldR = mRight;
15203
15204        boolean changed = isLayoutModeOptical(mParent) ?
15205                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15206
15207        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15208            onLayout(changed, l, t, r, b);
15209            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15210
15211            ListenerInfo li = mListenerInfo;
15212            if (li != null && li.mOnLayoutChangeListeners != null) {
15213                ArrayList<OnLayoutChangeListener> listenersCopy =
15214                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15215                int numListeners = listenersCopy.size();
15216                for (int i = 0; i < numListeners; ++i) {
15217                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15218                }
15219            }
15220        }
15221
15222        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15223        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15224    }
15225
15226    /**
15227     * Called from layout when this view should
15228     * assign a size and position to each of its children.
15229     *
15230     * Derived classes with children should override
15231     * this method and call layout on each of
15232     * their children.
15233     * @param changed This is a new size or position for this view
15234     * @param left Left position, relative to parent
15235     * @param top Top position, relative to parent
15236     * @param right Right position, relative to parent
15237     * @param bottom Bottom position, relative to parent
15238     */
15239    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15240    }
15241
15242    /**
15243     * Assign a size and position to this view.
15244     *
15245     * This is called from layout.
15246     *
15247     * @param left Left position, relative to parent
15248     * @param top Top position, relative to parent
15249     * @param right Right position, relative to parent
15250     * @param bottom Bottom position, relative to parent
15251     * @return true if the new size and position are different than the
15252     *         previous ones
15253     * {@hide}
15254     */
15255    protected boolean setFrame(int left, int top, int right, int bottom) {
15256        boolean changed = false;
15257
15258        if (DBG) {
15259            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15260                    + right + "," + bottom + ")");
15261        }
15262
15263        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15264            changed = true;
15265
15266            // Remember our drawn bit
15267            int drawn = mPrivateFlags & PFLAG_DRAWN;
15268
15269            int oldWidth = mRight - mLeft;
15270            int oldHeight = mBottom - mTop;
15271            int newWidth = right - left;
15272            int newHeight = bottom - top;
15273            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15274
15275            // Invalidate our old position
15276            invalidate(sizeChanged);
15277
15278            mLeft = left;
15279            mTop = top;
15280            mRight = right;
15281            mBottom = bottom;
15282            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15283
15284            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15285
15286
15287            if (sizeChanged) {
15288                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15289            }
15290
15291            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15292                // If we are visible, force the DRAWN bit to on so that
15293                // this invalidate will go through (at least to our parent).
15294                // This is because someone may have invalidated this view
15295                // before this call to setFrame came in, thereby clearing
15296                // the DRAWN bit.
15297                mPrivateFlags |= PFLAG_DRAWN;
15298                invalidate(sizeChanged);
15299                // parent display list may need to be recreated based on a change in the bounds
15300                // of any child
15301                invalidateParentCaches();
15302            }
15303
15304            // Reset drawn bit to original value (invalidate turns it off)
15305            mPrivateFlags |= drawn;
15306
15307            mBackgroundSizeChanged = true;
15308
15309            notifySubtreeAccessibilityStateChangedIfNeeded();
15310        }
15311        return changed;
15312    }
15313
15314    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15315        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15316        if (mOverlay != null) {
15317            mOverlay.getOverlayView().setRight(newWidth);
15318            mOverlay.getOverlayView().setBottom(newHeight);
15319        }
15320    }
15321
15322    /**
15323     * Finalize inflating a view from XML.  This is called as the last phase
15324     * of inflation, after all child views have been added.
15325     *
15326     * <p>Even if the subclass overrides onFinishInflate, they should always be
15327     * sure to call the super method, so that we get called.
15328     */
15329    protected void onFinishInflate() {
15330    }
15331
15332    /**
15333     * Returns the resources associated with this view.
15334     *
15335     * @return Resources object.
15336     */
15337    public Resources getResources() {
15338        return mResources;
15339    }
15340
15341    /**
15342     * Invalidates the specified Drawable.
15343     *
15344     * @param drawable the drawable to invalidate
15345     */
15346    @Override
15347    public void invalidateDrawable(@NonNull Drawable drawable) {
15348        if (verifyDrawable(drawable)) {
15349            final Rect dirty = drawable.getDirtyBounds();
15350            final int scrollX = mScrollX;
15351            final int scrollY = mScrollY;
15352
15353            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15354                    dirty.right + scrollX, dirty.bottom + scrollY);
15355
15356            if (drawable == mBackground) {
15357                queryOutlineFromBackgroundIfUndefined();
15358            }
15359        }
15360    }
15361
15362    /**
15363     * Schedules an action on a drawable to occur at a specified time.
15364     *
15365     * @param who the recipient of the action
15366     * @param what the action to run on the drawable
15367     * @param when the time at which the action must occur. Uses the
15368     *        {@link SystemClock#uptimeMillis} timebase.
15369     */
15370    @Override
15371    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15372        if (verifyDrawable(who) && what != null) {
15373            final long delay = when - SystemClock.uptimeMillis();
15374            if (mAttachInfo != null) {
15375                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15376                        Choreographer.CALLBACK_ANIMATION, what, who,
15377                        Choreographer.subtractFrameDelay(delay));
15378            } else {
15379                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15380            }
15381        }
15382    }
15383
15384    /**
15385     * Cancels a scheduled action on a drawable.
15386     *
15387     * @param who the recipient of the action
15388     * @param what the action to cancel
15389     */
15390    @Override
15391    public void unscheduleDrawable(Drawable who, Runnable what) {
15392        if (verifyDrawable(who) && what != null) {
15393            if (mAttachInfo != null) {
15394                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15395                        Choreographer.CALLBACK_ANIMATION, what, who);
15396            }
15397            ViewRootImpl.getRunQueue().removeCallbacks(what);
15398        }
15399    }
15400
15401    /**
15402     * Unschedule any events associated with the given Drawable.  This can be
15403     * used when selecting a new Drawable into a view, so that the previous
15404     * one is completely unscheduled.
15405     *
15406     * @param who The Drawable to unschedule.
15407     *
15408     * @see #drawableStateChanged
15409     */
15410    public void unscheduleDrawable(Drawable who) {
15411        if (mAttachInfo != null && who != null) {
15412            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15413                    Choreographer.CALLBACK_ANIMATION, null, who);
15414        }
15415    }
15416
15417    /**
15418     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15419     * that the View directionality can and will be resolved before its Drawables.
15420     *
15421     * Will call {@link View#onResolveDrawables} when resolution is done.
15422     *
15423     * @hide
15424     */
15425    protected void resolveDrawables() {
15426        // Drawables resolution may need to happen before resolving the layout direction (which is
15427        // done only during the measure() call).
15428        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15429        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15430        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15431        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15432        // direction to be resolved as its resolved value will be the same as its raw value.
15433        if (!isLayoutDirectionResolved() &&
15434                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15435            return;
15436        }
15437
15438        final int layoutDirection = isLayoutDirectionResolved() ?
15439                getLayoutDirection() : getRawLayoutDirection();
15440
15441        if (mBackground != null) {
15442            mBackground.setLayoutDirection(layoutDirection);
15443        }
15444        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15445        onResolveDrawables(layoutDirection);
15446    }
15447
15448    /**
15449     * Called when layout direction has been resolved.
15450     *
15451     * The default implementation does nothing.
15452     *
15453     * @param layoutDirection The resolved layout direction.
15454     *
15455     * @see #LAYOUT_DIRECTION_LTR
15456     * @see #LAYOUT_DIRECTION_RTL
15457     *
15458     * @hide
15459     */
15460    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15461    }
15462
15463    /**
15464     * @hide
15465     */
15466    protected void resetResolvedDrawables() {
15467        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15468    }
15469
15470    private boolean isDrawablesResolved() {
15471        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15472    }
15473
15474    /**
15475     * If your view subclass is displaying its own Drawable objects, it should
15476     * override this function and return true for any Drawable it is
15477     * displaying.  This allows animations for those drawables to be
15478     * scheduled.
15479     *
15480     * <p>Be sure to call through to the super class when overriding this
15481     * function.
15482     *
15483     * @param who The Drawable to verify.  Return true if it is one you are
15484     *            displaying, else return the result of calling through to the
15485     *            super class.
15486     *
15487     * @return boolean If true than the Drawable is being displayed in the
15488     *         view; else false and it is not allowed to animate.
15489     *
15490     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15491     * @see #drawableStateChanged()
15492     */
15493    protected boolean verifyDrawable(Drawable who) {
15494        return who == mBackground;
15495    }
15496
15497    /**
15498     * This function is called whenever the state of the view changes in such
15499     * a way that it impacts the state of drawables being shown.
15500     * <p>
15501     * If the View has a StateListAnimator, it will also be called to run necessary state
15502     * change animations.
15503     * <p>
15504     * Be sure to call through to the superclass when overriding this function.
15505     *
15506     * @see Drawable#setState(int[])
15507     */
15508    protected void drawableStateChanged() {
15509        final Drawable d = mBackground;
15510        if (d != null && d.isStateful()) {
15511            d.setState(getDrawableState());
15512        }
15513
15514        if (mStateListAnimator != null) {
15515            mStateListAnimator.setState(getDrawableState());
15516        }
15517    }
15518
15519    /**
15520     * This function is called whenever the drawable hotspot changes.
15521     * <p>
15522     * Be sure to call through to the superclass when overriding this function.
15523     *
15524     * @param x hotspot x coordinate
15525     * @param y hotspot y coordinate
15526     */
15527    public void drawableHotspotChanged(float x, float y) {
15528        if (mBackground != null) {
15529            mBackground.setHotspot(x, y);
15530        }
15531    }
15532
15533    /**
15534     * Call this to force a view to update its drawable state. This will cause
15535     * drawableStateChanged to be called on this view. Views that are interested
15536     * in the new state should call getDrawableState.
15537     *
15538     * @see #drawableStateChanged
15539     * @see #getDrawableState
15540     */
15541    public void refreshDrawableState() {
15542        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15543        drawableStateChanged();
15544
15545        ViewParent parent = mParent;
15546        if (parent != null) {
15547            parent.childDrawableStateChanged(this);
15548        }
15549    }
15550
15551    /**
15552     * Return an array of resource IDs of the drawable states representing the
15553     * current state of the view.
15554     *
15555     * @return The current drawable state
15556     *
15557     * @see Drawable#setState(int[])
15558     * @see #drawableStateChanged()
15559     * @see #onCreateDrawableState(int)
15560     */
15561    public final int[] getDrawableState() {
15562        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15563            return mDrawableState;
15564        } else {
15565            mDrawableState = onCreateDrawableState(0);
15566            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15567            return mDrawableState;
15568        }
15569    }
15570
15571    /**
15572     * Generate the new {@link android.graphics.drawable.Drawable} state for
15573     * this view. This is called by the view
15574     * system when the cached Drawable state is determined to be invalid.  To
15575     * retrieve the current state, you should use {@link #getDrawableState}.
15576     *
15577     * @param extraSpace if non-zero, this is the number of extra entries you
15578     * would like in the returned array in which you can place your own
15579     * states.
15580     *
15581     * @return Returns an array holding the current {@link Drawable} state of
15582     * the view.
15583     *
15584     * @see #mergeDrawableStates(int[], int[])
15585     */
15586    protected int[] onCreateDrawableState(int extraSpace) {
15587        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15588                mParent instanceof View) {
15589            return ((View) mParent).onCreateDrawableState(extraSpace);
15590        }
15591
15592        int[] drawableState;
15593
15594        int privateFlags = mPrivateFlags;
15595
15596        int viewStateIndex = 0;
15597        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15598        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15599        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15600        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15601        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15602        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15603        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15604                HardwareRenderer.isAvailable()) {
15605            // This is set if HW acceleration is requested, even if the current
15606            // process doesn't allow it.  This is just to allow app preview
15607            // windows to better match their app.
15608            viewStateIndex |= VIEW_STATE_ACCELERATED;
15609        }
15610        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15611
15612        final int privateFlags2 = mPrivateFlags2;
15613        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15614        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15615
15616        drawableState = VIEW_STATE_SETS[viewStateIndex];
15617
15618        //noinspection ConstantIfStatement
15619        if (false) {
15620            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15621            Log.i("View", toString()
15622                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15623                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15624                    + " fo=" + hasFocus()
15625                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15626                    + " wf=" + hasWindowFocus()
15627                    + ": " + Arrays.toString(drawableState));
15628        }
15629
15630        if (extraSpace == 0) {
15631            return drawableState;
15632        }
15633
15634        final int[] fullState;
15635        if (drawableState != null) {
15636            fullState = new int[drawableState.length + extraSpace];
15637            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15638        } else {
15639            fullState = new int[extraSpace];
15640        }
15641
15642        return fullState;
15643    }
15644
15645    /**
15646     * Merge your own state values in <var>additionalState</var> into the base
15647     * state values <var>baseState</var> that were returned by
15648     * {@link #onCreateDrawableState(int)}.
15649     *
15650     * @param baseState The base state values returned by
15651     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15652     * own additional state values.
15653     *
15654     * @param additionalState The additional state values you would like
15655     * added to <var>baseState</var>; this array is not modified.
15656     *
15657     * @return As a convenience, the <var>baseState</var> array you originally
15658     * passed into the function is returned.
15659     *
15660     * @see #onCreateDrawableState(int)
15661     */
15662    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15663        final int N = baseState.length;
15664        int i = N - 1;
15665        while (i >= 0 && baseState[i] == 0) {
15666            i--;
15667        }
15668        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15669        return baseState;
15670    }
15671
15672    /**
15673     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15674     * on all Drawable objects associated with this view.
15675     * <p>
15676     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15677     * attached to this view.
15678     */
15679    public void jumpDrawablesToCurrentState() {
15680        if (mBackground != null) {
15681            mBackground.jumpToCurrentState();
15682        }
15683        if (mStateListAnimator != null) {
15684            mStateListAnimator.jumpToCurrentState();
15685        }
15686    }
15687
15688    /**
15689     * Sets the background color for this view.
15690     * @param color the color of the background
15691     */
15692    @RemotableViewMethod
15693    public void setBackgroundColor(int color) {
15694        if (mBackground instanceof ColorDrawable) {
15695            ((ColorDrawable) mBackground.mutate()).setColor(color);
15696            computeOpaqueFlags();
15697            mBackgroundResource = 0;
15698        } else {
15699            setBackground(new ColorDrawable(color));
15700        }
15701    }
15702
15703    /**
15704     * Set the background to a given resource. The resource should refer to
15705     * a Drawable object or 0 to remove the background.
15706     * @param resid The identifier of the resource.
15707     *
15708     * @attr ref android.R.styleable#View_background
15709     */
15710    @RemotableViewMethod
15711    public void setBackgroundResource(int resid) {
15712        if (resid != 0 && resid == mBackgroundResource) {
15713            return;
15714        }
15715
15716        Drawable d = null;
15717        if (resid != 0) {
15718            d = mContext.getDrawable(resid);
15719        }
15720        setBackground(d);
15721
15722        mBackgroundResource = resid;
15723    }
15724
15725    /**
15726     * Set the background to a given Drawable, or remove the background. If the
15727     * background has padding, this View's padding is set to the background's
15728     * padding. However, when a background is removed, this View's padding isn't
15729     * touched. If setting the padding is desired, please use
15730     * {@link #setPadding(int, int, int, int)}.
15731     *
15732     * @param background The Drawable to use as the background, or null to remove the
15733     *        background
15734     */
15735    public void setBackground(Drawable background) {
15736        //noinspection deprecation
15737        setBackgroundDrawable(background);
15738    }
15739
15740    /**
15741     * @deprecated use {@link #setBackground(Drawable)} instead
15742     */
15743    @Deprecated
15744    public void setBackgroundDrawable(Drawable background) {
15745        computeOpaqueFlags();
15746
15747        if (background == mBackground) {
15748            return;
15749        }
15750
15751        boolean requestLayout = false;
15752
15753        mBackgroundResource = 0;
15754
15755        /*
15756         * Regardless of whether we're setting a new background or not, we want
15757         * to clear the previous drawable.
15758         */
15759        if (mBackground != null) {
15760            mBackground.setCallback(null);
15761            unscheduleDrawable(mBackground);
15762        }
15763
15764        if (background != null) {
15765            Rect padding = sThreadLocal.get();
15766            if (padding == null) {
15767                padding = new Rect();
15768                sThreadLocal.set(padding);
15769            }
15770            resetResolvedDrawables();
15771            background.setLayoutDirection(getLayoutDirection());
15772            if (background.getPadding(padding)) {
15773                resetResolvedPadding();
15774                switch (background.getLayoutDirection()) {
15775                    case LAYOUT_DIRECTION_RTL:
15776                        mUserPaddingLeftInitial = padding.right;
15777                        mUserPaddingRightInitial = padding.left;
15778                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15779                        break;
15780                    case LAYOUT_DIRECTION_LTR:
15781                    default:
15782                        mUserPaddingLeftInitial = padding.left;
15783                        mUserPaddingRightInitial = padding.right;
15784                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15785                }
15786                mLeftPaddingDefined = false;
15787                mRightPaddingDefined = false;
15788            }
15789
15790            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15791            // if it has a different minimum size, we should layout again
15792            if (mBackground == null
15793                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15794                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15795                requestLayout = true;
15796            }
15797
15798            background.setCallback(this);
15799            if (background.isStateful()) {
15800                background.setState(getDrawableState());
15801            }
15802            background.setVisible(getVisibility() == VISIBLE, false);
15803            mBackground = background;
15804
15805            applyBackgroundTint();
15806
15807            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15808                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15809                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15810                requestLayout = true;
15811            }
15812        } else {
15813            /* Remove the background */
15814            mBackground = null;
15815
15816            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15817                /*
15818                 * This view ONLY drew the background before and we're removing
15819                 * the background, so now it won't draw anything
15820                 * (hence we SKIP_DRAW)
15821                 */
15822                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15823                mPrivateFlags |= PFLAG_SKIP_DRAW;
15824            }
15825
15826            /*
15827             * When the background is set, we try to apply its padding to this
15828             * View. When the background is removed, we don't touch this View's
15829             * padding. This is noted in the Javadocs. Hence, we don't need to
15830             * requestLayout(), the invalidate() below is sufficient.
15831             */
15832
15833            // The old background's minimum size could have affected this
15834            // View's layout, so let's requestLayout
15835            requestLayout = true;
15836        }
15837
15838        computeOpaqueFlags();
15839
15840        if (requestLayout) {
15841            requestLayout();
15842        }
15843
15844        mBackgroundSizeChanged = true;
15845        invalidate(true);
15846    }
15847
15848    /**
15849     * Gets the background drawable
15850     *
15851     * @return The drawable used as the background for this view, if any.
15852     *
15853     * @see #setBackground(Drawable)
15854     *
15855     * @attr ref android.R.styleable#View_background
15856     */
15857    public Drawable getBackground() {
15858        return mBackground;
15859    }
15860
15861    /**
15862     * Applies a tint to the background drawable.
15863     * <p>
15864     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15865     * mutate the drawable and apply the specified tint and tint mode using
15866     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15867     *
15868     * @param tint the tint to apply, may be {@code null} to clear tint
15869     * @param tintMode the blending mode used to apply the tint, may be
15870     *                 {@code null} to clear tint
15871     *
15872     * @attr ref android.R.styleable#View_backgroundTint
15873     * @attr ref android.R.styleable#View_backgroundTintMode
15874     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15875     */
15876    private void setBackgroundTint(@Nullable ColorStateList tint,
15877            @Nullable PorterDuff.Mode tintMode) {
15878        mBackgroundTint = tint;
15879        mBackgroundTintMode = tintMode;
15880        mHasBackgroundTint = true;
15881
15882        applyBackgroundTint();
15883    }
15884
15885    /**
15886     * Applies a tint to the background drawable. Does not modify the current tint
15887     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15888     * <p>
15889     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15890     * mutate the drawable and apply the specified tint and tint mode using
15891     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15892     *
15893     * @param tint the tint to apply, may be {@code null} to clear tint
15894     *
15895     * @attr ref android.R.styleable#View_backgroundTint
15896     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15897     */
15898    public void setBackgroundTint(@Nullable ColorStateList tint) {
15899        setBackgroundTint(tint, mBackgroundTintMode);
15900    }
15901
15902    /**
15903     * @return the tint applied to the background drawable
15904     * @attr ref android.R.styleable#View_backgroundTint
15905     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15906     */
15907    @Nullable
15908    public ColorStateList getBackgroundTint() {
15909        return mBackgroundTint;
15910    }
15911
15912    /**
15913     * Specifies the blending mode used to apply the tint specified by
15914     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15915     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15916     *
15917     * @param tintMode the blending mode used to apply the tint, may be
15918     *                 {@code null} to clear tint
15919     * @attr ref android.R.styleable#View_backgroundTintMode
15920     * @see #setBackgroundTint(ColorStateList)
15921     */
15922    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15923        setBackgroundTint(mBackgroundTint, tintMode);
15924    }
15925
15926    /**
15927     * @return the blending mode used to apply the tint to the background drawable
15928     * @attr ref android.R.styleable#View_backgroundTintMode
15929     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15930     */
15931    @Nullable
15932    public PorterDuff.Mode getBackgroundTintMode() {
15933        return mBackgroundTintMode;
15934    }
15935
15936    private void applyBackgroundTint() {
15937        if (mBackground != null && mHasBackgroundTint) {
15938            mBackground = mBackground.mutate();
15939            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15940        }
15941    }
15942
15943    /**
15944     * Sets the padding. The view may add on the space required to display
15945     * the scrollbars, depending on the style and visibility of the scrollbars.
15946     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15947     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15948     * from the values set in this call.
15949     *
15950     * @attr ref android.R.styleable#View_padding
15951     * @attr ref android.R.styleable#View_paddingBottom
15952     * @attr ref android.R.styleable#View_paddingLeft
15953     * @attr ref android.R.styleable#View_paddingRight
15954     * @attr ref android.R.styleable#View_paddingTop
15955     * @param left the left padding in pixels
15956     * @param top the top padding in pixels
15957     * @param right the right padding in pixels
15958     * @param bottom the bottom padding in pixels
15959     */
15960    public void setPadding(int left, int top, int right, int bottom) {
15961        resetResolvedPadding();
15962
15963        mUserPaddingStart = UNDEFINED_PADDING;
15964        mUserPaddingEnd = UNDEFINED_PADDING;
15965
15966        mUserPaddingLeftInitial = left;
15967        mUserPaddingRightInitial = right;
15968
15969        mLeftPaddingDefined = true;
15970        mRightPaddingDefined = true;
15971
15972        internalSetPadding(left, top, right, bottom);
15973    }
15974
15975    /**
15976     * @hide
15977     */
15978    protected void internalSetPadding(int left, int top, int right, int bottom) {
15979        mUserPaddingLeft = left;
15980        mUserPaddingRight = right;
15981        mUserPaddingBottom = bottom;
15982
15983        final int viewFlags = mViewFlags;
15984        boolean changed = false;
15985
15986        // Common case is there are no scroll bars.
15987        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15988            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15989                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15990                        ? 0 : getVerticalScrollbarWidth();
15991                switch (mVerticalScrollbarPosition) {
15992                    case SCROLLBAR_POSITION_DEFAULT:
15993                        if (isLayoutRtl()) {
15994                            left += offset;
15995                        } else {
15996                            right += offset;
15997                        }
15998                        break;
15999                    case SCROLLBAR_POSITION_RIGHT:
16000                        right += offset;
16001                        break;
16002                    case SCROLLBAR_POSITION_LEFT:
16003                        left += offset;
16004                        break;
16005                }
16006            }
16007            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16008                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16009                        ? 0 : getHorizontalScrollbarHeight();
16010            }
16011        }
16012
16013        if (mPaddingLeft != left) {
16014            changed = true;
16015            mPaddingLeft = left;
16016        }
16017        if (mPaddingTop != top) {
16018            changed = true;
16019            mPaddingTop = top;
16020        }
16021        if (mPaddingRight != right) {
16022            changed = true;
16023            mPaddingRight = right;
16024        }
16025        if (mPaddingBottom != bottom) {
16026            changed = true;
16027            mPaddingBottom = bottom;
16028        }
16029
16030        if (changed) {
16031            requestLayout();
16032        }
16033    }
16034
16035    /**
16036     * Sets the relative padding. The view may add on the space required to display
16037     * the scrollbars, depending on the style and visibility of the scrollbars.
16038     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16039     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16040     * from the values set in this call.
16041     *
16042     * @attr ref android.R.styleable#View_padding
16043     * @attr ref android.R.styleable#View_paddingBottom
16044     * @attr ref android.R.styleable#View_paddingStart
16045     * @attr ref android.R.styleable#View_paddingEnd
16046     * @attr ref android.R.styleable#View_paddingTop
16047     * @param start the start padding in pixels
16048     * @param top the top padding in pixels
16049     * @param end the end padding in pixels
16050     * @param bottom the bottom padding in pixels
16051     */
16052    public void setPaddingRelative(int start, int top, int end, int bottom) {
16053        resetResolvedPadding();
16054
16055        mUserPaddingStart = start;
16056        mUserPaddingEnd = end;
16057        mLeftPaddingDefined = true;
16058        mRightPaddingDefined = true;
16059
16060        switch(getLayoutDirection()) {
16061            case LAYOUT_DIRECTION_RTL:
16062                mUserPaddingLeftInitial = end;
16063                mUserPaddingRightInitial = start;
16064                internalSetPadding(end, top, start, bottom);
16065                break;
16066            case LAYOUT_DIRECTION_LTR:
16067            default:
16068                mUserPaddingLeftInitial = start;
16069                mUserPaddingRightInitial = end;
16070                internalSetPadding(start, top, end, bottom);
16071        }
16072    }
16073
16074    /**
16075     * Returns the top padding of this view.
16076     *
16077     * @return the top padding in pixels
16078     */
16079    public int getPaddingTop() {
16080        return mPaddingTop;
16081    }
16082
16083    /**
16084     * Returns the bottom padding of this view. If there are inset and enabled
16085     * scrollbars, this value may include the space required to display the
16086     * scrollbars as well.
16087     *
16088     * @return the bottom padding in pixels
16089     */
16090    public int getPaddingBottom() {
16091        return mPaddingBottom;
16092    }
16093
16094    /**
16095     * Returns the left padding of this view. If there are inset and enabled
16096     * scrollbars, this value may include the space required to display the
16097     * scrollbars as well.
16098     *
16099     * @return the left padding in pixels
16100     */
16101    public int getPaddingLeft() {
16102        if (!isPaddingResolved()) {
16103            resolvePadding();
16104        }
16105        return mPaddingLeft;
16106    }
16107
16108    /**
16109     * Returns the start padding of this view depending on its resolved layout direction.
16110     * If there are inset and enabled scrollbars, this value may include the space
16111     * required to display the scrollbars as well.
16112     *
16113     * @return the start padding in pixels
16114     */
16115    public int getPaddingStart() {
16116        if (!isPaddingResolved()) {
16117            resolvePadding();
16118        }
16119        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16120                mPaddingRight : mPaddingLeft;
16121    }
16122
16123    /**
16124     * Returns the right padding of this view. If there are inset and enabled
16125     * scrollbars, this value may include the space required to display the
16126     * scrollbars as well.
16127     *
16128     * @return the right padding in pixels
16129     */
16130    public int getPaddingRight() {
16131        if (!isPaddingResolved()) {
16132            resolvePadding();
16133        }
16134        return mPaddingRight;
16135    }
16136
16137    /**
16138     * Returns the end padding of this view depending on its resolved layout direction.
16139     * If there are inset and enabled scrollbars, this value may include the space
16140     * required to display the scrollbars as well.
16141     *
16142     * @return the end padding in pixels
16143     */
16144    public int getPaddingEnd() {
16145        if (!isPaddingResolved()) {
16146            resolvePadding();
16147        }
16148        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16149                mPaddingLeft : mPaddingRight;
16150    }
16151
16152    /**
16153     * Return if the padding as been set thru relative values
16154     * {@link #setPaddingRelative(int, int, int, int)} or thru
16155     * @attr ref android.R.styleable#View_paddingStart or
16156     * @attr ref android.R.styleable#View_paddingEnd
16157     *
16158     * @return true if the padding is relative or false if it is not.
16159     */
16160    public boolean isPaddingRelative() {
16161        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16162    }
16163
16164    Insets computeOpticalInsets() {
16165        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16166    }
16167
16168    /**
16169     * @hide
16170     */
16171    public void resetPaddingToInitialValues() {
16172        if (isRtlCompatibilityMode()) {
16173            mPaddingLeft = mUserPaddingLeftInitial;
16174            mPaddingRight = mUserPaddingRightInitial;
16175            return;
16176        }
16177        if (isLayoutRtl()) {
16178            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16179            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16180        } else {
16181            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16182            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16183        }
16184    }
16185
16186    /**
16187     * @hide
16188     */
16189    public Insets getOpticalInsets() {
16190        if (mLayoutInsets == null) {
16191            mLayoutInsets = computeOpticalInsets();
16192        }
16193        return mLayoutInsets;
16194    }
16195
16196    /**
16197     * Set this view's optical insets.
16198     *
16199     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16200     * property. Views that compute their own optical insets should call it as part of measurement.
16201     * This method does not request layout. If you are setting optical insets outside of
16202     * measure/layout itself you will want to call requestLayout() yourself.
16203     * </p>
16204     * @hide
16205     */
16206    public void setOpticalInsets(Insets insets) {
16207        mLayoutInsets = insets;
16208    }
16209
16210    /**
16211     * Changes the selection state of this view. A view can be selected or not.
16212     * Note that selection is not the same as focus. Views are typically
16213     * selected in the context of an AdapterView like ListView or GridView;
16214     * the selected view is the view that is highlighted.
16215     *
16216     * @param selected true if the view must be selected, false otherwise
16217     */
16218    public void setSelected(boolean selected) {
16219        //noinspection DoubleNegation
16220        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16221            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16222            if (!selected) resetPressedState();
16223            invalidate(true);
16224            refreshDrawableState();
16225            dispatchSetSelected(selected);
16226            notifyViewAccessibilityStateChangedIfNeeded(
16227                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16228        }
16229    }
16230
16231    /**
16232     * Dispatch setSelected to all of this View's children.
16233     *
16234     * @see #setSelected(boolean)
16235     *
16236     * @param selected The new selected state
16237     */
16238    protected void dispatchSetSelected(boolean selected) {
16239    }
16240
16241    /**
16242     * Indicates the selection state of this view.
16243     *
16244     * @return true if the view is selected, false otherwise
16245     */
16246    @ViewDebug.ExportedProperty
16247    public boolean isSelected() {
16248        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16249    }
16250
16251    /**
16252     * Changes the activated state of this view. A view can be activated or not.
16253     * Note that activation is not the same as selection.  Selection is
16254     * a transient property, representing the view (hierarchy) the user is
16255     * currently interacting with.  Activation is a longer-term state that the
16256     * user can move views in and out of.  For example, in a list view with
16257     * single or multiple selection enabled, the views in the current selection
16258     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16259     * here.)  The activated state is propagated down to children of the view it
16260     * is set on.
16261     *
16262     * @param activated true if the view must be activated, false otherwise
16263     */
16264    public void setActivated(boolean activated) {
16265        //noinspection DoubleNegation
16266        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16267            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16268            invalidate(true);
16269            refreshDrawableState();
16270            dispatchSetActivated(activated);
16271        }
16272    }
16273
16274    /**
16275     * Dispatch setActivated to all of this View's children.
16276     *
16277     * @see #setActivated(boolean)
16278     *
16279     * @param activated The new activated state
16280     */
16281    protected void dispatchSetActivated(boolean activated) {
16282    }
16283
16284    /**
16285     * Indicates the activation state of this view.
16286     *
16287     * @return true if the view is activated, false otherwise
16288     */
16289    @ViewDebug.ExportedProperty
16290    public boolean isActivated() {
16291        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16292    }
16293
16294    /**
16295     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16296     * observer can be used to get notifications when global events, like
16297     * layout, happen.
16298     *
16299     * The returned ViewTreeObserver observer is not guaranteed to remain
16300     * valid for the lifetime of this View. If the caller of this method keeps
16301     * a long-lived reference to ViewTreeObserver, it should always check for
16302     * the return value of {@link ViewTreeObserver#isAlive()}.
16303     *
16304     * @return The ViewTreeObserver for this view's hierarchy.
16305     */
16306    public ViewTreeObserver getViewTreeObserver() {
16307        if (mAttachInfo != null) {
16308            return mAttachInfo.mTreeObserver;
16309        }
16310        if (mFloatingTreeObserver == null) {
16311            mFloatingTreeObserver = new ViewTreeObserver();
16312        }
16313        return mFloatingTreeObserver;
16314    }
16315
16316    /**
16317     * <p>Finds the topmost view in the current view hierarchy.</p>
16318     *
16319     * @return the topmost view containing this view
16320     */
16321    public View getRootView() {
16322        if (mAttachInfo != null) {
16323            final View v = mAttachInfo.mRootView;
16324            if (v != null) {
16325                return v;
16326            }
16327        }
16328
16329        View parent = this;
16330
16331        while (parent.mParent != null && parent.mParent instanceof View) {
16332            parent = (View) parent.mParent;
16333        }
16334
16335        return parent;
16336    }
16337
16338    /**
16339     * Transforms a motion event from view-local coordinates to on-screen
16340     * coordinates.
16341     *
16342     * @param ev the view-local motion event
16343     * @return false if the transformation could not be applied
16344     * @hide
16345     */
16346    public boolean toGlobalMotionEvent(MotionEvent ev) {
16347        final AttachInfo info = mAttachInfo;
16348        if (info == null) {
16349            return false;
16350        }
16351
16352        final Matrix m = info.mTmpMatrix;
16353        m.set(Matrix.IDENTITY_MATRIX);
16354        transformMatrixToGlobal(m);
16355        ev.transform(m);
16356        return true;
16357    }
16358
16359    /**
16360     * Transforms a motion event from on-screen coordinates to view-local
16361     * coordinates.
16362     *
16363     * @param ev the on-screen motion event
16364     * @return false if the transformation could not be applied
16365     * @hide
16366     */
16367    public boolean toLocalMotionEvent(MotionEvent ev) {
16368        final AttachInfo info = mAttachInfo;
16369        if (info == null) {
16370            return false;
16371        }
16372
16373        final Matrix m = info.mTmpMatrix;
16374        m.set(Matrix.IDENTITY_MATRIX);
16375        transformMatrixToLocal(m);
16376        ev.transform(m);
16377        return true;
16378    }
16379
16380    /**
16381     * Modifies the input matrix such that it maps view-local coordinates to
16382     * on-screen coordinates.
16383     *
16384     * @param m input matrix to modify
16385     */
16386    void transformMatrixToGlobal(Matrix m) {
16387        final ViewParent parent = mParent;
16388        if (parent instanceof View) {
16389            final View vp = (View) parent;
16390            vp.transformMatrixToGlobal(m);
16391            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16392        } else if (parent instanceof ViewRootImpl) {
16393            final ViewRootImpl vr = (ViewRootImpl) parent;
16394            vr.transformMatrixToGlobal(m);
16395            m.postTranslate(0, -vr.mCurScrollY);
16396        }
16397
16398        m.postTranslate(mLeft, mTop);
16399
16400        if (!hasIdentityMatrix()) {
16401            m.postConcat(getMatrix());
16402        }
16403    }
16404
16405    /**
16406     * Modifies the input matrix such that it maps on-screen coordinates to
16407     * view-local coordinates.
16408     *
16409     * @param m input matrix to modify
16410     */
16411    void transformMatrixToLocal(Matrix m) {
16412        final ViewParent parent = mParent;
16413        if (parent instanceof View) {
16414            final View vp = (View) parent;
16415            vp.transformMatrixToLocal(m);
16416            m.preTranslate(vp.mScrollX, vp.mScrollY);
16417        } else if (parent instanceof ViewRootImpl) {
16418            final ViewRootImpl vr = (ViewRootImpl) parent;
16419            vr.transformMatrixToLocal(m);
16420            m.preTranslate(0, vr.mCurScrollY);
16421        }
16422
16423        m.preTranslate(-mLeft, -mTop);
16424
16425        if (!hasIdentityMatrix()) {
16426            m.preConcat(getInverseMatrix());
16427        }
16428    }
16429
16430    /**
16431     * <p>Computes the coordinates of this view on the screen. The argument
16432     * must be an array of two integers. After the method returns, the array
16433     * contains the x and y location in that order.</p>
16434     *
16435     * @param location an array of two integers in which to hold the coordinates
16436     */
16437    public void getLocationOnScreen(int[] location) {
16438        getLocationInWindow(location);
16439
16440        final AttachInfo info = mAttachInfo;
16441        if (info != null) {
16442            location[0] += info.mWindowLeft;
16443            location[1] += info.mWindowTop;
16444        }
16445    }
16446
16447    /**
16448     * <p>Computes the coordinates of this view in its window. The argument
16449     * must be an array of two integers. After the method returns, the array
16450     * contains the x and y location in that order.</p>
16451     *
16452     * @param location an array of two integers in which to hold the coordinates
16453     */
16454    public void getLocationInWindow(int[] location) {
16455        if (location == null || location.length < 2) {
16456            throw new IllegalArgumentException("location must be an array of two integers");
16457        }
16458
16459        if (mAttachInfo == null) {
16460            // When the view is not attached to a window, this method does not make sense
16461            location[0] = location[1] = 0;
16462            return;
16463        }
16464
16465        float[] position = mAttachInfo.mTmpTransformLocation;
16466        position[0] = position[1] = 0.0f;
16467
16468        if (!hasIdentityMatrix()) {
16469            getMatrix().mapPoints(position);
16470        }
16471
16472        position[0] += mLeft;
16473        position[1] += mTop;
16474
16475        ViewParent viewParent = mParent;
16476        while (viewParent instanceof View) {
16477            final View view = (View) viewParent;
16478
16479            position[0] -= view.mScrollX;
16480            position[1] -= view.mScrollY;
16481
16482            if (!view.hasIdentityMatrix()) {
16483                view.getMatrix().mapPoints(position);
16484            }
16485
16486            position[0] += view.mLeft;
16487            position[1] += view.mTop;
16488
16489            viewParent = view.mParent;
16490         }
16491
16492        if (viewParent instanceof ViewRootImpl) {
16493            // *cough*
16494            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16495            position[1] -= vr.mCurScrollY;
16496        }
16497
16498        location[0] = (int) (position[0] + 0.5f);
16499        location[1] = (int) (position[1] + 0.5f);
16500    }
16501
16502    /**
16503     * {@hide}
16504     * @param id the id of the view to be found
16505     * @return the view of the specified id, null if cannot be found
16506     */
16507    protected View findViewTraversal(int id) {
16508        if (id == mID) {
16509            return this;
16510        }
16511        return null;
16512    }
16513
16514    /**
16515     * {@hide}
16516     * @param tag the tag of the view to be found
16517     * @return the view of specified tag, null if cannot be found
16518     */
16519    protected View findViewWithTagTraversal(Object tag) {
16520        if (tag != null && tag.equals(mTag)) {
16521            return this;
16522        }
16523        return null;
16524    }
16525
16526    /**
16527     * {@hide}
16528     * @param predicate The predicate to evaluate.
16529     * @param childToSkip If not null, ignores this child during the recursive traversal.
16530     * @return The first view that matches the predicate or null.
16531     */
16532    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16533        if (predicate.apply(this)) {
16534            return this;
16535        }
16536        return null;
16537    }
16538
16539    /**
16540     * Look for a child view with the given id.  If this view has the given
16541     * id, return this view.
16542     *
16543     * @param id The id to search for.
16544     * @return The view that has the given id in the hierarchy or null
16545     */
16546    public final View findViewById(int id) {
16547        if (id < 0) {
16548            return null;
16549        }
16550        return findViewTraversal(id);
16551    }
16552
16553    /**
16554     * Finds a view by its unuque and stable accessibility id.
16555     *
16556     * @param accessibilityId The searched accessibility id.
16557     * @return The found view.
16558     */
16559    final View findViewByAccessibilityId(int accessibilityId) {
16560        if (accessibilityId < 0) {
16561            return null;
16562        }
16563        return findViewByAccessibilityIdTraversal(accessibilityId);
16564    }
16565
16566    /**
16567     * Performs the traversal to find a view by its unuque and stable accessibility id.
16568     *
16569     * <strong>Note:</strong>This method does not stop at the root namespace
16570     * boundary since the user can touch the screen at an arbitrary location
16571     * potentially crossing the root namespace bounday which will send an
16572     * accessibility event to accessibility services and they should be able
16573     * to obtain the event source. Also accessibility ids are guaranteed to be
16574     * unique in the window.
16575     *
16576     * @param accessibilityId The accessibility id.
16577     * @return The found view.
16578     *
16579     * @hide
16580     */
16581    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16582        if (getAccessibilityViewId() == accessibilityId) {
16583            return this;
16584        }
16585        return null;
16586    }
16587
16588    /**
16589     * Look for a child view with the given tag.  If this view has the given
16590     * tag, return this view.
16591     *
16592     * @param tag The tag to search for, using "tag.equals(getTag())".
16593     * @return The View that has the given tag in the hierarchy or null
16594     */
16595    public final View findViewWithTag(Object tag) {
16596        if (tag == null) {
16597            return null;
16598        }
16599        return findViewWithTagTraversal(tag);
16600    }
16601
16602    /**
16603     * {@hide}
16604     * Look for a child view that matches the specified predicate.
16605     * If this view matches the predicate, return this view.
16606     *
16607     * @param predicate The predicate to evaluate.
16608     * @return The first view that matches the predicate or null.
16609     */
16610    public final View findViewByPredicate(Predicate<View> predicate) {
16611        return findViewByPredicateTraversal(predicate, null);
16612    }
16613
16614    /**
16615     * {@hide}
16616     * Look for a child view that matches the specified predicate,
16617     * starting with the specified view and its descendents and then
16618     * recusively searching the ancestors and siblings of that view
16619     * until this view is reached.
16620     *
16621     * This method is useful in cases where the predicate does not match
16622     * a single unique view (perhaps multiple views use the same id)
16623     * and we are trying to find the view that is "closest" in scope to the
16624     * starting view.
16625     *
16626     * @param start The view to start from.
16627     * @param predicate The predicate to evaluate.
16628     * @return The first view that matches the predicate or null.
16629     */
16630    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16631        View childToSkip = null;
16632        for (;;) {
16633            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16634            if (view != null || start == this) {
16635                return view;
16636            }
16637
16638            ViewParent parent = start.getParent();
16639            if (parent == null || !(parent instanceof View)) {
16640                return null;
16641            }
16642
16643            childToSkip = start;
16644            start = (View) parent;
16645        }
16646    }
16647
16648    /**
16649     * Sets the identifier for this view. The identifier does not have to be
16650     * unique in this view's hierarchy. The identifier should be a positive
16651     * number.
16652     *
16653     * @see #NO_ID
16654     * @see #getId()
16655     * @see #findViewById(int)
16656     *
16657     * @param id a number used to identify the view
16658     *
16659     * @attr ref android.R.styleable#View_id
16660     */
16661    public void setId(int id) {
16662        mID = id;
16663        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16664            mID = generateViewId();
16665        }
16666    }
16667
16668    /**
16669     * {@hide}
16670     *
16671     * @param isRoot true if the view belongs to the root namespace, false
16672     *        otherwise
16673     */
16674    public void setIsRootNamespace(boolean isRoot) {
16675        if (isRoot) {
16676            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16677        } else {
16678            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16679        }
16680    }
16681
16682    /**
16683     * {@hide}
16684     *
16685     * @return true if the view belongs to the root namespace, false otherwise
16686     */
16687    public boolean isRootNamespace() {
16688        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16689    }
16690
16691    /**
16692     * Returns this view's identifier.
16693     *
16694     * @return a positive integer used to identify the view or {@link #NO_ID}
16695     *         if the view has no ID
16696     *
16697     * @see #setId(int)
16698     * @see #findViewById(int)
16699     * @attr ref android.R.styleable#View_id
16700     */
16701    @ViewDebug.CapturedViewProperty
16702    public int getId() {
16703        return mID;
16704    }
16705
16706    /**
16707     * Returns this view's tag.
16708     *
16709     * @return the Object stored in this view as a tag, or {@code null} if not
16710     *         set
16711     *
16712     * @see #setTag(Object)
16713     * @see #getTag(int)
16714     */
16715    @ViewDebug.ExportedProperty
16716    public Object getTag() {
16717        return mTag;
16718    }
16719
16720    /**
16721     * Sets the tag associated with this view. A tag can be used to mark
16722     * a view in its hierarchy and does not have to be unique within the
16723     * hierarchy. Tags can also be used to store data within a view without
16724     * resorting to another data structure.
16725     *
16726     * @param tag an Object to tag the view with
16727     *
16728     * @see #getTag()
16729     * @see #setTag(int, Object)
16730     */
16731    public void setTag(final Object tag) {
16732        mTag = tag;
16733    }
16734
16735    /**
16736     * Returns the tag associated with this view and the specified key.
16737     *
16738     * @param key The key identifying the tag
16739     *
16740     * @return the Object stored in this view as a tag, or {@code null} if not
16741     *         set
16742     *
16743     * @see #setTag(int, Object)
16744     * @see #getTag()
16745     */
16746    public Object getTag(int key) {
16747        if (mKeyedTags != null) return mKeyedTags.get(key);
16748        return null;
16749    }
16750
16751    /**
16752     * Sets a tag associated with this view and a key. A tag can be used
16753     * to mark a view in its hierarchy and does not have to be unique within
16754     * the hierarchy. Tags can also be used to store data within a view
16755     * without resorting to another data structure.
16756     *
16757     * The specified key should be an id declared in the resources of the
16758     * application to ensure it is unique (see the <a
16759     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16760     * Keys identified as belonging to
16761     * the Android framework or not associated with any package will cause
16762     * an {@link IllegalArgumentException} to be thrown.
16763     *
16764     * @param key The key identifying the tag
16765     * @param tag An Object to tag the view with
16766     *
16767     * @throws IllegalArgumentException If they specified key is not valid
16768     *
16769     * @see #setTag(Object)
16770     * @see #getTag(int)
16771     */
16772    public void setTag(int key, final Object tag) {
16773        // If the package id is 0x00 or 0x01, it's either an undefined package
16774        // or a framework id
16775        if ((key >>> 24) < 2) {
16776            throw new IllegalArgumentException("The key must be an application-specific "
16777                    + "resource id.");
16778        }
16779
16780        setKeyedTag(key, tag);
16781    }
16782
16783    /**
16784     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16785     * framework id.
16786     *
16787     * @hide
16788     */
16789    public void setTagInternal(int key, Object tag) {
16790        if ((key >>> 24) != 0x1) {
16791            throw new IllegalArgumentException("The key must be a framework-specific "
16792                    + "resource id.");
16793        }
16794
16795        setKeyedTag(key, tag);
16796    }
16797
16798    private void setKeyedTag(int key, Object tag) {
16799        if (mKeyedTags == null) {
16800            mKeyedTags = new SparseArray<Object>(2);
16801        }
16802
16803        mKeyedTags.put(key, tag);
16804    }
16805
16806    /**
16807     * Prints information about this view in the log output, with the tag
16808     * {@link #VIEW_LOG_TAG}.
16809     *
16810     * @hide
16811     */
16812    public void debug() {
16813        debug(0);
16814    }
16815
16816    /**
16817     * Prints information about this view in the log output, with the tag
16818     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16819     * indentation defined by the <code>depth</code>.
16820     *
16821     * @param depth the indentation level
16822     *
16823     * @hide
16824     */
16825    protected void debug(int depth) {
16826        String output = debugIndent(depth - 1);
16827
16828        output += "+ " + this;
16829        int id = getId();
16830        if (id != -1) {
16831            output += " (id=" + id + ")";
16832        }
16833        Object tag = getTag();
16834        if (tag != null) {
16835            output += " (tag=" + tag + ")";
16836        }
16837        Log.d(VIEW_LOG_TAG, output);
16838
16839        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16840            output = debugIndent(depth) + " FOCUSED";
16841            Log.d(VIEW_LOG_TAG, output);
16842        }
16843
16844        output = debugIndent(depth);
16845        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16846                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16847                + "} ";
16848        Log.d(VIEW_LOG_TAG, output);
16849
16850        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16851                || mPaddingBottom != 0) {
16852            output = debugIndent(depth);
16853            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16854                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16855            Log.d(VIEW_LOG_TAG, output);
16856        }
16857
16858        output = debugIndent(depth);
16859        output += "mMeasureWidth=" + mMeasuredWidth +
16860                " mMeasureHeight=" + mMeasuredHeight;
16861        Log.d(VIEW_LOG_TAG, output);
16862
16863        output = debugIndent(depth);
16864        if (mLayoutParams == null) {
16865            output += "BAD! no layout params";
16866        } else {
16867            output = mLayoutParams.debug(output);
16868        }
16869        Log.d(VIEW_LOG_TAG, output);
16870
16871        output = debugIndent(depth);
16872        output += "flags={";
16873        output += View.printFlags(mViewFlags);
16874        output += "}";
16875        Log.d(VIEW_LOG_TAG, output);
16876
16877        output = debugIndent(depth);
16878        output += "privateFlags={";
16879        output += View.printPrivateFlags(mPrivateFlags);
16880        output += "}";
16881        Log.d(VIEW_LOG_TAG, output);
16882    }
16883
16884    /**
16885     * Creates a string of whitespaces used for indentation.
16886     *
16887     * @param depth the indentation level
16888     * @return a String containing (depth * 2 + 3) * 2 white spaces
16889     *
16890     * @hide
16891     */
16892    protected static String debugIndent(int depth) {
16893        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16894        for (int i = 0; i < (depth * 2) + 3; i++) {
16895            spaces.append(' ').append(' ');
16896        }
16897        return spaces.toString();
16898    }
16899
16900    /**
16901     * <p>Return the offset of the widget's text baseline from the widget's top
16902     * boundary. If this widget does not support baseline alignment, this
16903     * method returns -1. </p>
16904     *
16905     * @return the offset of the baseline within the widget's bounds or -1
16906     *         if baseline alignment is not supported
16907     */
16908    @ViewDebug.ExportedProperty(category = "layout")
16909    public int getBaseline() {
16910        return -1;
16911    }
16912
16913    /**
16914     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16915     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16916     * a layout pass.
16917     *
16918     * @return whether the view hierarchy is currently undergoing a layout pass
16919     */
16920    public boolean isInLayout() {
16921        ViewRootImpl viewRoot = getViewRootImpl();
16922        return (viewRoot != null && viewRoot.isInLayout());
16923    }
16924
16925    /**
16926     * Call this when something has changed which has invalidated the
16927     * layout of this view. This will schedule a layout pass of the view
16928     * tree. This should not be called while the view hierarchy is currently in a layout
16929     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16930     * end of the current layout pass (and then layout will run again) or after the current
16931     * frame is drawn and the next layout occurs.
16932     *
16933     * <p>Subclasses which override this method should call the superclass method to
16934     * handle possible request-during-layout errors correctly.</p>
16935     */
16936    public void requestLayout() {
16937        if (mMeasureCache != null) mMeasureCache.clear();
16938
16939        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16940            // Only trigger request-during-layout logic if this is the view requesting it,
16941            // not the views in its parent hierarchy
16942            ViewRootImpl viewRoot = getViewRootImpl();
16943            if (viewRoot != null && viewRoot.isInLayout()) {
16944                if (!viewRoot.requestLayoutDuringLayout(this)) {
16945                    return;
16946                }
16947            }
16948            mAttachInfo.mViewRequestingLayout = this;
16949        }
16950
16951        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16952        mPrivateFlags |= PFLAG_INVALIDATED;
16953
16954        if (mParent != null && !mParent.isLayoutRequested()) {
16955            mParent.requestLayout();
16956        }
16957        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16958            mAttachInfo.mViewRequestingLayout = null;
16959        }
16960    }
16961
16962    /**
16963     * Forces this view to be laid out during the next layout pass.
16964     * This method does not call requestLayout() or forceLayout()
16965     * on the parent.
16966     */
16967    public void forceLayout() {
16968        if (mMeasureCache != null) mMeasureCache.clear();
16969
16970        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16971        mPrivateFlags |= PFLAG_INVALIDATED;
16972    }
16973
16974    /**
16975     * <p>
16976     * This is called to find out how big a view should be. The parent
16977     * supplies constraint information in the width and height parameters.
16978     * </p>
16979     *
16980     * <p>
16981     * The actual measurement work of a view is performed in
16982     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16983     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16984     * </p>
16985     *
16986     *
16987     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16988     *        parent
16989     * @param heightMeasureSpec Vertical space requirements as imposed by the
16990     *        parent
16991     *
16992     * @see #onMeasure(int, int)
16993     */
16994    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16995        boolean optical = isLayoutModeOptical(this);
16996        if (optical != isLayoutModeOptical(mParent)) {
16997            Insets insets = getOpticalInsets();
16998            int oWidth  = insets.left + insets.right;
16999            int oHeight = insets.top  + insets.bottom;
17000            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17001            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17002        }
17003
17004        // Suppress sign extension for the low bytes
17005        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17006        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17007
17008        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17009                widthMeasureSpec != mOldWidthMeasureSpec ||
17010                heightMeasureSpec != mOldHeightMeasureSpec) {
17011
17012            // first clears the measured dimension flag
17013            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17014
17015            resolveRtlPropertiesIfNeeded();
17016
17017            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17018                    mMeasureCache.indexOfKey(key);
17019            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17020                // measure ourselves, this should set the measured dimension flag back
17021                onMeasure(widthMeasureSpec, heightMeasureSpec);
17022                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17023            } else {
17024                long value = mMeasureCache.valueAt(cacheIndex);
17025                // Casting a long to int drops the high 32 bits, no mask needed
17026                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17027                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17028            }
17029
17030            // flag not set, setMeasuredDimension() was not invoked, we raise
17031            // an exception to warn the developer
17032            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17033                throw new IllegalStateException("onMeasure() did not set the"
17034                        + " measured dimension by calling"
17035                        + " setMeasuredDimension()");
17036            }
17037
17038            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17039        }
17040
17041        mOldWidthMeasureSpec = widthMeasureSpec;
17042        mOldHeightMeasureSpec = heightMeasureSpec;
17043
17044        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17045                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17046    }
17047
17048    /**
17049     * <p>
17050     * Measure the view and its content to determine the measured width and the
17051     * measured height. This method is invoked by {@link #measure(int, int)} and
17052     * should be overriden by subclasses to provide accurate and efficient
17053     * measurement of their contents.
17054     * </p>
17055     *
17056     * <p>
17057     * <strong>CONTRACT:</strong> When overriding this method, you
17058     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17059     * measured width and height of this view. Failure to do so will trigger an
17060     * <code>IllegalStateException</code>, thrown by
17061     * {@link #measure(int, int)}. Calling the superclass'
17062     * {@link #onMeasure(int, int)} is a valid use.
17063     * </p>
17064     *
17065     * <p>
17066     * The base class implementation of measure defaults to the background size,
17067     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17068     * override {@link #onMeasure(int, int)} to provide better measurements of
17069     * their content.
17070     * </p>
17071     *
17072     * <p>
17073     * If this method is overridden, it is the subclass's responsibility to make
17074     * sure the measured height and width are at least the view's minimum height
17075     * and width ({@link #getSuggestedMinimumHeight()} and
17076     * {@link #getSuggestedMinimumWidth()}).
17077     * </p>
17078     *
17079     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17080     *                         The requirements are encoded with
17081     *                         {@link android.view.View.MeasureSpec}.
17082     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17083     *                         The requirements are encoded with
17084     *                         {@link android.view.View.MeasureSpec}.
17085     *
17086     * @see #getMeasuredWidth()
17087     * @see #getMeasuredHeight()
17088     * @see #setMeasuredDimension(int, int)
17089     * @see #getSuggestedMinimumHeight()
17090     * @see #getSuggestedMinimumWidth()
17091     * @see android.view.View.MeasureSpec#getMode(int)
17092     * @see android.view.View.MeasureSpec#getSize(int)
17093     */
17094    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17095        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17096                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17097    }
17098
17099    /**
17100     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17101     * measured width and measured height. Failing to do so will trigger an
17102     * exception at measurement time.</p>
17103     *
17104     * @param measuredWidth The measured width of this view.  May be a complex
17105     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17106     * {@link #MEASURED_STATE_TOO_SMALL}.
17107     * @param measuredHeight The measured height of this view.  May be a complex
17108     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17109     * {@link #MEASURED_STATE_TOO_SMALL}.
17110     */
17111    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17112        boolean optical = isLayoutModeOptical(this);
17113        if (optical != isLayoutModeOptical(mParent)) {
17114            Insets insets = getOpticalInsets();
17115            int opticalWidth  = insets.left + insets.right;
17116            int opticalHeight = insets.top  + insets.bottom;
17117
17118            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17119            measuredHeight += optical ? opticalHeight : -opticalHeight;
17120        }
17121        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17122    }
17123
17124    /**
17125     * Sets the measured dimension without extra processing for things like optical bounds.
17126     * Useful for reapplying consistent values that have already been cooked with adjustments
17127     * for optical bounds, etc. such as those from the measurement cache.
17128     *
17129     * @param measuredWidth The measured width of this view.  May be a complex
17130     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17131     * {@link #MEASURED_STATE_TOO_SMALL}.
17132     * @param measuredHeight The measured height of this view.  May be a complex
17133     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17134     * {@link #MEASURED_STATE_TOO_SMALL}.
17135     */
17136    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17137        mMeasuredWidth = measuredWidth;
17138        mMeasuredHeight = measuredHeight;
17139
17140        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17141    }
17142
17143    /**
17144     * Merge two states as returned by {@link #getMeasuredState()}.
17145     * @param curState The current state as returned from a view or the result
17146     * of combining multiple views.
17147     * @param newState The new view state to combine.
17148     * @return Returns a new integer reflecting the combination of the two
17149     * states.
17150     */
17151    public static int combineMeasuredStates(int curState, int newState) {
17152        return curState | newState;
17153    }
17154
17155    /**
17156     * Version of {@link #resolveSizeAndState(int, int, int)}
17157     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17158     */
17159    public static int resolveSize(int size, int measureSpec) {
17160        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17161    }
17162
17163    /**
17164     * Utility to reconcile a desired size and state, with constraints imposed
17165     * by a MeasureSpec.  Will take the desired size, unless a different size
17166     * is imposed by the constraints.  The returned value is a compound integer,
17167     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17168     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17169     * size is smaller than the size the view wants to be.
17170     *
17171     * @param size How big the view wants to be
17172     * @param measureSpec Constraints imposed by the parent
17173     * @return Size information bit mask as defined by
17174     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17175     */
17176    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17177        int result = size;
17178        int specMode = MeasureSpec.getMode(measureSpec);
17179        int specSize =  MeasureSpec.getSize(measureSpec);
17180        switch (specMode) {
17181        case MeasureSpec.UNSPECIFIED:
17182            result = size;
17183            break;
17184        case MeasureSpec.AT_MOST:
17185            if (specSize < size) {
17186                result = specSize | MEASURED_STATE_TOO_SMALL;
17187            } else {
17188                result = size;
17189            }
17190            break;
17191        case MeasureSpec.EXACTLY:
17192            result = specSize;
17193            break;
17194        }
17195        return result | (childMeasuredState&MEASURED_STATE_MASK);
17196    }
17197
17198    /**
17199     * Utility to return a default size. Uses the supplied size if the
17200     * MeasureSpec imposed no constraints. Will get larger if allowed
17201     * by the MeasureSpec.
17202     *
17203     * @param size Default size for this view
17204     * @param measureSpec Constraints imposed by the parent
17205     * @return The size this view should be.
17206     */
17207    public static int getDefaultSize(int size, int measureSpec) {
17208        int result = size;
17209        int specMode = MeasureSpec.getMode(measureSpec);
17210        int specSize = MeasureSpec.getSize(measureSpec);
17211
17212        switch (specMode) {
17213        case MeasureSpec.UNSPECIFIED:
17214            result = size;
17215            break;
17216        case MeasureSpec.AT_MOST:
17217        case MeasureSpec.EXACTLY:
17218            result = specSize;
17219            break;
17220        }
17221        return result;
17222    }
17223
17224    /**
17225     * Returns the suggested minimum height that the view should use. This
17226     * returns the maximum of the view's minimum height
17227     * and the background's minimum height
17228     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17229     * <p>
17230     * When being used in {@link #onMeasure(int, int)}, the caller should still
17231     * ensure the returned height is within the requirements of the parent.
17232     *
17233     * @return The suggested minimum height of the view.
17234     */
17235    protected int getSuggestedMinimumHeight() {
17236        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17237
17238    }
17239
17240    /**
17241     * Returns the suggested minimum width that the view should use. This
17242     * returns the maximum of the view's minimum width)
17243     * and the background's minimum width
17244     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17245     * <p>
17246     * When being used in {@link #onMeasure(int, int)}, the caller should still
17247     * ensure the returned width is within the requirements of the parent.
17248     *
17249     * @return The suggested minimum width of the view.
17250     */
17251    protected int getSuggestedMinimumWidth() {
17252        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17253    }
17254
17255    /**
17256     * Returns the minimum height of the view.
17257     *
17258     * @return the minimum height the view will try to be.
17259     *
17260     * @see #setMinimumHeight(int)
17261     *
17262     * @attr ref android.R.styleable#View_minHeight
17263     */
17264    public int getMinimumHeight() {
17265        return mMinHeight;
17266    }
17267
17268    /**
17269     * Sets the minimum height of the view. It is not guaranteed the view will
17270     * be able to achieve this minimum height (for example, if its parent layout
17271     * constrains it with less available height).
17272     *
17273     * @param minHeight The minimum height the view will try to be.
17274     *
17275     * @see #getMinimumHeight()
17276     *
17277     * @attr ref android.R.styleable#View_minHeight
17278     */
17279    public void setMinimumHeight(int minHeight) {
17280        mMinHeight = minHeight;
17281        requestLayout();
17282    }
17283
17284    /**
17285     * Returns the minimum width of the view.
17286     *
17287     * @return the minimum width the view will try to be.
17288     *
17289     * @see #setMinimumWidth(int)
17290     *
17291     * @attr ref android.R.styleable#View_minWidth
17292     */
17293    public int getMinimumWidth() {
17294        return mMinWidth;
17295    }
17296
17297    /**
17298     * Sets the minimum width of the view. It is not guaranteed the view will
17299     * be able to achieve this minimum width (for example, if its parent layout
17300     * constrains it with less available width).
17301     *
17302     * @param minWidth The minimum width the view will try to be.
17303     *
17304     * @see #getMinimumWidth()
17305     *
17306     * @attr ref android.R.styleable#View_minWidth
17307     */
17308    public void setMinimumWidth(int minWidth) {
17309        mMinWidth = minWidth;
17310        requestLayout();
17311
17312    }
17313
17314    /**
17315     * Get the animation currently associated with this view.
17316     *
17317     * @return The animation that is currently playing or
17318     *         scheduled to play for this view.
17319     */
17320    public Animation getAnimation() {
17321        return mCurrentAnimation;
17322    }
17323
17324    /**
17325     * Start the specified animation now.
17326     *
17327     * @param animation the animation to start now
17328     */
17329    public void startAnimation(Animation animation) {
17330        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17331        setAnimation(animation);
17332        invalidateParentCaches();
17333        invalidate(true);
17334    }
17335
17336    /**
17337     * Cancels any animations for this view.
17338     */
17339    public void clearAnimation() {
17340        if (mCurrentAnimation != null) {
17341            mCurrentAnimation.detach();
17342        }
17343        mCurrentAnimation = null;
17344        invalidateParentIfNeeded();
17345    }
17346
17347    /**
17348     * Sets the next animation to play for this view.
17349     * If you want the animation to play immediately, use
17350     * {@link #startAnimation(android.view.animation.Animation)} instead.
17351     * This method provides allows fine-grained
17352     * control over the start time and invalidation, but you
17353     * must make sure that 1) the animation has a start time set, and
17354     * 2) the view's parent (which controls animations on its children)
17355     * will be invalidated when the animation is supposed to
17356     * start.
17357     *
17358     * @param animation The next animation, or null.
17359     */
17360    public void setAnimation(Animation animation) {
17361        mCurrentAnimation = animation;
17362
17363        if (animation != null) {
17364            // If the screen is off assume the animation start time is now instead of
17365            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17366            // would cause the animation to start when the screen turns back on
17367            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17368                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17369                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17370            }
17371            animation.reset();
17372        }
17373    }
17374
17375    /**
17376     * Invoked by a parent ViewGroup to notify the start of the animation
17377     * currently associated with this view. If you override this method,
17378     * always call super.onAnimationStart();
17379     *
17380     * @see #setAnimation(android.view.animation.Animation)
17381     * @see #getAnimation()
17382     */
17383    protected void onAnimationStart() {
17384        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17385    }
17386
17387    /**
17388     * Invoked by a parent ViewGroup to notify the end of the animation
17389     * currently associated with this view. If you override this method,
17390     * always call super.onAnimationEnd();
17391     *
17392     * @see #setAnimation(android.view.animation.Animation)
17393     * @see #getAnimation()
17394     */
17395    protected void onAnimationEnd() {
17396        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17397    }
17398
17399    /**
17400     * Invoked if there is a Transform that involves alpha. Subclass that can
17401     * draw themselves with the specified alpha should return true, and then
17402     * respect that alpha when their onDraw() is called. If this returns false
17403     * then the view may be redirected to draw into an offscreen buffer to
17404     * fulfill the request, which will look fine, but may be slower than if the
17405     * subclass handles it internally. The default implementation returns false.
17406     *
17407     * @param alpha The alpha (0..255) to apply to the view's drawing
17408     * @return true if the view can draw with the specified alpha.
17409     */
17410    protected boolean onSetAlpha(int alpha) {
17411        return false;
17412    }
17413
17414    /**
17415     * This is used by the RootView to perform an optimization when
17416     * the view hierarchy contains one or several SurfaceView.
17417     * SurfaceView is always considered transparent, but its children are not,
17418     * therefore all View objects remove themselves from the global transparent
17419     * region (passed as a parameter to this function).
17420     *
17421     * @param region The transparent region for this ViewAncestor (window).
17422     *
17423     * @return Returns true if the effective visibility of the view at this
17424     * point is opaque, regardless of the transparent region; returns false
17425     * if it is possible for underlying windows to be seen behind the view.
17426     *
17427     * {@hide}
17428     */
17429    public boolean gatherTransparentRegion(Region region) {
17430        final AttachInfo attachInfo = mAttachInfo;
17431        if (region != null && attachInfo != null) {
17432            final int pflags = mPrivateFlags;
17433            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17434                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17435                // remove it from the transparent region.
17436                final int[] location = attachInfo.mTransparentLocation;
17437                getLocationInWindow(location);
17438                region.op(location[0], location[1], location[0] + mRight - mLeft,
17439                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17440            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17441                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17442                // exists, so we remove the background drawable's non-transparent
17443                // parts from this transparent region.
17444                applyDrawableToTransparentRegion(mBackground, region);
17445            }
17446        }
17447        return true;
17448    }
17449
17450    /**
17451     * Play a sound effect for this view.
17452     *
17453     * <p>The framework will play sound effects for some built in actions, such as
17454     * clicking, but you may wish to play these effects in your widget,
17455     * for instance, for internal navigation.
17456     *
17457     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17458     * {@link #isSoundEffectsEnabled()} is true.
17459     *
17460     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17461     */
17462    public void playSoundEffect(int soundConstant) {
17463        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17464            return;
17465        }
17466        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17467    }
17468
17469    /**
17470     * BZZZTT!!1!
17471     *
17472     * <p>Provide haptic feedback to the user for this view.
17473     *
17474     * <p>The framework will provide haptic feedback for some built in actions,
17475     * such as long presses, but you may wish to provide feedback for your
17476     * own widget.
17477     *
17478     * <p>The feedback will only be performed if
17479     * {@link #isHapticFeedbackEnabled()} is true.
17480     *
17481     * @param feedbackConstant One of the constants defined in
17482     * {@link HapticFeedbackConstants}
17483     */
17484    public boolean performHapticFeedback(int feedbackConstant) {
17485        return performHapticFeedback(feedbackConstant, 0);
17486    }
17487
17488    /**
17489     * BZZZTT!!1!
17490     *
17491     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17492     *
17493     * @param feedbackConstant One of the constants defined in
17494     * {@link HapticFeedbackConstants}
17495     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17496     */
17497    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17498        if (mAttachInfo == null) {
17499            return false;
17500        }
17501        //noinspection SimplifiableIfStatement
17502        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17503                && !isHapticFeedbackEnabled()) {
17504            return false;
17505        }
17506        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17507                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17508    }
17509
17510    /**
17511     * Request that the visibility of the status bar or other screen/window
17512     * decorations be changed.
17513     *
17514     * <p>This method is used to put the over device UI into temporary modes
17515     * where the user's attention is focused more on the application content,
17516     * by dimming or hiding surrounding system affordances.  This is typically
17517     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17518     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17519     * to be placed behind the action bar (and with these flags other system
17520     * affordances) so that smooth transitions between hiding and showing them
17521     * can be done.
17522     *
17523     * <p>Two representative examples of the use of system UI visibility is
17524     * implementing a content browsing application (like a magazine reader)
17525     * and a video playing application.
17526     *
17527     * <p>The first code shows a typical implementation of a View in a content
17528     * browsing application.  In this implementation, the application goes
17529     * into a content-oriented mode by hiding the status bar and action bar,
17530     * and putting the navigation elements into lights out mode.  The user can
17531     * then interact with content while in this mode.  Such an application should
17532     * provide an easy way for the user to toggle out of the mode (such as to
17533     * check information in the status bar or access notifications).  In the
17534     * implementation here, this is done simply by tapping on the content.
17535     *
17536     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17537     *      content}
17538     *
17539     * <p>This second code sample shows a typical implementation of a View
17540     * in a video playing application.  In this situation, while the video is
17541     * playing the application would like to go into a complete full-screen mode,
17542     * to use as much of the display as possible for the video.  When in this state
17543     * the user can not interact with the application; the system intercepts
17544     * touching on the screen to pop the UI out of full screen mode.  See
17545     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17546     *
17547     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17548     *      content}
17549     *
17550     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17551     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17552     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17553     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17554     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17555     */
17556    public void setSystemUiVisibility(int visibility) {
17557        if (visibility != mSystemUiVisibility) {
17558            mSystemUiVisibility = visibility;
17559            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17560                mParent.recomputeViewAttributes(this);
17561            }
17562        }
17563    }
17564
17565    /**
17566     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17567     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17568     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17569     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17570     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17571     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17572     */
17573    public int getSystemUiVisibility() {
17574        return mSystemUiVisibility;
17575    }
17576
17577    /**
17578     * Returns the current system UI visibility that is currently set for
17579     * the entire window.  This is the combination of the
17580     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17581     * views in the window.
17582     */
17583    public int getWindowSystemUiVisibility() {
17584        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17585    }
17586
17587    /**
17588     * Override to find out when the window's requested system UI visibility
17589     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17590     * This is different from the callbacks received through
17591     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17592     * in that this is only telling you about the local request of the window,
17593     * not the actual values applied by the system.
17594     */
17595    public void onWindowSystemUiVisibilityChanged(int visible) {
17596    }
17597
17598    /**
17599     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17600     * the view hierarchy.
17601     */
17602    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17603        onWindowSystemUiVisibilityChanged(visible);
17604    }
17605
17606    /**
17607     * Set a listener to receive callbacks when the visibility of the system bar changes.
17608     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17609     */
17610    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17611        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17612        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17613            mParent.recomputeViewAttributes(this);
17614        }
17615    }
17616
17617    /**
17618     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17619     * the view hierarchy.
17620     */
17621    public void dispatchSystemUiVisibilityChanged(int visibility) {
17622        ListenerInfo li = mListenerInfo;
17623        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17624            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17625                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17626        }
17627    }
17628
17629    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17630        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17631        if (val != mSystemUiVisibility) {
17632            setSystemUiVisibility(val);
17633            return true;
17634        }
17635        return false;
17636    }
17637
17638    /** @hide */
17639    public void setDisabledSystemUiVisibility(int flags) {
17640        if (mAttachInfo != null) {
17641            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17642                mAttachInfo.mDisabledSystemUiVisibility = flags;
17643                if (mParent != null) {
17644                    mParent.recomputeViewAttributes(this);
17645                }
17646            }
17647        }
17648    }
17649
17650    /**
17651     * Creates an image that the system displays during the drag and drop
17652     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17653     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17654     * appearance as the given View. The default also positions the center of the drag shadow
17655     * directly under the touch point. If no View is provided (the constructor with no parameters
17656     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17657     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17658     * default is an invisible drag shadow.
17659     * <p>
17660     * You are not required to use the View you provide to the constructor as the basis of the
17661     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17662     * anything you want as the drag shadow.
17663     * </p>
17664     * <p>
17665     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17666     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17667     *  size and position of the drag shadow. It uses this data to construct a
17668     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17669     *  so that your application can draw the shadow image in the Canvas.
17670     * </p>
17671     *
17672     * <div class="special reference">
17673     * <h3>Developer Guides</h3>
17674     * <p>For a guide to implementing drag and drop features, read the
17675     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17676     * </div>
17677     */
17678    public static class DragShadowBuilder {
17679        private final WeakReference<View> mView;
17680
17681        /**
17682         * Constructs a shadow image builder based on a View. By default, the resulting drag
17683         * shadow will have the same appearance and dimensions as the View, with the touch point
17684         * over the center of the View.
17685         * @param view A View. Any View in scope can be used.
17686         */
17687        public DragShadowBuilder(View view) {
17688            mView = new WeakReference<View>(view);
17689        }
17690
17691        /**
17692         * Construct a shadow builder object with no associated View.  This
17693         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17694         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17695         * to supply the drag shadow's dimensions and appearance without
17696         * reference to any View object. If they are not overridden, then the result is an
17697         * invisible drag shadow.
17698         */
17699        public DragShadowBuilder() {
17700            mView = new WeakReference<View>(null);
17701        }
17702
17703        /**
17704         * Returns the View object that had been passed to the
17705         * {@link #View.DragShadowBuilder(View)}
17706         * constructor.  If that View parameter was {@code null} or if the
17707         * {@link #View.DragShadowBuilder()}
17708         * constructor was used to instantiate the builder object, this method will return
17709         * null.
17710         *
17711         * @return The View object associate with this builder object.
17712         */
17713        @SuppressWarnings({"JavadocReference"})
17714        final public View getView() {
17715            return mView.get();
17716        }
17717
17718        /**
17719         * Provides the metrics for the shadow image. These include the dimensions of
17720         * the shadow image, and the point within that shadow that should
17721         * be centered under the touch location while dragging.
17722         * <p>
17723         * The default implementation sets the dimensions of the shadow to be the
17724         * same as the dimensions of the View itself and centers the shadow under
17725         * the touch point.
17726         * </p>
17727         *
17728         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17729         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17730         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17731         * image.
17732         *
17733         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17734         * shadow image that should be underneath the touch point during the drag and drop
17735         * operation. Your application must set {@link android.graphics.Point#x} to the
17736         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17737         */
17738        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17739            final View view = mView.get();
17740            if (view != null) {
17741                shadowSize.set(view.getWidth(), view.getHeight());
17742                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17743            } else {
17744                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17745            }
17746        }
17747
17748        /**
17749         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17750         * based on the dimensions it received from the
17751         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17752         *
17753         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17754         */
17755        public void onDrawShadow(Canvas canvas) {
17756            final View view = mView.get();
17757            if (view != null) {
17758                view.draw(canvas);
17759            } else {
17760                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17761            }
17762        }
17763    }
17764
17765    /**
17766     * Starts a drag and drop operation. When your application calls this method, it passes a
17767     * {@link android.view.View.DragShadowBuilder} object to the system. The
17768     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17769     * to get metrics for the drag shadow, and then calls the object's
17770     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17771     * <p>
17772     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17773     *  drag events to all the View objects in your application that are currently visible. It does
17774     *  this either by calling the View object's drag listener (an implementation of
17775     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17776     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17777     *  Both are passed a {@link android.view.DragEvent} object that has a
17778     *  {@link android.view.DragEvent#getAction()} value of
17779     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17780     * </p>
17781     * <p>
17782     * Your application can invoke startDrag() on any attached View object. The View object does not
17783     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17784     * be related to the View the user selected for dragging.
17785     * </p>
17786     * @param data A {@link android.content.ClipData} object pointing to the data to be
17787     * transferred by the drag and drop operation.
17788     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17789     * drag shadow.
17790     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17791     * drop operation. This Object is put into every DragEvent object sent by the system during the
17792     * current drag.
17793     * <p>
17794     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17795     * to the target Views. For example, it can contain flags that differentiate between a
17796     * a copy operation and a move operation.
17797     * </p>
17798     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17799     * so the parameter should be set to 0.
17800     * @return {@code true} if the method completes successfully, or
17801     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17802     * do a drag, and so no drag operation is in progress.
17803     */
17804    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17805            Object myLocalState, int flags) {
17806        if (ViewDebug.DEBUG_DRAG) {
17807            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17808        }
17809        boolean okay = false;
17810
17811        Point shadowSize = new Point();
17812        Point shadowTouchPoint = new Point();
17813        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17814
17815        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17816                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17817            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17818        }
17819
17820        if (ViewDebug.DEBUG_DRAG) {
17821            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17822                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17823        }
17824        Surface surface = new Surface();
17825        try {
17826            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17827                    flags, shadowSize.x, shadowSize.y, surface);
17828            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17829                    + " surface=" + surface);
17830            if (token != null) {
17831                Canvas canvas = surface.lockCanvas(null);
17832                try {
17833                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17834                    shadowBuilder.onDrawShadow(canvas);
17835                } finally {
17836                    surface.unlockCanvasAndPost(canvas);
17837                }
17838
17839                final ViewRootImpl root = getViewRootImpl();
17840
17841                // Cache the local state object for delivery with DragEvents
17842                root.setLocalDragState(myLocalState);
17843
17844                // repurpose 'shadowSize' for the last touch point
17845                root.getLastTouchPoint(shadowSize);
17846
17847                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17848                        shadowSize.x, shadowSize.y,
17849                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17850                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17851
17852                // Off and running!  Release our local surface instance; the drag
17853                // shadow surface is now managed by the system process.
17854                surface.release();
17855            }
17856        } catch (Exception e) {
17857            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17858            surface.destroy();
17859        }
17860
17861        return okay;
17862    }
17863
17864    /**
17865     * Handles drag events sent by the system following a call to
17866     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17867     *<p>
17868     * When the system calls this method, it passes a
17869     * {@link android.view.DragEvent} object. A call to
17870     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17871     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17872     * operation.
17873     * @param event The {@link android.view.DragEvent} sent by the system.
17874     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17875     * in DragEvent, indicating the type of drag event represented by this object.
17876     * @return {@code true} if the method was successful, otherwise {@code false}.
17877     * <p>
17878     *  The method should return {@code true} in response to an action type of
17879     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17880     *  operation.
17881     * </p>
17882     * <p>
17883     *  The method should also return {@code true} in response to an action type of
17884     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17885     *  {@code false} if it didn't.
17886     * </p>
17887     */
17888    public boolean onDragEvent(DragEvent event) {
17889        return false;
17890    }
17891
17892    /**
17893     * Detects if this View is enabled and has a drag event listener.
17894     * If both are true, then it calls the drag event listener with the
17895     * {@link android.view.DragEvent} it received. If the drag event listener returns
17896     * {@code true}, then dispatchDragEvent() returns {@code true}.
17897     * <p>
17898     * For all other cases, the method calls the
17899     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17900     * method and returns its result.
17901     * </p>
17902     * <p>
17903     * This ensures that a drag event is always consumed, even if the View does not have a drag
17904     * event listener. However, if the View has a listener and the listener returns true, then
17905     * onDragEvent() is not called.
17906     * </p>
17907     */
17908    public boolean dispatchDragEvent(DragEvent event) {
17909        ListenerInfo li = mListenerInfo;
17910        //noinspection SimplifiableIfStatement
17911        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17912                && li.mOnDragListener.onDrag(this, event)) {
17913            return true;
17914        }
17915        return onDragEvent(event);
17916    }
17917
17918    boolean canAcceptDrag() {
17919        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17920    }
17921
17922    /**
17923     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17924     * it is ever exposed at all.
17925     * @hide
17926     */
17927    public void onCloseSystemDialogs(String reason) {
17928    }
17929
17930    /**
17931     * Given a Drawable whose bounds have been set to draw into this view,
17932     * update a Region being computed for
17933     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17934     * that any non-transparent parts of the Drawable are removed from the
17935     * given transparent region.
17936     *
17937     * @param dr The Drawable whose transparency is to be applied to the region.
17938     * @param region A Region holding the current transparency information,
17939     * where any parts of the region that are set are considered to be
17940     * transparent.  On return, this region will be modified to have the
17941     * transparency information reduced by the corresponding parts of the
17942     * Drawable that are not transparent.
17943     * {@hide}
17944     */
17945    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17946        if (DBG) {
17947            Log.i("View", "Getting transparent region for: " + this);
17948        }
17949        final Region r = dr.getTransparentRegion();
17950        final Rect db = dr.getBounds();
17951        final AttachInfo attachInfo = mAttachInfo;
17952        if (r != null && attachInfo != null) {
17953            final int w = getRight()-getLeft();
17954            final int h = getBottom()-getTop();
17955            if (db.left > 0) {
17956                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17957                r.op(0, 0, db.left, h, Region.Op.UNION);
17958            }
17959            if (db.right < w) {
17960                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17961                r.op(db.right, 0, w, h, Region.Op.UNION);
17962            }
17963            if (db.top > 0) {
17964                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17965                r.op(0, 0, w, db.top, Region.Op.UNION);
17966            }
17967            if (db.bottom < h) {
17968                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17969                r.op(0, db.bottom, w, h, Region.Op.UNION);
17970            }
17971            final int[] location = attachInfo.mTransparentLocation;
17972            getLocationInWindow(location);
17973            r.translate(location[0], location[1]);
17974            region.op(r, Region.Op.INTERSECT);
17975        } else {
17976            region.op(db, Region.Op.DIFFERENCE);
17977        }
17978    }
17979
17980    private void checkForLongClick(int delayOffset) {
17981        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17982            mHasPerformedLongPress = false;
17983
17984            if (mPendingCheckForLongPress == null) {
17985                mPendingCheckForLongPress = new CheckForLongPress();
17986            }
17987            mPendingCheckForLongPress.rememberWindowAttachCount();
17988            postDelayed(mPendingCheckForLongPress,
17989                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17990        }
17991    }
17992
17993    /**
17994     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17995     * LayoutInflater} class, which provides a full range of options for view inflation.
17996     *
17997     * @param context The Context object for your activity or application.
17998     * @param resource The resource ID to inflate
17999     * @param root A view group that will be the parent.  Used to properly inflate the
18000     * layout_* parameters.
18001     * @see LayoutInflater
18002     */
18003    public static View inflate(Context context, int resource, ViewGroup root) {
18004        LayoutInflater factory = LayoutInflater.from(context);
18005        return factory.inflate(resource, root);
18006    }
18007
18008    /**
18009     * Scroll the view with standard behavior for scrolling beyond the normal
18010     * content boundaries. Views that call this method should override
18011     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18012     * results of an over-scroll operation.
18013     *
18014     * Views can use this method to handle any touch or fling-based scrolling.
18015     *
18016     * @param deltaX Change in X in pixels
18017     * @param deltaY Change in Y in pixels
18018     * @param scrollX Current X scroll value in pixels before applying deltaX
18019     * @param scrollY Current Y scroll value in pixels before applying deltaY
18020     * @param scrollRangeX Maximum content scroll range along the X axis
18021     * @param scrollRangeY Maximum content scroll range along the Y axis
18022     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18023     *          along the X axis.
18024     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18025     *          along the Y axis.
18026     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18027     * @return true if scrolling was clamped to an over-scroll boundary along either
18028     *          axis, false otherwise.
18029     */
18030    @SuppressWarnings({"UnusedParameters"})
18031    protected boolean overScrollBy(int deltaX, int deltaY,
18032            int scrollX, int scrollY,
18033            int scrollRangeX, int scrollRangeY,
18034            int maxOverScrollX, int maxOverScrollY,
18035            boolean isTouchEvent) {
18036        final int overScrollMode = mOverScrollMode;
18037        final boolean canScrollHorizontal =
18038                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18039        final boolean canScrollVertical =
18040                computeVerticalScrollRange() > computeVerticalScrollExtent();
18041        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18042                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18043        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18044                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18045
18046        int newScrollX = scrollX + deltaX;
18047        if (!overScrollHorizontal) {
18048            maxOverScrollX = 0;
18049        }
18050
18051        int newScrollY = scrollY + deltaY;
18052        if (!overScrollVertical) {
18053            maxOverScrollY = 0;
18054        }
18055
18056        // Clamp values if at the limits and record
18057        final int left = -maxOverScrollX;
18058        final int right = maxOverScrollX + scrollRangeX;
18059        final int top = -maxOverScrollY;
18060        final int bottom = maxOverScrollY + scrollRangeY;
18061
18062        boolean clampedX = false;
18063        if (newScrollX > right) {
18064            newScrollX = right;
18065            clampedX = true;
18066        } else if (newScrollX < left) {
18067            newScrollX = left;
18068            clampedX = true;
18069        }
18070
18071        boolean clampedY = false;
18072        if (newScrollY > bottom) {
18073            newScrollY = bottom;
18074            clampedY = true;
18075        } else if (newScrollY < top) {
18076            newScrollY = top;
18077            clampedY = true;
18078        }
18079
18080        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18081
18082        return clampedX || clampedY;
18083    }
18084
18085    /**
18086     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18087     * respond to the results of an over-scroll operation.
18088     *
18089     * @param scrollX New X scroll value in pixels
18090     * @param scrollY New Y scroll value in pixels
18091     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18092     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18093     */
18094    protected void onOverScrolled(int scrollX, int scrollY,
18095            boolean clampedX, boolean clampedY) {
18096        // Intentionally empty.
18097    }
18098
18099    /**
18100     * Returns the over-scroll mode for this view. The result will be
18101     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18102     * (allow over-scrolling only if the view content is larger than the container),
18103     * or {@link #OVER_SCROLL_NEVER}.
18104     *
18105     * @return This view's over-scroll mode.
18106     */
18107    public int getOverScrollMode() {
18108        return mOverScrollMode;
18109    }
18110
18111    /**
18112     * Set the over-scroll mode for this view. Valid over-scroll modes are
18113     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18114     * (allow over-scrolling only if the view content is larger than the container),
18115     * or {@link #OVER_SCROLL_NEVER}.
18116     *
18117     * Setting the over-scroll mode of a view will have an effect only if the
18118     * view is capable of scrolling.
18119     *
18120     * @param overScrollMode The new over-scroll mode for this view.
18121     */
18122    public void setOverScrollMode(int overScrollMode) {
18123        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18124                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18125                overScrollMode != OVER_SCROLL_NEVER) {
18126            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18127        }
18128        mOverScrollMode = overScrollMode;
18129    }
18130
18131    /**
18132     * Enable or disable nested scrolling for this view.
18133     *
18134     * <p>If this property is set to true the view will be permitted to initiate nested
18135     * scrolling operations with a compatible parent view in the current hierarchy. If this
18136     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18137     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18138     * the nested scroll.</p>
18139     *
18140     * @param enabled true to enable nested scrolling, false to disable
18141     *
18142     * @see #isNestedScrollingEnabled()
18143     */
18144    public void setNestedScrollingEnabled(boolean enabled) {
18145        if (enabled) {
18146            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18147        } else {
18148            stopNestedScroll();
18149            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18150        }
18151    }
18152
18153    /**
18154     * Returns true if nested scrolling is enabled for this view.
18155     *
18156     * <p>If nested scrolling is enabled and this View class implementation supports it,
18157     * this view will act as a nested scrolling child view when applicable, forwarding data
18158     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18159     * parent.</p>
18160     *
18161     * @return true if nested scrolling is enabled
18162     *
18163     * @see #setNestedScrollingEnabled(boolean)
18164     */
18165    public boolean isNestedScrollingEnabled() {
18166        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18167                PFLAG3_NESTED_SCROLLING_ENABLED;
18168    }
18169
18170    /**
18171     * Begin a nestable scroll operation along the given axes.
18172     *
18173     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18174     *
18175     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18176     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18177     * In the case of touch scrolling the nested scroll will be terminated automatically in
18178     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18179     * In the event of programmatic scrolling the caller must explicitly call
18180     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18181     *
18182     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18183     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18184     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18185     *
18186     * <p>At each incremental step of the scroll the caller should invoke
18187     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18188     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18189     * parent at least partially consumed the scroll and the caller should adjust the amount it
18190     * scrolls by.</p>
18191     *
18192     * <p>After applying the remainder of the scroll delta the caller should invoke
18193     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18194     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18195     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18196     * </p>
18197     *
18198     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18199     *             {@link #SCROLL_AXIS_VERTICAL}.
18200     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18201     *         the current gesture.
18202     *
18203     * @see #stopNestedScroll()
18204     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18205     * @see #dispatchNestedScroll(int, int, int, int, int[])
18206     */
18207    public boolean startNestedScroll(int axes) {
18208        if (hasNestedScrollingParent()) {
18209            // Already in progress
18210            return true;
18211        }
18212        if (isNestedScrollingEnabled()) {
18213            ViewParent p = getParent();
18214            View child = this;
18215            while (p != null) {
18216                try {
18217                    if (p.onStartNestedScroll(child, this, axes)) {
18218                        mNestedScrollingParent = p;
18219                        p.onNestedScrollAccepted(child, this, axes);
18220                        return true;
18221                    }
18222                } catch (AbstractMethodError e) {
18223                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18224                            "method onStartNestedScroll", e);
18225                    // Allow the search upward to continue
18226                }
18227                if (p instanceof View) {
18228                    child = (View) p;
18229                }
18230                p = p.getParent();
18231            }
18232        }
18233        return false;
18234    }
18235
18236    /**
18237     * Stop a nested scroll in progress.
18238     *
18239     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18240     *
18241     * @see #startNestedScroll(int)
18242     */
18243    public void stopNestedScroll() {
18244        if (mNestedScrollingParent != null) {
18245            mNestedScrollingParent.onStopNestedScroll(this);
18246            mNestedScrollingParent = null;
18247        }
18248    }
18249
18250    /**
18251     * Returns true if this view has a nested scrolling parent.
18252     *
18253     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18254     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18255     *
18256     * @return whether this view has a nested scrolling parent
18257     */
18258    public boolean hasNestedScrollingParent() {
18259        return mNestedScrollingParent != null;
18260    }
18261
18262    /**
18263     * Dispatch one step of a nested scroll in progress.
18264     *
18265     * <p>Implementations of views that support nested scrolling should call this to report
18266     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18267     * is not currently in progress or nested scrolling is not
18268     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18269     *
18270     * <p>Compatible View implementations should also call
18271     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18272     * consuming a component of the scroll event themselves.</p>
18273     *
18274     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18275     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18276     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18277     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18278     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18279     *                       in local view coordinates of this view from before this operation
18280     *                       to after it completes. View implementations may use this to adjust
18281     *                       expected input coordinate tracking.
18282     * @return true if the event was dispatched, false if it could not be dispatched.
18283     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18284     */
18285    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18286            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18287        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18288            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18289                int startX = 0;
18290                int startY = 0;
18291                if (offsetInWindow != null) {
18292                    getLocationInWindow(offsetInWindow);
18293                    startX = offsetInWindow[0];
18294                    startY = offsetInWindow[1];
18295                }
18296
18297                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18298                        dxUnconsumed, dyUnconsumed);
18299
18300                if (offsetInWindow != null) {
18301                    getLocationInWindow(offsetInWindow);
18302                    offsetInWindow[0] -= startX;
18303                    offsetInWindow[1] -= startY;
18304                }
18305                return true;
18306            } else if (offsetInWindow != null) {
18307                // No motion, no dispatch. Keep offsetInWindow up to date.
18308                offsetInWindow[0] = 0;
18309                offsetInWindow[1] = 0;
18310            }
18311        }
18312        return false;
18313    }
18314
18315    /**
18316     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18317     *
18318     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18319     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18320     * scrolling operation to consume some or all of the scroll operation before the child view
18321     * consumes it.</p>
18322     *
18323     * @param dx Horizontal scroll distance in pixels
18324     * @param dy Vertical scroll distance in pixels
18325     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18326     *                 and consumed[1] the consumed dy.
18327     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18328     *                       in local view coordinates of this view from before this operation
18329     *                       to after it completes. View implementations may use this to adjust
18330     *                       expected input coordinate tracking.
18331     * @return true if the parent consumed some or all of the scroll delta
18332     * @see #dispatchNestedScroll(int, int, int, int, int[])
18333     */
18334    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18335        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18336            if (dx != 0 || dy != 0) {
18337                int startX = 0;
18338                int startY = 0;
18339                if (offsetInWindow != null) {
18340                    getLocationInWindow(offsetInWindow);
18341                    startX = offsetInWindow[0];
18342                    startY = offsetInWindow[1];
18343                }
18344
18345                if (consumed == null) {
18346                    if (mTempNestedScrollConsumed == null) {
18347                        mTempNestedScrollConsumed = new int[2];
18348                    }
18349                    consumed = mTempNestedScrollConsumed;
18350                }
18351                consumed[0] = 0;
18352                consumed[1] = 0;
18353                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18354
18355                if (offsetInWindow != null) {
18356                    getLocationInWindow(offsetInWindow);
18357                    offsetInWindow[0] -= startX;
18358                    offsetInWindow[1] -= startY;
18359                }
18360                return consumed[0] != 0 || consumed[1] != 0;
18361            } else if (offsetInWindow != null) {
18362                offsetInWindow[0] = 0;
18363                offsetInWindow[1] = 0;
18364            }
18365        }
18366        return false;
18367    }
18368
18369    /**
18370     * Dispatch a fling to a nested scrolling parent.
18371     *
18372     * <p>This method should be used to indicate that a nested scrolling child has detected
18373     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18374     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18375     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18376     * along a scrollable axis.</p>
18377     *
18378     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18379     * its own content, it can use this method to delegate the fling to its nested scrolling
18380     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18381     *
18382     * @param velocityX Horizontal fling velocity in pixels per second
18383     * @param velocityY Vertical fling velocity in pixels per second
18384     * @param consumed true if the child consumed the fling, false otherwise
18385     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18386     */
18387    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18388        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18389            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18390        }
18391        return false;
18392    }
18393
18394    /**
18395     * Gets a scale factor that determines the distance the view should scroll
18396     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18397     * @return The vertical scroll scale factor.
18398     * @hide
18399     */
18400    protected float getVerticalScrollFactor() {
18401        if (mVerticalScrollFactor == 0) {
18402            TypedValue outValue = new TypedValue();
18403            if (!mContext.getTheme().resolveAttribute(
18404                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18405                throw new IllegalStateException(
18406                        "Expected theme to define listPreferredItemHeight.");
18407            }
18408            mVerticalScrollFactor = outValue.getDimension(
18409                    mContext.getResources().getDisplayMetrics());
18410        }
18411        return mVerticalScrollFactor;
18412    }
18413
18414    /**
18415     * Gets a scale factor that determines the distance the view should scroll
18416     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18417     * @return The horizontal scroll scale factor.
18418     * @hide
18419     */
18420    protected float getHorizontalScrollFactor() {
18421        // TODO: Should use something else.
18422        return getVerticalScrollFactor();
18423    }
18424
18425    /**
18426     * Return the value specifying the text direction or policy that was set with
18427     * {@link #setTextDirection(int)}.
18428     *
18429     * @return the defined text direction. It can be one of:
18430     *
18431     * {@link #TEXT_DIRECTION_INHERIT},
18432     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18433     * {@link #TEXT_DIRECTION_ANY_RTL},
18434     * {@link #TEXT_DIRECTION_LTR},
18435     * {@link #TEXT_DIRECTION_RTL},
18436     * {@link #TEXT_DIRECTION_LOCALE}
18437     *
18438     * @attr ref android.R.styleable#View_textDirection
18439     *
18440     * @hide
18441     */
18442    @ViewDebug.ExportedProperty(category = "text", mapping = {
18443            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18444            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18445            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18446            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18447            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18448            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18449    })
18450    public int getRawTextDirection() {
18451        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18452    }
18453
18454    /**
18455     * Set the text direction.
18456     *
18457     * @param textDirection the direction to set. Should be one of:
18458     *
18459     * {@link #TEXT_DIRECTION_INHERIT},
18460     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18461     * {@link #TEXT_DIRECTION_ANY_RTL},
18462     * {@link #TEXT_DIRECTION_LTR},
18463     * {@link #TEXT_DIRECTION_RTL},
18464     * {@link #TEXT_DIRECTION_LOCALE}
18465     *
18466     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18467     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18468     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18469     *
18470     * @attr ref android.R.styleable#View_textDirection
18471     */
18472    public void setTextDirection(int textDirection) {
18473        if (getRawTextDirection() != textDirection) {
18474            // Reset the current text direction and the resolved one
18475            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18476            resetResolvedTextDirection();
18477            // Set the new text direction
18478            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18479            // Do resolution
18480            resolveTextDirection();
18481            // Notify change
18482            onRtlPropertiesChanged(getLayoutDirection());
18483            // Refresh
18484            requestLayout();
18485            invalidate(true);
18486        }
18487    }
18488
18489    /**
18490     * Return the resolved text direction.
18491     *
18492     * @return the resolved text direction. Returns one of:
18493     *
18494     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18495     * {@link #TEXT_DIRECTION_ANY_RTL},
18496     * {@link #TEXT_DIRECTION_LTR},
18497     * {@link #TEXT_DIRECTION_RTL},
18498     * {@link #TEXT_DIRECTION_LOCALE}
18499     *
18500     * @attr ref android.R.styleable#View_textDirection
18501     */
18502    @ViewDebug.ExportedProperty(category = "text", mapping = {
18503            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18504            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18505            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18506            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18507            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18508            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18509    })
18510    public int getTextDirection() {
18511        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18512    }
18513
18514    /**
18515     * Resolve the text direction.
18516     *
18517     * @return true if resolution has been done, false otherwise.
18518     *
18519     * @hide
18520     */
18521    public boolean resolveTextDirection() {
18522        // Reset any previous text direction resolution
18523        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18524
18525        if (hasRtlSupport()) {
18526            // Set resolved text direction flag depending on text direction flag
18527            final int textDirection = getRawTextDirection();
18528            switch(textDirection) {
18529                case TEXT_DIRECTION_INHERIT:
18530                    if (!canResolveTextDirection()) {
18531                        // We cannot do the resolution if there is no parent, so use the default one
18532                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18533                        // Resolution will need to happen again later
18534                        return false;
18535                    }
18536
18537                    // Parent has not yet resolved, so we still return the default
18538                    try {
18539                        if (!mParent.isTextDirectionResolved()) {
18540                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18541                            // Resolution will need to happen again later
18542                            return false;
18543                        }
18544                    } catch (AbstractMethodError e) {
18545                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18546                                " does not fully implement ViewParent", e);
18547                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18548                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18549                        return true;
18550                    }
18551
18552                    // Set current resolved direction to the same value as the parent's one
18553                    int parentResolvedDirection;
18554                    try {
18555                        parentResolvedDirection = mParent.getTextDirection();
18556                    } catch (AbstractMethodError e) {
18557                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18558                                " does not fully implement ViewParent", e);
18559                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18560                    }
18561                    switch (parentResolvedDirection) {
18562                        case TEXT_DIRECTION_FIRST_STRONG:
18563                        case TEXT_DIRECTION_ANY_RTL:
18564                        case TEXT_DIRECTION_LTR:
18565                        case TEXT_DIRECTION_RTL:
18566                        case TEXT_DIRECTION_LOCALE:
18567                            mPrivateFlags2 |=
18568                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18569                            break;
18570                        default:
18571                            // Default resolved direction is "first strong" heuristic
18572                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18573                    }
18574                    break;
18575                case TEXT_DIRECTION_FIRST_STRONG:
18576                case TEXT_DIRECTION_ANY_RTL:
18577                case TEXT_DIRECTION_LTR:
18578                case TEXT_DIRECTION_RTL:
18579                case TEXT_DIRECTION_LOCALE:
18580                    // Resolved direction is the same as text direction
18581                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18582                    break;
18583                default:
18584                    // Default resolved direction is "first strong" heuristic
18585                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18586            }
18587        } else {
18588            // Default resolved direction is "first strong" heuristic
18589            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18590        }
18591
18592        // Set to resolved
18593        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18594        return true;
18595    }
18596
18597    /**
18598     * Check if text direction resolution can be done.
18599     *
18600     * @return true if text direction resolution can be done otherwise return false.
18601     */
18602    public boolean canResolveTextDirection() {
18603        switch (getRawTextDirection()) {
18604            case TEXT_DIRECTION_INHERIT:
18605                if (mParent != null) {
18606                    try {
18607                        return mParent.canResolveTextDirection();
18608                    } catch (AbstractMethodError e) {
18609                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18610                                " does not fully implement ViewParent", e);
18611                    }
18612                }
18613                return false;
18614
18615            default:
18616                return true;
18617        }
18618    }
18619
18620    /**
18621     * Reset resolved text direction. Text direction will be resolved during a call to
18622     * {@link #onMeasure(int, int)}.
18623     *
18624     * @hide
18625     */
18626    public void resetResolvedTextDirection() {
18627        // Reset any previous text direction resolution
18628        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18629        // Set to default value
18630        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18631    }
18632
18633    /**
18634     * @return true if text direction is inherited.
18635     *
18636     * @hide
18637     */
18638    public boolean isTextDirectionInherited() {
18639        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18640    }
18641
18642    /**
18643     * @return true if text direction is resolved.
18644     */
18645    public boolean isTextDirectionResolved() {
18646        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18647    }
18648
18649    /**
18650     * Return the value specifying the text alignment or policy that was set with
18651     * {@link #setTextAlignment(int)}.
18652     *
18653     * @return the defined text alignment. It can be one of:
18654     *
18655     * {@link #TEXT_ALIGNMENT_INHERIT},
18656     * {@link #TEXT_ALIGNMENT_GRAVITY},
18657     * {@link #TEXT_ALIGNMENT_CENTER},
18658     * {@link #TEXT_ALIGNMENT_TEXT_START},
18659     * {@link #TEXT_ALIGNMENT_TEXT_END},
18660     * {@link #TEXT_ALIGNMENT_VIEW_START},
18661     * {@link #TEXT_ALIGNMENT_VIEW_END}
18662     *
18663     * @attr ref android.R.styleable#View_textAlignment
18664     *
18665     * @hide
18666     */
18667    @ViewDebug.ExportedProperty(category = "text", mapping = {
18668            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18669            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18670            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18671            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18672            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18673            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18674            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18675    })
18676    @TextAlignment
18677    public int getRawTextAlignment() {
18678        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18679    }
18680
18681    /**
18682     * Set the text alignment.
18683     *
18684     * @param textAlignment The text alignment to set. Should be one of
18685     *
18686     * {@link #TEXT_ALIGNMENT_INHERIT},
18687     * {@link #TEXT_ALIGNMENT_GRAVITY},
18688     * {@link #TEXT_ALIGNMENT_CENTER},
18689     * {@link #TEXT_ALIGNMENT_TEXT_START},
18690     * {@link #TEXT_ALIGNMENT_TEXT_END},
18691     * {@link #TEXT_ALIGNMENT_VIEW_START},
18692     * {@link #TEXT_ALIGNMENT_VIEW_END}
18693     *
18694     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18695     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18696     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18697     *
18698     * @attr ref android.R.styleable#View_textAlignment
18699     */
18700    public void setTextAlignment(@TextAlignment int textAlignment) {
18701        if (textAlignment != getRawTextAlignment()) {
18702            // Reset the current and resolved text alignment
18703            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18704            resetResolvedTextAlignment();
18705            // Set the new text alignment
18706            mPrivateFlags2 |=
18707                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18708            // Do resolution
18709            resolveTextAlignment();
18710            // Notify change
18711            onRtlPropertiesChanged(getLayoutDirection());
18712            // Refresh
18713            requestLayout();
18714            invalidate(true);
18715        }
18716    }
18717
18718    /**
18719     * Return the resolved text alignment.
18720     *
18721     * @return the resolved text alignment. Returns one of:
18722     *
18723     * {@link #TEXT_ALIGNMENT_GRAVITY},
18724     * {@link #TEXT_ALIGNMENT_CENTER},
18725     * {@link #TEXT_ALIGNMENT_TEXT_START},
18726     * {@link #TEXT_ALIGNMENT_TEXT_END},
18727     * {@link #TEXT_ALIGNMENT_VIEW_START},
18728     * {@link #TEXT_ALIGNMENT_VIEW_END}
18729     *
18730     * @attr ref android.R.styleable#View_textAlignment
18731     */
18732    @ViewDebug.ExportedProperty(category = "text", mapping = {
18733            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18734            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18735            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18736            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18737            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18738            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18739            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18740    })
18741    @TextAlignment
18742    public int getTextAlignment() {
18743        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18744                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18745    }
18746
18747    /**
18748     * Resolve the text alignment.
18749     *
18750     * @return true if resolution has been done, false otherwise.
18751     *
18752     * @hide
18753     */
18754    public boolean resolveTextAlignment() {
18755        // Reset any previous text alignment resolution
18756        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18757
18758        if (hasRtlSupport()) {
18759            // Set resolved text alignment flag depending on text alignment flag
18760            final int textAlignment = getRawTextAlignment();
18761            switch (textAlignment) {
18762                case TEXT_ALIGNMENT_INHERIT:
18763                    // Check if we can resolve the text alignment
18764                    if (!canResolveTextAlignment()) {
18765                        // We cannot do the resolution if there is no parent so use the default
18766                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18767                        // Resolution will need to happen again later
18768                        return false;
18769                    }
18770
18771                    // Parent has not yet resolved, so we still return the default
18772                    try {
18773                        if (!mParent.isTextAlignmentResolved()) {
18774                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18775                            // Resolution will need to happen again later
18776                            return false;
18777                        }
18778                    } catch (AbstractMethodError e) {
18779                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18780                                " does not fully implement ViewParent", e);
18781                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18782                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18783                        return true;
18784                    }
18785
18786                    int parentResolvedTextAlignment;
18787                    try {
18788                        parentResolvedTextAlignment = mParent.getTextAlignment();
18789                    } catch (AbstractMethodError e) {
18790                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18791                                " does not fully implement ViewParent", e);
18792                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18793                    }
18794                    switch (parentResolvedTextAlignment) {
18795                        case TEXT_ALIGNMENT_GRAVITY:
18796                        case TEXT_ALIGNMENT_TEXT_START:
18797                        case TEXT_ALIGNMENT_TEXT_END:
18798                        case TEXT_ALIGNMENT_CENTER:
18799                        case TEXT_ALIGNMENT_VIEW_START:
18800                        case TEXT_ALIGNMENT_VIEW_END:
18801                            // Resolved text alignment is the same as the parent resolved
18802                            // text alignment
18803                            mPrivateFlags2 |=
18804                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18805                            break;
18806                        default:
18807                            // Use default resolved text alignment
18808                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18809                    }
18810                    break;
18811                case TEXT_ALIGNMENT_GRAVITY:
18812                case TEXT_ALIGNMENT_TEXT_START:
18813                case TEXT_ALIGNMENT_TEXT_END:
18814                case TEXT_ALIGNMENT_CENTER:
18815                case TEXT_ALIGNMENT_VIEW_START:
18816                case TEXT_ALIGNMENT_VIEW_END:
18817                    // Resolved text alignment is the same as text alignment
18818                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18819                    break;
18820                default:
18821                    // Use default resolved text alignment
18822                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18823            }
18824        } else {
18825            // Use default resolved text alignment
18826            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18827        }
18828
18829        // Set the resolved
18830        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18831        return true;
18832    }
18833
18834    /**
18835     * Check if text alignment resolution can be done.
18836     *
18837     * @return true if text alignment resolution can be done otherwise return false.
18838     */
18839    public boolean canResolveTextAlignment() {
18840        switch (getRawTextAlignment()) {
18841            case TEXT_DIRECTION_INHERIT:
18842                if (mParent != null) {
18843                    try {
18844                        return mParent.canResolveTextAlignment();
18845                    } catch (AbstractMethodError e) {
18846                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18847                                " does not fully implement ViewParent", e);
18848                    }
18849                }
18850                return false;
18851
18852            default:
18853                return true;
18854        }
18855    }
18856
18857    /**
18858     * Reset resolved text alignment. Text alignment will be resolved during a call to
18859     * {@link #onMeasure(int, int)}.
18860     *
18861     * @hide
18862     */
18863    public void resetResolvedTextAlignment() {
18864        // Reset any previous text alignment resolution
18865        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18866        // Set to default
18867        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18868    }
18869
18870    /**
18871     * @return true if text alignment is inherited.
18872     *
18873     * @hide
18874     */
18875    public boolean isTextAlignmentInherited() {
18876        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18877    }
18878
18879    /**
18880     * @return true if text alignment is resolved.
18881     */
18882    public boolean isTextAlignmentResolved() {
18883        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18884    }
18885
18886    /**
18887     * Generate a value suitable for use in {@link #setId(int)}.
18888     * This value will not collide with ID values generated at build time by aapt for R.id.
18889     *
18890     * @return a generated ID value
18891     */
18892    public static int generateViewId() {
18893        for (;;) {
18894            final int result = sNextGeneratedId.get();
18895            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18896            int newValue = result + 1;
18897            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18898            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18899                return result;
18900            }
18901        }
18902    }
18903
18904    /**
18905     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18906     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18907     *                           a normal View or a ViewGroup with
18908     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18909     * @hide
18910     */
18911    public void captureTransitioningViews(List<View> transitioningViews) {
18912        if (getVisibility() == View.VISIBLE) {
18913            transitioningViews.add(this);
18914        }
18915    }
18916
18917    /**
18918     * Adds all Views that have {@link #getViewName()} non-null to namedElements.
18919     * @param namedElements Will contain all Views in the hierarchy having a view name.
18920     * @hide
18921     */
18922    public void findNamedViews(Map<String, View> namedElements) {
18923        if (getVisibility() == VISIBLE) {
18924            String viewName = getViewName();
18925            if (viewName != null) {
18926                namedElements.put(viewName, this);
18927            }
18928        }
18929    }
18930
18931    //
18932    // Properties
18933    //
18934    /**
18935     * A Property wrapper around the <code>alpha</code> functionality handled by the
18936     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18937     */
18938    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18939        @Override
18940        public void setValue(View object, float value) {
18941            object.setAlpha(value);
18942        }
18943
18944        @Override
18945        public Float get(View object) {
18946            return object.getAlpha();
18947        }
18948    };
18949
18950    /**
18951     * A Property wrapper around the <code>translationX</code> functionality handled by the
18952     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18953     */
18954    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18955        @Override
18956        public void setValue(View object, float value) {
18957            object.setTranslationX(value);
18958        }
18959
18960                @Override
18961        public Float get(View object) {
18962            return object.getTranslationX();
18963        }
18964    };
18965
18966    /**
18967     * A Property wrapper around the <code>translationY</code> functionality handled by the
18968     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18969     */
18970    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18971        @Override
18972        public void setValue(View object, float value) {
18973            object.setTranslationY(value);
18974        }
18975
18976        @Override
18977        public Float get(View object) {
18978            return object.getTranslationY();
18979        }
18980    };
18981
18982    /**
18983     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18984     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18985     */
18986    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18987        @Override
18988        public void setValue(View object, float value) {
18989            object.setTranslationZ(value);
18990        }
18991
18992        @Override
18993        public Float get(View object) {
18994            return object.getTranslationZ();
18995        }
18996    };
18997
18998    /**
18999     * A Property wrapper around the <code>x</code> functionality handled by the
19000     * {@link View#setX(float)} and {@link View#getX()} methods.
19001     */
19002    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19003        @Override
19004        public void setValue(View object, float value) {
19005            object.setX(value);
19006        }
19007
19008        @Override
19009        public Float get(View object) {
19010            return object.getX();
19011        }
19012    };
19013
19014    /**
19015     * A Property wrapper around the <code>y</code> functionality handled by the
19016     * {@link View#setY(float)} and {@link View#getY()} methods.
19017     */
19018    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19019        @Override
19020        public void setValue(View object, float value) {
19021            object.setY(value);
19022        }
19023
19024        @Override
19025        public Float get(View object) {
19026            return object.getY();
19027        }
19028    };
19029
19030    /**
19031     * A Property wrapper around the <code>z</code> functionality handled by the
19032     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19033     */
19034    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19035        @Override
19036        public void setValue(View object, float value) {
19037            object.setZ(value);
19038        }
19039
19040        @Override
19041        public Float get(View object) {
19042            return object.getZ();
19043        }
19044    };
19045
19046    /**
19047     * A Property wrapper around the <code>rotation</code> functionality handled by the
19048     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19049     */
19050    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19051        @Override
19052        public void setValue(View object, float value) {
19053            object.setRotation(value);
19054        }
19055
19056        @Override
19057        public Float get(View object) {
19058            return object.getRotation();
19059        }
19060    };
19061
19062    /**
19063     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19064     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19065     */
19066    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19067        @Override
19068        public void setValue(View object, float value) {
19069            object.setRotationX(value);
19070        }
19071
19072        @Override
19073        public Float get(View object) {
19074            return object.getRotationX();
19075        }
19076    };
19077
19078    /**
19079     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19080     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19081     */
19082    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19083        @Override
19084        public void setValue(View object, float value) {
19085            object.setRotationY(value);
19086        }
19087
19088        @Override
19089        public Float get(View object) {
19090            return object.getRotationY();
19091        }
19092    };
19093
19094    /**
19095     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19096     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19097     */
19098    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19099        @Override
19100        public void setValue(View object, float value) {
19101            object.setScaleX(value);
19102        }
19103
19104        @Override
19105        public Float get(View object) {
19106            return object.getScaleX();
19107        }
19108    };
19109
19110    /**
19111     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19112     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19113     */
19114    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19115        @Override
19116        public void setValue(View object, float value) {
19117            object.setScaleY(value);
19118        }
19119
19120        @Override
19121        public Float get(View object) {
19122            return object.getScaleY();
19123        }
19124    };
19125
19126    /**
19127     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19128     * Each MeasureSpec represents a requirement for either the width or the height.
19129     * A MeasureSpec is comprised of a size and a mode. There are three possible
19130     * modes:
19131     * <dl>
19132     * <dt>UNSPECIFIED</dt>
19133     * <dd>
19134     * The parent has not imposed any constraint on the child. It can be whatever size
19135     * it wants.
19136     * </dd>
19137     *
19138     * <dt>EXACTLY</dt>
19139     * <dd>
19140     * The parent has determined an exact size for the child. The child is going to be
19141     * given those bounds regardless of how big it wants to be.
19142     * </dd>
19143     *
19144     * <dt>AT_MOST</dt>
19145     * <dd>
19146     * The child can be as large as it wants up to the specified size.
19147     * </dd>
19148     * </dl>
19149     *
19150     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19151     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19152     */
19153    public static class MeasureSpec {
19154        private static final int MODE_SHIFT = 30;
19155        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19156
19157        /**
19158         * Measure specification mode: The parent has not imposed any constraint
19159         * on the child. It can be whatever size it wants.
19160         */
19161        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19162
19163        /**
19164         * Measure specification mode: The parent has determined an exact size
19165         * for the child. The child is going to be given those bounds regardless
19166         * of how big it wants to be.
19167         */
19168        public static final int EXACTLY     = 1 << MODE_SHIFT;
19169
19170        /**
19171         * Measure specification mode: The child can be as large as it wants up
19172         * to the specified size.
19173         */
19174        public static final int AT_MOST     = 2 << MODE_SHIFT;
19175
19176        /**
19177         * Creates a measure specification based on the supplied size and mode.
19178         *
19179         * The mode must always be one of the following:
19180         * <ul>
19181         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19182         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19183         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19184         * </ul>
19185         *
19186         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19187         * implementation was such that the order of arguments did not matter
19188         * and overflow in either value could impact the resulting MeasureSpec.
19189         * {@link android.widget.RelativeLayout} was affected by this bug.
19190         * Apps targeting API levels greater than 17 will get the fixed, more strict
19191         * behavior.</p>
19192         *
19193         * @param size the size of the measure specification
19194         * @param mode the mode of the measure specification
19195         * @return the measure specification based on size and mode
19196         */
19197        public static int makeMeasureSpec(int size, int mode) {
19198            if (sUseBrokenMakeMeasureSpec) {
19199                return size + mode;
19200            } else {
19201                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19202            }
19203        }
19204
19205        /**
19206         * Extracts the mode from the supplied measure specification.
19207         *
19208         * @param measureSpec the measure specification to extract the mode from
19209         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19210         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19211         *         {@link android.view.View.MeasureSpec#EXACTLY}
19212         */
19213        public static int getMode(int measureSpec) {
19214            return (measureSpec & MODE_MASK);
19215        }
19216
19217        /**
19218         * Extracts the size from the supplied measure specification.
19219         *
19220         * @param measureSpec the measure specification to extract the size from
19221         * @return the size in pixels defined in the supplied measure specification
19222         */
19223        public static int getSize(int measureSpec) {
19224            return (measureSpec & ~MODE_MASK);
19225        }
19226
19227        static int adjust(int measureSpec, int delta) {
19228            final int mode = getMode(measureSpec);
19229            if (mode == UNSPECIFIED) {
19230                // No need to adjust size for UNSPECIFIED mode.
19231                return makeMeasureSpec(0, UNSPECIFIED);
19232            }
19233            int size = getSize(measureSpec) + delta;
19234            if (size < 0) {
19235                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19236                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19237                size = 0;
19238            }
19239            return makeMeasureSpec(size, mode);
19240        }
19241
19242        /**
19243         * Returns a String representation of the specified measure
19244         * specification.
19245         *
19246         * @param measureSpec the measure specification to convert to a String
19247         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19248         */
19249        public static String toString(int measureSpec) {
19250            int mode = getMode(measureSpec);
19251            int size = getSize(measureSpec);
19252
19253            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19254
19255            if (mode == UNSPECIFIED)
19256                sb.append("UNSPECIFIED ");
19257            else if (mode == EXACTLY)
19258                sb.append("EXACTLY ");
19259            else if (mode == AT_MOST)
19260                sb.append("AT_MOST ");
19261            else
19262                sb.append(mode).append(" ");
19263
19264            sb.append(size);
19265            return sb.toString();
19266        }
19267    }
19268
19269    private final class CheckForLongPress implements Runnable {
19270        private int mOriginalWindowAttachCount;
19271
19272        @Override
19273        public void run() {
19274            if (isPressed() && (mParent != null)
19275                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19276                if (performLongClick()) {
19277                    mHasPerformedLongPress = true;
19278                }
19279            }
19280        }
19281
19282        public void rememberWindowAttachCount() {
19283            mOriginalWindowAttachCount = mWindowAttachCount;
19284        }
19285    }
19286
19287    private final class CheckForTap implements Runnable {
19288        public float x;
19289        public float y;
19290
19291        @Override
19292        public void run() {
19293            mPrivateFlags &= ~PFLAG_PREPRESSED;
19294            setPressed(true, x, y);
19295            checkForLongClick(ViewConfiguration.getTapTimeout());
19296        }
19297    }
19298
19299    private final class PerformClick implements Runnable {
19300        @Override
19301        public void run() {
19302            performClick();
19303        }
19304    }
19305
19306    /** @hide */
19307    public void hackTurnOffWindowResizeAnim(boolean off) {
19308        mAttachInfo.mTurnOffWindowResizeAnim = off;
19309    }
19310
19311    /**
19312     * This method returns a ViewPropertyAnimator object, which can be used to animate
19313     * specific properties on this View.
19314     *
19315     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19316     */
19317    public ViewPropertyAnimator animate() {
19318        if (mAnimator == null) {
19319            mAnimator = new ViewPropertyAnimator(this);
19320        }
19321        return mAnimator;
19322    }
19323
19324    /**
19325     * Sets the name of the View to be used to identify Views in Transitions.
19326     * Names should be unique in the View hierarchy.
19327     *
19328     * @param viewName The name of the View to uniquely identify it for Transitions.
19329     */
19330    public final void setViewName(String viewName) {
19331        mViewName = viewName;
19332    }
19333
19334    /**
19335     * Returns the name of the View to be used to identify Views in Transitions.
19336     * Names should be unique in the View hierarchy.
19337     *
19338     * <p>This returns null if the View has not been given a name.</p>
19339     *
19340     * @return The name used of the View to be used to identify Views in Transitions or null
19341     * if no name has been given.
19342     */
19343    public String getViewName() {
19344        return mViewName;
19345    }
19346
19347    /**
19348     * Interface definition for a callback to be invoked when a hardware key event is
19349     * dispatched to this view. The callback will be invoked before the key event is
19350     * given to the view. This is only useful for hardware keyboards; a software input
19351     * method has no obligation to trigger this listener.
19352     */
19353    public interface OnKeyListener {
19354        /**
19355         * Called when a hardware key is dispatched to a view. This allows listeners to
19356         * get a chance to respond before the target view.
19357         * <p>Key presses in software keyboards will generally NOT trigger this method,
19358         * although some may elect to do so in some situations. Do not assume a
19359         * software input method has to be key-based; even if it is, it may use key presses
19360         * in a different way than you expect, so there is no way to reliably catch soft
19361         * input key presses.
19362         *
19363         * @param v The view the key has been dispatched to.
19364         * @param keyCode The code for the physical key that was pressed
19365         * @param event The KeyEvent object containing full information about
19366         *        the event.
19367         * @return True if the listener has consumed the event, false otherwise.
19368         */
19369        boolean onKey(View v, int keyCode, KeyEvent event);
19370    }
19371
19372    /**
19373     * Interface definition for a callback to be invoked when a touch event is
19374     * dispatched to this view. The callback will be invoked before the touch
19375     * event is given to the view.
19376     */
19377    public interface OnTouchListener {
19378        /**
19379         * Called when a touch event is dispatched to a view. This allows listeners to
19380         * get a chance to respond before the target view.
19381         *
19382         * @param v The view the touch event has been dispatched to.
19383         * @param event The MotionEvent object containing full information about
19384         *        the event.
19385         * @return True if the listener has consumed the event, false otherwise.
19386         */
19387        boolean onTouch(View v, MotionEvent event);
19388    }
19389
19390    /**
19391     * Interface definition for a callback to be invoked when a hover event is
19392     * dispatched to this view. The callback will be invoked before the hover
19393     * event is given to the view.
19394     */
19395    public interface OnHoverListener {
19396        /**
19397         * Called when a hover event is dispatched to a view. This allows listeners to
19398         * get a chance to respond before the target view.
19399         *
19400         * @param v The view the hover event has been dispatched to.
19401         * @param event The MotionEvent object containing full information about
19402         *        the event.
19403         * @return True if the listener has consumed the event, false otherwise.
19404         */
19405        boolean onHover(View v, MotionEvent event);
19406    }
19407
19408    /**
19409     * Interface definition for a callback to be invoked when a generic motion event is
19410     * dispatched to this view. The callback will be invoked before the generic motion
19411     * event is given to the view.
19412     */
19413    public interface OnGenericMotionListener {
19414        /**
19415         * Called when a generic motion event is dispatched to a view. This allows listeners to
19416         * get a chance to respond before the target view.
19417         *
19418         * @param v The view the generic motion event has been dispatched to.
19419         * @param event The MotionEvent object containing full information about
19420         *        the event.
19421         * @return True if the listener has consumed the event, false otherwise.
19422         */
19423        boolean onGenericMotion(View v, MotionEvent event);
19424    }
19425
19426    /**
19427     * Interface definition for a callback to be invoked when a view has been clicked and held.
19428     */
19429    public interface OnLongClickListener {
19430        /**
19431         * Called when a view has been clicked and held.
19432         *
19433         * @param v The view that was clicked and held.
19434         *
19435         * @return true if the callback consumed the long click, false otherwise.
19436         */
19437        boolean onLongClick(View v);
19438    }
19439
19440    /**
19441     * Interface definition for a callback to be invoked when a drag is being dispatched
19442     * to this view.  The callback will be invoked before the hosting view's own
19443     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19444     * onDrag(event) behavior, it should return 'false' from this callback.
19445     *
19446     * <div class="special reference">
19447     * <h3>Developer Guides</h3>
19448     * <p>For a guide to implementing drag and drop features, read the
19449     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19450     * </div>
19451     */
19452    public interface OnDragListener {
19453        /**
19454         * Called when a drag event is dispatched to a view. This allows listeners
19455         * to get a chance to override base View behavior.
19456         *
19457         * @param v The View that received the drag event.
19458         * @param event The {@link android.view.DragEvent} object for the drag event.
19459         * @return {@code true} if the drag event was handled successfully, or {@code false}
19460         * if the drag event was not handled. Note that {@code false} will trigger the View
19461         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19462         */
19463        boolean onDrag(View v, DragEvent event);
19464    }
19465
19466    /**
19467     * Interface definition for a callback to be invoked when the focus state of
19468     * a view changed.
19469     */
19470    public interface OnFocusChangeListener {
19471        /**
19472         * Called when the focus state of a view has changed.
19473         *
19474         * @param v The view whose state has changed.
19475         * @param hasFocus The new focus state of v.
19476         */
19477        void onFocusChange(View v, boolean hasFocus);
19478    }
19479
19480    /**
19481     * Interface definition for a callback to be invoked when a view is clicked.
19482     */
19483    public interface OnClickListener {
19484        /**
19485         * Called when a view has been clicked.
19486         *
19487         * @param v The view that was clicked.
19488         */
19489        void onClick(View v);
19490    }
19491
19492    /**
19493     * Interface definition for a callback to be invoked when the context menu
19494     * for this view is being built.
19495     */
19496    public interface OnCreateContextMenuListener {
19497        /**
19498         * Called when the context menu for this view is being built. It is not
19499         * safe to hold onto the menu after this method returns.
19500         *
19501         * @param menu The context menu that is being built
19502         * @param v The view for which the context menu is being built
19503         * @param menuInfo Extra information about the item for which the
19504         *            context menu should be shown. This information will vary
19505         *            depending on the class of v.
19506         */
19507        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19508    }
19509
19510    /**
19511     * Interface definition for a callback to be invoked when the status bar changes
19512     * visibility.  This reports <strong>global</strong> changes to the system UI
19513     * state, not what the application is requesting.
19514     *
19515     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19516     */
19517    public interface OnSystemUiVisibilityChangeListener {
19518        /**
19519         * Called when the status bar changes visibility because of a call to
19520         * {@link View#setSystemUiVisibility(int)}.
19521         *
19522         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19523         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19524         * This tells you the <strong>global</strong> state of these UI visibility
19525         * flags, not what your app is currently applying.
19526         */
19527        public void onSystemUiVisibilityChange(int visibility);
19528    }
19529
19530    /**
19531     * Interface definition for a callback to be invoked when this view is attached
19532     * or detached from its window.
19533     */
19534    public interface OnAttachStateChangeListener {
19535        /**
19536         * Called when the view is attached to a window.
19537         * @param v The view that was attached
19538         */
19539        public void onViewAttachedToWindow(View v);
19540        /**
19541         * Called when the view is detached from a window.
19542         * @param v The view that was detached
19543         */
19544        public void onViewDetachedFromWindow(View v);
19545    }
19546
19547    /**
19548     * Listener for applying window insets on a view in a custom way.
19549     *
19550     * <p>Apps may choose to implement this interface if they want to apply custom policy
19551     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19552     * is set, its
19553     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19554     * method will be called instead of the View's own
19555     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19556     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19557     * the View's normal behavior as part of its own.</p>
19558     */
19559    public interface OnApplyWindowInsetsListener {
19560        /**
19561         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19562         * on a View, this listener method will be called instead of the view's own
19563         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19564         *
19565         * @param v The view applying window insets
19566         * @param insets The insets to apply
19567         * @return The insets supplied, minus any insets that were consumed
19568         */
19569        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19570    }
19571
19572    private final class UnsetPressedState implements Runnable {
19573        @Override
19574        public void run() {
19575            setPressed(false);
19576        }
19577    }
19578
19579    /**
19580     * Base class for derived classes that want to save and restore their own
19581     * state in {@link android.view.View#onSaveInstanceState()}.
19582     */
19583    public static class BaseSavedState extends AbsSavedState {
19584        /**
19585         * Constructor used when reading from a parcel. Reads the state of the superclass.
19586         *
19587         * @param source
19588         */
19589        public BaseSavedState(Parcel source) {
19590            super(source);
19591        }
19592
19593        /**
19594         * Constructor called by derived classes when creating their SavedState objects
19595         *
19596         * @param superState The state of the superclass of this view
19597         */
19598        public BaseSavedState(Parcelable superState) {
19599            super(superState);
19600        }
19601
19602        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19603                new Parcelable.Creator<BaseSavedState>() {
19604            public BaseSavedState createFromParcel(Parcel in) {
19605                return new BaseSavedState(in);
19606            }
19607
19608            public BaseSavedState[] newArray(int size) {
19609                return new BaseSavedState[size];
19610            }
19611        };
19612    }
19613
19614    /**
19615     * A set of information given to a view when it is attached to its parent
19616     * window.
19617     */
19618    final static class AttachInfo {
19619        interface Callbacks {
19620            void playSoundEffect(int effectId);
19621            boolean performHapticFeedback(int effectId, boolean always);
19622        }
19623
19624        /**
19625         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19626         * to a Handler. This class contains the target (View) to invalidate and
19627         * the coordinates of the dirty rectangle.
19628         *
19629         * For performance purposes, this class also implements a pool of up to
19630         * POOL_LIMIT objects that get reused. This reduces memory allocations
19631         * whenever possible.
19632         */
19633        static class InvalidateInfo {
19634            private static final int POOL_LIMIT = 10;
19635
19636            private static final SynchronizedPool<InvalidateInfo> sPool =
19637                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19638
19639            View target;
19640
19641            int left;
19642            int top;
19643            int right;
19644            int bottom;
19645
19646            public static InvalidateInfo obtain() {
19647                InvalidateInfo instance = sPool.acquire();
19648                return (instance != null) ? instance : new InvalidateInfo();
19649            }
19650
19651            public void recycle() {
19652                target = null;
19653                sPool.release(this);
19654            }
19655        }
19656
19657        final IWindowSession mSession;
19658
19659        final IWindow mWindow;
19660
19661        final IBinder mWindowToken;
19662
19663        final Display mDisplay;
19664
19665        final Callbacks mRootCallbacks;
19666
19667        IWindowId mIWindowId;
19668        WindowId mWindowId;
19669
19670        /**
19671         * The top view of the hierarchy.
19672         */
19673        View mRootView;
19674
19675        IBinder mPanelParentWindowToken;
19676
19677        boolean mHardwareAccelerated;
19678        boolean mHardwareAccelerationRequested;
19679        HardwareRenderer mHardwareRenderer;
19680
19681        /**
19682         * The state of the display to which the window is attached, as reported
19683         * by {@link Display#getState()}.  Note that the display state constants
19684         * declared by {@link Display} do not exactly line up with the screen state
19685         * constants declared by {@link View} (there are more display states than
19686         * screen states).
19687         */
19688        int mDisplayState = Display.STATE_UNKNOWN;
19689
19690        /**
19691         * Scale factor used by the compatibility mode
19692         */
19693        float mApplicationScale;
19694
19695        /**
19696         * Indicates whether the application is in compatibility mode
19697         */
19698        boolean mScalingRequired;
19699
19700        /**
19701         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19702         */
19703        boolean mTurnOffWindowResizeAnim;
19704
19705        /**
19706         * Left position of this view's window
19707         */
19708        int mWindowLeft;
19709
19710        /**
19711         * Top position of this view's window
19712         */
19713        int mWindowTop;
19714
19715        /**
19716         * Indicates whether views need to use 32-bit drawing caches
19717         */
19718        boolean mUse32BitDrawingCache;
19719
19720        /**
19721         * For windows that are full-screen but using insets to layout inside
19722         * of the screen areas, these are the current insets to appear inside
19723         * the overscan area of the display.
19724         */
19725        final Rect mOverscanInsets = new Rect();
19726
19727        /**
19728         * For windows that are full-screen but using insets to layout inside
19729         * of the screen decorations, these are the current insets for the
19730         * content of the window.
19731         */
19732        final Rect mContentInsets = new Rect();
19733
19734        /**
19735         * For windows that are full-screen but using insets to layout inside
19736         * of the screen decorations, these are the current insets for the
19737         * actual visible parts of the window.
19738         */
19739        final Rect mVisibleInsets = new Rect();
19740
19741        /**
19742         * The internal insets given by this window.  This value is
19743         * supplied by the client (through
19744         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19745         * be given to the window manager when changed to be used in laying
19746         * out windows behind it.
19747         */
19748        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19749                = new ViewTreeObserver.InternalInsetsInfo();
19750
19751        /**
19752         * Set to true when mGivenInternalInsets is non-empty.
19753         */
19754        boolean mHasNonEmptyGivenInternalInsets;
19755
19756        /**
19757         * All views in the window's hierarchy that serve as scroll containers,
19758         * used to determine if the window can be resized or must be panned
19759         * to adjust for a soft input area.
19760         */
19761        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19762
19763        final KeyEvent.DispatcherState mKeyDispatchState
19764                = new KeyEvent.DispatcherState();
19765
19766        /**
19767         * Indicates whether the view's window currently has the focus.
19768         */
19769        boolean mHasWindowFocus;
19770
19771        /**
19772         * The current visibility of the window.
19773         */
19774        int mWindowVisibility;
19775
19776        /**
19777         * Indicates the time at which drawing started to occur.
19778         */
19779        long mDrawingTime;
19780
19781        /**
19782         * Indicates whether or not ignoring the DIRTY_MASK flags.
19783         */
19784        boolean mIgnoreDirtyState;
19785
19786        /**
19787         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19788         * to avoid clearing that flag prematurely.
19789         */
19790        boolean mSetIgnoreDirtyState = false;
19791
19792        /**
19793         * Indicates whether the view's window is currently in touch mode.
19794         */
19795        boolean mInTouchMode;
19796
19797        /**
19798         * Indicates whether the view has requested unbuffered input dispatching for the current
19799         * event stream.
19800         */
19801        boolean mUnbufferedDispatchRequested;
19802
19803        /**
19804         * Indicates that ViewAncestor should trigger a global layout change
19805         * the next time it performs a traversal
19806         */
19807        boolean mRecomputeGlobalAttributes;
19808
19809        /**
19810         * Always report new attributes at next traversal.
19811         */
19812        boolean mForceReportNewAttributes;
19813
19814        /**
19815         * Set during a traveral if any views want to keep the screen on.
19816         */
19817        boolean mKeepScreenOn;
19818
19819        /**
19820         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19821         */
19822        int mSystemUiVisibility;
19823
19824        /**
19825         * Hack to force certain system UI visibility flags to be cleared.
19826         */
19827        int mDisabledSystemUiVisibility;
19828
19829        /**
19830         * Last global system UI visibility reported by the window manager.
19831         */
19832        int mGlobalSystemUiVisibility;
19833
19834        /**
19835         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19836         * attached.
19837         */
19838        boolean mHasSystemUiListeners;
19839
19840        /**
19841         * Set if the window has requested to extend into the overscan region
19842         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19843         */
19844        boolean mOverscanRequested;
19845
19846        /**
19847         * Set if the visibility of any views has changed.
19848         */
19849        boolean mViewVisibilityChanged;
19850
19851        /**
19852         * Set to true if a view has been scrolled.
19853         */
19854        boolean mViewScrollChanged;
19855
19856        /**
19857         * Global to the view hierarchy used as a temporary for dealing with
19858         * x/y points in the transparent region computations.
19859         */
19860        final int[] mTransparentLocation = new int[2];
19861
19862        /**
19863         * Global to the view hierarchy used as a temporary for dealing with
19864         * x/y points in the ViewGroup.invalidateChild implementation.
19865         */
19866        final int[] mInvalidateChildLocation = new int[2];
19867
19868        /**
19869         * Global to the view hierarchy used as a temporary for dealng with
19870         * computing absolute on-screen location.
19871         */
19872        final int[] mTmpLocation = new int[2];
19873
19874        /**
19875         * Global to the view hierarchy used as a temporary for dealing with
19876         * x/y location when view is transformed.
19877         */
19878        final float[] mTmpTransformLocation = new float[2];
19879
19880        /**
19881         * The view tree observer used to dispatch global events like
19882         * layout, pre-draw, touch mode change, etc.
19883         */
19884        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19885
19886        /**
19887         * A Canvas used by the view hierarchy to perform bitmap caching.
19888         */
19889        Canvas mCanvas;
19890
19891        /**
19892         * The view root impl.
19893         */
19894        final ViewRootImpl mViewRootImpl;
19895
19896        /**
19897         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19898         * handler can be used to pump events in the UI events queue.
19899         */
19900        final Handler mHandler;
19901
19902        /**
19903         * Temporary for use in computing invalidate rectangles while
19904         * calling up the hierarchy.
19905         */
19906        final Rect mTmpInvalRect = new Rect();
19907
19908        /**
19909         * Temporary for use in computing hit areas with transformed views
19910         */
19911        final RectF mTmpTransformRect = new RectF();
19912
19913        /**
19914         * Temporary for use in transforming invalidation rect
19915         */
19916        final Matrix mTmpMatrix = new Matrix();
19917
19918        /**
19919         * Temporary for use in transforming invalidation rect
19920         */
19921        final Transformation mTmpTransformation = new Transformation();
19922
19923        /**
19924         * Temporary list for use in collecting focusable descendents of a view.
19925         */
19926        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19927
19928        /**
19929         * The id of the window for accessibility purposes.
19930         */
19931        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19932
19933        /**
19934         * Flags related to accessibility processing.
19935         *
19936         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19937         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19938         */
19939        int mAccessibilityFetchFlags;
19940
19941        /**
19942         * The drawable for highlighting accessibility focus.
19943         */
19944        Drawable mAccessibilityFocusDrawable;
19945
19946        /**
19947         * Show where the margins, bounds and layout bounds are for each view.
19948         */
19949        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19950
19951        /**
19952         * Point used to compute visible regions.
19953         */
19954        final Point mPoint = new Point();
19955
19956        /**
19957         * Used to track which View originated a requestLayout() call, used when
19958         * requestLayout() is called during layout.
19959         */
19960        View mViewRequestingLayout;
19961
19962        /**
19963         * Creates a new set of attachment information with the specified
19964         * events handler and thread.
19965         *
19966         * @param handler the events handler the view must use
19967         */
19968        AttachInfo(IWindowSession session, IWindow window, Display display,
19969                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19970            mSession = session;
19971            mWindow = window;
19972            mWindowToken = window.asBinder();
19973            mDisplay = display;
19974            mViewRootImpl = viewRootImpl;
19975            mHandler = handler;
19976            mRootCallbacks = effectPlayer;
19977        }
19978    }
19979
19980    /**
19981     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19982     * is supported. This avoids keeping too many unused fields in most
19983     * instances of View.</p>
19984     */
19985    private static class ScrollabilityCache implements Runnable {
19986
19987        /**
19988         * Scrollbars are not visible
19989         */
19990        public static final int OFF = 0;
19991
19992        /**
19993         * Scrollbars are visible
19994         */
19995        public static final int ON = 1;
19996
19997        /**
19998         * Scrollbars are fading away
19999         */
20000        public static final int FADING = 2;
20001
20002        public boolean fadeScrollBars;
20003
20004        public int fadingEdgeLength;
20005        public int scrollBarDefaultDelayBeforeFade;
20006        public int scrollBarFadeDuration;
20007
20008        public int scrollBarSize;
20009        public ScrollBarDrawable scrollBar;
20010        public float[] interpolatorValues;
20011        public View host;
20012
20013        public final Paint paint;
20014        public final Matrix matrix;
20015        public Shader shader;
20016
20017        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20018
20019        private static final float[] OPAQUE = { 255 };
20020        private static final float[] TRANSPARENT = { 0.0f };
20021
20022        /**
20023         * When fading should start. This time moves into the future every time
20024         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20025         */
20026        public long fadeStartTime;
20027
20028
20029        /**
20030         * The current state of the scrollbars: ON, OFF, or FADING
20031         */
20032        public int state = OFF;
20033
20034        private int mLastColor;
20035
20036        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20037            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20038            scrollBarSize = configuration.getScaledScrollBarSize();
20039            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20040            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20041
20042            paint = new Paint();
20043            matrix = new Matrix();
20044            // use use a height of 1, and then wack the matrix each time we
20045            // actually use it.
20046            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20047            paint.setShader(shader);
20048            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20049
20050            this.host = host;
20051        }
20052
20053        public void setFadeColor(int color) {
20054            if (color != mLastColor) {
20055                mLastColor = color;
20056
20057                if (color != 0) {
20058                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20059                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20060                    paint.setShader(shader);
20061                    // Restore the default transfer mode (src_over)
20062                    paint.setXfermode(null);
20063                } else {
20064                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20065                    paint.setShader(shader);
20066                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20067                }
20068            }
20069        }
20070
20071        public void run() {
20072            long now = AnimationUtils.currentAnimationTimeMillis();
20073            if (now >= fadeStartTime) {
20074
20075                // the animation fades the scrollbars out by changing
20076                // the opacity (alpha) from fully opaque to fully
20077                // transparent
20078                int nextFrame = (int) now;
20079                int framesCount = 0;
20080
20081                Interpolator interpolator = scrollBarInterpolator;
20082
20083                // Start opaque
20084                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20085
20086                // End transparent
20087                nextFrame += scrollBarFadeDuration;
20088                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20089
20090                state = FADING;
20091
20092                // Kick off the fade animation
20093                host.invalidate(true);
20094            }
20095        }
20096    }
20097
20098    /**
20099     * Resuable callback for sending
20100     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20101     */
20102    private class SendViewScrolledAccessibilityEvent implements Runnable {
20103        public volatile boolean mIsPending;
20104
20105        public void run() {
20106            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20107            mIsPending = false;
20108        }
20109    }
20110
20111    /**
20112     * <p>
20113     * This class represents a delegate that can be registered in a {@link View}
20114     * to enhance accessibility support via composition rather via inheritance.
20115     * It is specifically targeted to widget developers that extend basic View
20116     * classes i.e. classes in package android.view, that would like their
20117     * applications to be backwards compatible.
20118     * </p>
20119     * <div class="special reference">
20120     * <h3>Developer Guides</h3>
20121     * <p>For more information about making applications accessible, read the
20122     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20123     * developer guide.</p>
20124     * </div>
20125     * <p>
20126     * A scenario in which a developer would like to use an accessibility delegate
20127     * is overriding a method introduced in a later API version then the minimal API
20128     * version supported by the application. For example, the method
20129     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20130     * in API version 4 when the accessibility APIs were first introduced. If a
20131     * developer would like his application to run on API version 4 devices (assuming
20132     * all other APIs used by the application are version 4 or lower) and take advantage
20133     * of this method, instead of overriding the method which would break the application's
20134     * backwards compatibility, he can override the corresponding method in this
20135     * delegate and register the delegate in the target View if the API version of
20136     * the system is high enough i.e. the API version is same or higher to the API
20137     * version that introduced
20138     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20139     * </p>
20140     * <p>
20141     * Here is an example implementation:
20142     * </p>
20143     * <code><pre><p>
20144     * if (Build.VERSION.SDK_INT >= 14) {
20145     *     // If the API version is equal of higher than the version in
20146     *     // which onInitializeAccessibilityNodeInfo was introduced we
20147     *     // register a delegate with a customized implementation.
20148     *     View view = findViewById(R.id.view_id);
20149     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20150     *         public void onInitializeAccessibilityNodeInfo(View host,
20151     *                 AccessibilityNodeInfo info) {
20152     *             // Let the default implementation populate the info.
20153     *             super.onInitializeAccessibilityNodeInfo(host, info);
20154     *             // Set some other information.
20155     *             info.setEnabled(host.isEnabled());
20156     *         }
20157     *     });
20158     * }
20159     * </code></pre></p>
20160     * <p>
20161     * This delegate contains methods that correspond to the accessibility methods
20162     * in View. If a delegate has been specified the implementation in View hands
20163     * off handling to the corresponding method in this delegate. The default
20164     * implementation the delegate methods behaves exactly as the corresponding
20165     * method in View for the case of no accessibility delegate been set. Hence,
20166     * to customize the behavior of a View method, clients can override only the
20167     * corresponding delegate method without altering the behavior of the rest
20168     * accessibility related methods of the host view.
20169     * </p>
20170     */
20171    public static class AccessibilityDelegate {
20172
20173        /**
20174         * Sends an accessibility event of the given type. If accessibility is not
20175         * enabled this method has no effect.
20176         * <p>
20177         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20178         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20179         * been set.
20180         * </p>
20181         *
20182         * @param host The View hosting the delegate.
20183         * @param eventType The type of the event to send.
20184         *
20185         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20186         */
20187        public void sendAccessibilityEvent(View host, int eventType) {
20188            host.sendAccessibilityEventInternal(eventType);
20189        }
20190
20191        /**
20192         * Performs the specified accessibility action on the view. For
20193         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20194         * <p>
20195         * The default implementation behaves as
20196         * {@link View#performAccessibilityAction(int, Bundle)
20197         *  View#performAccessibilityAction(int, Bundle)} for the case of
20198         *  no accessibility delegate been set.
20199         * </p>
20200         *
20201         * @param action The action to perform.
20202         * @return Whether the action was performed.
20203         *
20204         * @see View#performAccessibilityAction(int, Bundle)
20205         *      View#performAccessibilityAction(int, Bundle)
20206         */
20207        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20208            return host.performAccessibilityActionInternal(action, args);
20209        }
20210
20211        /**
20212         * Sends an accessibility event. This method behaves exactly as
20213         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20214         * empty {@link AccessibilityEvent} and does not perform a check whether
20215         * accessibility is enabled.
20216         * <p>
20217         * The default implementation behaves as
20218         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20219         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20220         * the case of no accessibility delegate been set.
20221         * </p>
20222         *
20223         * @param host The View hosting the delegate.
20224         * @param event The event to send.
20225         *
20226         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20227         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20228         */
20229        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20230            host.sendAccessibilityEventUncheckedInternal(event);
20231        }
20232
20233        /**
20234         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20235         * to its children for adding their text content to the event.
20236         * <p>
20237         * The default implementation behaves as
20238         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20239         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20240         * the case of no accessibility delegate been set.
20241         * </p>
20242         *
20243         * @param host The View hosting the delegate.
20244         * @param event The event.
20245         * @return True if the event population was completed.
20246         *
20247         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20248         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20249         */
20250        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20251            return host.dispatchPopulateAccessibilityEventInternal(event);
20252        }
20253
20254        /**
20255         * Gives a chance to the host View to populate the accessibility event with its
20256         * text content.
20257         * <p>
20258         * The default implementation behaves as
20259         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20260         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20261         * the case of no accessibility delegate been set.
20262         * </p>
20263         *
20264         * @param host The View hosting the delegate.
20265         * @param event The accessibility event which to populate.
20266         *
20267         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20268         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20269         */
20270        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20271            host.onPopulateAccessibilityEventInternal(event);
20272        }
20273
20274        /**
20275         * Initializes an {@link AccessibilityEvent} with information about the
20276         * the host View which is the event source.
20277         * <p>
20278         * The default implementation behaves as
20279         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20280         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20281         * the case of no accessibility delegate been set.
20282         * </p>
20283         *
20284         * @param host The View hosting the delegate.
20285         * @param event The event to initialize.
20286         *
20287         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20288         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20289         */
20290        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20291            host.onInitializeAccessibilityEventInternal(event);
20292        }
20293
20294        /**
20295         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20296         * <p>
20297         * The default implementation behaves as
20298         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20299         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20300         * the case of no accessibility delegate been set.
20301         * </p>
20302         *
20303         * @param host The View hosting the delegate.
20304         * @param info The instance to initialize.
20305         *
20306         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20307         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20308         */
20309        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20310            host.onInitializeAccessibilityNodeInfoInternal(info);
20311        }
20312
20313        /**
20314         * Called when a child of the host View has requested sending an
20315         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20316         * to augment the event.
20317         * <p>
20318         * The default implementation behaves as
20319         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20320         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20321         * the case of no accessibility delegate been set.
20322         * </p>
20323         *
20324         * @param host The View hosting the delegate.
20325         * @param child The child which requests sending the event.
20326         * @param event The event to be sent.
20327         * @return True if the event should be sent
20328         *
20329         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20330         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20331         */
20332        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20333                AccessibilityEvent event) {
20334            return host.onRequestSendAccessibilityEventInternal(child, event);
20335        }
20336
20337        /**
20338         * Gets the provider for managing a virtual view hierarchy rooted at this View
20339         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20340         * that explore the window content.
20341         * <p>
20342         * The default implementation behaves as
20343         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20344         * the case of no accessibility delegate been set.
20345         * </p>
20346         *
20347         * @return The provider.
20348         *
20349         * @see AccessibilityNodeProvider
20350         */
20351        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20352            return null;
20353        }
20354
20355        /**
20356         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20357         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20358         * This method is responsible for obtaining an accessibility node info from a
20359         * pool of reusable instances and calling
20360         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20361         * view to initialize the former.
20362         * <p>
20363         * <strong>Note:</strong> The client is responsible for recycling the obtained
20364         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20365         * creation.
20366         * </p>
20367         * <p>
20368         * The default implementation behaves as
20369         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20370         * the case of no accessibility delegate been set.
20371         * </p>
20372         * @return A populated {@link AccessibilityNodeInfo}.
20373         *
20374         * @see AccessibilityNodeInfo
20375         *
20376         * @hide
20377         */
20378        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20379            return host.createAccessibilityNodeInfoInternal();
20380        }
20381    }
20382
20383    private class MatchIdPredicate implements Predicate<View> {
20384        public int mId;
20385
20386        @Override
20387        public boolean apply(View view) {
20388            return (view.mID == mId);
20389        }
20390    }
20391
20392    private class MatchLabelForPredicate implements Predicate<View> {
20393        private int mLabeledId;
20394
20395        @Override
20396        public boolean apply(View view) {
20397            return (view.mLabelForId == mLabeledId);
20398        }
20399    }
20400
20401    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20402        private int mChangeTypes = 0;
20403        private boolean mPosted;
20404        private boolean mPostedWithDelay;
20405        private long mLastEventTimeMillis;
20406
20407        @Override
20408        public void run() {
20409            mPosted = false;
20410            mPostedWithDelay = false;
20411            mLastEventTimeMillis = SystemClock.uptimeMillis();
20412            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20413                final AccessibilityEvent event = AccessibilityEvent.obtain();
20414                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20415                event.setContentChangeTypes(mChangeTypes);
20416                sendAccessibilityEventUnchecked(event);
20417            }
20418            mChangeTypes = 0;
20419        }
20420
20421        public void runOrPost(int changeType) {
20422            mChangeTypes |= changeType;
20423
20424            // If this is a live region or the child of a live region, collect
20425            // all events from this frame and send them on the next frame.
20426            if (inLiveRegion()) {
20427                // If we're already posted with a delay, remove that.
20428                if (mPostedWithDelay) {
20429                    removeCallbacks(this);
20430                    mPostedWithDelay = false;
20431                }
20432                // Only post if we're not already posted.
20433                if (!mPosted) {
20434                    post(this);
20435                    mPosted = true;
20436                }
20437                return;
20438            }
20439
20440            if (mPosted) {
20441                return;
20442            }
20443            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20444            final long minEventIntevalMillis =
20445                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20446            if (timeSinceLastMillis >= minEventIntevalMillis) {
20447                removeCallbacks(this);
20448                run();
20449            } else {
20450                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20451                mPosted = true;
20452                mPostedWithDelay = true;
20453            }
20454        }
20455    }
20456
20457    private boolean inLiveRegion() {
20458        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20459            return true;
20460        }
20461
20462        ViewParent parent = getParent();
20463        while (parent instanceof View) {
20464            if (((View) parent).getAccessibilityLiveRegion()
20465                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20466                return true;
20467            }
20468            parent = parent.getParent();
20469        }
20470
20471        return false;
20472    }
20473
20474    /**
20475     * Dump all private flags in readable format, useful for documentation and
20476     * sanity checking.
20477     */
20478    private static void dumpFlags() {
20479        final HashMap<String, String> found = Maps.newHashMap();
20480        try {
20481            for (Field field : View.class.getDeclaredFields()) {
20482                final int modifiers = field.getModifiers();
20483                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20484                    if (field.getType().equals(int.class)) {
20485                        final int value = field.getInt(null);
20486                        dumpFlag(found, field.getName(), value);
20487                    } else if (field.getType().equals(int[].class)) {
20488                        final int[] values = (int[]) field.get(null);
20489                        for (int i = 0; i < values.length; i++) {
20490                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20491                        }
20492                    }
20493                }
20494            }
20495        } catch (IllegalAccessException e) {
20496            throw new RuntimeException(e);
20497        }
20498
20499        final ArrayList<String> keys = Lists.newArrayList();
20500        keys.addAll(found.keySet());
20501        Collections.sort(keys);
20502        for (String key : keys) {
20503            Log.d(VIEW_LOG_TAG, found.get(key));
20504        }
20505    }
20506
20507    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20508        // Sort flags by prefix, then by bits, always keeping unique keys
20509        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20510        final int prefix = name.indexOf('_');
20511        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20512        final String output = bits + " " + name;
20513        found.put(key, output);
20514    }
20515}
20516