View.java revision 287c0361877057e50190cc0d7224e5bb2a7c4955
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_transitionName
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     * RenderNode used for backgrounds.
3197     * <p>
3198     * When non-null and valid, this is expected to contain an up-to-date copy
3199     * of the background drawable. It is cleared on temporary detach, and reset
3200     * on cleanup.
3201     */
3202    private RenderNode mBackgroundRenderNode;
3203
3204    private int mBackgroundResource;
3205    private boolean mBackgroundSizeChanged;
3206
3207    private String mTransitionName;
3208
3209    static class 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                        initializeFadingEdgeInternal(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_transitionName:
4020                    setTransitionName(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            initializeScrollbarsInternal(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        // This method probably shouldn't have been included in the SDK to begin with.
4240        // It relies on 'a' having been initialized using an attribute filter array that is
4241        // not publicly available to the SDK. The old method has been renamed
4242        // to initializeFadingEdgeInternal and hidden for framework use only;
4243        // this one initializes using defaults to make it safe to call for apps.
4244
4245        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4246
4247        initializeFadingEdgeInternal(arr);
4248
4249        arr.recycle();
4250    }
4251
4252    /**
4253     * <p>
4254     * Initializes the fading edges from a given set of styled attributes. This
4255     * method should be called by subclasses that need fading edges and when an
4256     * instance of these subclasses is created programmatically rather than
4257     * being inflated from XML. This method is automatically called when the XML
4258     * is inflated.
4259     * </p>
4260     *
4261     * @param a the styled attributes set to initialize the fading edges from
4262     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4263     */
4264    protected void initializeFadingEdgeInternal(TypedArray a) {
4265        initScrollCache();
4266
4267        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4268                R.styleable.View_fadingEdgeLength,
4269                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4270    }
4271
4272    /**
4273     * Returns the size of the vertical faded edges used to indicate that more
4274     * content in this view is visible.
4275     *
4276     * @return The size in pixels of the vertical faded edge or 0 if vertical
4277     *         faded edges are not enabled for this view.
4278     * @attr ref android.R.styleable#View_fadingEdgeLength
4279     */
4280    public int getVerticalFadingEdgeLength() {
4281        if (isVerticalFadingEdgeEnabled()) {
4282            ScrollabilityCache cache = mScrollCache;
4283            if (cache != null) {
4284                return cache.fadingEdgeLength;
4285            }
4286        }
4287        return 0;
4288    }
4289
4290    /**
4291     * Set the size of the faded edge used to indicate that more content in this
4292     * view is available.  Will not change whether the fading edge is enabled; use
4293     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4294     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4295     * for the vertical or horizontal fading edges.
4296     *
4297     * @param length The size in pixels of the faded edge used to indicate that more
4298     *        content in this view is visible.
4299     */
4300    public void setFadingEdgeLength(int length) {
4301        initScrollCache();
4302        mScrollCache.fadingEdgeLength = length;
4303    }
4304
4305    /**
4306     * Returns the size of the horizontal faded edges used to indicate that more
4307     * content in this view is visible.
4308     *
4309     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4310     *         faded edges are not enabled for this view.
4311     * @attr ref android.R.styleable#View_fadingEdgeLength
4312     */
4313    public int getHorizontalFadingEdgeLength() {
4314        if (isHorizontalFadingEdgeEnabled()) {
4315            ScrollabilityCache cache = mScrollCache;
4316            if (cache != null) {
4317                return cache.fadingEdgeLength;
4318            }
4319        }
4320        return 0;
4321    }
4322
4323    /**
4324     * Returns the width of the vertical scrollbar.
4325     *
4326     * @return The width in pixels of the vertical scrollbar or 0 if there
4327     *         is no vertical scrollbar.
4328     */
4329    public int getVerticalScrollbarWidth() {
4330        ScrollabilityCache cache = mScrollCache;
4331        if (cache != null) {
4332            ScrollBarDrawable scrollBar = cache.scrollBar;
4333            if (scrollBar != null) {
4334                int size = scrollBar.getSize(true);
4335                if (size <= 0) {
4336                    size = cache.scrollBarSize;
4337                }
4338                return size;
4339            }
4340            return 0;
4341        }
4342        return 0;
4343    }
4344
4345    /**
4346     * Returns the height of the horizontal scrollbar.
4347     *
4348     * @return The height in pixels of the horizontal scrollbar or 0 if
4349     *         there is no horizontal scrollbar.
4350     */
4351    protected int getHorizontalScrollbarHeight() {
4352        ScrollabilityCache cache = mScrollCache;
4353        if (cache != null) {
4354            ScrollBarDrawable scrollBar = cache.scrollBar;
4355            if (scrollBar != null) {
4356                int size = scrollBar.getSize(false);
4357                if (size <= 0) {
4358                    size = cache.scrollBarSize;
4359                }
4360                return size;
4361            }
4362            return 0;
4363        }
4364        return 0;
4365    }
4366
4367    /**
4368     * <p>
4369     * Initializes the scrollbars from a given set of styled attributes. This
4370     * method should be called by subclasses that need scrollbars and when an
4371     * instance of these subclasses is created programmatically rather than
4372     * being inflated from XML. This method is automatically called when the XML
4373     * is inflated.
4374     * </p>
4375     *
4376     * @param a the styled attributes set to initialize the scrollbars from
4377     */
4378    protected void initializeScrollbars(TypedArray a) {
4379        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4380        // using the View filter array which is not available to the SDK. As such, internal
4381        // framework usage now uses initializeScrollbarsInternal and we grab a default
4382        // TypedArray with the right filter instead here.
4383        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4384
4385        initializeScrollbarsInternal(arr);
4386
4387        // We ignored the method parameter. Recycle the one we actually did use.
4388        arr.recycle();
4389    }
4390
4391    /**
4392     * <p>
4393     * Initializes the scrollbars from a given set of styled attributes. This
4394     * method should be called by subclasses that need scrollbars and when an
4395     * instance of these subclasses is created programmatically rather than
4396     * being inflated from XML. This method is automatically called when the XML
4397     * is inflated.
4398     * </p>
4399     *
4400     * @param a the styled attributes set to initialize the scrollbars from
4401     * @hide
4402     */
4403    protected void initializeScrollbarsInternal(TypedArray a) {
4404        initScrollCache();
4405
4406        final ScrollabilityCache scrollabilityCache = mScrollCache;
4407
4408        if (scrollabilityCache.scrollBar == null) {
4409            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4410        }
4411
4412        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4413
4414        if (!fadeScrollbars) {
4415            scrollabilityCache.state = ScrollabilityCache.ON;
4416        }
4417        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4418
4419
4420        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4421                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4422                        .getScrollBarFadeDuration());
4423        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4424                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4425                ViewConfiguration.getScrollDefaultDelay());
4426
4427
4428        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4429                com.android.internal.R.styleable.View_scrollbarSize,
4430                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4431
4432        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4433        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4434
4435        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4436        if (thumb != null) {
4437            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4438        }
4439
4440        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4441                false);
4442        if (alwaysDraw) {
4443            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4444        }
4445
4446        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4447        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4448
4449        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4450        if (thumb != null) {
4451            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4452        }
4453
4454        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4455                false);
4456        if (alwaysDraw) {
4457            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4458        }
4459
4460        // Apply layout direction to the new Drawables if needed
4461        final int layoutDirection = getLayoutDirection();
4462        if (track != null) {
4463            track.setLayoutDirection(layoutDirection);
4464        }
4465        if (thumb != null) {
4466            thumb.setLayoutDirection(layoutDirection);
4467        }
4468
4469        // Re-apply user/background padding so that scrollbar(s) get added
4470        resolvePadding();
4471    }
4472
4473    /**
4474     * <p>
4475     * Initalizes the scrollability cache if necessary.
4476     * </p>
4477     */
4478    private void initScrollCache() {
4479        if (mScrollCache == null) {
4480            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4481        }
4482    }
4483
4484    private ScrollabilityCache getScrollCache() {
4485        initScrollCache();
4486        return mScrollCache;
4487    }
4488
4489    /**
4490     * Set the position of the vertical scroll bar. Should be one of
4491     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4492     * {@link #SCROLLBAR_POSITION_RIGHT}.
4493     *
4494     * @param position Where the vertical scroll bar should be positioned.
4495     */
4496    public void setVerticalScrollbarPosition(int position) {
4497        if (mVerticalScrollbarPosition != position) {
4498            mVerticalScrollbarPosition = position;
4499            computeOpaqueFlags();
4500            resolvePadding();
4501        }
4502    }
4503
4504    /**
4505     * @return The position where the vertical scroll bar will show, if applicable.
4506     * @see #setVerticalScrollbarPosition(int)
4507     */
4508    public int getVerticalScrollbarPosition() {
4509        return mVerticalScrollbarPosition;
4510    }
4511
4512    ListenerInfo getListenerInfo() {
4513        if (mListenerInfo != null) {
4514            return mListenerInfo;
4515        }
4516        mListenerInfo = new ListenerInfo();
4517        return mListenerInfo;
4518    }
4519
4520    /**
4521     * Register a callback to be invoked when focus of this view changed.
4522     *
4523     * @param l The callback that will run.
4524     */
4525    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4526        getListenerInfo().mOnFocusChangeListener = l;
4527    }
4528
4529    /**
4530     * Add a listener that will be called when the bounds of the view change due to
4531     * layout processing.
4532     *
4533     * @param listener The listener that will be called when layout bounds change.
4534     */
4535    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4536        ListenerInfo li = getListenerInfo();
4537        if (li.mOnLayoutChangeListeners == null) {
4538            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4539        }
4540        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4541            li.mOnLayoutChangeListeners.add(listener);
4542        }
4543    }
4544
4545    /**
4546     * Remove a listener for layout changes.
4547     *
4548     * @param listener The listener for layout bounds change.
4549     */
4550    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4551        ListenerInfo li = mListenerInfo;
4552        if (li == null || li.mOnLayoutChangeListeners == null) {
4553            return;
4554        }
4555        li.mOnLayoutChangeListeners.remove(listener);
4556    }
4557
4558    /**
4559     * Add a listener for attach state changes.
4560     *
4561     * This listener will be called whenever this view is attached or detached
4562     * from a window. Remove the listener using
4563     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4564     *
4565     * @param listener Listener to attach
4566     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4567     */
4568    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4569        ListenerInfo li = getListenerInfo();
4570        if (li.mOnAttachStateChangeListeners == null) {
4571            li.mOnAttachStateChangeListeners
4572                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4573        }
4574        li.mOnAttachStateChangeListeners.add(listener);
4575    }
4576
4577    /**
4578     * Remove a listener for attach state changes. The listener will receive no further
4579     * notification of window attach/detach events.
4580     *
4581     * @param listener Listener to remove
4582     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4583     */
4584    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4585        ListenerInfo li = mListenerInfo;
4586        if (li == null || li.mOnAttachStateChangeListeners == null) {
4587            return;
4588        }
4589        li.mOnAttachStateChangeListeners.remove(listener);
4590    }
4591
4592    /**
4593     * Returns the focus-change callback registered for this view.
4594     *
4595     * @return The callback, or null if one is not registered.
4596     */
4597    public OnFocusChangeListener getOnFocusChangeListener() {
4598        ListenerInfo li = mListenerInfo;
4599        return li != null ? li.mOnFocusChangeListener : null;
4600    }
4601
4602    /**
4603     * Register a callback to be invoked when this view is clicked. If this view is not
4604     * clickable, it becomes clickable.
4605     *
4606     * @param l The callback that will run
4607     *
4608     * @see #setClickable(boolean)
4609     */
4610    public void setOnClickListener(OnClickListener l) {
4611        if (!isClickable()) {
4612            setClickable(true);
4613        }
4614        getListenerInfo().mOnClickListener = l;
4615    }
4616
4617    /**
4618     * Return whether this view has an attached OnClickListener.  Returns
4619     * true if there is a listener, false if there is none.
4620     */
4621    public boolean hasOnClickListeners() {
4622        ListenerInfo li = mListenerInfo;
4623        return (li != null && li.mOnClickListener != null);
4624    }
4625
4626    /**
4627     * Register a callback to be invoked when this view is clicked and held. If this view is not
4628     * long clickable, it becomes long clickable.
4629     *
4630     * @param l The callback that will run
4631     *
4632     * @see #setLongClickable(boolean)
4633     */
4634    public void setOnLongClickListener(OnLongClickListener l) {
4635        if (!isLongClickable()) {
4636            setLongClickable(true);
4637        }
4638        getListenerInfo().mOnLongClickListener = l;
4639    }
4640
4641    /**
4642     * Register a callback to be invoked when the context menu for this view is
4643     * being built. If this view is not long clickable, it becomes long clickable.
4644     *
4645     * @param l The callback that will run
4646     *
4647     */
4648    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4649        if (!isLongClickable()) {
4650            setLongClickable(true);
4651        }
4652        getListenerInfo().mOnCreateContextMenuListener = l;
4653    }
4654
4655    /**
4656     * Call this view's OnClickListener, if it is defined.  Performs all normal
4657     * actions associated with clicking: reporting accessibility event, playing
4658     * a sound, etc.
4659     *
4660     * @return True there was an assigned OnClickListener that was called, false
4661     *         otherwise is returned.
4662     */
4663    public boolean performClick() {
4664        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4665
4666        ListenerInfo li = mListenerInfo;
4667        if (li != null && li.mOnClickListener != null) {
4668            playSoundEffect(SoundEffectConstants.CLICK);
4669            li.mOnClickListener.onClick(this);
4670            return true;
4671        }
4672
4673        return false;
4674    }
4675
4676    /**
4677     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4678     * this only calls the listener, and does not do any associated clicking
4679     * actions like reporting an accessibility event.
4680     *
4681     * @return True there was an assigned OnClickListener that was called, false
4682     *         otherwise is returned.
4683     */
4684    public boolean callOnClick() {
4685        ListenerInfo li = mListenerInfo;
4686        if (li != null && li.mOnClickListener != null) {
4687            li.mOnClickListener.onClick(this);
4688            return true;
4689        }
4690        return false;
4691    }
4692
4693    /**
4694     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4695     * OnLongClickListener did not consume the event.
4696     *
4697     * @return True if one of the above receivers consumed the event, false otherwise.
4698     */
4699    public boolean performLongClick() {
4700        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4701
4702        boolean handled = false;
4703        ListenerInfo li = mListenerInfo;
4704        if (li != null && li.mOnLongClickListener != null) {
4705            handled = li.mOnLongClickListener.onLongClick(View.this);
4706        }
4707        if (!handled) {
4708            handled = showContextMenu();
4709        }
4710        if (handled) {
4711            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4712        }
4713        return handled;
4714    }
4715
4716    /**
4717     * Performs button-related actions during a touch down event.
4718     *
4719     * @param event The event.
4720     * @return True if the down was consumed.
4721     *
4722     * @hide
4723     */
4724    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4725        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4726            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4727                return true;
4728            }
4729        }
4730        return false;
4731    }
4732
4733    /**
4734     * Bring up the context menu for this view.
4735     *
4736     * @return Whether a context menu was displayed.
4737     */
4738    public boolean showContextMenu() {
4739        return getParent().showContextMenuForChild(this);
4740    }
4741
4742    /**
4743     * Bring up the context menu for this view, referring to the item under the specified point.
4744     *
4745     * @param x The referenced x coordinate.
4746     * @param y The referenced y coordinate.
4747     * @param metaState The keyboard modifiers that were pressed.
4748     * @return Whether a context menu was displayed.
4749     *
4750     * @hide
4751     */
4752    public boolean showContextMenu(float x, float y, int metaState) {
4753        return showContextMenu();
4754    }
4755
4756    /**
4757     * Start an action mode.
4758     *
4759     * @param callback Callback that will control the lifecycle of the action mode
4760     * @return The new action mode if it is started, null otherwise
4761     *
4762     * @see ActionMode
4763     */
4764    public ActionMode startActionMode(ActionMode.Callback callback) {
4765        ViewParent parent = getParent();
4766        if (parent == null) return null;
4767        return parent.startActionModeForChild(this, callback);
4768    }
4769
4770    /**
4771     * Register a callback to be invoked when a hardware key is pressed in this view.
4772     * Key presses in software input methods will generally not trigger the methods of
4773     * this listener.
4774     * @param l the key listener to attach to this view
4775     */
4776    public void setOnKeyListener(OnKeyListener l) {
4777        getListenerInfo().mOnKeyListener = l;
4778    }
4779
4780    /**
4781     * Register a callback to be invoked when a touch event is sent to this view.
4782     * @param l the touch listener to attach to this view
4783     */
4784    public void setOnTouchListener(OnTouchListener l) {
4785        getListenerInfo().mOnTouchListener = l;
4786    }
4787
4788    /**
4789     * Register a callback to be invoked when a generic motion event is sent to this view.
4790     * @param l the generic motion listener to attach to this view
4791     */
4792    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4793        getListenerInfo().mOnGenericMotionListener = l;
4794    }
4795
4796    /**
4797     * Register a callback to be invoked when a hover event is sent to this view.
4798     * @param l the hover listener to attach to this view
4799     */
4800    public void setOnHoverListener(OnHoverListener l) {
4801        getListenerInfo().mOnHoverListener = l;
4802    }
4803
4804    /**
4805     * Register a drag event listener callback object for this View. The parameter is
4806     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4807     * View, the system calls the
4808     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4809     * @param l An implementation of {@link android.view.View.OnDragListener}.
4810     */
4811    public void setOnDragListener(OnDragListener l) {
4812        getListenerInfo().mOnDragListener = l;
4813    }
4814
4815    /**
4816     * Give this view focus. This will cause
4817     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4818     *
4819     * Note: this does not check whether this {@link View} should get focus, it just
4820     * gives it focus no matter what.  It should only be called internally by framework
4821     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4822     *
4823     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4824     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4825     *        focus moved when requestFocus() is called. It may not always
4826     *        apply, in which case use the default View.FOCUS_DOWN.
4827     * @param previouslyFocusedRect The rectangle of the view that had focus
4828     *        prior in this View's coordinate system.
4829     */
4830    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4831        if (DBG) {
4832            System.out.println(this + " requestFocus()");
4833        }
4834
4835        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4836            mPrivateFlags |= PFLAG_FOCUSED;
4837
4838            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4839
4840            if (mParent != null) {
4841                mParent.requestChildFocus(this, this);
4842            }
4843
4844            if (mAttachInfo != null) {
4845                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4846            }
4847
4848            onFocusChanged(true, direction, previouslyFocusedRect);
4849            manageFocusHotspot(true, oldFocus);
4850            refreshDrawableState();
4851        }
4852    }
4853
4854    /**
4855     * Forwards focus information to the background drawable, if necessary. When
4856     * the view is gaining focus, <code>v</code> is the previous focus holder.
4857     * When the view is losing focus, <code>v</code> is the next focus holder.
4858     *
4859     * @param focused whether this view is focused
4860     * @param v previous or the next focus holder, or null if none
4861     */
4862    private void manageFocusHotspot(boolean focused, View v) {
4863        final Rect r = new Rect();
4864        if (!focused && v != null && mAttachInfo != null) {
4865            v.getBoundsOnScreen(r);
4866            final int[] location = mAttachInfo.mTmpLocation;
4867            getLocationOnScreen(location);
4868            r.offset(-location[0], -location[1]);
4869        } else {
4870            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4871        }
4872
4873        final float x = r.exactCenterX();
4874        final float y = r.exactCenterY();
4875        drawableHotspotChanged(x, y);
4876    }
4877
4878    /**
4879     * Request that a rectangle of this view be visible on the screen,
4880     * scrolling if necessary just enough.
4881     *
4882     * <p>A View should call this if it maintains some notion of which part
4883     * of its content is interesting.  For example, a text editing view
4884     * should call this when its cursor moves.
4885     *
4886     * @param rectangle The rectangle.
4887     * @return Whether any parent scrolled.
4888     */
4889    public boolean requestRectangleOnScreen(Rect rectangle) {
4890        return requestRectangleOnScreen(rectangle, false);
4891    }
4892
4893    /**
4894     * Request that a rectangle of this view be visible on the screen,
4895     * scrolling if necessary just enough.
4896     *
4897     * <p>A View should call this if it maintains some notion of which part
4898     * of its content is interesting.  For example, a text editing view
4899     * should call this when its cursor moves.
4900     *
4901     * <p>When <code>immediate</code> is set to true, scrolling will not be
4902     * animated.
4903     *
4904     * @param rectangle The rectangle.
4905     * @param immediate True to forbid animated scrolling, false otherwise
4906     * @return Whether any parent scrolled.
4907     */
4908    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4909        if (mParent == null) {
4910            return false;
4911        }
4912
4913        View child = this;
4914
4915        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4916        position.set(rectangle);
4917
4918        ViewParent parent = mParent;
4919        boolean scrolled = false;
4920        while (parent != null) {
4921            rectangle.set((int) position.left, (int) position.top,
4922                    (int) position.right, (int) position.bottom);
4923
4924            scrolled |= parent.requestChildRectangleOnScreen(child,
4925                    rectangle, immediate);
4926
4927            if (!child.hasIdentityMatrix()) {
4928                child.getMatrix().mapRect(position);
4929            }
4930
4931            position.offset(child.mLeft, child.mTop);
4932
4933            if (!(parent instanceof View)) {
4934                break;
4935            }
4936
4937            View parentView = (View) parent;
4938
4939            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4940
4941            child = parentView;
4942            parent = child.getParent();
4943        }
4944
4945        return scrolled;
4946    }
4947
4948    /**
4949     * Called when this view wants to give up focus. If focus is cleared
4950     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4951     * <p>
4952     * <strong>Note:</strong> When a View clears focus the framework is trying
4953     * to give focus to the first focusable View from the top. Hence, if this
4954     * View is the first from the top that can take focus, then all callbacks
4955     * related to clearing focus will be invoked after wich the framework will
4956     * give focus to this view.
4957     * </p>
4958     */
4959    public void clearFocus() {
4960        if (DBG) {
4961            System.out.println(this + " clearFocus()");
4962        }
4963
4964        clearFocusInternal(null, true, true);
4965    }
4966
4967    /**
4968     * Clears focus from the view, optionally propagating the change up through
4969     * the parent hierarchy and requesting that the root view place new focus.
4970     *
4971     * @param propagate whether to propagate the change up through the parent
4972     *            hierarchy
4973     * @param refocus when propagate is true, specifies whether to request the
4974     *            root view place new focus
4975     */
4976    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4977        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4978            mPrivateFlags &= ~PFLAG_FOCUSED;
4979
4980            if (propagate && mParent != null) {
4981                mParent.clearChildFocus(this);
4982            }
4983
4984            onFocusChanged(false, 0, null);
4985
4986            manageFocusHotspot(false, focused);
4987            refreshDrawableState();
4988
4989            if (propagate && (!refocus || !rootViewRequestFocus())) {
4990                notifyGlobalFocusCleared(this);
4991            }
4992        }
4993    }
4994
4995    void notifyGlobalFocusCleared(View oldFocus) {
4996        if (oldFocus != null && mAttachInfo != null) {
4997            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4998        }
4999    }
5000
5001    boolean rootViewRequestFocus() {
5002        final View root = getRootView();
5003        return root != null && root.requestFocus();
5004    }
5005
5006    /**
5007     * Called internally by the view system when a new view is getting focus.
5008     * This is what clears the old focus.
5009     * <p>
5010     * <b>NOTE:</b> The parent view's focused child must be updated manually
5011     * after calling this method. Otherwise, the view hierarchy may be left in
5012     * an inconstent state.
5013     */
5014    void unFocus(View focused) {
5015        if (DBG) {
5016            System.out.println(this + " unFocus()");
5017        }
5018
5019        clearFocusInternal(focused, false, false);
5020    }
5021
5022    /**
5023     * Returns true if this view has focus iteself, or is the ancestor of the
5024     * view that has focus.
5025     *
5026     * @return True if this view has or contains focus, false otherwise.
5027     */
5028    @ViewDebug.ExportedProperty(category = "focus")
5029    public boolean hasFocus() {
5030        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5031    }
5032
5033    /**
5034     * Returns true if this view is focusable or if it contains a reachable View
5035     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5036     * is a View whose parents do not block descendants focus.
5037     *
5038     * Only {@link #VISIBLE} views are considered focusable.
5039     *
5040     * @return True if the view is focusable or if the view contains a focusable
5041     *         View, false otherwise.
5042     *
5043     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5044     */
5045    public boolean hasFocusable() {
5046        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5047    }
5048
5049    /**
5050     * Called by the view system when the focus state of this view changes.
5051     * When the focus change event is caused by directional navigation, direction
5052     * and previouslyFocusedRect provide insight into where the focus is coming from.
5053     * When overriding, be sure to call up through to the super class so that
5054     * the standard focus handling will occur.
5055     *
5056     * @param gainFocus True if the View has focus; false otherwise.
5057     * @param direction The direction focus has moved when requestFocus()
5058     *                  is called to give this view focus. Values are
5059     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5060     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5061     *                  It may not always apply, in which case use the default.
5062     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5063     *        system, of the previously focused view.  If applicable, this will be
5064     *        passed in as finer grained information about where the focus is coming
5065     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5066     */
5067    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5068            @Nullable Rect previouslyFocusedRect) {
5069        if (gainFocus) {
5070            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5071        } else {
5072            notifyViewAccessibilityStateChangedIfNeeded(
5073                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5074        }
5075
5076        InputMethodManager imm = InputMethodManager.peekInstance();
5077        if (!gainFocus) {
5078            if (isPressed()) {
5079                setPressed(false);
5080            }
5081            if (imm != null && mAttachInfo != null
5082                    && mAttachInfo.mHasWindowFocus) {
5083                imm.focusOut(this);
5084            }
5085            onFocusLost();
5086        } else if (imm != null && mAttachInfo != null
5087                && mAttachInfo.mHasWindowFocus) {
5088            imm.focusIn(this);
5089        }
5090
5091        invalidate(true);
5092        ListenerInfo li = mListenerInfo;
5093        if (li != null && li.mOnFocusChangeListener != null) {
5094            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5095        }
5096
5097        if (mAttachInfo != null) {
5098            mAttachInfo.mKeyDispatchState.reset(this);
5099        }
5100    }
5101
5102    /**
5103     * Sends an accessibility event of the given type. If accessibility is
5104     * not enabled this method has no effect. The default implementation calls
5105     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5106     * to populate information about the event source (this View), then calls
5107     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5108     * populate the text content of the event source including its descendants,
5109     * and last calls
5110     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5111     * on its parent to resuest sending of the event to interested parties.
5112     * <p>
5113     * If an {@link AccessibilityDelegate} has been specified via calling
5114     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5115     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5116     * responsible for handling this call.
5117     * </p>
5118     *
5119     * @param eventType The type of the event to send, as defined by several types from
5120     * {@link android.view.accessibility.AccessibilityEvent}, such as
5121     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5122     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5123     *
5124     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5125     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5126     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5127     * @see AccessibilityDelegate
5128     */
5129    public void sendAccessibilityEvent(int eventType) {
5130        if (mAccessibilityDelegate != null) {
5131            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5132        } else {
5133            sendAccessibilityEventInternal(eventType);
5134        }
5135    }
5136
5137    /**
5138     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5139     * {@link AccessibilityEvent} to make an announcement which is related to some
5140     * sort of a context change for which none of the events representing UI transitions
5141     * is a good fit. For example, announcing a new page in a book. If accessibility
5142     * is not enabled this method does nothing.
5143     *
5144     * @param text The announcement text.
5145     */
5146    public void announceForAccessibility(CharSequence text) {
5147        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5148            AccessibilityEvent event = AccessibilityEvent.obtain(
5149                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5150            onInitializeAccessibilityEvent(event);
5151            event.getText().add(text);
5152            event.setContentDescription(null);
5153            mParent.requestSendAccessibilityEvent(this, event);
5154        }
5155    }
5156
5157    /**
5158     * @see #sendAccessibilityEvent(int)
5159     *
5160     * Note: Called from the default {@link AccessibilityDelegate}.
5161     */
5162    void sendAccessibilityEventInternal(int eventType) {
5163        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5164            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5165        }
5166    }
5167
5168    /**
5169     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5170     * takes as an argument an empty {@link AccessibilityEvent} and does not
5171     * perform a check whether accessibility is enabled.
5172     * <p>
5173     * If an {@link AccessibilityDelegate} has been specified via calling
5174     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5175     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5176     * is responsible for handling this call.
5177     * </p>
5178     *
5179     * @param event The event to send.
5180     *
5181     * @see #sendAccessibilityEvent(int)
5182     */
5183    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5184        if (mAccessibilityDelegate != null) {
5185            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5186        } else {
5187            sendAccessibilityEventUncheckedInternal(event);
5188        }
5189    }
5190
5191    /**
5192     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5193     *
5194     * Note: Called from the default {@link AccessibilityDelegate}.
5195     */
5196    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5197        if (!isShown()) {
5198            return;
5199        }
5200        onInitializeAccessibilityEvent(event);
5201        // Only a subset of accessibility events populates text content.
5202        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5203            dispatchPopulateAccessibilityEvent(event);
5204        }
5205        // In the beginning we called #isShown(), so we know that getParent() is not null.
5206        getParent().requestSendAccessibilityEvent(this, event);
5207    }
5208
5209    /**
5210     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5211     * to its children for adding their text content to the event. Note that the
5212     * event text is populated in a separate dispatch path since we add to the
5213     * event not only the text of the source but also the text of all its descendants.
5214     * A typical implementation will call
5215     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5216     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5217     * on each child. Override this method if custom population of the event text
5218     * content is required.
5219     * <p>
5220     * If an {@link AccessibilityDelegate} has been specified via calling
5221     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5222     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5223     * is responsible for handling this call.
5224     * </p>
5225     * <p>
5226     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5227     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5228     * </p>
5229     *
5230     * @param event The event.
5231     *
5232     * @return True if the event population was completed.
5233     */
5234    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5235        if (mAccessibilityDelegate != null) {
5236            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5237        } else {
5238            return dispatchPopulateAccessibilityEventInternal(event);
5239        }
5240    }
5241
5242    /**
5243     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5244     *
5245     * Note: Called from the default {@link AccessibilityDelegate}.
5246     */
5247    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5248        onPopulateAccessibilityEvent(event);
5249        return false;
5250    }
5251
5252    /**
5253     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5254     * giving a chance to this View to populate the accessibility event with its
5255     * text content. While this method is free to modify event
5256     * attributes other than text content, doing so should normally be performed in
5257     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5258     * <p>
5259     * Example: Adding formatted date string to an accessibility event in addition
5260     *          to the text added by the super implementation:
5261     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5262     *     super.onPopulateAccessibilityEvent(event);
5263     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5264     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5265     *         mCurrentDate.getTimeInMillis(), flags);
5266     *     event.getText().add(selectedDateUtterance);
5267     * }</pre>
5268     * <p>
5269     * If an {@link AccessibilityDelegate} has been specified via calling
5270     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5271     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5272     * is responsible for handling this call.
5273     * </p>
5274     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5275     * information to the event, in case the default implementation has basic information to add.
5276     * </p>
5277     *
5278     * @param event The accessibility event which to populate.
5279     *
5280     * @see #sendAccessibilityEvent(int)
5281     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5282     */
5283    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5284        if (mAccessibilityDelegate != null) {
5285            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5286        } else {
5287            onPopulateAccessibilityEventInternal(event);
5288        }
5289    }
5290
5291    /**
5292     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5293     *
5294     * Note: Called from the default {@link AccessibilityDelegate}.
5295     */
5296    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5297    }
5298
5299    /**
5300     * Initializes an {@link AccessibilityEvent} with information about
5301     * this View which is the event source. In other words, the source of
5302     * an accessibility event is the view whose state change triggered firing
5303     * the event.
5304     * <p>
5305     * Example: Setting the password property of an event in addition
5306     *          to properties set by the super implementation:
5307     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5308     *     super.onInitializeAccessibilityEvent(event);
5309     *     event.setPassword(true);
5310     * }</pre>
5311     * <p>
5312     * If an {@link AccessibilityDelegate} has been specified via calling
5313     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5314     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5315     * is responsible for handling this call.
5316     * </p>
5317     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5318     * information to the event, in case the default implementation has basic information to add.
5319     * </p>
5320     * @param event The event to initialize.
5321     *
5322     * @see #sendAccessibilityEvent(int)
5323     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5324     */
5325    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5326        if (mAccessibilityDelegate != null) {
5327            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5328        } else {
5329            onInitializeAccessibilityEventInternal(event);
5330        }
5331    }
5332
5333    /**
5334     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5335     *
5336     * Note: Called from the default {@link AccessibilityDelegate}.
5337     */
5338    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5339        event.setSource(this);
5340        event.setClassName(View.class.getName());
5341        event.setPackageName(getContext().getPackageName());
5342        event.setEnabled(isEnabled());
5343        event.setContentDescription(mContentDescription);
5344
5345        switch (event.getEventType()) {
5346            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5347                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5348                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5349                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5350                event.setItemCount(focusablesTempList.size());
5351                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5352                if (mAttachInfo != null) {
5353                    focusablesTempList.clear();
5354                }
5355            } break;
5356            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5357                CharSequence text = getIterableTextForAccessibility();
5358                if (text != null && text.length() > 0) {
5359                    event.setFromIndex(getAccessibilitySelectionStart());
5360                    event.setToIndex(getAccessibilitySelectionEnd());
5361                    event.setItemCount(text.length());
5362                }
5363            } break;
5364        }
5365    }
5366
5367    /**
5368     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5369     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5370     * This method is responsible for obtaining an accessibility node info from a
5371     * pool of reusable instances and calling
5372     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5373     * initialize the former.
5374     * <p>
5375     * Note: The client is responsible for recycling the obtained instance by calling
5376     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5377     * </p>
5378     *
5379     * @return A populated {@link AccessibilityNodeInfo}.
5380     *
5381     * @see AccessibilityNodeInfo
5382     */
5383    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5384        if (mAccessibilityDelegate != null) {
5385            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5386        } else {
5387            return createAccessibilityNodeInfoInternal();
5388        }
5389    }
5390
5391    /**
5392     * @see #createAccessibilityNodeInfo()
5393     */
5394    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5395        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5396        if (provider != null) {
5397            return provider.createAccessibilityNodeInfo(View.NO_ID);
5398        } else {
5399            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5400            onInitializeAccessibilityNodeInfo(info);
5401            return info;
5402        }
5403    }
5404
5405    /**
5406     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5407     * The base implementation sets:
5408     * <ul>
5409     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5410     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5411     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5412     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5413     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5414     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5415     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5416     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5417     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5418     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5419     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5420     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5421     * </ul>
5422     * <p>
5423     * Subclasses should override this method, call the super implementation,
5424     * and set additional attributes.
5425     * </p>
5426     * <p>
5427     * If an {@link AccessibilityDelegate} has been specified via calling
5428     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5429     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5430     * is responsible for handling this call.
5431     * </p>
5432     *
5433     * @param info The instance to initialize.
5434     */
5435    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5436        if (mAccessibilityDelegate != null) {
5437            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5438        } else {
5439            onInitializeAccessibilityNodeInfoInternal(info);
5440        }
5441    }
5442
5443    /**
5444     * Gets the location of this view in screen coordintates.
5445     *
5446     * @param outRect The output location
5447     * @hide
5448     */
5449    public void getBoundsOnScreen(Rect outRect) {
5450        if (mAttachInfo == null) {
5451            return;
5452        }
5453
5454        RectF position = mAttachInfo.mTmpTransformRect;
5455        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5456
5457        if (!hasIdentityMatrix()) {
5458            getMatrix().mapRect(position);
5459        }
5460
5461        position.offset(mLeft, mTop);
5462
5463        ViewParent parent = mParent;
5464        while (parent instanceof View) {
5465            View parentView = (View) parent;
5466
5467            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5468
5469            if (!parentView.hasIdentityMatrix()) {
5470                parentView.getMatrix().mapRect(position);
5471            }
5472
5473            position.offset(parentView.mLeft, parentView.mTop);
5474
5475            parent = parentView.mParent;
5476        }
5477
5478        if (parent instanceof ViewRootImpl) {
5479            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5480            position.offset(0, -viewRootImpl.mCurScrollY);
5481        }
5482
5483        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5484
5485        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5486                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5487    }
5488
5489    /**
5490     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5491     *
5492     * Note: Called from the default {@link AccessibilityDelegate}.
5493     */
5494    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5495        Rect bounds = mAttachInfo.mTmpInvalRect;
5496
5497        getDrawingRect(bounds);
5498        info.setBoundsInParent(bounds);
5499
5500        getBoundsOnScreen(bounds);
5501        info.setBoundsInScreen(bounds);
5502
5503        ViewParent parent = getParentForAccessibility();
5504        if (parent instanceof View) {
5505            info.setParent((View) parent);
5506        }
5507
5508        if (mID != View.NO_ID) {
5509            View rootView = getRootView();
5510            if (rootView == null) {
5511                rootView = this;
5512            }
5513            View label = rootView.findLabelForView(this, mID);
5514            if (label != null) {
5515                info.setLabeledBy(label);
5516            }
5517
5518            if ((mAttachInfo.mAccessibilityFetchFlags
5519                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5520                    && Resources.resourceHasPackage(mID)) {
5521                try {
5522                    String viewId = getResources().getResourceName(mID);
5523                    info.setViewIdResourceName(viewId);
5524                } catch (Resources.NotFoundException nfe) {
5525                    /* ignore */
5526                }
5527            }
5528        }
5529
5530        if (mLabelForId != View.NO_ID) {
5531            View rootView = getRootView();
5532            if (rootView == null) {
5533                rootView = this;
5534            }
5535            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5536            if (labeled != null) {
5537                info.setLabelFor(labeled);
5538            }
5539        }
5540
5541        info.setVisibleToUser(isVisibleToUser());
5542
5543        info.setPackageName(mContext.getPackageName());
5544        info.setClassName(View.class.getName());
5545        info.setContentDescription(getContentDescription());
5546
5547        info.setEnabled(isEnabled());
5548        info.setClickable(isClickable());
5549        info.setFocusable(isFocusable());
5550        info.setFocused(isFocused());
5551        info.setAccessibilityFocused(isAccessibilityFocused());
5552        info.setSelected(isSelected());
5553        info.setLongClickable(isLongClickable());
5554        info.setLiveRegion(getAccessibilityLiveRegion());
5555
5556        // TODO: These make sense only if we are in an AdapterView but all
5557        // views can be selected. Maybe from accessibility perspective
5558        // we should report as selectable view in an AdapterView.
5559        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5560        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5561
5562        if (isFocusable()) {
5563            if (isFocused()) {
5564                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5565            } else {
5566                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5567            }
5568        }
5569
5570        if (!isAccessibilityFocused()) {
5571            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5572        } else {
5573            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5574        }
5575
5576        if (isClickable() && isEnabled()) {
5577            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5578        }
5579
5580        if (isLongClickable() && isEnabled()) {
5581            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5582        }
5583
5584        CharSequence text = getIterableTextForAccessibility();
5585        if (text != null && text.length() > 0) {
5586            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5587
5588            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5589            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5590            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5591            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5592                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5593                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5594        }
5595    }
5596
5597    private View findLabelForView(View view, int labeledId) {
5598        if (mMatchLabelForPredicate == null) {
5599            mMatchLabelForPredicate = new MatchLabelForPredicate();
5600        }
5601        mMatchLabelForPredicate.mLabeledId = labeledId;
5602        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5603    }
5604
5605    /**
5606     * Computes whether this view is visible to the user. Such a view is
5607     * attached, visible, all its predecessors are visible, it is not clipped
5608     * entirely by its predecessors, and has an alpha greater than zero.
5609     *
5610     * @return Whether the view is visible on the screen.
5611     *
5612     * @hide
5613     */
5614    protected boolean isVisibleToUser() {
5615        return isVisibleToUser(null);
5616    }
5617
5618    /**
5619     * Computes whether the given portion of this view is visible to the user.
5620     * Such a view is attached, visible, all its predecessors are visible,
5621     * has an alpha greater than zero, and the specified portion is not
5622     * clipped entirely by its predecessors.
5623     *
5624     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5625     *                    <code>null</code>, and the entire view will be tested in this case.
5626     *                    When <code>true</code> is returned by the function, the actual visible
5627     *                    region will be stored in this parameter; that is, if boundInView is fully
5628     *                    contained within the view, no modification will be made, otherwise regions
5629     *                    outside of the visible area of the view will be clipped.
5630     *
5631     * @return Whether the specified portion of the view is visible on the screen.
5632     *
5633     * @hide
5634     */
5635    protected boolean isVisibleToUser(Rect boundInView) {
5636        if (mAttachInfo != null) {
5637            // Attached to invisible window means this view is not visible.
5638            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5639                return false;
5640            }
5641            // An invisible predecessor or one with alpha zero means
5642            // that this view is not visible to the user.
5643            Object current = this;
5644            while (current instanceof View) {
5645                View view = (View) current;
5646                // We have attach info so this view is attached and there is no
5647                // need to check whether we reach to ViewRootImpl on the way up.
5648                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5649                        view.getVisibility() != VISIBLE) {
5650                    return false;
5651                }
5652                current = view.mParent;
5653            }
5654            // Check if the view is entirely covered by its predecessors.
5655            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5656            Point offset = mAttachInfo.mPoint;
5657            if (!getGlobalVisibleRect(visibleRect, offset)) {
5658                return false;
5659            }
5660            // Check if the visible portion intersects the rectangle of interest.
5661            if (boundInView != null) {
5662                visibleRect.offset(-offset.x, -offset.y);
5663                return boundInView.intersect(visibleRect);
5664            }
5665            return true;
5666        }
5667        return false;
5668    }
5669
5670    /**
5671     * Returns the delegate for implementing accessibility support via
5672     * composition. For more details see {@link AccessibilityDelegate}.
5673     *
5674     * @return The delegate, or null if none set.
5675     *
5676     * @hide
5677     */
5678    public AccessibilityDelegate getAccessibilityDelegate() {
5679        return mAccessibilityDelegate;
5680    }
5681
5682    /**
5683     * Sets a delegate for implementing accessibility support via composition as
5684     * opposed to inheritance. The delegate's primary use is for implementing
5685     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5686     *
5687     * @param delegate The delegate instance.
5688     *
5689     * @see AccessibilityDelegate
5690     */
5691    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5692        mAccessibilityDelegate = delegate;
5693    }
5694
5695    /**
5696     * Gets the provider for managing a virtual view hierarchy rooted at this View
5697     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5698     * that explore the window content.
5699     * <p>
5700     * If this method returns an instance, this instance is responsible for managing
5701     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5702     * View including the one representing the View itself. Similarly the returned
5703     * instance is responsible for performing accessibility actions on any virtual
5704     * view or the root view itself.
5705     * </p>
5706     * <p>
5707     * If an {@link AccessibilityDelegate} has been specified via calling
5708     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5709     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5710     * is responsible for handling this call.
5711     * </p>
5712     *
5713     * @return The provider.
5714     *
5715     * @see AccessibilityNodeProvider
5716     */
5717    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5718        if (mAccessibilityDelegate != null) {
5719            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5720        } else {
5721            return null;
5722        }
5723    }
5724
5725    /**
5726     * Gets the unique identifier of this view on the screen for accessibility purposes.
5727     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5728     *
5729     * @return The view accessibility id.
5730     *
5731     * @hide
5732     */
5733    public int getAccessibilityViewId() {
5734        if (mAccessibilityViewId == NO_ID) {
5735            mAccessibilityViewId = sNextAccessibilityViewId++;
5736        }
5737        return mAccessibilityViewId;
5738    }
5739
5740    /**
5741     * Gets the unique identifier of the window in which this View reseides.
5742     *
5743     * @return The window accessibility id.
5744     *
5745     * @hide
5746     */
5747    public int getAccessibilityWindowId() {
5748        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5749                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5750    }
5751
5752    /**
5753     * Gets the {@link View} description. It briefly describes the view and is
5754     * primarily used for accessibility support. Set this property to enable
5755     * better accessibility support for your application. This is especially
5756     * true for views that do not have textual representation (For example,
5757     * ImageButton).
5758     *
5759     * @return The content description.
5760     *
5761     * @attr ref android.R.styleable#View_contentDescription
5762     */
5763    @ViewDebug.ExportedProperty(category = "accessibility")
5764    public CharSequence getContentDescription() {
5765        return mContentDescription;
5766    }
5767
5768    /**
5769     * Sets the {@link View} description. It briefly describes the view and is
5770     * primarily used for accessibility support. Set this property to enable
5771     * better accessibility support for your application. This is especially
5772     * true for views that do not have textual representation (For example,
5773     * ImageButton).
5774     *
5775     * @param contentDescription The content description.
5776     *
5777     * @attr ref android.R.styleable#View_contentDescription
5778     */
5779    @RemotableViewMethod
5780    public void setContentDescription(CharSequence contentDescription) {
5781        if (mContentDescription == null) {
5782            if (contentDescription == null) {
5783                return;
5784            }
5785        } else if (mContentDescription.equals(contentDescription)) {
5786            return;
5787        }
5788        mContentDescription = contentDescription;
5789        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5790        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5791            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5792            notifySubtreeAccessibilityStateChangedIfNeeded();
5793        } else {
5794            notifyViewAccessibilityStateChangedIfNeeded(
5795                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5796        }
5797    }
5798
5799    /**
5800     * Gets the id of a view for which this view serves as a label for
5801     * accessibility purposes.
5802     *
5803     * @return The labeled view id.
5804     */
5805    @ViewDebug.ExportedProperty(category = "accessibility")
5806    public int getLabelFor() {
5807        return mLabelForId;
5808    }
5809
5810    /**
5811     * Sets the id of a view for which this view serves as a label for
5812     * accessibility purposes.
5813     *
5814     * @param id The labeled view id.
5815     */
5816    @RemotableViewMethod
5817    public void setLabelFor(int id) {
5818        mLabelForId = id;
5819        if (mLabelForId != View.NO_ID
5820                && mID == View.NO_ID) {
5821            mID = generateViewId();
5822        }
5823    }
5824
5825    /**
5826     * Invoked whenever this view loses focus, either by losing window focus or by losing
5827     * focus within its window. This method can be used to clear any state tied to the
5828     * focus. For instance, if a button is held pressed with the trackball and the window
5829     * loses focus, this method can be used to cancel the press.
5830     *
5831     * Subclasses of View overriding this method should always call super.onFocusLost().
5832     *
5833     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5834     * @see #onWindowFocusChanged(boolean)
5835     *
5836     * @hide pending API council approval
5837     */
5838    protected void onFocusLost() {
5839        resetPressedState();
5840    }
5841
5842    private void resetPressedState() {
5843        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5844            return;
5845        }
5846
5847        if (isPressed()) {
5848            setPressed(false);
5849
5850            if (!mHasPerformedLongPress) {
5851                removeLongPressCallback();
5852            }
5853        }
5854    }
5855
5856    /**
5857     * Returns true if this view has focus
5858     *
5859     * @return True if this view has focus, false otherwise.
5860     */
5861    @ViewDebug.ExportedProperty(category = "focus")
5862    public boolean isFocused() {
5863        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5864    }
5865
5866    /**
5867     * Find the view in the hierarchy rooted at this view that currently has
5868     * focus.
5869     *
5870     * @return The view that currently has focus, or null if no focused view can
5871     *         be found.
5872     */
5873    public View findFocus() {
5874        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5875    }
5876
5877    /**
5878     * Indicates whether this view is one of the set of scrollable containers in
5879     * its window.
5880     *
5881     * @return whether this view is one of the set of scrollable containers in
5882     * its window
5883     *
5884     * @attr ref android.R.styleable#View_isScrollContainer
5885     */
5886    public boolean isScrollContainer() {
5887        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5888    }
5889
5890    /**
5891     * Change whether this view is one of the set of scrollable containers in
5892     * its window.  This will be used to determine whether the window can
5893     * resize or must pan when a soft input area is open -- scrollable
5894     * containers allow the window to use resize mode since the container
5895     * will appropriately shrink.
5896     *
5897     * @attr ref android.R.styleable#View_isScrollContainer
5898     */
5899    public void setScrollContainer(boolean isScrollContainer) {
5900        if (isScrollContainer) {
5901            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5902                mAttachInfo.mScrollContainers.add(this);
5903                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5904            }
5905            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5906        } else {
5907            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5908                mAttachInfo.mScrollContainers.remove(this);
5909            }
5910            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5911        }
5912    }
5913
5914    /**
5915     * Returns the quality of the drawing cache.
5916     *
5917     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5918     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5919     *
5920     * @see #setDrawingCacheQuality(int)
5921     * @see #setDrawingCacheEnabled(boolean)
5922     * @see #isDrawingCacheEnabled()
5923     *
5924     * @attr ref android.R.styleable#View_drawingCacheQuality
5925     */
5926    @DrawingCacheQuality
5927    public int getDrawingCacheQuality() {
5928        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5929    }
5930
5931    /**
5932     * Set the drawing cache quality of this view. This value is used only when the
5933     * drawing cache is enabled
5934     *
5935     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5936     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5937     *
5938     * @see #getDrawingCacheQuality()
5939     * @see #setDrawingCacheEnabled(boolean)
5940     * @see #isDrawingCacheEnabled()
5941     *
5942     * @attr ref android.R.styleable#View_drawingCacheQuality
5943     */
5944    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5945        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5946    }
5947
5948    /**
5949     * Returns whether the screen should remain on, corresponding to the current
5950     * value of {@link #KEEP_SCREEN_ON}.
5951     *
5952     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5953     *
5954     * @see #setKeepScreenOn(boolean)
5955     *
5956     * @attr ref android.R.styleable#View_keepScreenOn
5957     */
5958    public boolean getKeepScreenOn() {
5959        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5960    }
5961
5962    /**
5963     * Controls whether the screen should remain on, modifying the
5964     * value of {@link #KEEP_SCREEN_ON}.
5965     *
5966     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5967     *
5968     * @see #getKeepScreenOn()
5969     *
5970     * @attr ref android.R.styleable#View_keepScreenOn
5971     */
5972    public void setKeepScreenOn(boolean keepScreenOn) {
5973        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5974    }
5975
5976    /**
5977     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5978     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5979     *
5980     * @attr ref android.R.styleable#View_nextFocusLeft
5981     */
5982    public int getNextFocusLeftId() {
5983        return mNextFocusLeftId;
5984    }
5985
5986    /**
5987     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5988     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5989     * decide automatically.
5990     *
5991     * @attr ref android.R.styleable#View_nextFocusLeft
5992     */
5993    public void setNextFocusLeftId(int nextFocusLeftId) {
5994        mNextFocusLeftId = nextFocusLeftId;
5995    }
5996
5997    /**
5998     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5999     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6000     *
6001     * @attr ref android.R.styleable#View_nextFocusRight
6002     */
6003    public int getNextFocusRightId() {
6004        return mNextFocusRightId;
6005    }
6006
6007    /**
6008     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6009     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6010     * decide automatically.
6011     *
6012     * @attr ref android.R.styleable#View_nextFocusRight
6013     */
6014    public void setNextFocusRightId(int nextFocusRightId) {
6015        mNextFocusRightId = nextFocusRightId;
6016    }
6017
6018    /**
6019     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6020     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6021     *
6022     * @attr ref android.R.styleable#View_nextFocusUp
6023     */
6024    public int getNextFocusUpId() {
6025        return mNextFocusUpId;
6026    }
6027
6028    /**
6029     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6030     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6031     * decide automatically.
6032     *
6033     * @attr ref android.R.styleable#View_nextFocusUp
6034     */
6035    public void setNextFocusUpId(int nextFocusUpId) {
6036        mNextFocusUpId = nextFocusUpId;
6037    }
6038
6039    /**
6040     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6041     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6042     *
6043     * @attr ref android.R.styleable#View_nextFocusDown
6044     */
6045    public int getNextFocusDownId() {
6046        return mNextFocusDownId;
6047    }
6048
6049    /**
6050     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6051     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6052     * decide automatically.
6053     *
6054     * @attr ref android.R.styleable#View_nextFocusDown
6055     */
6056    public void setNextFocusDownId(int nextFocusDownId) {
6057        mNextFocusDownId = nextFocusDownId;
6058    }
6059
6060    /**
6061     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6062     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6063     *
6064     * @attr ref android.R.styleable#View_nextFocusForward
6065     */
6066    public int getNextFocusForwardId() {
6067        return mNextFocusForwardId;
6068    }
6069
6070    /**
6071     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6072     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6073     * decide automatically.
6074     *
6075     * @attr ref android.R.styleable#View_nextFocusForward
6076     */
6077    public void setNextFocusForwardId(int nextFocusForwardId) {
6078        mNextFocusForwardId = nextFocusForwardId;
6079    }
6080
6081    /**
6082     * Returns the visibility of this view and all of its ancestors
6083     *
6084     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6085     */
6086    public boolean isShown() {
6087        View current = this;
6088        //noinspection ConstantConditions
6089        do {
6090            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6091                return false;
6092            }
6093            ViewParent parent = current.mParent;
6094            if (parent == null) {
6095                return false; // We are not attached to the view root
6096            }
6097            if (!(parent instanceof View)) {
6098                return true;
6099            }
6100            current = (View) parent;
6101        } while (current != null);
6102
6103        return false;
6104    }
6105
6106    /**
6107     * Called by the view hierarchy when the content insets for a window have
6108     * changed, to allow it to adjust its content to fit within those windows.
6109     * The content insets tell you the space that the status bar, input method,
6110     * and other system windows infringe on the application's window.
6111     *
6112     * <p>You do not normally need to deal with this function, since the default
6113     * window decoration given to applications takes care of applying it to the
6114     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6115     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6116     * and your content can be placed under those system elements.  You can then
6117     * use this method within your view hierarchy if you have parts of your UI
6118     * which you would like to ensure are not being covered.
6119     *
6120     * <p>The default implementation of this method simply applies the content
6121     * insets to the view's padding, consuming that content (modifying the
6122     * insets to be 0), and returning true.  This behavior is off by default, but can
6123     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6124     *
6125     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6126     * insets object is propagated down the hierarchy, so any changes made to it will
6127     * be seen by all following views (including potentially ones above in
6128     * the hierarchy since this is a depth-first traversal).  The first view
6129     * that returns true will abort the entire traversal.
6130     *
6131     * <p>The default implementation works well for a situation where it is
6132     * used with a container that covers the entire window, allowing it to
6133     * apply the appropriate insets to its content on all edges.  If you need
6134     * a more complicated layout (such as two different views fitting system
6135     * windows, one on the top of the window, and one on the bottom),
6136     * you can override the method and handle the insets however you would like.
6137     * Note that the insets provided by the framework are always relative to the
6138     * far edges of the window, not accounting for the location of the called view
6139     * within that window.  (In fact when this method is called you do not yet know
6140     * where the layout will place the view, as it is done before layout happens.)
6141     *
6142     * <p>Note: unlike many View methods, there is no dispatch phase to this
6143     * call.  If you are overriding it in a ViewGroup and want to allow the
6144     * call to continue to your children, you must be sure to call the super
6145     * implementation.
6146     *
6147     * <p>Here is a sample layout that makes use of fitting system windows
6148     * to have controls for a video view placed inside of the window decorations
6149     * that it hides and shows.  This can be used with code like the second
6150     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6151     *
6152     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6153     *
6154     * @param insets Current content insets of the window.  Prior to
6155     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6156     * the insets or else you and Android will be unhappy.
6157     *
6158     * @return {@code true} if this view applied the insets and it should not
6159     * continue propagating further down the hierarchy, {@code false} otherwise.
6160     * @see #getFitsSystemWindows()
6161     * @see #setFitsSystemWindows(boolean)
6162     * @see #setSystemUiVisibility(int)
6163     *
6164     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6165     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6166     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6167     * to implement handling their own insets.
6168     */
6169    protected boolean fitSystemWindows(Rect insets) {
6170        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6171            if (insets == null) {
6172                // Null insets by definition have already been consumed.
6173                // This call cannot apply insets since there are none to apply,
6174                // so return false.
6175                return false;
6176            }
6177            // If we're not in the process of dispatching the newer apply insets call,
6178            // that means we're not in the compatibility path. Dispatch into the newer
6179            // apply insets path and take things from there.
6180            try {
6181                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6182                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6183            } finally {
6184                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6185            }
6186        } else {
6187            // We're being called from the newer apply insets path.
6188            // Perform the standard fallback behavior.
6189            return fitSystemWindowsInt(insets);
6190        }
6191    }
6192
6193    private boolean fitSystemWindowsInt(Rect insets) {
6194        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6195            mUserPaddingStart = UNDEFINED_PADDING;
6196            mUserPaddingEnd = UNDEFINED_PADDING;
6197            Rect localInsets = sThreadLocal.get();
6198            if (localInsets == null) {
6199                localInsets = new Rect();
6200                sThreadLocal.set(localInsets);
6201            }
6202            boolean res = computeFitSystemWindows(insets, localInsets);
6203            mUserPaddingLeftInitial = localInsets.left;
6204            mUserPaddingRightInitial = localInsets.right;
6205            internalSetPadding(localInsets.left, localInsets.top,
6206                    localInsets.right, localInsets.bottom);
6207            return res;
6208        }
6209        return false;
6210    }
6211
6212    /**
6213     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6214     *
6215     * <p>This method should be overridden by views that wish to apply a policy different from or
6216     * in addition to the default behavior. Clients that wish to force a view subtree
6217     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6218     *
6219     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6220     * it will be called during dispatch instead of this method. The listener may optionally
6221     * call this method from its own implementation if it wishes to apply the view's default
6222     * insets policy in addition to its own.</p>
6223     *
6224     * <p>Implementations of this method should either return the insets parameter unchanged
6225     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6226     * that this view applied itself. This allows new inset types added in future platform
6227     * versions to pass through existing implementations unchanged without being erroneously
6228     * consumed.</p>
6229     *
6230     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6231     * property is set then the view will consume the system window insets and apply them
6232     * as padding for the view.</p>
6233     *
6234     * @param insets Insets to apply
6235     * @return The supplied insets with any applied insets consumed
6236     */
6237    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6238        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6239            // We weren't called from within a direct call to fitSystemWindows,
6240            // call into it as a fallback in case we're in a class that overrides it
6241            // and has logic to perform.
6242            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6243                return insets.consumeSystemWindowInsets();
6244            }
6245        } else {
6246            // We were called from within a direct call to fitSystemWindows.
6247            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6248                return insets.consumeSystemWindowInsets();
6249            }
6250        }
6251        return insets;
6252    }
6253
6254    /**
6255     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6256     * window insets to this view. The listener's
6257     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6258     * method will be called instead of the view's
6259     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6260     *
6261     * @param listener Listener to set
6262     *
6263     * @see #onApplyWindowInsets(WindowInsets)
6264     */
6265    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6266        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6267    }
6268
6269    /**
6270     * Request to apply the given window insets to this view or another view in its subtree.
6271     *
6272     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6273     * obscured by window decorations or overlays. This can include the status and navigation bars,
6274     * action bars, input methods and more. New inset categories may be added in the future.
6275     * The method returns the insets provided minus any that were applied by this view or its
6276     * children.</p>
6277     *
6278     * <p>Clients wishing to provide custom behavior should override the
6279     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6280     * {@link OnApplyWindowInsetsListener} via the
6281     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6282     * method.</p>
6283     *
6284     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6285     * </p>
6286     *
6287     * @param insets Insets to apply
6288     * @return The provided insets minus the insets that were consumed
6289     */
6290    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6291        try {
6292            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6293            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6294                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6295            } else {
6296                return onApplyWindowInsets(insets);
6297            }
6298        } finally {
6299            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6300        }
6301    }
6302
6303    /**
6304     * @hide Compute the insets that should be consumed by this view and the ones
6305     * that should propagate to those under it.
6306     */
6307    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6308        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6309                || mAttachInfo == null
6310                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6311                        && !mAttachInfo.mOverscanRequested)) {
6312            outLocalInsets.set(inoutInsets);
6313            inoutInsets.set(0, 0, 0, 0);
6314            return true;
6315        } else {
6316            // The application wants to take care of fitting system window for
6317            // the content...  however we still need to take care of any overscan here.
6318            final Rect overscan = mAttachInfo.mOverscanInsets;
6319            outLocalInsets.set(overscan);
6320            inoutInsets.left -= overscan.left;
6321            inoutInsets.top -= overscan.top;
6322            inoutInsets.right -= overscan.right;
6323            inoutInsets.bottom -= overscan.bottom;
6324            return false;
6325        }
6326    }
6327
6328    /**
6329     * Sets whether or not this view should account for system screen decorations
6330     * such as the status bar and inset its content; that is, controlling whether
6331     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6332     * executed.  See that method for more details.
6333     *
6334     * <p>Note that if you are providing your own implementation of
6335     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6336     * flag to true -- your implementation will be overriding the default
6337     * implementation that checks this flag.
6338     *
6339     * @param fitSystemWindows If true, then the default implementation of
6340     * {@link #fitSystemWindows(Rect)} will be executed.
6341     *
6342     * @attr ref android.R.styleable#View_fitsSystemWindows
6343     * @see #getFitsSystemWindows()
6344     * @see #fitSystemWindows(Rect)
6345     * @see #setSystemUiVisibility(int)
6346     */
6347    public void setFitsSystemWindows(boolean fitSystemWindows) {
6348        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6349    }
6350
6351    /**
6352     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6353     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6354     * will be executed.
6355     *
6356     * @return {@code true} if the default implementation of
6357     * {@link #fitSystemWindows(Rect)} will be executed.
6358     *
6359     * @attr ref android.R.styleable#View_fitsSystemWindows
6360     * @see #setFitsSystemWindows(boolean)
6361     * @see #fitSystemWindows(Rect)
6362     * @see #setSystemUiVisibility(int)
6363     */
6364    public boolean getFitsSystemWindows() {
6365        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6366    }
6367
6368    /** @hide */
6369    public boolean fitsSystemWindows() {
6370        return getFitsSystemWindows();
6371    }
6372
6373    /**
6374     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6375     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6376     */
6377    public void requestFitSystemWindows() {
6378        if (mParent != null) {
6379            mParent.requestFitSystemWindows();
6380        }
6381    }
6382
6383    /**
6384     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6385     */
6386    public void requestApplyInsets() {
6387        requestFitSystemWindows();
6388    }
6389
6390    /**
6391     * For use by PhoneWindow to make its own system window fitting optional.
6392     * @hide
6393     */
6394    public void makeOptionalFitsSystemWindows() {
6395        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6396    }
6397
6398    /**
6399     * Returns the visibility status for this view.
6400     *
6401     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6402     * @attr ref android.R.styleable#View_visibility
6403     */
6404    @ViewDebug.ExportedProperty(mapping = {
6405        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6406        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6407        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6408    })
6409    @Visibility
6410    public int getVisibility() {
6411        return mViewFlags & VISIBILITY_MASK;
6412    }
6413
6414    /**
6415     * Set the enabled state of this view.
6416     *
6417     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6418     * @attr ref android.R.styleable#View_visibility
6419     */
6420    @RemotableViewMethod
6421    public void setVisibility(@Visibility int visibility) {
6422        setFlags(visibility, VISIBILITY_MASK);
6423        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6424    }
6425
6426    /**
6427     * Returns the enabled status for this view. The interpretation of the
6428     * enabled state varies by subclass.
6429     *
6430     * @return True if this view is enabled, false otherwise.
6431     */
6432    @ViewDebug.ExportedProperty
6433    public boolean isEnabled() {
6434        return (mViewFlags & ENABLED_MASK) == ENABLED;
6435    }
6436
6437    /**
6438     * Set the enabled state of this view. The interpretation of the enabled
6439     * state varies by subclass.
6440     *
6441     * @param enabled True if this view is enabled, false otherwise.
6442     */
6443    @RemotableViewMethod
6444    public void setEnabled(boolean enabled) {
6445        if (enabled == isEnabled()) return;
6446
6447        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6448
6449        /*
6450         * The View most likely has to change its appearance, so refresh
6451         * the drawable state.
6452         */
6453        refreshDrawableState();
6454
6455        // Invalidate too, since the default behavior for views is to be
6456        // be drawn at 50% alpha rather than to change the drawable.
6457        invalidate(true);
6458
6459        if (!enabled) {
6460            cancelPendingInputEvents();
6461        }
6462    }
6463
6464    /**
6465     * Set whether this view can receive the focus.
6466     *
6467     * Setting this to false will also ensure that this view is not focusable
6468     * in touch mode.
6469     *
6470     * @param focusable If true, this view can receive the focus.
6471     *
6472     * @see #setFocusableInTouchMode(boolean)
6473     * @attr ref android.R.styleable#View_focusable
6474     */
6475    public void setFocusable(boolean focusable) {
6476        if (!focusable) {
6477            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6478        }
6479        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6480    }
6481
6482    /**
6483     * Set whether this view can receive focus while in touch mode.
6484     *
6485     * Setting this to true will also ensure that this view is focusable.
6486     *
6487     * @param focusableInTouchMode If true, this view can receive the focus while
6488     *   in touch mode.
6489     *
6490     * @see #setFocusable(boolean)
6491     * @attr ref android.R.styleable#View_focusableInTouchMode
6492     */
6493    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6494        // Focusable in touch mode should always be set before the focusable flag
6495        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6496        // which, in touch mode, will not successfully request focus on this view
6497        // because the focusable in touch mode flag is not set
6498        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6499        if (focusableInTouchMode) {
6500            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6501        }
6502    }
6503
6504    /**
6505     * Set whether this view should have sound effects enabled for events such as
6506     * clicking and touching.
6507     *
6508     * <p>You may wish to disable sound effects for a view if you already play sounds,
6509     * for instance, a dial key that plays dtmf tones.
6510     *
6511     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6512     * @see #isSoundEffectsEnabled()
6513     * @see #playSoundEffect(int)
6514     * @attr ref android.R.styleable#View_soundEffectsEnabled
6515     */
6516    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6517        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6518    }
6519
6520    /**
6521     * @return whether this view should have sound effects enabled for events such as
6522     *     clicking and touching.
6523     *
6524     * @see #setSoundEffectsEnabled(boolean)
6525     * @see #playSoundEffect(int)
6526     * @attr ref android.R.styleable#View_soundEffectsEnabled
6527     */
6528    @ViewDebug.ExportedProperty
6529    public boolean isSoundEffectsEnabled() {
6530        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6531    }
6532
6533    /**
6534     * Set whether this view should have haptic feedback for events such as
6535     * long presses.
6536     *
6537     * <p>You may wish to disable haptic feedback if your view already controls
6538     * its own haptic feedback.
6539     *
6540     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6541     * @see #isHapticFeedbackEnabled()
6542     * @see #performHapticFeedback(int)
6543     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6544     */
6545    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6546        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6547    }
6548
6549    /**
6550     * @return whether this view should have haptic feedback enabled for events
6551     * long presses.
6552     *
6553     * @see #setHapticFeedbackEnabled(boolean)
6554     * @see #performHapticFeedback(int)
6555     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6556     */
6557    @ViewDebug.ExportedProperty
6558    public boolean isHapticFeedbackEnabled() {
6559        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6560    }
6561
6562    /**
6563     * Returns the layout direction for this view.
6564     *
6565     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6566     *   {@link #LAYOUT_DIRECTION_RTL},
6567     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6568     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6569     *
6570     * @attr ref android.R.styleable#View_layoutDirection
6571     *
6572     * @hide
6573     */
6574    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6575        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6576        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6577        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6578        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6579    })
6580    @LayoutDir
6581    public int getRawLayoutDirection() {
6582        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6583    }
6584
6585    /**
6586     * Set the layout direction for this view. This will propagate a reset of layout direction
6587     * resolution to the view's children and resolve layout direction for this view.
6588     *
6589     * @param layoutDirection the layout direction to set. Should be one of:
6590     *
6591     * {@link #LAYOUT_DIRECTION_LTR},
6592     * {@link #LAYOUT_DIRECTION_RTL},
6593     * {@link #LAYOUT_DIRECTION_INHERIT},
6594     * {@link #LAYOUT_DIRECTION_LOCALE}.
6595     *
6596     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6597     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6598     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6599     *
6600     * @attr ref android.R.styleable#View_layoutDirection
6601     */
6602    @RemotableViewMethod
6603    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6604        if (getRawLayoutDirection() != layoutDirection) {
6605            // Reset the current layout direction and the resolved one
6606            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6607            resetRtlProperties();
6608            // Set the new layout direction (filtered)
6609            mPrivateFlags2 |=
6610                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6611            // We need to resolve all RTL properties as they all depend on layout direction
6612            resolveRtlPropertiesIfNeeded();
6613            requestLayout();
6614            invalidate(true);
6615        }
6616    }
6617
6618    /**
6619     * Returns the resolved layout direction for this view.
6620     *
6621     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6622     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6623     *
6624     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6625     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6626     *
6627     * @attr ref android.R.styleable#View_layoutDirection
6628     */
6629    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6630        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6631        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6632    })
6633    @ResolvedLayoutDir
6634    public int getLayoutDirection() {
6635        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6636        if (targetSdkVersion < JELLY_BEAN_MR1) {
6637            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6638            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6639        }
6640        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6641                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6642    }
6643
6644    /**
6645     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6646     * layout attribute and/or the inherited value from the parent
6647     *
6648     * @return true if the layout is right-to-left.
6649     *
6650     * @hide
6651     */
6652    @ViewDebug.ExportedProperty(category = "layout")
6653    public boolean isLayoutRtl() {
6654        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6655    }
6656
6657    /**
6658     * Indicates whether the view is currently tracking transient state that the
6659     * app should not need to concern itself with saving and restoring, but that
6660     * the framework should take special note to preserve when possible.
6661     *
6662     * <p>A view with transient state cannot be trivially rebound from an external
6663     * data source, such as an adapter binding item views in a list. This may be
6664     * because the view is performing an animation, tracking user selection
6665     * of content, or similar.</p>
6666     *
6667     * @return true if the view has transient state
6668     */
6669    @ViewDebug.ExportedProperty(category = "layout")
6670    public boolean hasTransientState() {
6671        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6672    }
6673
6674    /**
6675     * Set whether this view is currently tracking transient state that the
6676     * framework should attempt to preserve when possible. This flag is reference counted,
6677     * so every call to setHasTransientState(true) should be paired with a later call
6678     * to setHasTransientState(false).
6679     *
6680     * <p>A view with transient state cannot be trivially rebound from an external
6681     * data source, such as an adapter binding item views in a list. This may be
6682     * because the view is performing an animation, tracking user selection
6683     * of content, or similar.</p>
6684     *
6685     * @param hasTransientState true if this view has transient state
6686     */
6687    public void setHasTransientState(boolean hasTransientState) {
6688        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6689                mTransientStateCount - 1;
6690        if (mTransientStateCount < 0) {
6691            mTransientStateCount = 0;
6692            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6693                    "unmatched pair of setHasTransientState calls");
6694        } else if ((hasTransientState && mTransientStateCount == 1) ||
6695                (!hasTransientState && mTransientStateCount == 0)) {
6696            // update flag if we've just incremented up from 0 or decremented down to 0
6697            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6698                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6699            if (mParent != null) {
6700                try {
6701                    mParent.childHasTransientStateChanged(this, hasTransientState);
6702                } catch (AbstractMethodError e) {
6703                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6704                            " does not fully implement ViewParent", e);
6705                }
6706            }
6707        }
6708    }
6709
6710    /**
6711     * Returns true if this view is currently attached to a window.
6712     */
6713    public boolean isAttachedToWindow() {
6714        return mAttachInfo != null;
6715    }
6716
6717    /**
6718     * Returns true if this view has been through at least one layout since it
6719     * was last attached to or detached from a window.
6720     */
6721    public boolean isLaidOut() {
6722        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6723    }
6724
6725    /**
6726     * If this view doesn't do any drawing on its own, set this flag to
6727     * allow further optimizations. By default, this flag is not set on
6728     * View, but could be set on some View subclasses such as ViewGroup.
6729     *
6730     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6731     * you should clear this flag.
6732     *
6733     * @param willNotDraw whether or not this View draw on its own
6734     */
6735    public void setWillNotDraw(boolean willNotDraw) {
6736        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6737    }
6738
6739    /**
6740     * Returns whether or not this View draws on its own.
6741     *
6742     * @return true if this view has nothing to draw, false otherwise
6743     */
6744    @ViewDebug.ExportedProperty(category = "drawing")
6745    public boolean willNotDraw() {
6746        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6747    }
6748
6749    /**
6750     * When a View's drawing cache is enabled, drawing is redirected to an
6751     * offscreen bitmap. Some views, like an ImageView, must be able to
6752     * bypass this mechanism if they already draw a single bitmap, to avoid
6753     * unnecessary usage of the memory.
6754     *
6755     * @param willNotCacheDrawing true if this view does not cache its
6756     *        drawing, false otherwise
6757     */
6758    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6759        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6760    }
6761
6762    /**
6763     * Returns whether or not this View can cache its drawing or not.
6764     *
6765     * @return true if this view does not cache its drawing, false otherwise
6766     */
6767    @ViewDebug.ExportedProperty(category = "drawing")
6768    public boolean willNotCacheDrawing() {
6769        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6770    }
6771
6772    /**
6773     * Indicates whether this view reacts to click events or not.
6774     *
6775     * @return true if the view is clickable, false otherwise
6776     *
6777     * @see #setClickable(boolean)
6778     * @attr ref android.R.styleable#View_clickable
6779     */
6780    @ViewDebug.ExportedProperty
6781    public boolean isClickable() {
6782        return (mViewFlags & CLICKABLE) == CLICKABLE;
6783    }
6784
6785    /**
6786     * Enables or disables click events for this view. When a view
6787     * is clickable it will change its state to "pressed" on every click.
6788     * Subclasses should set the view clickable to visually react to
6789     * user's clicks.
6790     *
6791     * @param clickable true to make the view clickable, false otherwise
6792     *
6793     * @see #isClickable()
6794     * @attr ref android.R.styleable#View_clickable
6795     */
6796    public void setClickable(boolean clickable) {
6797        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6798    }
6799
6800    /**
6801     * Indicates whether this view reacts to long click events or not.
6802     *
6803     * @return true if the view is long clickable, false otherwise
6804     *
6805     * @see #setLongClickable(boolean)
6806     * @attr ref android.R.styleable#View_longClickable
6807     */
6808    public boolean isLongClickable() {
6809        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6810    }
6811
6812    /**
6813     * Enables or disables long click events for this view. When a view is long
6814     * clickable it reacts to the user holding down the button for a longer
6815     * duration than a tap. This event can either launch the listener or a
6816     * context menu.
6817     *
6818     * @param longClickable true to make the view long clickable, false otherwise
6819     * @see #isLongClickable()
6820     * @attr ref android.R.styleable#View_longClickable
6821     */
6822    public void setLongClickable(boolean longClickable) {
6823        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6824    }
6825
6826    /**
6827     * Sets the pressed state for this view and provides a touch coordinate for
6828     * animation hinting.
6829     *
6830     * @param pressed Pass true to set the View's internal state to "pressed",
6831     *            or false to reverts the View's internal state from a
6832     *            previously set "pressed" state.
6833     * @param x The x coordinate of the touch that caused the press
6834     * @param y The y coordinate of the touch that caused the press
6835     */
6836    private void setPressed(boolean pressed, float x, float y) {
6837        if (pressed) {
6838            drawableHotspotChanged(x, y);
6839        }
6840
6841        setPressed(pressed);
6842    }
6843
6844    /**
6845     * Sets the pressed state for this view.
6846     *
6847     * @see #isClickable()
6848     * @see #setClickable(boolean)
6849     *
6850     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6851     *        the View's internal state from a previously set "pressed" state.
6852     */
6853    public void setPressed(boolean pressed) {
6854        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6855
6856        if (pressed) {
6857            mPrivateFlags |= PFLAG_PRESSED;
6858        } else {
6859            mPrivateFlags &= ~PFLAG_PRESSED;
6860        }
6861
6862        if (needsRefresh) {
6863            refreshDrawableState();
6864        }
6865        dispatchSetPressed(pressed);
6866    }
6867
6868    /**
6869     * Dispatch setPressed to all of this View's children.
6870     *
6871     * @see #setPressed(boolean)
6872     *
6873     * @param pressed The new pressed state
6874     */
6875    protected void dispatchSetPressed(boolean pressed) {
6876    }
6877
6878    /**
6879     * Indicates whether the view is currently in pressed state. Unless
6880     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6881     * the pressed state.
6882     *
6883     * @see #setPressed(boolean)
6884     * @see #isClickable()
6885     * @see #setClickable(boolean)
6886     *
6887     * @return true if the view is currently pressed, false otherwise
6888     */
6889    public boolean isPressed() {
6890        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6891    }
6892
6893    /**
6894     * Indicates whether this view will save its state (that is,
6895     * whether its {@link #onSaveInstanceState} method will be called).
6896     *
6897     * @return Returns true if the view state saving is enabled, else false.
6898     *
6899     * @see #setSaveEnabled(boolean)
6900     * @attr ref android.R.styleable#View_saveEnabled
6901     */
6902    public boolean isSaveEnabled() {
6903        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6904    }
6905
6906    /**
6907     * Controls whether the saving of this view's state is
6908     * enabled (that is, whether its {@link #onSaveInstanceState} method
6909     * will be called).  Note that even if freezing is enabled, the
6910     * view still must have an id assigned to it (via {@link #setId(int)})
6911     * for its state to be saved.  This flag can only disable the
6912     * saving of this view; any child views may still have their state saved.
6913     *
6914     * @param enabled Set to false to <em>disable</em> state saving, or true
6915     * (the default) to allow it.
6916     *
6917     * @see #isSaveEnabled()
6918     * @see #setId(int)
6919     * @see #onSaveInstanceState()
6920     * @attr ref android.R.styleable#View_saveEnabled
6921     */
6922    public void setSaveEnabled(boolean enabled) {
6923        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6924    }
6925
6926    /**
6927     * Gets whether the framework should discard touches when the view's
6928     * window is obscured by another visible window.
6929     * Refer to the {@link View} security documentation for more details.
6930     *
6931     * @return True if touch filtering is enabled.
6932     *
6933     * @see #setFilterTouchesWhenObscured(boolean)
6934     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6935     */
6936    @ViewDebug.ExportedProperty
6937    public boolean getFilterTouchesWhenObscured() {
6938        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6939    }
6940
6941    /**
6942     * Sets whether the framework should discard touches when the view's
6943     * window is obscured by another visible window.
6944     * Refer to the {@link View} security documentation for more details.
6945     *
6946     * @param enabled True if touch filtering should be enabled.
6947     *
6948     * @see #getFilterTouchesWhenObscured
6949     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6950     */
6951    public void setFilterTouchesWhenObscured(boolean enabled) {
6952        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6953                FILTER_TOUCHES_WHEN_OBSCURED);
6954    }
6955
6956    /**
6957     * Indicates whether the entire hierarchy under this view will save its
6958     * state when a state saving traversal occurs from its parent.  The default
6959     * is true; if false, these views will not be saved unless
6960     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6961     *
6962     * @return Returns true if the view state saving from parent is enabled, else false.
6963     *
6964     * @see #setSaveFromParentEnabled(boolean)
6965     */
6966    public boolean isSaveFromParentEnabled() {
6967        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6968    }
6969
6970    /**
6971     * Controls whether the entire hierarchy under this view will save its
6972     * state when a state saving traversal occurs from its parent.  The default
6973     * is true; if false, these views will not be saved unless
6974     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6975     *
6976     * @param enabled Set to false to <em>disable</em> state saving, or true
6977     * (the default) to allow it.
6978     *
6979     * @see #isSaveFromParentEnabled()
6980     * @see #setId(int)
6981     * @see #onSaveInstanceState()
6982     */
6983    public void setSaveFromParentEnabled(boolean enabled) {
6984        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6985    }
6986
6987
6988    /**
6989     * Returns whether this View is able to take focus.
6990     *
6991     * @return True if this view can take focus, or false otherwise.
6992     * @attr ref android.R.styleable#View_focusable
6993     */
6994    @ViewDebug.ExportedProperty(category = "focus")
6995    public final boolean isFocusable() {
6996        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6997    }
6998
6999    /**
7000     * When a view is focusable, it may not want to take focus when in touch mode.
7001     * For example, a button would like focus when the user is navigating via a D-pad
7002     * so that the user can click on it, but once the user starts touching the screen,
7003     * the button shouldn't take focus
7004     * @return Whether the view is focusable in touch mode.
7005     * @attr ref android.R.styleable#View_focusableInTouchMode
7006     */
7007    @ViewDebug.ExportedProperty
7008    public final boolean isFocusableInTouchMode() {
7009        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7010    }
7011
7012    /**
7013     * Find the nearest view in the specified direction that can take focus.
7014     * This does not actually give focus to that view.
7015     *
7016     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7017     *
7018     * @return The nearest focusable in the specified direction, or null if none
7019     *         can be found.
7020     */
7021    public View focusSearch(@FocusRealDirection int direction) {
7022        if (mParent != null) {
7023            return mParent.focusSearch(this, direction);
7024        } else {
7025            return null;
7026        }
7027    }
7028
7029    /**
7030     * This method is the last chance for the focused view and its ancestors to
7031     * respond to an arrow key. This is called when the focused view did not
7032     * consume the key internally, nor could the view system find a new view in
7033     * the requested direction to give focus to.
7034     *
7035     * @param focused The currently focused view.
7036     * @param direction The direction focus wants to move. One of FOCUS_UP,
7037     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7038     * @return True if the this view consumed this unhandled move.
7039     */
7040    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7041        return false;
7042    }
7043
7044    /**
7045     * If a user manually specified the next view id for a particular direction,
7046     * use the root to look up the view.
7047     * @param root The root view of the hierarchy containing this view.
7048     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7049     * or FOCUS_BACKWARD.
7050     * @return The user specified next view, or null if there is none.
7051     */
7052    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7053        switch (direction) {
7054            case FOCUS_LEFT:
7055                if (mNextFocusLeftId == View.NO_ID) return null;
7056                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7057            case FOCUS_RIGHT:
7058                if (mNextFocusRightId == View.NO_ID) return null;
7059                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7060            case FOCUS_UP:
7061                if (mNextFocusUpId == View.NO_ID) return null;
7062                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7063            case FOCUS_DOWN:
7064                if (mNextFocusDownId == View.NO_ID) return null;
7065                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7066            case FOCUS_FORWARD:
7067                if (mNextFocusForwardId == View.NO_ID) return null;
7068                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7069            case FOCUS_BACKWARD: {
7070                if (mID == View.NO_ID) return null;
7071                final int id = mID;
7072                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7073                    @Override
7074                    public boolean apply(View t) {
7075                        return t.mNextFocusForwardId == id;
7076                    }
7077                });
7078            }
7079        }
7080        return null;
7081    }
7082
7083    private View findViewInsideOutShouldExist(View root, int id) {
7084        if (mMatchIdPredicate == null) {
7085            mMatchIdPredicate = new MatchIdPredicate();
7086        }
7087        mMatchIdPredicate.mId = id;
7088        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7089        if (result == null) {
7090            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7091        }
7092        return result;
7093    }
7094
7095    /**
7096     * Find and return all focusable views that are descendants of this view,
7097     * possibly including this view if it is focusable itself.
7098     *
7099     * @param direction The direction of the focus
7100     * @return A list of focusable views
7101     */
7102    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7103        ArrayList<View> result = new ArrayList<View>(24);
7104        addFocusables(result, direction);
7105        return result;
7106    }
7107
7108    /**
7109     * Add any focusable views that are descendants of this view (possibly
7110     * including this view if it is focusable itself) to views.  If we are in touch mode,
7111     * only add views that are also focusable in touch mode.
7112     *
7113     * @param views Focusable views found so far
7114     * @param direction The direction of the focus
7115     */
7116    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7117        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7118    }
7119
7120    /**
7121     * Adds any focusable views that are descendants of this view (possibly
7122     * including this view if it is focusable itself) to views. This method
7123     * adds all focusable views regardless if we are in touch mode or
7124     * only views focusable in touch mode if we are in touch mode or
7125     * only views that can take accessibility focus if accessibility is enabeld
7126     * depending on the focusable mode paramater.
7127     *
7128     * @param views Focusable views found so far or null if all we are interested is
7129     *        the number of focusables.
7130     * @param direction The direction of the focus.
7131     * @param focusableMode The type of focusables to be added.
7132     *
7133     * @see #FOCUSABLES_ALL
7134     * @see #FOCUSABLES_TOUCH_MODE
7135     */
7136    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7137            @FocusableMode int focusableMode) {
7138        if (views == null) {
7139            return;
7140        }
7141        if (!isFocusable()) {
7142            return;
7143        }
7144        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7145                && isInTouchMode() && !isFocusableInTouchMode()) {
7146            return;
7147        }
7148        views.add(this);
7149    }
7150
7151    /**
7152     * Finds the Views that contain given text. The containment is case insensitive.
7153     * The search is performed by either the text that the View renders or the content
7154     * description that describes the view for accessibility purposes and the view does
7155     * not render or both. Clients can specify how the search is to be performed via
7156     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7157     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7158     *
7159     * @param outViews The output list of matching Views.
7160     * @param searched The text to match against.
7161     *
7162     * @see #FIND_VIEWS_WITH_TEXT
7163     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7164     * @see #setContentDescription(CharSequence)
7165     */
7166    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7167            @FindViewFlags int flags) {
7168        if (getAccessibilityNodeProvider() != null) {
7169            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7170                outViews.add(this);
7171            }
7172        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7173                && (searched != null && searched.length() > 0)
7174                && (mContentDescription != null && mContentDescription.length() > 0)) {
7175            String searchedLowerCase = searched.toString().toLowerCase();
7176            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7177            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7178                outViews.add(this);
7179            }
7180        }
7181    }
7182
7183    /**
7184     * Find and return all touchable views that are descendants of this view,
7185     * possibly including this view if it is touchable itself.
7186     *
7187     * @return A list of touchable views
7188     */
7189    public ArrayList<View> getTouchables() {
7190        ArrayList<View> result = new ArrayList<View>();
7191        addTouchables(result);
7192        return result;
7193    }
7194
7195    /**
7196     * Add any touchable views that are descendants of this view (possibly
7197     * including this view if it is touchable itself) to views.
7198     *
7199     * @param views Touchable views found so far
7200     */
7201    public void addTouchables(ArrayList<View> views) {
7202        final int viewFlags = mViewFlags;
7203
7204        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7205                && (viewFlags & ENABLED_MASK) == ENABLED) {
7206            views.add(this);
7207        }
7208    }
7209
7210    /**
7211     * Returns whether this View is accessibility focused.
7212     *
7213     * @return True if this View is accessibility focused.
7214     */
7215    public boolean isAccessibilityFocused() {
7216        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7217    }
7218
7219    /**
7220     * Call this to try to give accessibility focus to this view.
7221     *
7222     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7223     * returns false or the view is no visible or the view already has accessibility
7224     * focus.
7225     *
7226     * See also {@link #focusSearch(int)}, which is what you call to say that you
7227     * have focus, and you want your parent to look for the next one.
7228     *
7229     * @return Whether this view actually took accessibility focus.
7230     *
7231     * @hide
7232     */
7233    public boolean requestAccessibilityFocus() {
7234        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7235        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7236            return false;
7237        }
7238        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7239            return false;
7240        }
7241        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7242            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7243            ViewRootImpl viewRootImpl = getViewRootImpl();
7244            if (viewRootImpl != null) {
7245                viewRootImpl.setAccessibilityFocus(this, null);
7246            }
7247            Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect();
7248            getDrawingRect(rect);
7249            requestRectangleOnScreen(rect, false);
7250            invalidate();
7251            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7252            return true;
7253        }
7254        return false;
7255    }
7256
7257    /**
7258     * Call this to try to clear accessibility focus of this view.
7259     *
7260     * See also {@link #focusSearch(int)}, which is what you call to say that you
7261     * have focus, and you want your parent to look for the next one.
7262     *
7263     * @hide
7264     */
7265    public void clearAccessibilityFocus() {
7266        clearAccessibilityFocusNoCallbacks();
7267        // Clear the global reference of accessibility focus if this
7268        // view or any of its descendants had accessibility focus.
7269        ViewRootImpl viewRootImpl = getViewRootImpl();
7270        if (viewRootImpl != null) {
7271            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7272            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7273                viewRootImpl.setAccessibilityFocus(null, null);
7274            }
7275        }
7276    }
7277
7278    private void sendAccessibilityHoverEvent(int eventType) {
7279        // Since we are not delivering to a client accessibility events from not
7280        // important views (unless the clinet request that) we need to fire the
7281        // event from the deepest view exposed to the client. As a consequence if
7282        // the user crosses a not exposed view the client will see enter and exit
7283        // of the exposed predecessor followed by and enter and exit of that same
7284        // predecessor when entering and exiting the not exposed descendant. This
7285        // is fine since the client has a clear idea which view is hovered at the
7286        // price of a couple more events being sent. This is a simple and
7287        // working solution.
7288        View source = this;
7289        while (true) {
7290            if (source.includeForAccessibility()) {
7291                source.sendAccessibilityEvent(eventType);
7292                return;
7293            }
7294            ViewParent parent = source.getParent();
7295            if (parent instanceof View) {
7296                source = (View) parent;
7297            } else {
7298                return;
7299            }
7300        }
7301    }
7302
7303    /**
7304     * Clears accessibility focus without calling any callback methods
7305     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7306     * is used for clearing accessibility focus when giving this focus to
7307     * another view.
7308     */
7309    void clearAccessibilityFocusNoCallbacks() {
7310        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7311            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7312            invalidate();
7313            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7314        }
7315    }
7316
7317    /**
7318     * Call this to try to give focus to a specific view or to one of its
7319     * descendants.
7320     *
7321     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7322     * false), or if it is focusable and it is not focusable in touch mode
7323     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7324     *
7325     * See also {@link #focusSearch(int)}, which is what you call to say that you
7326     * have focus, and you want your parent to look for the next one.
7327     *
7328     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7329     * {@link #FOCUS_DOWN} and <code>null</code>.
7330     *
7331     * @return Whether this view or one of its descendants actually took focus.
7332     */
7333    public final boolean requestFocus() {
7334        return requestFocus(View.FOCUS_DOWN);
7335    }
7336
7337    /**
7338     * Call this to try to give focus to a specific view or to one of its
7339     * descendants and give it a hint about what direction focus is heading.
7340     *
7341     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7342     * false), or if it is focusable and it is not focusable in touch mode
7343     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7344     *
7345     * See also {@link #focusSearch(int)}, which is what you call to say that you
7346     * have focus, and you want your parent to look for the next one.
7347     *
7348     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7349     * <code>null</code> set for the previously focused rectangle.
7350     *
7351     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7352     * @return Whether this view or one of its descendants actually took focus.
7353     */
7354    public final boolean requestFocus(int direction) {
7355        return requestFocus(direction, null);
7356    }
7357
7358    /**
7359     * Call this to try to give focus to a specific view or to one of its descendants
7360     * and give it hints about the direction and a specific rectangle that the focus
7361     * is coming from.  The rectangle can help give larger views a finer grained hint
7362     * about where focus is coming from, and therefore, where to show selection, or
7363     * forward focus change internally.
7364     *
7365     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7366     * false), or if it is focusable and it is not focusable in touch mode
7367     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7368     *
7369     * A View will not take focus if it is not visible.
7370     *
7371     * A View will not take focus if one of its parents has
7372     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7373     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7374     *
7375     * See also {@link #focusSearch(int)}, which is what you call to say that you
7376     * have focus, and you want your parent to look for the next one.
7377     *
7378     * You may wish to override this method if your custom {@link View} has an internal
7379     * {@link View} that it wishes to forward the request to.
7380     *
7381     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7382     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7383     *        to give a finer grained hint about where focus is coming from.  May be null
7384     *        if there is no hint.
7385     * @return Whether this view or one of its descendants actually took focus.
7386     */
7387    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7388        return requestFocusNoSearch(direction, previouslyFocusedRect);
7389    }
7390
7391    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7392        // need to be focusable
7393        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7394                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7395            return false;
7396        }
7397
7398        // need to be focusable in touch mode if in touch mode
7399        if (isInTouchMode() &&
7400            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7401               return false;
7402        }
7403
7404        // need to not have any parents blocking us
7405        if (hasAncestorThatBlocksDescendantFocus()) {
7406            return false;
7407        }
7408
7409        handleFocusGainInternal(direction, previouslyFocusedRect);
7410        return true;
7411    }
7412
7413    /**
7414     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7415     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7416     * touch mode to request focus when they are touched.
7417     *
7418     * @return Whether this view or one of its descendants actually took focus.
7419     *
7420     * @see #isInTouchMode()
7421     *
7422     */
7423    public final boolean requestFocusFromTouch() {
7424        // Leave touch mode if we need to
7425        if (isInTouchMode()) {
7426            ViewRootImpl viewRoot = getViewRootImpl();
7427            if (viewRoot != null) {
7428                viewRoot.ensureTouchMode(false);
7429            }
7430        }
7431        return requestFocus(View.FOCUS_DOWN);
7432    }
7433
7434    /**
7435     * @return Whether any ancestor of this view blocks descendant focus.
7436     */
7437    private boolean hasAncestorThatBlocksDescendantFocus() {
7438        ViewParent ancestor = mParent;
7439        while (ancestor instanceof ViewGroup) {
7440            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7441            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7442                return true;
7443            } else {
7444                ancestor = vgAncestor.getParent();
7445            }
7446        }
7447        return false;
7448    }
7449
7450    /**
7451     * Gets the mode for determining whether this View is important for accessibility
7452     * which is if it fires accessibility events and if it is reported to
7453     * accessibility services that query the screen.
7454     *
7455     * @return The mode for determining whether a View is important for accessibility.
7456     *
7457     * @attr ref android.R.styleable#View_importantForAccessibility
7458     *
7459     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7460     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7461     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7462     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7463     */
7464    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7465            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7466            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7467            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7468            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7469                    to = "noHideDescendants")
7470        })
7471    public int getImportantForAccessibility() {
7472        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7473                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7474    }
7475
7476    /**
7477     * Sets the live region mode for this view. This indicates to accessibility
7478     * services whether they should automatically notify the user about changes
7479     * to the view's content description or text, or to the content descriptions
7480     * or text of the view's children (where applicable).
7481     * <p>
7482     * For example, in a login screen with a TextView that displays an "incorrect
7483     * password" notification, that view should be marked as a live region with
7484     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7485     * <p>
7486     * To disable change notifications for this view, use
7487     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7488     * mode for most views.
7489     * <p>
7490     * To indicate that the user should be notified of changes, use
7491     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7492     * <p>
7493     * If the view's changes should interrupt ongoing speech and notify the user
7494     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7495     *
7496     * @param mode The live region mode for this view, one of:
7497     *        <ul>
7498     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7499     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7500     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7501     *        </ul>
7502     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7503     */
7504    public void setAccessibilityLiveRegion(int mode) {
7505        if (mode != getAccessibilityLiveRegion()) {
7506            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7507            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7508                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7509            notifyViewAccessibilityStateChangedIfNeeded(
7510                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7511        }
7512    }
7513
7514    /**
7515     * Gets the live region mode for this View.
7516     *
7517     * @return The live region mode for the view.
7518     *
7519     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7520     *
7521     * @see #setAccessibilityLiveRegion(int)
7522     */
7523    public int getAccessibilityLiveRegion() {
7524        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7525                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7526    }
7527
7528    /**
7529     * Sets how to determine whether this view is important for accessibility
7530     * which is if it fires accessibility events and if it is reported to
7531     * accessibility services that query the screen.
7532     *
7533     * @param mode How to determine whether this view is important for accessibility.
7534     *
7535     * @attr ref android.R.styleable#View_importantForAccessibility
7536     *
7537     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7538     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7539     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7540     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7541     */
7542    public void setImportantForAccessibility(int mode) {
7543        final int oldMode = getImportantForAccessibility();
7544        if (mode != oldMode) {
7545            // If we're moving between AUTO and another state, we might not need
7546            // to send a subtree changed notification. We'll store the computed
7547            // importance, since we'll need to check it later to make sure.
7548            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7549                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7550            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7551            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7552            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7553                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7554            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7555                notifySubtreeAccessibilityStateChangedIfNeeded();
7556            } else {
7557                notifyViewAccessibilityStateChangedIfNeeded(
7558                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7559            }
7560        }
7561    }
7562
7563    /**
7564     * Computes whether this view should be exposed for accessibility. In
7565     * general, views that are interactive or provide information are exposed
7566     * while views that serve only as containers are hidden.
7567     * <p>
7568     * If an ancestor of this view has importance
7569     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7570     * returns <code>false</code>.
7571     * <p>
7572     * Otherwise, the value is computed according to the view's
7573     * {@link #getImportantForAccessibility()} value:
7574     * <ol>
7575     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7576     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7577     * </code>
7578     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7579     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7580     * view satisfies any of the following:
7581     * <ul>
7582     * <li>Is actionable, e.g. {@link #isClickable()},
7583     * {@link #isLongClickable()}, or {@link #isFocusable()}
7584     * <li>Has an {@link AccessibilityDelegate}
7585     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7586     * {@link OnKeyListener}, etc.
7587     * <li>Is an accessibility live region, e.g.
7588     * {@link #getAccessibilityLiveRegion()} is not
7589     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7590     * </ul>
7591     * </ol>
7592     *
7593     * @return Whether the view is exposed for accessibility.
7594     * @see #setImportantForAccessibility(int)
7595     * @see #getImportantForAccessibility()
7596     */
7597    public boolean isImportantForAccessibility() {
7598        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7599                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7600        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7601                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7602            return false;
7603        }
7604
7605        // Check parent mode to ensure we're not hidden.
7606        ViewParent parent = mParent;
7607        while (parent instanceof View) {
7608            if (((View) parent).getImportantForAccessibility()
7609                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7610                return false;
7611            }
7612            parent = parent.getParent();
7613        }
7614
7615        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7616                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7617                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7618    }
7619
7620    /**
7621     * Gets the parent for accessibility purposes. Note that the parent for
7622     * accessibility is not necessary the immediate parent. It is the first
7623     * predecessor that is important for accessibility.
7624     *
7625     * @return The parent for accessibility purposes.
7626     */
7627    public ViewParent getParentForAccessibility() {
7628        if (mParent instanceof View) {
7629            View parentView = (View) mParent;
7630            if (parentView.includeForAccessibility()) {
7631                return mParent;
7632            } else {
7633                return mParent.getParentForAccessibility();
7634            }
7635        }
7636        return null;
7637    }
7638
7639    /**
7640     * Adds the children of a given View for accessibility. Since some Views are
7641     * not important for accessibility the children for accessibility are not
7642     * necessarily direct children of the view, rather they are the first level of
7643     * descendants important for accessibility.
7644     *
7645     * @param children The list of children for accessibility.
7646     */
7647    public void addChildrenForAccessibility(ArrayList<View> children) {
7648
7649    }
7650
7651    /**
7652     * Whether to regard this view for accessibility. A view is regarded for
7653     * accessibility if it is important for accessibility or the querying
7654     * accessibility service has explicitly requested that view not
7655     * important for accessibility are regarded.
7656     *
7657     * @return Whether to regard the view for accessibility.
7658     *
7659     * @hide
7660     */
7661    public boolean includeForAccessibility() {
7662        if (mAttachInfo != null) {
7663            return (mAttachInfo.mAccessibilityFetchFlags
7664                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7665                    || isImportantForAccessibility();
7666        }
7667        return false;
7668    }
7669
7670    /**
7671     * Returns whether the View is considered actionable from
7672     * accessibility perspective. Such view are important for
7673     * accessibility.
7674     *
7675     * @return True if the view is actionable for accessibility.
7676     *
7677     * @hide
7678     */
7679    public boolean isActionableForAccessibility() {
7680        return (isClickable() || isLongClickable() || isFocusable());
7681    }
7682
7683    /**
7684     * Returns whether the View has registered callbacks which makes it
7685     * important for accessibility.
7686     *
7687     * @return True if the view is actionable for accessibility.
7688     */
7689    private boolean hasListenersForAccessibility() {
7690        ListenerInfo info = getListenerInfo();
7691        return mTouchDelegate != null || info.mOnKeyListener != null
7692                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7693                || info.mOnHoverListener != null || info.mOnDragListener != null;
7694    }
7695
7696    /**
7697     * Notifies that the accessibility state of this view changed. The change
7698     * is local to this view and does not represent structural changes such
7699     * as children and parent. For example, the view became focusable. The
7700     * notification is at at most once every
7701     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7702     * to avoid unnecessary load to the system. Also once a view has a pending
7703     * notification this method is a NOP until the notification has been sent.
7704     *
7705     * @hide
7706     */
7707    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7708        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7709            return;
7710        }
7711        if (mSendViewStateChangedAccessibilityEvent == null) {
7712            mSendViewStateChangedAccessibilityEvent =
7713                    new SendViewStateChangedAccessibilityEvent();
7714        }
7715        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7716    }
7717
7718    /**
7719     * Notifies that the accessibility state of this view changed. The change
7720     * is *not* local to this view and does represent structural changes such
7721     * as children and parent. For example, the view size changed. The
7722     * notification is at at most once every
7723     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7724     * to avoid unnecessary load to the system. Also once a view has a pending
7725     * notification this method is a NOP until the notification has been sent.
7726     *
7727     * @hide
7728     */
7729    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7730        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7731            return;
7732        }
7733        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7734            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7735            if (mParent != null) {
7736                try {
7737                    mParent.notifySubtreeAccessibilityStateChanged(
7738                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7739                } catch (AbstractMethodError e) {
7740                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7741                            " does not fully implement ViewParent", e);
7742                }
7743            }
7744        }
7745    }
7746
7747    /**
7748     * Reset the flag indicating the accessibility state of the subtree rooted
7749     * at this view changed.
7750     */
7751    void resetSubtreeAccessibilityStateChanged() {
7752        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7753    }
7754
7755    /**
7756     * Performs the specified accessibility action on the view. For
7757     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7758     * <p>
7759     * If an {@link AccessibilityDelegate} has been specified via calling
7760     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7761     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7762     * is responsible for handling this call.
7763     * </p>
7764     *
7765     * @param action The action to perform.
7766     * @param arguments Optional action arguments.
7767     * @return Whether the action was performed.
7768     */
7769    public boolean performAccessibilityAction(int action, Bundle arguments) {
7770      if (mAccessibilityDelegate != null) {
7771          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7772      } else {
7773          return performAccessibilityActionInternal(action, arguments);
7774      }
7775    }
7776
7777   /**
7778    * @see #performAccessibilityAction(int, Bundle)
7779    *
7780    * Note: Called from the default {@link AccessibilityDelegate}.
7781    */
7782    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7783        switch (action) {
7784            case AccessibilityNodeInfo.ACTION_CLICK: {
7785                if (isClickable()) {
7786                    performClick();
7787                    return true;
7788                }
7789            } break;
7790            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7791                if (isLongClickable()) {
7792                    performLongClick();
7793                    return true;
7794                }
7795            } break;
7796            case AccessibilityNodeInfo.ACTION_FOCUS: {
7797                if (!hasFocus()) {
7798                    // Get out of touch mode since accessibility
7799                    // wants to move focus around.
7800                    getViewRootImpl().ensureTouchMode(false);
7801                    return requestFocus();
7802                }
7803            } break;
7804            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7805                if (hasFocus()) {
7806                    clearFocus();
7807                    return !isFocused();
7808                }
7809            } break;
7810            case AccessibilityNodeInfo.ACTION_SELECT: {
7811                if (!isSelected()) {
7812                    setSelected(true);
7813                    return isSelected();
7814                }
7815            } break;
7816            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7817                if (isSelected()) {
7818                    setSelected(false);
7819                    return !isSelected();
7820                }
7821            } break;
7822            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7823                if (!isAccessibilityFocused()) {
7824                    return requestAccessibilityFocus();
7825                }
7826            } break;
7827            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7828                if (isAccessibilityFocused()) {
7829                    clearAccessibilityFocus();
7830                    return true;
7831                }
7832            } break;
7833            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7834                if (arguments != null) {
7835                    final int granularity = arguments.getInt(
7836                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7837                    final boolean extendSelection = arguments.getBoolean(
7838                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7839                    return traverseAtGranularity(granularity, true, extendSelection);
7840                }
7841            } break;
7842            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7843                if (arguments != null) {
7844                    final int granularity = arguments.getInt(
7845                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7846                    final boolean extendSelection = arguments.getBoolean(
7847                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7848                    return traverseAtGranularity(granularity, false, extendSelection);
7849                }
7850            } break;
7851            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7852                CharSequence text = getIterableTextForAccessibility();
7853                if (text == null) {
7854                    return false;
7855                }
7856                final int start = (arguments != null) ? arguments.getInt(
7857                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7858                final int end = (arguments != null) ? arguments.getInt(
7859                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7860                // Only cursor position can be specified (selection length == 0)
7861                if ((getAccessibilitySelectionStart() != start
7862                        || getAccessibilitySelectionEnd() != end)
7863                        && (start == end)) {
7864                    setAccessibilitySelection(start, end);
7865                    notifyViewAccessibilityStateChangedIfNeeded(
7866                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7867                    return true;
7868                }
7869            } break;
7870        }
7871        return false;
7872    }
7873
7874    private boolean traverseAtGranularity(int granularity, boolean forward,
7875            boolean extendSelection) {
7876        CharSequence text = getIterableTextForAccessibility();
7877        if (text == null || text.length() == 0) {
7878            return false;
7879        }
7880        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7881        if (iterator == null) {
7882            return false;
7883        }
7884        int current = getAccessibilitySelectionEnd();
7885        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7886            current = forward ? 0 : text.length();
7887        }
7888        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7889        if (range == null) {
7890            return false;
7891        }
7892        final int segmentStart = range[0];
7893        final int segmentEnd = range[1];
7894        int selectionStart;
7895        int selectionEnd;
7896        if (extendSelection && isAccessibilitySelectionExtendable()) {
7897            selectionStart = getAccessibilitySelectionStart();
7898            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7899                selectionStart = forward ? segmentStart : segmentEnd;
7900            }
7901            selectionEnd = forward ? segmentEnd : segmentStart;
7902        } else {
7903            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7904        }
7905        setAccessibilitySelection(selectionStart, selectionEnd);
7906        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7907                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7908        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7909        return true;
7910    }
7911
7912    /**
7913     * Gets the text reported for accessibility purposes.
7914     *
7915     * @return The accessibility text.
7916     *
7917     * @hide
7918     */
7919    public CharSequence getIterableTextForAccessibility() {
7920        return getContentDescription();
7921    }
7922
7923    /**
7924     * Gets whether accessibility selection can be extended.
7925     *
7926     * @return If selection is extensible.
7927     *
7928     * @hide
7929     */
7930    public boolean isAccessibilitySelectionExtendable() {
7931        return false;
7932    }
7933
7934    /**
7935     * @hide
7936     */
7937    public int getAccessibilitySelectionStart() {
7938        return mAccessibilityCursorPosition;
7939    }
7940
7941    /**
7942     * @hide
7943     */
7944    public int getAccessibilitySelectionEnd() {
7945        return getAccessibilitySelectionStart();
7946    }
7947
7948    /**
7949     * @hide
7950     */
7951    public void setAccessibilitySelection(int start, int end) {
7952        if (start ==  end && end == mAccessibilityCursorPosition) {
7953            return;
7954        }
7955        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7956            mAccessibilityCursorPosition = start;
7957        } else {
7958            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7959        }
7960        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7961    }
7962
7963    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7964            int fromIndex, int toIndex) {
7965        if (mParent == null) {
7966            return;
7967        }
7968        AccessibilityEvent event = AccessibilityEvent.obtain(
7969                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7970        onInitializeAccessibilityEvent(event);
7971        onPopulateAccessibilityEvent(event);
7972        event.setFromIndex(fromIndex);
7973        event.setToIndex(toIndex);
7974        event.setAction(action);
7975        event.setMovementGranularity(granularity);
7976        mParent.requestSendAccessibilityEvent(this, event);
7977    }
7978
7979    /**
7980     * @hide
7981     */
7982    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7983        switch (granularity) {
7984            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7985                CharSequence text = getIterableTextForAccessibility();
7986                if (text != null && text.length() > 0) {
7987                    CharacterTextSegmentIterator iterator =
7988                        CharacterTextSegmentIterator.getInstance(
7989                                mContext.getResources().getConfiguration().locale);
7990                    iterator.initialize(text.toString());
7991                    return iterator;
7992                }
7993            } break;
7994            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7995                CharSequence text = getIterableTextForAccessibility();
7996                if (text != null && text.length() > 0) {
7997                    WordTextSegmentIterator iterator =
7998                        WordTextSegmentIterator.getInstance(
7999                                mContext.getResources().getConfiguration().locale);
8000                    iterator.initialize(text.toString());
8001                    return iterator;
8002                }
8003            } break;
8004            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8005                CharSequence text = getIterableTextForAccessibility();
8006                if (text != null && text.length() > 0) {
8007                    ParagraphTextSegmentIterator iterator =
8008                        ParagraphTextSegmentIterator.getInstance();
8009                    iterator.initialize(text.toString());
8010                    return iterator;
8011                }
8012            } break;
8013        }
8014        return null;
8015    }
8016
8017    /**
8018     * @hide
8019     */
8020    public void dispatchStartTemporaryDetach() {
8021        onStartTemporaryDetach();
8022    }
8023
8024    /**
8025     * This is called when a container is going to temporarily detach a child, with
8026     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8027     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8028     * {@link #onDetachedFromWindow()} when the container is done.
8029     */
8030    public void onStartTemporaryDetach() {
8031        removeUnsetPressCallback();
8032        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8033    }
8034
8035    /**
8036     * @hide
8037     */
8038    public void dispatchFinishTemporaryDetach() {
8039        onFinishTemporaryDetach();
8040    }
8041
8042    /**
8043     * Called after {@link #onStartTemporaryDetach} when the container is done
8044     * changing the view.
8045     */
8046    public void onFinishTemporaryDetach() {
8047    }
8048
8049    /**
8050     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8051     * for this view's window.  Returns null if the view is not currently attached
8052     * to the window.  Normally you will not need to use this directly, but
8053     * just use the standard high-level event callbacks like
8054     * {@link #onKeyDown(int, KeyEvent)}.
8055     */
8056    public KeyEvent.DispatcherState getKeyDispatcherState() {
8057        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8058    }
8059
8060    /**
8061     * Dispatch a key event before it is processed by any input method
8062     * associated with the view hierarchy.  This can be used to intercept
8063     * key events in special situations before the IME consumes them; a
8064     * typical example would be handling the BACK key to update the application's
8065     * UI instead of allowing the IME to see it and close itself.
8066     *
8067     * @param event The key event to be dispatched.
8068     * @return True if the event was handled, false otherwise.
8069     */
8070    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8071        return onKeyPreIme(event.getKeyCode(), event);
8072    }
8073
8074    /**
8075     * Dispatch a key event to the next view on the focus path. This path runs
8076     * from the top of the view tree down to the currently focused view. If this
8077     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8078     * the next node down the focus path. This method also fires any key
8079     * listeners.
8080     *
8081     * @param event The key event to be dispatched.
8082     * @return True if the event was handled, false otherwise.
8083     */
8084    public boolean dispatchKeyEvent(KeyEvent event) {
8085        if (mInputEventConsistencyVerifier != null) {
8086            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8087        }
8088
8089        // Give any attached key listener a first crack at the event.
8090        //noinspection SimplifiableIfStatement
8091        ListenerInfo li = mListenerInfo;
8092        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8093                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8094            return true;
8095        }
8096
8097        if (event.dispatch(this, mAttachInfo != null
8098                ? mAttachInfo.mKeyDispatchState : null, this)) {
8099            return true;
8100        }
8101
8102        if (mInputEventConsistencyVerifier != null) {
8103            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8104        }
8105        return false;
8106    }
8107
8108    /**
8109     * Dispatches a key shortcut event.
8110     *
8111     * @param event The key event to be dispatched.
8112     * @return True if the event was handled by the view, false otherwise.
8113     */
8114    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8115        return onKeyShortcut(event.getKeyCode(), event);
8116    }
8117
8118    /**
8119     * Pass the touch screen motion event down to the target view, or this
8120     * view if it is the target.
8121     *
8122     * @param event The motion event to be dispatched.
8123     * @return True if the event was handled by the view, false otherwise.
8124     */
8125    public boolean dispatchTouchEvent(MotionEvent event) {
8126        boolean result = false;
8127
8128        if (mInputEventConsistencyVerifier != null) {
8129            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8130        }
8131
8132        final int actionMasked = event.getActionMasked();
8133        if (actionMasked == MotionEvent.ACTION_DOWN) {
8134            // Defensive cleanup for new gesture
8135            stopNestedScroll();
8136        }
8137
8138        if (onFilterTouchEventForSecurity(event)) {
8139            //noinspection SimplifiableIfStatement
8140            ListenerInfo li = mListenerInfo;
8141            if (li != null && li.mOnTouchListener != null
8142                    && (mViewFlags & ENABLED_MASK) == ENABLED
8143                    && li.mOnTouchListener.onTouch(this, event)) {
8144                result = true;
8145            }
8146
8147            if (!result && onTouchEvent(event)) {
8148                result = true;
8149            }
8150        }
8151
8152        if (!result && mInputEventConsistencyVerifier != null) {
8153            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8154        }
8155
8156        // Clean up after nested scrolls if this is the end of a gesture;
8157        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8158        // of the gesture.
8159        if (actionMasked == MotionEvent.ACTION_UP ||
8160                actionMasked == MotionEvent.ACTION_CANCEL ||
8161                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8162            stopNestedScroll();
8163        }
8164
8165        return result;
8166    }
8167
8168    /**
8169     * Filter the touch event to apply security policies.
8170     *
8171     * @param event The motion event to be filtered.
8172     * @return True if the event should be dispatched, false if the event should be dropped.
8173     *
8174     * @see #getFilterTouchesWhenObscured
8175     */
8176    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8177        //noinspection RedundantIfStatement
8178        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8179                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8180            // Window is obscured, drop this touch.
8181            return false;
8182        }
8183        return true;
8184    }
8185
8186    /**
8187     * Pass a trackball motion event down to the focused view.
8188     *
8189     * @param event The motion event to be dispatched.
8190     * @return True if the event was handled by the view, false otherwise.
8191     */
8192    public boolean dispatchTrackballEvent(MotionEvent event) {
8193        if (mInputEventConsistencyVerifier != null) {
8194            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8195        }
8196
8197        return onTrackballEvent(event);
8198    }
8199
8200    /**
8201     * Dispatch a generic motion event.
8202     * <p>
8203     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8204     * are delivered to the view under the pointer.  All other generic motion events are
8205     * delivered to the focused view.  Hover events are handled specially and are delivered
8206     * to {@link #onHoverEvent(MotionEvent)}.
8207     * </p>
8208     *
8209     * @param event The motion event to be dispatched.
8210     * @return True if the event was handled by the view, false otherwise.
8211     */
8212    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8213        if (mInputEventConsistencyVerifier != null) {
8214            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8215        }
8216
8217        final int source = event.getSource();
8218        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8219            final int action = event.getAction();
8220            if (action == MotionEvent.ACTION_HOVER_ENTER
8221                    || action == MotionEvent.ACTION_HOVER_MOVE
8222                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8223                if (dispatchHoverEvent(event)) {
8224                    return true;
8225                }
8226            } else if (dispatchGenericPointerEvent(event)) {
8227                return true;
8228            }
8229        } else if (dispatchGenericFocusedEvent(event)) {
8230            return true;
8231        }
8232
8233        if (dispatchGenericMotionEventInternal(event)) {
8234            return true;
8235        }
8236
8237        if (mInputEventConsistencyVerifier != null) {
8238            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8239        }
8240        return false;
8241    }
8242
8243    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8244        //noinspection SimplifiableIfStatement
8245        ListenerInfo li = mListenerInfo;
8246        if (li != null && li.mOnGenericMotionListener != null
8247                && (mViewFlags & ENABLED_MASK) == ENABLED
8248                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8249            return true;
8250        }
8251
8252        if (onGenericMotionEvent(event)) {
8253            return true;
8254        }
8255
8256        if (mInputEventConsistencyVerifier != null) {
8257            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8258        }
8259        return false;
8260    }
8261
8262    /**
8263     * Dispatch a hover event.
8264     * <p>
8265     * Do not call this method directly.
8266     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8267     * </p>
8268     *
8269     * @param event The motion event to be dispatched.
8270     * @return True if the event was handled by the view, false otherwise.
8271     */
8272    protected boolean dispatchHoverEvent(MotionEvent event) {
8273        ListenerInfo li = mListenerInfo;
8274        //noinspection SimplifiableIfStatement
8275        if (li != null && li.mOnHoverListener != null
8276                && (mViewFlags & ENABLED_MASK) == ENABLED
8277                && li.mOnHoverListener.onHover(this, event)) {
8278            return true;
8279        }
8280
8281        return onHoverEvent(event);
8282    }
8283
8284    /**
8285     * Returns true if the view has a child to which it has recently sent
8286     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8287     * it does not have a hovered child, then it must be the innermost hovered view.
8288     * @hide
8289     */
8290    protected boolean hasHoveredChild() {
8291        return false;
8292    }
8293
8294    /**
8295     * Dispatch a generic motion event to the view under the first pointer.
8296     * <p>
8297     * Do not call this method directly.
8298     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8299     * </p>
8300     *
8301     * @param event The motion event to be dispatched.
8302     * @return True if the event was handled by the view, false otherwise.
8303     */
8304    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8305        return false;
8306    }
8307
8308    /**
8309     * Dispatch a generic motion event to the currently focused view.
8310     * <p>
8311     * Do not call this method directly.
8312     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8313     * </p>
8314     *
8315     * @param event The motion event to be dispatched.
8316     * @return True if the event was handled by the view, false otherwise.
8317     */
8318    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8319        return false;
8320    }
8321
8322    /**
8323     * Dispatch a pointer event.
8324     * <p>
8325     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8326     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8327     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8328     * and should not be expected to handle other pointing device features.
8329     * </p>
8330     *
8331     * @param event The motion event to be dispatched.
8332     * @return True if the event was handled by the view, false otherwise.
8333     * @hide
8334     */
8335    public final boolean dispatchPointerEvent(MotionEvent event) {
8336        if (event.isTouchEvent()) {
8337            return dispatchTouchEvent(event);
8338        } else {
8339            return dispatchGenericMotionEvent(event);
8340        }
8341    }
8342
8343    /**
8344     * Called when the window containing this view gains or loses window focus.
8345     * ViewGroups should override to route to their children.
8346     *
8347     * @param hasFocus True if the window containing this view now has focus,
8348     *        false otherwise.
8349     */
8350    public void dispatchWindowFocusChanged(boolean hasFocus) {
8351        onWindowFocusChanged(hasFocus);
8352    }
8353
8354    /**
8355     * Called when the window containing this view gains or loses focus.  Note
8356     * that this is separate from view focus: to receive key events, both
8357     * your view and its window must have focus.  If a window is displayed
8358     * on top of yours that takes input focus, then your own window will lose
8359     * focus but the view focus will remain unchanged.
8360     *
8361     * @param hasWindowFocus True if the window containing this view now has
8362     *        focus, false otherwise.
8363     */
8364    public void onWindowFocusChanged(boolean hasWindowFocus) {
8365        InputMethodManager imm = InputMethodManager.peekInstance();
8366        if (!hasWindowFocus) {
8367            if (isPressed()) {
8368                setPressed(false);
8369            }
8370            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8371                imm.focusOut(this);
8372            }
8373            removeLongPressCallback();
8374            removeTapCallback();
8375            onFocusLost();
8376        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8377            imm.focusIn(this);
8378        }
8379        refreshDrawableState();
8380    }
8381
8382    /**
8383     * Returns true if this view is in a window that currently has window focus.
8384     * Note that this is not the same as the view itself having focus.
8385     *
8386     * @return True if this view is in a window that currently has window focus.
8387     */
8388    public boolean hasWindowFocus() {
8389        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8390    }
8391
8392    /**
8393     * Dispatch a view visibility change down the view hierarchy.
8394     * ViewGroups should override to route to their children.
8395     * @param changedView The view whose visibility changed. Could be 'this' or
8396     * an ancestor view.
8397     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8398     * {@link #INVISIBLE} or {@link #GONE}.
8399     */
8400    protected void dispatchVisibilityChanged(@NonNull View changedView,
8401            @Visibility int visibility) {
8402        onVisibilityChanged(changedView, visibility);
8403    }
8404
8405    /**
8406     * Called when the visibility of the view or an ancestor of the view is changed.
8407     * @param changedView The view whose visibility changed. Could be 'this' or
8408     * an ancestor view.
8409     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8410     * {@link #INVISIBLE} or {@link #GONE}.
8411     */
8412    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8413        if (visibility == VISIBLE) {
8414            if (mAttachInfo != null) {
8415                initialAwakenScrollBars();
8416            } else {
8417                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8418            }
8419        }
8420    }
8421
8422    /**
8423     * Dispatch a hint about whether this view is displayed. For instance, when
8424     * a View moves out of the screen, it might receives a display hint indicating
8425     * the view is not displayed. Applications should not <em>rely</em> on this hint
8426     * as there is no guarantee that they will receive one.
8427     *
8428     * @param hint A hint about whether or not this view is displayed:
8429     * {@link #VISIBLE} or {@link #INVISIBLE}.
8430     */
8431    public void dispatchDisplayHint(@Visibility int hint) {
8432        onDisplayHint(hint);
8433    }
8434
8435    /**
8436     * Gives this view a hint about whether is displayed or not. For instance, when
8437     * a View moves out of the screen, it might receives a display hint indicating
8438     * the view is not displayed. Applications should not <em>rely</em> on this hint
8439     * as there is no guarantee that they will receive one.
8440     *
8441     * @param hint A hint about whether or not this view is displayed:
8442     * {@link #VISIBLE} or {@link #INVISIBLE}.
8443     */
8444    protected void onDisplayHint(@Visibility int hint) {
8445    }
8446
8447    /**
8448     * Dispatch a window visibility change down the view hierarchy.
8449     * ViewGroups should override to route to their children.
8450     *
8451     * @param visibility The new visibility of the window.
8452     *
8453     * @see #onWindowVisibilityChanged(int)
8454     */
8455    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8456        onWindowVisibilityChanged(visibility);
8457    }
8458
8459    /**
8460     * Called when the window containing has change its visibility
8461     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8462     * that this tells you whether or not your window is being made visible
8463     * to the window manager; this does <em>not</em> tell you whether or not
8464     * your window is obscured by other windows on the screen, even if it
8465     * is itself visible.
8466     *
8467     * @param visibility The new visibility of the window.
8468     */
8469    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8470        if (visibility == VISIBLE) {
8471            initialAwakenScrollBars();
8472        }
8473    }
8474
8475    /**
8476     * Returns the current visibility of the window this view is attached to
8477     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8478     *
8479     * @return Returns the current visibility of the view's window.
8480     */
8481    @Visibility
8482    public int getWindowVisibility() {
8483        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8484    }
8485
8486    /**
8487     * Retrieve the overall visible display size in which the window this view is
8488     * attached to has been positioned in.  This takes into account screen
8489     * decorations above the window, for both cases where the window itself
8490     * is being position inside of them or the window is being placed under
8491     * then and covered insets are used for the window to position its content
8492     * inside.  In effect, this tells you the available area where content can
8493     * be placed and remain visible to users.
8494     *
8495     * <p>This function requires an IPC back to the window manager to retrieve
8496     * the requested information, so should not be used in performance critical
8497     * code like drawing.
8498     *
8499     * @param outRect Filled in with the visible display frame.  If the view
8500     * is not attached to a window, this is simply the raw display size.
8501     */
8502    public void getWindowVisibleDisplayFrame(Rect outRect) {
8503        if (mAttachInfo != null) {
8504            try {
8505                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8506            } catch (RemoteException e) {
8507                return;
8508            }
8509            // XXX This is really broken, and probably all needs to be done
8510            // in the window manager, and we need to know more about whether
8511            // we want the area behind or in front of the IME.
8512            final Rect insets = mAttachInfo.mVisibleInsets;
8513            outRect.left += insets.left;
8514            outRect.top += insets.top;
8515            outRect.right -= insets.right;
8516            outRect.bottom -= insets.bottom;
8517            return;
8518        }
8519        // The view is not attached to a display so we don't have a context.
8520        // Make a best guess about the display size.
8521        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8522        d.getRectSize(outRect);
8523    }
8524
8525    /**
8526     * Dispatch a notification about a resource configuration change down
8527     * the view hierarchy.
8528     * ViewGroups should override to route to their children.
8529     *
8530     * @param newConfig The new resource configuration.
8531     *
8532     * @see #onConfigurationChanged(android.content.res.Configuration)
8533     */
8534    public void dispatchConfigurationChanged(Configuration newConfig) {
8535        onConfigurationChanged(newConfig);
8536    }
8537
8538    /**
8539     * Called when the current configuration of the resources being used
8540     * by the application have changed.  You can use this to decide when
8541     * to reload resources that can changed based on orientation and other
8542     * configuration characterstics.  You only need to use this if you are
8543     * not relying on the normal {@link android.app.Activity} mechanism of
8544     * recreating the activity instance upon a configuration change.
8545     *
8546     * @param newConfig The new resource configuration.
8547     */
8548    protected void onConfigurationChanged(Configuration newConfig) {
8549    }
8550
8551    /**
8552     * Private function to aggregate all per-view attributes in to the view
8553     * root.
8554     */
8555    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8556        performCollectViewAttributes(attachInfo, visibility);
8557    }
8558
8559    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8560        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8561            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8562                attachInfo.mKeepScreenOn = true;
8563            }
8564            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8565            ListenerInfo li = mListenerInfo;
8566            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8567                attachInfo.mHasSystemUiListeners = true;
8568            }
8569        }
8570    }
8571
8572    void needGlobalAttributesUpdate(boolean force) {
8573        final AttachInfo ai = mAttachInfo;
8574        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8575            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8576                    || ai.mHasSystemUiListeners) {
8577                ai.mRecomputeGlobalAttributes = true;
8578            }
8579        }
8580    }
8581
8582    /**
8583     * Returns whether the device is currently in touch mode.  Touch mode is entered
8584     * once the user begins interacting with the device by touch, and affects various
8585     * things like whether focus is always visible to the user.
8586     *
8587     * @return Whether the device is in touch mode.
8588     */
8589    @ViewDebug.ExportedProperty
8590    public boolean isInTouchMode() {
8591        if (mAttachInfo != null) {
8592            return mAttachInfo.mInTouchMode;
8593        } else {
8594            return ViewRootImpl.isInTouchMode();
8595        }
8596    }
8597
8598    /**
8599     * Returns the context the view is running in, through which it can
8600     * access the current theme, resources, etc.
8601     *
8602     * @return The view's Context.
8603     */
8604    @ViewDebug.CapturedViewProperty
8605    public final Context getContext() {
8606        return mContext;
8607    }
8608
8609    /**
8610     * Handle a key event before it is processed by any input method
8611     * associated with the view hierarchy.  This can be used to intercept
8612     * key events in special situations before the IME consumes them; a
8613     * typical example would be handling the BACK key to update the application's
8614     * UI instead of allowing the IME to see it and close itself.
8615     *
8616     * @param keyCode The value in event.getKeyCode().
8617     * @param event Description of the key event.
8618     * @return If you handled the event, return true. If you want to allow the
8619     *         event to be handled by the next receiver, return false.
8620     */
8621    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8622        return false;
8623    }
8624
8625    /**
8626     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8627     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8628     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8629     * is released, if the view is enabled and clickable.
8630     *
8631     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8632     * although some may elect to do so in some situations. Do not rely on this to
8633     * catch software key presses.
8634     *
8635     * @param keyCode A key code that represents the button pressed, from
8636     *                {@link android.view.KeyEvent}.
8637     * @param event   The KeyEvent object that defines the button action.
8638     */
8639    public boolean onKeyDown(int keyCode, KeyEvent event) {
8640        boolean result = false;
8641
8642        if (KeyEvent.isConfirmKey(keyCode)) {
8643            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8644                return true;
8645            }
8646            // Long clickable items don't necessarily have to be clickable
8647            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8648                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8649                    (event.getRepeatCount() == 0)) {
8650                setPressed(true);
8651                checkForLongClick(0);
8652                return true;
8653            }
8654        }
8655        return result;
8656    }
8657
8658    /**
8659     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8660     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8661     * the event).
8662     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8663     * although some may elect to do so in some situations. Do not rely on this to
8664     * catch software key presses.
8665     */
8666    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8667        return false;
8668    }
8669
8670    /**
8671     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8672     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8673     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8674     * {@link KeyEvent#KEYCODE_ENTER} is released.
8675     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8676     * although some may elect to do so in some situations. Do not rely on this to
8677     * catch software key presses.
8678     *
8679     * @param keyCode A key code that represents the button pressed, from
8680     *                {@link android.view.KeyEvent}.
8681     * @param event   The KeyEvent object that defines the button action.
8682     */
8683    public boolean onKeyUp(int keyCode, KeyEvent event) {
8684        if (KeyEvent.isConfirmKey(keyCode)) {
8685            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8686                return true;
8687            }
8688            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8689                setPressed(false);
8690
8691                if (!mHasPerformedLongPress) {
8692                    // This is a tap, so remove the longpress check
8693                    removeLongPressCallback();
8694                    return performClick();
8695                }
8696            }
8697        }
8698        return false;
8699    }
8700
8701    /**
8702     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8703     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8704     * the event).
8705     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8706     * although some may elect to do so in some situations. Do not rely on this to
8707     * catch software key presses.
8708     *
8709     * @param keyCode     A key code that represents the button pressed, from
8710     *                    {@link android.view.KeyEvent}.
8711     * @param repeatCount The number of times the action was made.
8712     * @param event       The KeyEvent object that defines the button action.
8713     */
8714    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8715        return false;
8716    }
8717
8718    /**
8719     * Called on the focused view when a key shortcut event is not handled.
8720     * Override this method to implement local key shortcuts for the View.
8721     * Key shortcuts can also be implemented by setting the
8722     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8723     *
8724     * @param keyCode The value in event.getKeyCode().
8725     * @param event Description of the key event.
8726     * @return If you handled the event, return true. If you want to allow the
8727     *         event to be handled by the next receiver, return false.
8728     */
8729    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8730        return false;
8731    }
8732
8733    /**
8734     * Check whether the called view is a text editor, in which case it
8735     * would make sense to automatically display a soft input window for
8736     * it.  Subclasses should override this if they implement
8737     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8738     * a call on that method would return a non-null InputConnection, and
8739     * they are really a first-class editor that the user would normally
8740     * start typing on when the go into a window containing your view.
8741     *
8742     * <p>The default implementation always returns false.  This does
8743     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8744     * will not be called or the user can not otherwise perform edits on your
8745     * view; it is just a hint to the system that this is not the primary
8746     * purpose of this view.
8747     *
8748     * @return Returns true if this view is a text editor, else false.
8749     */
8750    public boolean onCheckIsTextEditor() {
8751        return false;
8752    }
8753
8754    /**
8755     * Create a new InputConnection for an InputMethod to interact
8756     * with the view.  The default implementation returns null, since it doesn't
8757     * support input methods.  You can override this to implement such support.
8758     * This is only needed for views that take focus and text input.
8759     *
8760     * <p>When implementing this, you probably also want to implement
8761     * {@link #onCheckIsTextEditor()} to indicate you will return a
8762     * non-null InputConnection.</p>
8763     *
8764     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8765     * object correctly and in its entirety, so that the connected IME can rely
8766     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8767     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8768     * must be filled in with the correct cursor position for IMEs to work correctly
8769     * with your application.</p>
8770     *
8771     * @param outAttrs Fill in with attribute information about the connection.
8772     */
8773    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8774        return null;
8775    }
8776
8777    /**
8778     * Called by the {@link android.view.inputmethod.InputMethodManager}
8779     * when a view who is not the current
8780     * input connection target is trying to make a call on the manager.  The
8781     * default implementation returns false; you can override this to return
8782     * true for certain views if you are performing InputConnection proxying
8783     * to them.
8784     * @param view The View that is making the InputMethodManager call.
8785     * @return Return true to allow the call, false to reject.
8786     */
8787    public boolean checkInputConnectionProxy(View view) {
8788        return false;
8789    }
8790
8791    /**
8792     * Show the context menu for this view. It is not safe to hold on to the
8793     * menu after returning from this method.
8794     *
8795     * You should normally not overload this method. Overload
8796     * {@link #onCreateContextMenu(ContextMenu)} or define an
8797     * {@link OnCreateContextMenuListener} to add items to the context menu.
8798     *
8799     * @param menu The context menu to populate
8800     */
8801    public void createContextMenu(ContextMenu menu) {
8802        ContextMenuInfo menuInfo = getContextMenuInfo();
8803
8804        // Sets the current menu info so all items added to menu will have
8805        // my extra info set.
8806        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8807
8808        onCreateContextMenu(menu);
8809        ListenerInfo li = mListenerInfo;
8810        if (li != null && li.mOnCreateContextMenuListener != null) {
8811            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8812        }
8813
8814        // Clear the extra information so subsequent items that aren't mine don't
8815        // have my extra info.
8816        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8817
8818        if (mParent != null) {
8819            mParent.createContextMenu(menu);
8820        }
8821    }
8822
8823    /**
8824     * Views should implement this if they have extra information to associate
8825     * with the context menu. The return result is supplied as a parameter to
8826     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8827     * callback.
8828     *
8829     * @return Extra information about the item for which the context menu
8830     *         should be shown. This information will vary across different
8831     *         subclasses of View.
8832     */
8833    protected ContextMenuInfo getContextMenuInfo() {
8834        return null;
8835    }
8836
8837    /**
8838     * Views should implement this if the view itself is going to add items to
8839     * the context menu.
8840     *
8841     * @param menu the context menu to populate
8842     */
8843    protected void onCreateContextMenu(ContextMenu menu) {
8844    }
8845
8846    /**
8847     * Implement this method to handle trackball motion events.  The
8848     * <em>relative</em> movement of the trackball since the last event
8849     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8850     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8851     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8852     * they will often be fractional values, representing the more fine-grained
8853     * movement information available from a trackball).
8854     *
8855     * @param event The motion event.
8856     * @return True if the event was handled, false otherwise.
8857     */
8858    public boolean onTrackballEvent(MotionEvent event) {
8859        return false;
8860    }
8861
8862    /**
8863     * Implement this method to handle generic motion events.
8864     * <p>
8865     * Generic motion events describe joystick movements, mouse hovers, track pad
8866     * touches, scroll wheel movements and other input events.  The
8867     * {@link MotionEvent#getSource() source} of the motion event specifies
8868     * the class of input that was received.  Implementations of this method
8869     * must examine the bits in the source before processing the event.
8870     * The following code example shows how this is done.
8871     * </p><p>
8872     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8873     * are delivered to the view under the pointer.  All other generic motion events are
8874     * delivered to the focused view.
8875     * </p>
8876     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8877     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8878     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8879     *             // process the joystick movement...
8880     *             return true;
8881     *         }
8882     *     }
8883     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8884     *         switch (event.getAction()) {
8885     *             case MotionEvent.ACTION_HOVER_MOVE:
8886     *                 // process the mouse hover movement...
8887     *                 return true;
8888     *             case MotionEvent.ACTION_SCROLL:
8889     *                 // process the scroll wheel movement...
8890     *                 return true;
8891     *         }
8892     *     }
8893     *     return super.onGenericMotionEvent(event);
8894     * }</pre>
8895     *
8896     * @param event The generic motion event being processed.
8897     * @return True if the event was handled, false otherwise.
8898     */
8899    public boolean onGenericMotionEvent(MotionEvent event) {
8900        return false;
8901    }
8902
8903    /**
8904     * Implement this method to handle hover events.
8905     * <p>
8906     * This method is called whenever a pointer is hovering into, over, or out of the
8907     * bounds of a view and the view is not currently being touched.
8908     * Hover events are represented as pointer events with action
8909     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8910     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8911     * </p>
8912     * <ul>
8913     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8914     * when the pointer enters the bounds of the view.</li>
8915     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8916     * when the pointer has already entered the bounds of the view and has moved.</li>
8917     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8918     * when the pointer has exited the bounds of the view or when the pointer is
8919     * about to go down due to a button click, tap, or similar user action that
8920     * causes the view to be touched.</li>
8921     * </ul>
8922     * <p>
8923     * The view should implement this method to return true to indicate that it is
8924     * handling the hover event, such as by changing its drawable state.
8925     * </p><p>
8926     * The default implementation calls {@link #setHovered} to update the hovered state
8927     * of the view when a hover enter or hover exit event is received, if the view
8928     * is enabled and is clickable.  The default implementation also sends hover
8929     * accessibility events.
8930     * </p>
8931     *
8932     * @param event The motion event that describes the hover.
8933     * @return True if the view handled the hover event.
8934     *
8935     * @see #isHovered
8936     * @see #setHovered
8937     * @see #onHoverChanged
8938     */
8939    public boolean onHoverEvent(MotionEvent event) {
8940        // The root view may receive hover (or touch) events that are outside the bounds of
8941        // the window.  This code ensures that we only send accessibility events for
8942        // hovers that are actually within the bounds of the root view.
8943        final int action = event.getActionMasked();
8944        if (!mSendingHoverAccessibilityEvents) {
8945            if ((action == MotionEvent.ACTION_HOVER_ENTER
8946                    || action == MotionEvent.ACTION_HOVER_MOVE)
8947                    && !hasHoveredChild()
8948                    && pointInView(event.getX(), event.getY())) {
8949                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8950                mSendingHoverAccessibilityEvents = true;
8951            }
8952        } else {
8953            if (action == MotionEvent.ACTION_HOVER_EXIT
8954                    || (action == MotionEvent.ACTION_MOVE
8955                            && !pointInView(event.getX(), event.getY()))) {
8956                mSendingHoverAccessibilityEvents = false;
8957                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8958            }
8959        }
8960
8961        if (isHoverable()) {
8962            switch (action) {
8963                case MotionEvent.ACTION_HOVER_ENTER:
8964                    setHovered(true);
8965                    break;
8966                case MotionEvent.ACTION_HOVER_EXIT:
8967                    setHovered(false);
8968                    break;
8969            }
8970
8971            // Dispatch the event to onGenericMotionEvent before returning true.
8972            // This is to provide compatibility with existing applications that
8973            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8974            // break because of the new default handling for hoverable views
8975            // in onHoverEvent.
8976            // Note that onGenericMotionEvent will be called by default when
8977            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8978            dispatchGenericMotionEventInternal(event);
8979            // The event was already handled by calling setHovered(), so always
8980            // return true.
8981            return true;
8982        }
8983
8984        return false;
8985    }
8986
8987    /**
8988     * Returns true if the view should handle {@link #onHoverEvent}
8989     * by calling {@link #setHovered} to change its hovered state.
8990     *
8991     * @return True if the view is hoverable.
8992     */
8993    private boolean isHoverable() {
8994        final int viewFlags = mViewFlags;
8995        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8996            return false;
8997        }
8998
8999        return (viewFlags & CLICKABLE) == CLICKABLE
9000                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9001    }
9002
9003    /**
9004     * Returns true if the view is currently hovered.
9005     *
9006     * @return True if the view is currently hovered.
9007     *
9008     * @see #setHovered
9009     * @see #onHoverChanged
9010     */
9011    @ViewDebug.ExportedProperty
9012    public boolean isHovered() {
9013        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9014    }
9015
9016    /**
9017     * Sets whether the view is currently hovered.
9018     * <p>
9019     * Calling this method also changes the drawable state of the view.  This
9020     * enables the view to react to hover by using different drawable resources
9021     * to change its appearance.
9022     * </p><p>
9023     * The {@link #onHoverChanged} method is called when the hovered state changes.
9024     * </p>
9025     *
9026     * @param hovered True if the view is hovered.
9027     *
9028     * @see #isHovered
9029     * @see #onHoverChanged
9030     */
9031    public void setHovered(boolean hovered) {
9032        if (hovered) {
9033            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9034                mPrivateFlags |= PFLAG_HOVERED;
9035                refreshDrawableState();
9036                onHoverChanged(true);
9037            }
9038        } else {
9039            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9040                mPrivateFlags &= ~PFLAG_HOVERED;
9041                refreshDrawableState();
9042                onHoverChanged(false);
9043            }
9044        }
9045    }
9046
9047    /**
9048     * Implement this method to handle hover state changes.
9049     * <p>
9050     * This method is called whenever the hover state changes as a result of a
9051     * call to {@link #setHovered}.
9052     * </p>
9053     *
9054     * @param hovered The current hover state, as returned by {@link #isHovered}.
9055     *
9056     * @see #isHovered
9057     * @see #setHovered
9058     */
9059    public void onHoverChanged(boolean hovered) {
9060    }
9061
9062    /**
9063     * Implement this method to handle touch screen motion events.
9064     * <p>
9065     * If this method is used to detect click actions, it is recommended that
9066     * the actions be performed by implementing and calling
9067     * {@link #performClick()}. This will ensure consistent system behavior,
9068     * including:
9069     * <ul>
9070     * <li>obeying click sound preferences
9071     * <li>dispatching OnClickListener calls
9072     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9073     * accessibility features are enabled
9074     * </ul>
9075     *
9076     * @param event The motion event.
9077     * @return True if the event was handled, false otherwise.
9078     */
9079    public boolean onTouchEvent(MotionEvent event) {
9080        final float x = event.getX();
9081        final float y = event.getY();
9082        final int viewFlags = mViewFlags;
9083
9084        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9085            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9086                setPressed(false);
9087            }
9088            // A disabled view that is clickable still consumes the touch
9089            // events, it just doesn't respond to them.
9090            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9091                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9092        }
9093
9094        if (mTouchDelegate != null) {
9095            if (mTouchDelegate.onTouchEvent(event)) {
9096                return true;
9097            }
9098        }
9099
9100        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9101                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9102            switch (event.getAction()) {
9103                case MotionEvent.ACTION_UP:
9104                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9105                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9106                        // take focus if we don't have it already and we should in
9107                        // touch mode.
9108                        boolean focusTaken = false;
9109                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9110                            focusTaken = requestFocus();
9111                        }
9112
9113                        if (prepressed) {
9114                            // The button is being released before we actually
9115                            // showed it as pressed.  Make it show the pressed
9116                            // state now (before scheduling the click) to ensure
9117                            // the user sees it.
9118                            setPressed(true, x, y);
9119                       }
9120
9121                        if (!mHasPerformedLongPress) {
9122                            // This is a tap, so remove the longpress check
9123                            removeLongPressCallback();
9124
9125                            // Only perform take click actions if we were in the pressed state
9126                            if (!focusTaken) {
9127                                // Use a Runnable and post this rather than calling
9128                                // performClick directly. This lets other visual state
9129                                // of the view update before click actions start.
9130                                if (mPerformClick == null) {
9131                                    mPerformClick = new PerformClick();
9132                                }
9133                                if (!post(mPerformClick)) {
9134                                    performClick();
9135                                }
9136                            }
9137                        }
9138
9139                        if (mUnsetPressedState == null) {
9140                            mUnsetPressedState = new UnsetPressedState();
9141                        }
9142
9143                        if (prepressed) {
9144                            postDelayed(mUnsetPressedState,
9145                                    ViewConfiguration.getPressedStateDuration());
9146                        } else if (!post(mUnsetPressedState)) {
9147                            // If the post failed, unpress right now
9148                            mUnsetPressedState.run();
9149                        }
9150
9151                        removeTapCallback();
9152                    }
9153                    break;
9154
9155                case MotionEvent.ACTION_DOWN:
9156                    mHasPerformedLongPress = false;
9157
9158                    if (performButtonActionOnTouchDown(event)) {
9159                        break;
9160                    }
9161
9162                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9163                    boolean isInScrollingContainer = isInScrollingContainer();
9164
9165                    // For views inside a scrolling container, delay the pressed feedback for
9166                    // a short period in case this is a scroll.
9167                    if (isInScrollingContainer) {
9168                        mPrivateFlags |= PFLAG_PREPRESSED;
9169                        if (mPendingCheckForTap == null) {
9170                            mPendingCheckForTap = new CheckForTap();
9171                        }
9172                        mPendingCheckForTap.x = event.getX();
9173                        mPendingCheckForTap.y = event.getY();
9174                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9175                    } else {
9176                        // Not inside a scrolling container, so show the feedback right away
9177                        setPressed(true, x, y);
9178                        checkForLongClick(0);
9179                    }
9180                    break;
9181
9182                case MotionEvent.ACTION_CANCEL:
9183                    setPressed(false);
9184                    removeTapCallback();
9185                    removeLongPressCallback();
9186                    break;
9187
9188                case MotionEvent.ACTION_MOVE:
9189                    drawableHotspotChanged(x, y);
9190
9191                    // Be lenient about moving outside of buttons
9192                    if (!pointInView(x, y, mTouchSlop)) {
9193                        // Outside button
9194                        removeTapCallback();
9195                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9196                            // Remove any future long press/tap checks
9197                            removeLongPressCallback();
9198
9199                            setPressed(false);
9200                        }
9201                    }
9202                    break;
9203            }
9204
9205            return true;
9206        }
9207
9208        return false;
9209    }
9210
9211    /**
9212     * @hide
9213     */
9214    public boolean isInScrollingContainer() {
9215        ViewParent p = getParent();
9216        while (p != null && p instanceof ViewGroup) {
9217            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9218                return true;
9219            }
9220            p = p.getParent();
9221        }
9222        return false;
9223    }
9224
9225    /**
9226     * Remove the longpress detection timer.
9227     */
9228    private void removeLongPressCallback() {
9229        if (mPendingCheckForLongPress != null) {
9230          removeCallbacks(mPendingCheckForLongPress);
9231        }
9232    }
9233
9234    /**
9235     * Remove the pending click action
9236     */
9237    private void removePerformClickCallback() {
9238        if (mPerformClick != null) {
9239            removeCallbacks(mPerformClick);
9240        }
9241    }
9242
9243    /**
9244     * Remove the prepress detection timer.
9245     */
9246    private void removeUnsetPressCallback() {
9247        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9248            setPressed(false);
9249            removeCallbacks(mUnsetPressedState);
9250        }
9251    }
9252
9253    /**
9254     * Remove the tap detection timer.
9255     */
9256    private void removeTapCallback() {
9257        if (mPendingCheckForTap != null) {
9258            mPrivateFlags &= ~PFLAG_PREPRESSED;
9259            removeCallbacks(mPendingCheckForTap);
9260        }
9261    }
9262
9263    /**
9264     * Cancels a pending long press.  Your subclass can use this if you
9265     * want the context menu to come up if the user presses and holds
9266     * at the same place, but you don't want it to come up if they press
9267     * and then move around enough to cause scrolling.
9268     */
9269    public void cancelLongPress() {
9270        removeLongPressCallback();
9271
9272        /*
9273         * The prepressed state handled by the tap callback is a display
9274         * construct, but the tap callback will post a long press callback
9275         * less its own timeout. Remove it here.
9276         */
9277        removeTapCallback();
9278    }
9279
9280    /**
9281     * Remove the pending callback for sending a
9282     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9283     */
9284    private void removeSendViewScrolledAccessibilityEventCallback() {
9285        if (mSendViewScrolledAccessibilityEvent != null) {
9286            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9287            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9288        }
9289    }
9290
9291    /**
9292     * Sets the TouchDelegate for this View.
9293     */
9294    public void setTouchDelegate(TouchDelegate delegate) {
9295        mTouchDelegate = delegate;
9296    }
9297
9298    /**
9299     * Gets the TouchDelegate for this View.
9300     */
9301    public TouchDelegate getTouchDelegate() {
9302        return mTouchDelegate;
9303    }
9304
9305    /**
9306     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9307     *
9308     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9309     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9310     * available. This method should only be called for touch events.
9311     *
9312     * <p class="note">This api is not intended for most applications. Buffered dispatch
9313     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9314     * streams will not improve your input latency. Side effects include: increased latency,
9315     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9316     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9317     * you.</p>
9318     */
9319    public final void requestUnbufferedDispatch(MotionEvent event) {
9320        final int action = event.getAction();
9321        if (mAttachInfo == null
9322                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9323                || !event.isTouchEvent()) {
9324            return;
9325        }
9326        mAttachInfo.mUnbufferedDispatchRequested = true;
9327    }
9328
9329    /**
9330     * Set flags controlling behavior of this view.
9331     *
9332     * @param flags Constant indicating the value which should be set
9333     * @param mask Constant indicating the bit range that should be changed
9334     */
9335    void setFlags(int flags, int mask) {
9336        final boolean accessibilityEnabled =
9337                AccessibilityManager.getInstance(mContext).isEnabled();
9338        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9339
9340        int old = mViewFlags;
9341        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9342
9343        int changed = mViewFlags ^ old;
9344        if (changed == 0) {
9345            return;
9346        }
9347        int privateFlags = mPrivateFlags;
9348
9349        /* Check if the FOCUSABLE bit has changed */
9350        if (((changed & FOCUSABLE_MASK) != 0) &&
9351                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9352            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9353                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9354                /* Give up focus if we are no longer focusable */
9355                clearFocus();
9356            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9357                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9358                /*
9359                 * Tell the view system that we are now available to take focus
9360                 * if no one else already has it.
9361                 */
9362                if (mParent != null) mParent.focusableViewAvailable(this);
9363            }
9364        }
9365
9366        final int newVisibility = flags & VISIBILITY_MASK;
9367        if (newVisibility == VISIBLE) {
9368            if ((changed & VISIBILITY_MASK) != 0) {
9369                /*
9370                 * If this view is becoming visible, invalidate it in case it changed while
9371                 * it was not visible. Marking it drawn ensures that the invalidation will
9372                 * go through.
9373                 */
9374                mPrivateFlags |= PFLAG_DRAWN;
9375                invalidate(true);
9376
9377                needGlobalAttributesUpdate(true);
9378
9379                // a view becoming visible is worth notifying the parent
9380                // about in case nothing has focus.  even if this specific view
9381                // isn't focusable, it may contain something that is, so let
9382                // the root view try to give this focus if nothing else does.
9383                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9384                    mParent.focusableViewAvailable(this);
9385                }
9386            }
9387        }
9388
9389        /* Check if the GONE bit has changed */
9390        if ((changed & GONE) != 0) {
9391            needGlobalAttributesUpdate(false);
9392            requestLayout();
9393
9394            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9395                if (hasFocus()) clearFocus();
9396                clearAccessibilityFocus();
9397                destroyDrawingCache();
9398                if (mParent instanceof View) {
9399                    // GONE views noop invalidation, so invalidate the parent
9400                    ((View) mParent).invalidate(true);
9401                }
9402                // Mark the view drawn to ensure that it gets invalidated properly the next
9403                // time it is visible and gets invalidated
9404                mPrivateFlags |= PFLAG_DRAWN;
9405            }
9406            if (mAttachInfo != null) {
9407                mAttachInfo.mViewVisibilityChanged = true;
9408            }
9409        }
9410
9411        /* Check if the VISIBLE bit has changed */
9412        if ((changed & INVISIBLE) != 0) {
9413            needGlobalAttributesUpdate(false);
9414            /*
9415             * If this view is becoming invisible, set the DRAWN flag so that
9416             * the next invalidate() will not be skipped.
9417             */
9418            mPrivateFlags |= PFLAG_DRAWN;
9419
9420            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9421                // root view becoming invisible shouldn't clear focus and accessibility focus
9422                if (getRootView() != this) {
9423                    if (hasFocus()) clearFocus();
9424                    clearAccessibilityFocus();
9425                }
9426            }
9427            if (mAttachInfo != null) {
9428                mAttachInfo.mViewVisibilityChanged = true;
9429            }
9430        }
9431
9432        if ((changed & VISIBILITY_MASK) != 0) {
9433            // If the view is invisible, cleanup its display list to free up resources
9434            if (newVisibility != VISIBLE && mAttachInfo != null) {
9435                cleanupDraw();
9436            }
9437
9438            if (mParent instanceof ViewGroup) {
9439                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9440                        (changed & VISIBILITY_MASK), newVisibility);
9441                ((View) mParent).invalidate(true);
9442            } else if (mParent != null) {
9443                mParent.invalidateChild(this, null);
9444            }
9445            dispatchVisibilityChanged(this, newVisibility);
9446
9447            notifySubtreeAccessibilityStateChangedIfNeeded();
9448        }
9449
9450        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9451            destroyDrawingCache();
9452        }
9453
9454        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9455            destroyDrawingCache();
9456            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9457            invalidateParentCaches();
9458        }
9459
9460        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9461            destroyDrawingCache();
9462            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9463        }
9464
9465        if ((changed & DRAW_MASK) != 0) {
9466            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9467                if (mBackground != null) {
9468                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9469                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9470                } else {
9471                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9472                }
9473            } else {
9474                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9475            }
9476            requestLayout();
9477            invalidate(true);
9478        }
9479
9480        if ((changed & KEEP_SCREEN_ON) != 0) {
9481            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9482                mParent.recomputeViewAttributes(this);
9483            }
9484        }
9485
9486        if (accessibilityEnabled) {
9487            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9488                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9489                if (oldIncludeForAccessibility != includeForAccessibility()) {
9490                    notifySubtreeAccessibilityStateChangedIfNeeded();
9491                } else {
9492                    notifyViewAccessibilityStateChangedIfNeeded(
9493                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9494                }
9495            } else if ((changed & ENABLED_MASK) != 0) {
9496                notifyViewAccessibilityStateChangedIfNeeded(
9497                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9498            }
9499        }
9500    }
9501
9502    /**
9503     * Change the view's z order in the tree, so it's on top of other sibling
9504     * views. This ordering change may affect layout, if the parent container
9505     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9506     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9507     * method should be followed by calls to {@link #requestLayout()} and
9508     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9509     * with the new child ordering.
9510     *
9511     * @see ViewGroup#bringChildToFront(View)
9512     */
9513    public void bringToFront() {
9514        if (mParent != null) {
9515            mParent.bringChildToFront(this);
9516        }
9517    }
9518
9519    /**
9520     * This is called in response to an internal scroll in this view (i.e., the
9521     * view scrolled its own contents). This is typically as a result of
9522     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9523     * called.
9524     *
9525     * @param l Current horizontal scroll origin.
9526     * @param t Current vertical scroll origin.
9527     * @param oldl Previous horizontal scroll origin.
9528     * @param oldt Previous vertical scroll origin.
9529     */
9530    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9531        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9532            postSendViewScrolledAccessibilityEventCallback();
9533        }
9534
9535        mBackgroundSizeChanged = true;
9536
9537        final AttachInfo ai = mAttachInfo;
9538        if (ai != null) {
9539            ai.mViewScrollChanged = true;
9540        }
9541    }
9542
9543    /**
9544     * Interface definition for a callback to be invoked when the layout bounds of a view
9545     * changes due to layout processing.
9546     */
9547    public interface OnLayoutChangeListener {
9548        /**
9549         * Called when the layout bounds of a view changes due to layout processing.
9550         *
9551         * @param v The view whose bounds have changed.
9552         * @param left The new value of the view's left property.
9553         * @param top The new value of the view's top property.
9554         * @param right The new value of the view's right property.
9555         * @param bottom The new value of the view's bottom property.
9556         * @param oldLeft The previous value of the view's left property.
9557         * @param oldTop The previous value of the view's top property.
9558         * @param oldRight The previous value of the view's right property.
9559         * @param oldBottom The previous value of the view's bottom property.
9560         */
9561        void onLayoutChange(View v, int left, int top, int right, int bottom,
9562            int oldLeft, int oldTop, int oldRight, int oldBottom);
9563    }
9564
9565    /**
9566     * This is called during layout when the size of this view has changed. If
9567     * you were just added to the view hierarchy, you're called with the old
9568     * values of 0.
9569     *
9570     * @param w Current width of this view.
9571     * @param h Current height of this view.
9572     * @param oldw Old width of this view.
9573     * @param oldh Old height of this view.
9574     */
9575    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9576    }
9577
9578    /**
9579     * Called by draw to draw the child views. This may be overridden
9580     * by derived classes to gain control just before its children are drawn
9581     * (but after its own view has been drawn).
9582     * @param canvas the canvas on which to draw the view
9583     */
9584    protected void dispatchDraw(Canvas canvas) {
9585
9586    }
9587
9588    /**
9589     * Gets the parent of this view. Note that the parent is a
9590     * ViewParent and not necessarily a View.
9591     *
9592     * @return Parent of this view.
9593     */
9594    public final ViewParent getParent() {
9595        return mParent;
9596    }
9597
9598    /**
9599     * Set the horizontal scrolled position of your view. This will cause a call to
9600     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9601     * invalidated.
9602     * @param value the x position to scroll to
9603     */
9604    public void setScrollX(int value) {
9605        scrollTo(value, mScrollY);
9606    }
9607
9608    /**
9609     * Set the vertical scrolled position of your view. This will cause a call to
9610     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9611     * invalidated.
9612     * @param value the y position to scroll to
9613     */
9614    public void setScrollY(int value) {
9615        scrollTo(mScrollX, value);
9616    }
9617
9618    /**
9619     * Return the scrolled left position of this view. This is the left edge of
9620     * the displayed part of your view. You do not need to draw any pixels
9621     * farther left, since those are outside of the frame of your view on
9622     * screen.
9623     *
9624     * @return The left edge of the displayed part of your view, in pixels.
9625     */
9626    public final int getScrollX() {
9627        return mScrollX;
9628    }
9629
9630    /**
9631     * Return the scrolled top position of this view. This is the top edge of
9632     * the displayed part of your view. You do not need to draw any pixels above
9633     * it, since those are outside of the frame of your view on screen.
9634     *
9635     * @return The top edge of the displayed part of your view, in pixels.
9636     */
9637    public final int getScrollY() {
9638        return mScrollY;
9639    }
9640
9641    /**
9642     * Return the width of the your view.
9643     *
9644     * @return The width of your view, in pixels.
9645     */
9646    @ViewDebug.ExportedProperty(category = "layout")
9647    public final int getWidth() {
9648        return mRight - mLeft;
9649    }
9650
9651    /**
9652     * Return the height of your view.
9653     *
9654     * @return The height of your view, in pixels.
9655     */
9656    @ViewDebug.ExportedProperty(category = "layout")
9657    public final int getHeight() {
9658        return mBottom - mTop;
9659    }
9660
9661    /**
9662     * Return the visible drawing bounds of your view. Fills in the output
9663     * rectangle with the values from getScrollX(), getScrollY(),
9664     * getWidth(), and getHeight(). These bounds do not account for any
9665     * transformation properties currently set on the view, such as
9666     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9667     *
9668     * @param outRect The (scrolled) drawing bounds of the view.
9669     */
9670    public void getDrawingRect(Rect outRect) {
9671        outRect.left = mScrollX;
9672        outRect.top = mScrollY;
9673        outRect.right = mScrollX + (mRight - mLeft);
9674        outRect.bottom = mScrollY + (mBottom - mTop);
9675    }
9676
9677    /**
9678     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9679     * raw width component (that is the result is masked by
9680     * {@link #MEASURED_SIZE_MASK}).
9681     *
9682     * @return The raw measured width of this view.
9683     */
9684    public final int getMeasuredWidth() {
9685        return mMeasuredWidth & MEASURED_SIZE_MASK;
9686    }
9687
9688    /**
9689     * Return the full width measurement information for this view as computed
9690     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9691     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9692     * This should be used during measurement and layout calculations only. Use
9693     * {@link #getWidth()} to see how wide a view is after layout.
9694     *
9695     * @return The measured width of this view as a bit mask.
9696     */
9697    public final int getMeasuredWidthAndState() {
9698        return mMeasuredWidth;
9699    }
9700
9701    /**
9702     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9703     * raw width component (that is the result is masked by
9704     * {@link #MEASURED_SIZE_MASK}).
9705     *
9706     * @return The raw measured height of this view.
9707     */
9708    public final int getMeasuredHeight() {
9709        return mMeasuredHeight & MEASURED_SIZE_MASK;
9710    }
9711
9712    /**
9713     * Return the full height measurement information for this view as computed
9714     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9715     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9716     * This should be used during measurement and layout calculations only. Use
9717     * {@link #getHeight()} to see how wide a view is after layout.
9718     *
9719     * @return The measured width of this view as a bit mask.
9720     */
9721    public final int getMeasuredHeightAndState() {
9722        return mMeasuredHeight;
9723    }
9724
9725    /**
9726     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9727     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9728     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9729     * and the height component is at the shifted bits
9730     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9731     */
9732    public final int getMeasuredState() {
9733        return (mMeasuredWidth&MEASURED_STATE_MASK)
9734                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9735                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9736    }
9737
9738    /**
9739     * The transform matrix of this view, which is calculated based on the current
9740     * rotation, scale, and pivot properties.
9741     *
9742     * @see #getRotation()
9743     * @see #getScaleX()
9744     * @see #getScaleY()
9745     * @see #getPivotX()
9746     * @see #getPivotY()
9747     * @return The current transform matrix for the view
9748     */
9749    public Matrix getMatrix() {
9750        ensureTransformationInfo();
9751        final Matrix matrix = mTransformationInfo.mMatrix;
9752        mRenderNode.getMatrix(matrix);
9753        return matrix;
9754    }
9755
9756    /**
9757     * Returns true if the transform matrix is the identity matrix.
9758     * Recomputes the matrix if necessary.
9759     *
9760     * @return True if the transform matrix is the identity matrix, false otherwise.
9761     */
9762    final boolean hasIdentityMatrix() {
9763        return mRenderNode.hasIdentityMatrix();
9764    }
9765
9766    void ensureTransformationInfo() {
9767        if (mTransformationInfo == null) {
9768            mTransformationInfo = new TransformationInfo();
9769        }
9770    }
9771
9772   /**
9773     * Utility method to retrieve the inverse of the current mMatrix property.
9774     * We cache the matrix to avoid recalculating it when transform properties
9775     * have not changed.
9776     *
9777     * @return The inverse of the current matrix of this view.
9778     */
9779    final Matrix getInverseMatrix() {
9780        ensureTransformationInfo();
9781        if (mTransformationInfo.mInverseMatrix == null) {
9782            mTransformationInfo.mInverseMatrix = new Matrix();
9783        }
9784        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9785        mRenderNode.getInverseMatrix(matrix);
9786        return matrix;
9787    }
9788
9789    /**
9790     * Gets the distance along the Z axis from the camera to this view.
9791     *
9792     * @see #setCameraDistance(float)
9793     *
9794     * @return The distance along the Z axis.
9795     */
9796    public float getCameraDistance() {
9797        final float dpi = mResources.getDisplayMetrics().densityDpi;
9798        return -(mRenderNode.getCameraDistance() * dpi);
9799    }
9800
9801    /**
9802     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9803     * views are drawn) from the camera to this view. The camera's distance
9804     * affects 3D transformations, for instance rotations around the X and Y
9805     * axis. If the rotationX or rotationY properties are changed and this view is
9806     * large (more than half the size of the screen), it is recommended to always
9807     * use a camera distance that's greater than the height (X axis rotation) or
9808     * the width (Y axis rotation) of this view.</p>
9809     *
9810     * <p>The distance of the camera from the view plane can have an affect on the
9811     * perspective distortion of the view when it is rotated around the x or y axis.
9812     * For example, a large distance will result in a large viewing angle, and there
9813     * will not be much perspective distortion of the view as it rotates. A short
9814     * distance may cause much more perspective distortion upon rotation, and can
9815     * also result in some drawing artifacts if the rotated view ends up partially
9816     * behind the camera (which is why the recommendation is to use a distance at
9817     * least as far as the size of the view, if the view is to be rotated.)</p>
9818     *
9819     * <p>The distance is expressed in "depth pixels." The default distance depends
9820     * on the screen density. For instance, on a medium density display, the
9821     * default distance is 1280. On a high density display, the default distance
9822     * is 1920.</p>
9823     *
9824     * <p>If you want to specify a distance that leads to visually consistent
9825     * results across various densities, use the following formula:</p>
9826     * <pre>
9827     * float scale = context.getResources().getDisplayMetrics().density;
9828     * view.setCameraDistance(distance * scale);
9829     * </pre>
9830     *
9831     * <p>The density scale factor of a high density display is 1.5,
9832     * and 1920 = 1280 * 1.5.</p>
9833     *
9834     * @param distance The distance in "depth pixels", if negative the opposite
9835     *        value is used
9836     *
9837     * @see #setRotationX(float)
9838     * @see #setRotationY(float)
9839     */
9840    public void setCameraDistance(float distance) {
9841        final float dpi = mResources.getDisplayMetrics().densityDpi;
9842
9843        invalidateViewProperty(true, false);
9844        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9845        invalidateViewProperty(false, false);
9846
9847        invalidateParentIfNeededAndWasQuickRejected();
9848    }
9849
9850    /**
9851     * The degrees that the view is rotated around the pivot point.
9852     *
9853     * @see #setRotation(float)
9854     * @see #getPivotX()
9855     * @see #getPivotY()
9856     *
9857     * @return The degrees of rotation.
9858     */
9859    @ViewDebug.ExportedProperty(category = "drawing")
9860    public float getRotation() {
9861        return mRenderNode.getRotation();
9862    }
9863
9864    /**
9865     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9866     * result in clockwise rotation.
9867     *
9868     * @param rotation The degrees of rotation.
9869     *
9870     * @see #getRotation()
9871     * @see #getPivotX()
9872     * @see #getPivotY()
9873     * @see #setRotationX(float)
9874     * @see #setRotationY(float)
9875     *
9876     * @attr ref android.R.styleable#View_rotation
9877     */
9878    public void setRotation(float rotation) {
9879        if (rotation != getRotation()) {
9880            // Double-invalidation is necessary to capture view's old and new areas
9881            invalidateViewProperty(true, false);
9882            mRenderNode.setRotation(rotation);
9883            invalidateViewProperty(false, true);
9884
9885            invalidateParentIfNeededAndWasQuickRejected();
9886            notifySubtreeAccessibilityStateChangedIfNeeded();
9887        }
9888    }
9889
9890    /**
9891     * The degrees that the view is rotated around the vertical axis through the pivot point.
9892     *
9893     * @see #getPivotX()
9894     * @see #getPivotY()
9895     * @see #setRotationY(float)
9896     *
9897     * @return The degrees of Y rotation.
9898     */
9899    @ViewDebug.ExportedProperty(category = "drawing")
9900    public float getRotationY() {
9901        return mRenderNode.getRotationY();
9902    }
9903
9904    /**
9905     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9906     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9907     * down the y axis.
9908     *
9909     * When rotating large views, it is recommended to adjust the camera distance
9910     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9911     *
9912     * @param rotationY The degrees of Y rotation.
9913     *
9914     * @see #getRotationY()
9915     * @see #getPivotX()
9916     * @see #getPivotY()
9917     * @see #setRotation(float)
9918     * @see #setRotationX(float)
9919     * @see #setCameraDistance(float)
9920     *
9921     * @attr ref android.R.styleable#View_rotationY
9922     */
9923    public void setRotationY(float rotationY) {
9924        if (rotationY != getRotationY()) {
9925            invalidateViewProperty(true, false);
9926            mRenderNode.setRotationY(rotationY);
9927            invalidateViewProperty(false, true);
9928
9929            invalidateParentIfNeededAndWasQuickRejected();
9930            notifySubtreeAccessibilityStateChangedIfNeeded();
9931        }
9932    }
9933
9934    /**
9935     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9936     *
9937     * @see #getPivotX()
9938     * @see #getPivotY()
9939     * @see #setRotationX(float)
9940     *
9941     * @return The degrees of X rotation.
9942     */
9943    @ViewDebug.ExportedProperty(category = "drawing")
9944    public float getRotationX() {
9945        return mRenderNode.getRotationX();
9946    }
9947
9948    /**
9949     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9950     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9951     * x axis.
9952     *
9953     * When rotating large views, it is recommended to adjust the camera distance
9954     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9955     *
9956     * @param rotationX The degrees of X rotation.
9957     *
9958     * @see #getRotationX()
9959     * @see #getPivotX()
9960     * @see #getPivotY()
9961     * @see #setRotation(float)
9962     * @see #setRotationY(float)
9963     * @see #setCameraDistance(float)
9964     *
9965     * @attr ref android.R.styleable#View_rotationX
9966     */
9967    public void setRotationX(float rotationX) {
9968        if (rotationX != getRotationX()) {
9969            invalidateViewProperty(true, false);
9970            mRenderNode.setRotationX(rotationX);
9971            invalidateViewProperty(false, true);
9972
9973            invalidateParentIfNeededAndWasQuickRejected();
9974            notifySubtreeAccessibilityStateChangedIfNeeded();
9975        }
9976    }
9977
9978    /**
9979     * The amount that the view is scaled in x around the pivot point, as a proportion of
9980     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9981     *
9982     * <p>By default, this is 1.0f.
9983     *
9984     * @see #getPivotX()
9985     * @see #getPivotY()
9986     * @return The scaling factor.
9987     */
9988    @ViewDebug.ExportedProperty(category = "drawing")
9989    public float getScaleX() {
9990        return mRenderNode.getScaleX();
9991    }
9992
9993    /**
9994     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9995     * the view's unscaled width. A value of 1 means that no scaling is applied.
9996     *
9997     * @param scaleX The scaling factor.
9998     * @see #getPivotX()
9999     * @see #getPivotY()
10000     *
10001     * @attr ref android.R.styleable#View_scaleX
10002     */
10003    public void setScaleX(float scaleX) {
10004        if (scaleX != getScaleX()) {
10005            invalidateViewProperty(true, false);
10006            mRenderNode.setScaleX(scaleX);
10007            invalidateViewProperty(false, true);
10008
10009            invalidateParentIfNeededAndWasQuickRejected();
10010            notifySubtreeAccessibilityStateChangedIfNeeded();
10011        }
10012    }
10013
10014    /**
10015     * The amount that the view is scaled in y around the pivot point, as a proportion of
10016     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10017     *
10018     * <p>By default, this is 1.0f.
10019     *
10020     * @see #getPivotX()
10021     * @see #getPivotY()
10022     * @return The scaling factor.
10023     */
10024    @ViewDebug.ExportedProperty(category = "drawing")
10025    public float getScaleY() {
10026        return mRenderNode.getScaleY();
10027    }
10028
10029    /**
10030     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10031     * the view's unscaled width. A value of 1 means that no scaling is applied.
10032     *
10033     * @param scaleY The scaling factor.
10034     * @see #getPivotX()
10035     * @see #getPivotY()
10036     *
10037     * @attr ref android.R.styleable#View_scaleY
10038     */
10039    public void setScaleY(float scaleY) {
10040        if (scaleY != getScaleY()) {
10041            invalidateViewProperty(true, false);
10042            mRenderNode.setScaleY(scaleY);
10043            invalidateViewProperty(false, true);
10044
10045            invalidateParentIfNeededAndWasQuickRejected();
10046            notifySubtreeAccessibilityStateChangedIfNeeded();
10047        }
10048    }
10049
10050    /**
10051     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10052     * and {@link #setScaleX(float) scaled}.
10053     *
10054     * @see #getRotation()
10055     * @see #getScaleX()
10056     * @see #getScaleY()
10057     * @see #getPivotY()
10058     * @return The x location of the pivot point.
10059     *
10060     * @attr ref android.R.styleable#View_transformPivotX
10061     */
10062    @ViewDebug.ExportedProperty(category = "drawing")
10063    public float getPivotX() {
10064        return mRenderNode.getPivotX();
10065    }
10066
10067    /**
10068     * Sets the x location of the point around which the view is
10069     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10070     * By default, the pivot point is centered on the object.
10071     * Setting this property disables this behavior and causes the view to use only the
10072     * explicitly set pivotX and pivotY values.
10073     *
10074     * @param pivotX The x location of the pivot point.
10075     * @see #getRotation()
10076     * @see #getScaleX()
10077     * @see #getScaleY()
10078     * @see #getPivotY()
10079     *
10080     * @attr ref android.R.styleable#View_transformPivotX
10081     */
10082    public void setPivotX(float pivotX) {
10083        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10084            invalidateViewProperty(true, false);
10085            mRenderNode.setPivotX(pivotX);
10086            invalidateViewProperty(false, true);
10087
10088            invalidateParentIfNeededAndWasQuickRejected();
10089        }
10090    }
10091
10092    /**
10093     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10094     * and {@link #setScaleY(float) scaled}.
10095     *
10096     * @see #getRotation()
10097     * @see #getScaleX()
10098     * @see #getScaleY()
10099     * @see #getPivotY()
10100     * @return The y location of the pivot point.
10101     *
10102     * @attr ref android.R.styleable#View_transformPivotY
10103     */
10104    @ViewDebug.ExportedProperty(category = "drawing")
10105    public float getPivotY() {
10106        return mRenderNode.getPivotY();
10107    }
10108
10109    /**
10110     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10111     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10112     * Setting this property disables this behavior and causes the view to use only the
10113     * explicitly set pivotX and pivotY values.
10114     *
10115     * @param pivotY The y location of the pivot point.
10116     * @see #getRotation()
10117     * @see #getScaleX()
10118     * @see #getScaleY()
10119     * @see #getPivotY()
10120     *
10121     * @attr ref android.R.styleable#View_transformPivotY
10122     */
10123    public void setPivotY(float pivotY) {
10124        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10125            invalidateViewProperty(true, false);
10126            mRenderNode.setPivotY(pivotY);
10127            invalidateViewProperty(false, true);
10128
10129            invalidateParentIfNeededAndWasQuickRejected();
10130        }
10131    }
10132
10133    /**
10134     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10135     * completely transparent and 1 means the view is completely opaque.
10136     *
10137     * <p>By default this is 1.0f.
10138     * @return The opacity of the view.
10139     */
10140    @ViewDebug.ExportedProperty(category = "drawing")
10141    public float getAlpha() {
10142        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10143    }
10144
10145    /**
10146     * Returns whether this View has content which overlaps.
10147     *
10148     * <p>This function, intended to be overridden by specific View types, is an optimization when
10149     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10150     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10151     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10152     * directly. An example of overlapping rendering is a TextView with a background image, such as
10153     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10154     * ImageView with only the foreground image. The default implementation returns true; subclasses
10155     * should override if they have cases which can be optimized.</p>
10156     *
10157     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10158     * necessitates that a View return true if it uses the methods internally without passing the
10159     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10160     *
10161     * @return true if the content in this view might overlap, false otherwise.
10162     */
10163    public boolean hasOverlappingRendering() {
10164        return true;
10165    }
10166
10167    /**
10168     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10169     * completely transparent and 1 means the view is completely opaque.</p>
10170     *
10171     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10172     * performance implications, especially for large views. It is best to use the alpha property
10173     * sparingly and transiently, as in the case of fading animations.</p>
10174     *
10175     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10176     * strongly recommended for performance reasons to either override
10177     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10178     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10179     *
10180     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10181     * responsible for applying the opacity itself.</p>
10182     *
10183     * <p>Note that if the view is backed by a
10184     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10185     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10186     * 1.0 will supercede the alpha of the layer paint.</p>
10187     *
10188     * @param alpha The opacity of the view.
10189     *
10190     * @see #hasOverlappingRendering()
10191     * @see #setLayerType(int, android.graphics.Paint)
10192     *
10193     * @attr ref android.R.styleable#View_alpha
10194     */
10195    public void setAlpha(float alpha) {
10196        ensureTransformationInfo();
10197        if (mTransformationInfo.mAlpha != alpha) {
10198            mTransformationInfo.mAlpha = alpha;
10199            if (onSetAlpha((int) (alpha * 255))) {
10200                mPrivateFlags |= PFLAG_ALPHA_SET;
10201                // subclass is handling alpha - don't optimize rendering cache invalidation
10202                invalidateParentCaches();
10203                invalidate(true);
10204            } else {
10205                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10206                invalidateViewProperty(true, false);
10207                mRenderNode.setAlpha(getFinalAlpha());
10208                notifyViewAccessibilityStateChangedIfNeeded(
10209                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10210            }
10211        }
10212    }
10213
10214    /**
10215     * Faster version of setAlpha() which performs the same steps except there are
10216     * no calls to invalidate(). The caller of this function should perform proper invalidation
10217     * on the parent and this object. The return value indicates whether the subclass handles
10218     * alpha (the return value for onSetAlpha()).
10219     *
10220     * @param alpha The new value for the alpha property
10221     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10222     *         the new value for the alpha property is different from the old value
10223     */
10224    boolean setAlphaNoInvalidation(float alpha) {
10225        ensureTransformationInfo();
10226        if (mTransformationInfo.mAlpha != alpha) {
10227            mTransformationInfo.mAlpha = alpha;
10228            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10229            if (subclassHandlesAlpha) {
10230                mPrivateFlags |= PFLAG_ALPHA_SET;
10231                return true;
10232            } else {
10233                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10234                mRenderNode.setAlpha(getFinalAlpha());
10235            }
10236        }
10237        return false;
10238    }
10239
10240    /**
10241     * This property is hidden and intended only for use by the Fade transition, which
10242     * animates it to produce a visual translucency that does not side-effect (or get
10243     * affected by) the real alpha property. This value is composited with the other
10244     * alpha value (and the AlphaAnimation value, when that is present) to produce
10245     * a final visual translucency result, which is what is passed into the DisplayList.
10246     *
10247     * @hide
10248     */
10249    public void setTransitionAlpha(float alpha) {
10250        ensureTransformationInfo();
10251        if (mTransformationInfo.mTransitionAlpha != alpha) {
10252            mTransformationInfo.mTransitionAlpha = alpha;
10253            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10254            invalidateViewProperty(true, false);
10255            mRenderNode.setAlpha(getFinalAlpha());
10256        }
10257    }
10258
10259    /**
10260     * Calculates the visual alpha of this view, which is a combination of the actual
10261     * alpha value and the transitionAlpha value (if set).
10262     */
10263    private float getFinalAlpha() {
10264        if (mTransformationInfo != null) {
10265            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10266        }
10267        return 1;
10268    }
10269
10270    /**
10271     * This property is hidden and intended only for use by the Fade transition, which
10272     * animates it to produce a visual translucency that does not side-effect (or get
10273     * affected by) the real alpha property. This value is composited with the other
10274     * alpha value (and the AlphaAnimation value, when that is present) to produce
10275     * a final visual translucency result, which is what is passed into the DisplayList.
10276     *
10277     * @hide
10278     */
10279    public float getTransitionAlpha() {
10280        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10281    }
10282
10283    /**
10284     * Top position of this view relative to its parent.
10285     *
10286     * @return The top of this view, in pixels.
10287     */
10288    @ViewDebug.CapturedViewProperty
10289    public final int getTop() {
10290        return mTop;
10291    }
10292
10293    /**
10294     * Sets the top position of this view relative to its parent. This method is meant to be called
10295     * by the layout system and should not generally be called otherwise, because the property
10296     * may be changed at any time by the layout.
10297     *
10298     * @param top The top of this view, in pixels.
10299     */
10300    public final void setTop(int top) {
10301        if (top != mTop) {
10302            final boolean matrixIsIdentity = hasIdentityMatrix();
10303            if (matrixIsIdentity) {
10304                if (mAttachInfo != null) {
10305                    int minTop;
10306                    int yLoc;
10307                    if (top < mTop) {
10308                        minTop = top;
10309                        yLoc = top - mTop;
10310                    } else {
10311                        minTop = mTop;
10312                        yLoc = 0;
10313                    }
10314                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10315                }
10316            } else {
10317                // Double-invalidation is necessary to capture view's old and new areas
10318                invalidate(true);
10319            }
10320
10321            int width = mRight - mLeft;
10322            int oldHeight = mBottom - mTop;
10323
10324            mTop = top;
10325            mRenderNode.setTop(mTop);
10326
10327            sizeChange(width, mBottom - mTop, width, oldHeight);
10328
10329            if (!matrixIsIdentity) {
10330                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10331                invalidate(true);
10332            }
10333            mBackgroundSizeChanged = true;
10334            invalidateParentIfNeeded();
10335            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10336                // View was rejected last time it was drawn by its parent; this may have changed
10337                invalidateParentIfNeeded();
10338            }
10339        }
10340    }
10341
10342    /**
10343     * Bottom position of this view relative to its parent.
10344     *
10345     * @return The bottom of this view, in pixels.
10346     */
10347    @ViewDebug.CapturedViewProperty
10348    public final int getBottom() {
10349        return mBottom;
10350    }
10351
10352    /**
10353     * True if this view has changed since the last time being drawn.
10354     *
10355     * @return The dirty state of this view.
10356     */
10357    public boolean isDirty() {
10358        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10359    }
10360
10361    /**
10362     * Sets the bottom position of this view relative to its parent. This method is meant to be
10363     * called by the layout system and should not generally be called otherwise, because the
10364     * property may be changed at any time by the layout.
10365     *
10366     * @param bottom The bottom of this view, in pixels.
10367     */
10368    public final void setBottom(int bottom) {
10369        if (bottom != mBottom) {
10370            final boolean matrixIsIdentity = hasIdentityMatrix();
10371            if (matrixIsIdentity) {
10372                if (mAttachInfo != null) {
10373                    int maxBottom;
10374                    if (bottom < mBottom) {
10375                        maxBottom = mBottom;
10376                    } else {
10377                        maxBottom = bottom;
10378                    }
10379                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10380                }
10381            } else {
10382                // Double-invalidation is necessary to capture view's old and new areas
10383                invalidate(true);
10384            }
10385
10386            int width = mRight - mLeft;
10387            int oldHeight = mBottom - mTop;
10388
10389            mBottom = bottom;
10390            mRenderNode.setBottom(mBottom);
10391
10392            sizeChange(width, mBottom - mTop, width, oldHeight);
10393
10394            if (!matrixIsIdentity) {
10395                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10396                invalidate(true);
10397            }
10398            mBackgroundSizeChanged = true;
10399            invalidateParentIfNeeded();
10400            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10401                // View was rejected last time it was drawn by its parent; this may have changed
10402                invalidateParentIfNeeded();
10403            }
10404        }
10405    }
10406
10407    /**
10408     * Left position of this view relative to its parent.
10409     *
10410     * @return The left edge of this view, in pixels.
10411     */
10412    @ViewDebug.CapturedViewProperty
10413    public final int getLeft() {
10414        return mLeft;
10415    }
10416
10417    /**
10418     * Sets the left position of this view relative to its parent. This method is meant to be called
10419     * by the layout system and should not generally be called otherwise, because the property
10420     * may be changed at any time by the layout.
10421     *
10422     * @param left The left of this view, in pixels.
10423     */
10424    public final void setLeft(int left) {
10425        if (left != mLeft) {
10426            final boolean matrixIsIdentity = hasIdentityMatrix();
10427            if (matrixIsIdentity) {
10428                if (mAttachInfo != null) {
10429                    int minLeft;
10430                    int xLoc;
10431                    if (left < mLeft) {
10432                        minLeft = left;
10433                        xLoc = left - mLeft;
10434                    } else {
10435                        minLeft = mLeft;
10436                        xLoc = 0;
10437                    }
10438                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10439                }
10440            } else {
10441                // Double-invalidation is necessary to capture view's old and new areas
10442                invalidate(true);
10443            }
10444
10445            int oldWidth = mRight - mLeft;
10446            int height = mBottom - mTop;
10447
10448            mLeft = left;
10449            mRenderNode.setLeft(left);
10450
10451            sizeChange(mRight - mLeft, height, oldWidth, height);
10452
10453            if (!matrixIsIdentity) {
10454                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10455                invalidate(true);
10456            }
10457            mBackgroundSizeChanged = true;
10458            invalidateParentIfNeeded();
10459            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10460                // View was rejected last time it was drawn by its parent; this may have changed
10461                invalidateParentIfNeeded();
10462            }
10463        }
10464    }
10465
10466    /**
10467     * Right position of this view relative to its parent.
10468     *
10469     * @return The right edge of this view, in pixels.
10470     */
10471    @ViewDebug.CapturedViewProperty
10472    public final int getRight() {
10473        return mRight;
10474    }
10475
10476    /**
10477     * Sets the right position of this view relative to its parent. This method is meant to be called
10478     * by the layout system and should not generally be called otherwise, because the property
10479     * may be changed at any time by the layout.
10480     *
10481     * @param right The right of this view, in pixels.
10482     */
10483    public final void setRight(int right) {
10484        if (right != mRight) {
10485            final boolean matrixIsIdentity = hasIdentityMatrix();
10486            if (matrixIsIdentity) {
10487                if (mAttachInfo != null) {
10488                    int maxRight;
10489                    if (right < mRight) {
10490                        maxRight = mRight;
10491                    } else {
10492                        maxRight = right;
10493                    }
10494                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10495                }
10496            } else {
10497                // Double-invalidation is necessary to capture view's old and new areas
10498                invalidate(true);
10499            }
10500
10501            int oldWidth = mRight - mLeft;
10502            int height = mBottom - mTop;
10503
10504            mRight = right;
10505            mRenderNode.setRight(mRight);
10506
10507            sizeChange(mRight - mLeft, height, oldWidth, height);
10508
10509            if (!matrixIsIdentity) {
10510                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10511                invalidate(true);
10512            }
10513            mBackgroundSizeChanged = true;
10514            invalidateParentIfNeeded();
10515            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10516                // View was rejected last time it was drawn by its parent; this may have changed
10517                invalidateParentIfNeeded();
10518            }
10519        }
10520    }
10521
10522    /**
10523     * The visual x position of this view, in pixels. This is equivalent to the
10524     * {@link #setTranslationX(float) translationX} property plus the current
10525     * {@link #getLeft() left} property.
10526     *
10527     * @return The visual x position of this view, in pixels.
10528     */
10529    @ViewDebug.ExportedProperty(category = "drawing")
10530    public float getX() {
10531        return mLeft + getTranslationX();
10532    }
10533
10534    /**
10535     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10536     * {@link #setTranslationX(float) translationX} property to be the difference between
10537     * the x value passed in and the current {@link #getLeft() left} property.
10538     *
10539     * @param x The visual x position of this view, in pixels.
10540     */
10541    public void setX(float x) {
10542        setTranslationX(x - mLeft);
10543    }
10544
10545    /**
10546     * The visual y position of this view, in pixels. This is equivalent to the
10547     * {@link #setTranslationY(float) translationY} property plus the current
10548     * {@link #getTop() top} property.
10549     *
10550     * @return The visual y position of this view, in pixels.
10551     */
10552    @ViewDebug.ExportedProperty(category = "drawing")
10553    public float getY() {
10554        return mTop + getTranslationY();
10555    }
10556
10557    /**
10558     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10559     * {@link #setTranslationY(float) translationY} property to be the difference between
10560     * the y value passed in and the current {@link #getTop() top} property.
10561     *
10562     * @param y The visual y position of this view, in pixels.
10563     */
10564    public void setY(float y) {
10565        setTranslationY(y - mTop);
10566    }
10567
10568    /**
10569     * The visual z position of this view, in pixels. This is equivalent to the
10570     * {@link #setTranslationZ(float) translationZ} property plus the current
10571     * {@link #getElevation() elevation} property.
10572     *
10573     * @return The visual z position of this view, in pixels.
10574     */
10575    @ViewDebug.ExportedProperty(category = "drawing")
10576    public float getZ() {
10577        return getElevation() + getTranslationZ();
10578    }
10579
10580    /**
10581     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10582     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10583     * the x value passed in and the current {@link #getElevation() elevation} property.
10584     *
10585     * @param z The visual z position of this view, in pixels.
10586     */
10587    public void setZ(float z) {
10588        setTranslationZ(z - getElevation());
10589    }
10590
10591    /**
10592     * The base elevation of this view relative to its parent, in pixels.
10593     *
10594     * @return The base depth position of the view, in pixels.
10595     */
10596    @ViewDebug.ExportedProperty(category = "drawing")
10597    public float getElevation() {
10598        return mRenderNode.getElevation();
10599    }
10600
10601    /**
10602     * Sets the base elevation of this view, in pixels.
10603     *
10604     * @attr ref android.R.styleable#View_elevation
10605     */
10606    public void setElevation(float elevation) {
10607        if (elevation != getElevation()) {
10608            invalidateViewProperty(true, false);
10609            mRenderNode.setElevation(elevation);
10610            invalidateViewProperty(false, true);
10611
10612            invalidateParentIfNeededAndWasQuickRejected();
10613        }
10614    }
10615
10616    /**
10617     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10618     * This position is post-layout, in addition to wherever the object's
10619     * layout placed it.
10620     *
10621     * @return The horizontal position of this view relative to its left position, in pixels.
10622     */
10623    @ViewDebug.ExportedProperty(category = "drawing")
10624    public float getTranslationX() {
10625        return mRenderNode.getTranslationX();
10626    }
10627
10628    /**
10629     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10630     * This effectively positions the object post-layout, in addition to wherever the object's
10631     * layout placed it.
10632     *
10633     * @param translationX The horizontal position of this view relative to its left position,
10634     * in pixels.
10635     *
10636     * @attr ref android.R.styleable#View_translationX
10637     */
10638    public void setTranslationX(float translationX) {
10639        if (translationX != getTranslationX()) {
10640            invalidateViewProperty(true, false);
10641            mRenderNode.setTranslationX(translationX);
10642            invalidateViewProperty(false, true);
10643
10644            invalidateParentIfNeededAndWasQuickRejected();
10645            notifySubtreeAccessibilityStateChangedIfNeeded();
10646        }
10647    }
10648
10649    /**
10650     * The vertical location of this view relative to its {@link #getTop() top} position.
10651     * This position is post-layout, in addition to wherever the object's
10652     * layout placed it.
10653     *
10654     * @return The vertical position of this view relative to its top position,
10655     * in pixels.
10656     */
10657    @ViewDebug.ExportedProperty(category = "drawing")
10658    public float getTranslationY() {
10659        return mRenderNode.getTranslationY();
10660    }
10661
10662    /**
10663     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10664     * This effectively positions the object post-layout, in addition to wherever the object's
10665     * layout placed it.
10666     *
10667     * @param translationY The vertical position of this view relative to its top position,
10668     * in pixels.
10669     *
10670     * @attr ref android.R.styleable#View_translationY
10671     */
10672    public void setTranslationY(float translationY) {
10673        if (translationY != getTranslationY()) {
10674            invalidateViewProperty(true, false);
10675            mRenderNode.setTranslationY(translationY);
10676            invalidateViewProperty(false, true);
10677
10678            invalidateParentIfNeededAndWasQuickRejected();
10679        }
10680    }
10681
10682    /**
10683     * The depth location of this view relative to its {@link #getElevation() elevation}.
10684     *
10685     * @return The depth of this view relative to its elevation.
10686     */
10687    @ViewDebug.ExportedProperty(category = "drawing")
10688    public float getTranslationZ() {
10689        return mRenderNode.getTranslationZ();
10690    }
10691
10692    /**
10693     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10694     *
10695     * @attr ref android.R.styleable#View_translationZ
10696     */
10697    public void setTranslationZ(float translationZ) {
10698        if (translationZ != getTranslationZ()) {
10699            invalidateViewProperty(true, false);
10700            mRenderNode.setTranslationZ(translationZ);
10701            invalidateViewProperty(false, true);
10702
10703            invalidateParentIfNeededAndWasQuickRejected();
10704        }
10705    }
10706
10707    /**
10708     * Returns a ValueAnimator which can animate a clearing circle.
10709     * <p>
10710     * The View is prevented from drawing within the circle, so the content
10711     * behind the View shows through.
10712     *
10713     * @param centerX The x coordinate of the center of the animating circle.
10714     * @param centerY The y coordinate of the center of the animating circle.
10715     * @param startRadius The starting radius of the animating circle.
10716     * @param endRadius The ending radius of the animating circle.
10717     *
10718     * @hide
10719     */
10720    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10721            float startRadius, float endRadius) {
10722        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10723                startRadius, endRadius, true);
10724    }
10725
10726    /**
10727     * Returns the current StateListAnimator if exists.
10728     *
10729     * @return StateListAnimator or null if it does not exists
10730     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10731     */
10732    public StateListAnimator getStateListAnimator() {
10733        return mStateListAnimator;
10734    }
10735
10736    /**
10737     * Attaches the provided StateListAnimator to this View.
10738     * <p>
10739     * Any previously attached StateListAnimator will be detached.
10740     *
10741     * @param stateListAnimator The StateListAnimator to update the view
10742     * @see {@link android.animation.StateListAnimator}
10743     */
10744    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10745        if (mStateListAnimator == stateListAnimator) {
10746            return;
10747        }
10748        if (mStateListAnimator != null) {
10749            mStateListAnimator.setTarget(null);
10750        }
10751        mStateListAnimator = stateListAnimator;
10752        if (stateListAnimator != null) {
10753            stateListAnimator.setTarget(this);
10754            if (isAttachedToWindow()) {
10755                stateListAnimator.setState(getDrawableState());
10756            }
10757        }
10758    }
10759
10760    /**
10761     * Sets the {@link Outline} of the view, which defines the shape of the shadow it
10762     * casts, and enables outline clipping.
10763     * <p>
10764     * By default, a View queries its Outline from its background drawable, via
10765     * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows
10766     * this behavior to be overridden.
10767     * <p>
10768     * If the outline is {@link Outline#isEmpty()} or is <code>null</code>,
10769     * shadows will not be cast.
10770     * <p>
10771     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10772     *
10773     * @param outline The new outline of the view.
10774     *
10775     * @see #setClipToOutline(boolean)
10776     * @see #getClipToOutline()
10777     */
10778    public void setOutline(@Nullable Outline outline) {
10779        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10780
10781        if (outline == null || outline.isEmpty()) {
10782            if (mOutline != null) {
10783                mOutline.setEmpty();
10784            }
10785        } else {
10786            // always copy the path since caller may reuse
10787            if (mOutline == null) {
10788                mOutline = new Outline();
10789            }
10790            mOutline.set(outline);
10791        }
10792        mRenderNode.setOutline(mOutline);
10793    }
10794
10795    /**
10796     * Returns whether the Outline should be used to clip the contents of the View.
10797     * <p>
10798     * Note that this flag will only be respected if the View's Outline returns true from
10799     * {@link Outline#canClip()}.
10800     *
10801     * @see #setOutline(Outline)
10802     * @see #setClipToOutline(boolean)
10803     */
10804    public final boolean getClipToOutline() {
10805        return mRenderNode.getClipToOutline();
10806    }
10807
10808    /**
10809     * Sets whether the View's Outline should be used to clip the contents of the View.
10810     * <p>
10811     * Note that this flag will only be respected if the View's Outline returns true from
10812     * {@link Outline#canClip()}.
10813     *
10814     * @see #setOutline(Outline)
10815     * @see #getClipToOutline()
10816     */
10817    public void setClipToOutline(boolean clipToOutline) {
10818        damageInParent();
10819        if (getClipToOutline() != clipToOutline) {
10820            mRenderNode.setClipToOutline(clipToOutline);
10821        }
10822    }
10823
10824    private void queryOutlineFromBackgroundIfUndefined() {
10825        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
10826            // Outline not currently defined, query from background
10827            if (mOutline == null) {
10828                mOutline = new Outline();
10829            } else {
10830                //invalidate outline, to ensure background calculates it
10831                mOutline.setEmpty();
10832            }
10833            if (mBackground.getOutline(mOutline)) {
10834                if (mOutline.isEmpty()) {
10835                    throw new IllegalStateException("Background drawable failed to build outline");
10836                }
10837                mRenderNode.setOutline(mOutline);
10838            } else {
10839                mRenderNode.setOutline(null);
10840            }
10841            notifySubtreeAccessibilityStateChangedIfNeeded();
10842        }
10843    }
10844
10845    /**
10846     * Private API to be used for reveal animation
10847     *
10848     * @hide
10849     */
10850    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10851            float x, float y, float radius) {
10852        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10853        // TODO: Handle this invalidate in a better way, or purely in native.
10854        invalidate();
10855    }
10856
10857    /**
10858     * Hit rectangle in parent's coordinates
10859     *
10860     * @param outRect The hit rectangle of the view.
10861     */
10862    public void getHitRect(Rect outRect) {
10863        if (hasIdentityMatrix() || mAttachInfo == null) {
10864            outRect.set(mLeft, mTop, mRight, mBottom);
10865        } else {
10866            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10867            tmpRect.set(0, 0, getWidth(), getHeight());
10868            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10869            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10870                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10871        }
10872    }
10873
10874    /**
10875     * Determines whether the given point, in local coordinates is inside the view.
10876     */
10877    /*package*/ final boolean pointInView(float localX, float localY) {
10878        return localX >= 0 && localX < (mRight - mLeft)
10879                && localY >= 0 && localY < (mBottom - mTop);
10880    }
10881
10882    /**
10883     * Utility method to determine whether the given point, in local coordinates,
10884     * is inside the view, where the area of the view is expanded by the slop factor.
10885     * This method is called while processing touch-move events to determine if the event
10886     * is still within the view.
10887     *
10888     * @hide
10889     */
10890    public boolean pointInView(float localX, float localY, float slop) {
10891        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10892                localY < ((mBottom - mTop) + slop);
10893    }
10894
10895    /**
10896     * When a view has focus and the user navigates away from it, the next view is searched for
10897     * starting from the rectangle filled in by this method.
10898     *
10899     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10900     * of the view.  However, if your view maintains some idea of internal selection,
10901     * such as a cursor, or a selected row or column, you should override this method and
10902     * fill in a more specific rectangle.
10903     *
10904     * @param r The rectangle to fill in, in this view's coordinates.
10905     */
10906    public void getFocusedRect(Rect r) {
10907        getDrawingRect(r);
10908    }
10909
10910    /**
10911     * If some part of this view is not clipped by any of its parents, then
10912     * return that area in r in global (root) coordinates. To convert r to local
10913     * coordinates (without taking possible View rotations into account), offset
10914     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10915     * If the view is completely clipped or translated out, return false.
10916     *
10917     * @param r If true is returned, r holds the global coordinates of the
10918     *        visible portion of this view.
10919     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10920     *        between this view and its root. globalOffet may be null.
10921     * @return true if r is non-empty (i.e. part of the view is visible at the
10922     *         root level.
10923     */
10924    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10925        int width = mRight - mLeft;
10926        int height = mBottom - mTop;
10927        if (width > 0 && height > 0) {
10928            r.set(0, 0, width, height);
10929            if (globalOffset != null) {
10930                globalOffset.set(-mScrollX, -mScrollY);
10931            }
10932            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10933        }
10934        return false;
10935    }
10936
10937    public final boolean getGlobalVisibleRect(Rect r) {
10938        return getGlobalVisibleRect(r, null);
10939    }
10940
10941    public final boolean getLocalVisibleRect(Rect r) {
10942        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10943        if (getGlobalVisibleRect(r, offset)) {
10944            r.offset(-offset.x, -offset.y); // make r local
10945            return true;
10946        }
10947        return false;
10948    }
10949
10950    /**
10951     * Offset this view's vertical location by the specified number of pixels.
10952     *
10953     * @param offset the number of pixels to offset the view by
10954     */
10955    public void offsetTopAndBottom(int offset) {
10956        if (offset != 0) {
10957            final boolean matrixIsIdentity = hasIdentityMatrix();
10958            if (matrixIsIdentity) {
10959                if (isHardwareAccelerated()) {
10960                    invalidateViewProperty(false, false);
10961                } else {
10962                    final ViewParent p = mParent;
10963                    if (p != null && mAttachInfo != null) {
10964                        final Rect r = mAttachInfo.mTmpInvalRect;
10965                        int minTop;
10966                        int maxBottom;
10967                        int yLoc;
10968                        if (offset < 0) {
10969                            minTop = mTop + offset;
10970                            maxBottom = mBottom;
10971                            yLoc = offset;
10972                        } else {
10973                            minTop = mTop;
10974                            maxBottom = mBottom + offset;
10975                            yLoc = 0;
10976                        }
10977                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10978                        p.invalidateChild(this, r);
10979                    }
10980                }
10981            } else {
10982                invalidateViewProperty(false, false);
10983            }
10984
10985            mTop += offset;
10986            mBottom += offset;
10987            mRenderNode.offsetTopAndBottom(offset);
10988            if (isHardwareAccelerated()) {
10989                invalidateViewProperty(false, false);
10990            } else {
10991                if (!matrixIsIdentity) {
10992                    invalidateViewProperty(false, true);
10993                }
10994                invalidateParentIfNeeded();
10995            }
10996            notifySubtreeAccessibilityStateChangedIfNeeded();
10997        }
10998    }
10999
11000    /**
11001     * Offset this view's horizontal location by the specified amount of pixels.
11002     *
11003     * @param offset the number of pixels to offset the view by
11004     */
11005    public void offsetLeftAndRight(int offset) {
11006        if (offset != 0) {
11007            final boolean matrixIsIdentity = hasIdentityMatrix();
11008            if (matrixIsIdentity) {
11009                if (isHardwareAccelerated()) {
11010                    invalidateViewProperty(false, false);
11011                } else {
11012                    final ViewParent p = mParent;
11013                    if (p != null && mAttachInfo != null) {
11014                        final Rect r = mAttachInfo.mTmpInvalRect;
11015                        int minLeft;
11016                        int maxRight;
11017                        if (offset < 0) {
11018                            minLeft = mLeft + offset;
11019                            maxRight = mRight;
11020                        } else {
11021                            minLeft = mLeft;
11022                            maxRight = mRight + offset;
11023                        }
11024                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11025                        p.invalidateChild(this, r);
11026                    }
11027                }
11028            } else {
11029                invalidateViewProperty(false, false);
11030            }
11031
11032            mLeft += offset;
11033            mRight += offset;
11034            mRenderNode.offsetLeftAndRight(offset);
11035            if (isHardwareAccelerated()) {
11036                invalidateViewProperty(false, false);
11037            } else {
11038                if (!matrixIsIdentity) {
11039                    invalidateViewProperty(false, true);
11040                }
11041                invalidateParentIfNeeded();
11042            }
11043            notifySubtreeAccessibilityStateChangedIfNeeded();
11044        }
11045    }
11046
11047    /**
11048     * Get the LayoutParams associated with this view. All views should have
11049     * layout parameters. These supply parameters to the <i>parent</i> of this
11050     * view specifying how it should be arranged. There are many subclasses of
11051     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11052     * of ViewGroup that are responsible for arranging their children.
11053     *
11054     * This method may return null if this View is not attached to a parent
11055     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11056     * was not invoked successfully. When a View is attached to a parent
11057     * ViewGroup, this method must not return null.
11058     *
11059     * @return The LayoutParams associated with this view, or null if no
11060     *         parameters have been set yet
11061     */
11062    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11063    public ViewGroup.LayoutParams getLayoutParams() {
11064        return mLayoutParams;
11065    }
11066
11067    /**
11068     * Set the layout parameters associated with this view. These supply
11069     * parameters to the <i>parent</i> of this view specifying how it should be
11070     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11071     * correspond to the different subclasses of ViewGroup that are responsible
11072     * for arranging their children.
11073     *
11074     * @param params The layout parameters for this view, cannot be null
11075     */
11076    public void setLayoutParams(ViewGroup.LayoutParams params) {
11077        if (params == null) {
11078            throw new NullPointerException("Layout parameters cannot be null");
11079        }
11080        mLayoutParams = params;
11081        resolveLayoutParams();
11082        if (mParent instanceof ViewGroup) {
11083            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11084        }
11085        requestLayout();
11086    }
11087
11088    /**
11089     * Resolve the layout parameters depending on the resolved layout direction
11090     *
11091     * @hide
11092     */
11093    public void resolveLayoutParams() {
11094        if (mLayoutParams != null) {
11095            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11096        }
11097    }
11098
11099    /**
11100     * Set the scrolled position of your view. This will cause a call to
11101     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11102     * invalidated.
11103     * @param x the x position to scroll to
11104     * @param y the y position to scroll to
11105     */
11106    public void scrollTo(int x, int y) {
11107        if (mScrollX != x || mScrollY != y) {
11108            int oldX = mScrollX;
11109            int oldY = mScrollY;
11110            mScrollX = x;
11111            mScrollY = y;
11112            invalidateParentCaches();
11113            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11114            if (!awakenScrollBars()) {
11115                postInvalidateOnAnimation();
11116            }
11117        }
11118    }
11119
11120    /**
11121     * Move the scrolled position of your view. This will cause a call to
11122     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11123     * invalidated.
11124     * @param x the amount of pixels to scroll by horizontally
11125     * @param y the amount of pixels to scroll by vertically
11126     */
11127    public void scrollBy(int x, int y) {
11128        scrollTo(mScrollX + x, mScrollY + y);
11129    }
11130
11131    /**
11132     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11133     * animation to fade the scrollbars out after a default delay. If a subclass
11134     * provides animated scrolling, the start delay should equal the duration
11135     * of the scrolling animation.</p>
11136     *
11137     * <p>The animation starts only if at least one of the scrollbars is
11138     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11139     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11140     * this method returns true, and false otherwise. If the animation is
11141     * started, this method calls {@link #invalidate()}; in that case the
11142     * caller should not call {@link #invalidate()}.</p>
11143     *
11144     * <p>This method should be invoked every time a subclass directly updates
11145     * the scroll parameters.</p>
11146     *
11147     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11148     * and {@link #scrollTo(int, int)}.</p>
11149     *
11150     * @return true if the animation is played, false otherwise
11151     *
11152     * @see #awakenScrollBars(int)
11153     * @see #scrollBy(int, int)
11154     * @see #scrollTo(int, int)
11155     * @see #isHorizontalScrollBarEnabled()
11156     * @see #isVerticalScrollBarEnabled()
11157     * @see #setHorizontalScrollBarEnabled(boolean)
11158     * @see #setVerticalScrollBarEnabled(boolean)
11159     */
11160    protected boolean awakenScrollBars() {
11161        return mScrollCache != null &&
11162                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11163    }
11164
11165    /**
11166     * Trigger the scrollbars to draw.
11167     * This method differs from awakenScrollBars() only in its default duration.
11168     * initialAwakenScrollBars() will show the scroll bars for longer than
11169     * usual to give the user more of a chance to notice them.
11170     *
11171     * @return true if the animation is played, false otherwise.
11172     */
11173    private boolean initialAwakenScrollBars() {
11174        return mScrollCache != null &&
11175                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11176    }
11177
11178    /**
11179     * <p>
11180     * Trigger the scrollbars to draw. When invoked this method starts an
11181     * animation to fade the scrollbars out after a fixed delay. If a subclass
11182     * provides animated scrolling, the start delay should equal the duration of
11183     * the scrolling animation.
11184     * </p>
11185     *
11186     * <p>
11187     * The animation starts only if at least one of the scrollbars is enabled,
11188     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11189     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11190     * this method returns true, and false otherwise. If the animation is
11191     * started, this method calls {@link #invalidate()}; in that case the caller
11192     * should not call {@link #invalidate()}.
11193     * </p>
11194     *
11195     * <p>
11196     * This method should be invoked everytime a subclass directly updates the
11197     * scroll parameters.
11198     * </p>
11199     *
11200     * @param startDelay the delay, in milliseconds, after which the animation
11201     *        should start; when the delay is 0, the animation starts
11202     *        immediately
11203     * @return true if the animation is played, false otherwise
11204     *
11205     * @see #scrollBy(int, int)
11206     * @see #scrollTo(int, int)
11207     * @see #isHorizontalScrollBarEnabled()
11208     * @see #isVerticalScrollBarEnabled()
11209     * @see #setHorizontalScrollBarEnabled(boolean)
11210     * @see #setVerticalScrollBarEnabled(boolean)
11211     */
11212    protected boolean awakenScrollBars(int startDelay) {
11213        return awakenScrollBars(startDelay, true);
11214    }
11215
11216    /**
11217     * <p>
11218     * Trigger the scrollbars to draw. When invoked this method starts an
11219     * animation to fade the scrollbars out after a fixed delay. If a subclass
11220     * provides animated scrolling, the start delay should equal the duration of
11221     * the scrolling animation.
11222     * </p>
11223     *
11224     * <p>
11225     * The animation starts only if at least one of the scrollbars is enabled,
11226     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11227     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11228     * this method returns true, and false otherwise. If the animation is
11229     * started, this method calls {@link #invalidate()} if the invalidate parameter
11230     * is set to true; in that case the caller
11231     * should not call {@link #invalidate()}.
11232     * </p>
11233     *
11234     * <p>
11235     * This method should be invoked everytime a subclass directly updates the
11236     * scroll parameters.
11237     * </p>
11238     *
11239     * @param startDelay the delay, in milliseconds, after which the animation
11240     *        should start; when the delay is 0, the animation starts
11241     *        immediately
11242     *
11243     * @param invalidate Wheter this method should call invalidate
11244     *
11245     * @return true if the animation is played, false otherwise
11246     *
11247     * @see #scrollBy(int, int)
11248     * @see #scrollTo(int, int)
11249     * @see #isHorizontalScrollBarEnabled()
11250     * @see #isVerticalScrollBarEnabled()
11251     * @see #setHorizontalScrollBarEnabled(boolean)
11252     * @see #setVerticalScrollBarEnabled(boolean)
11253     */
11254    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11255        final ScrollabilityCache scrollCache = mScrollCache;
11256
11257        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11258            return false;
11259        }
11260
11261        if (scrollCache.scrollBar == null) {
11262            scrollCache.scrollBar = new ScrollBarDrawable();
11263        }
11264
11265        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11266
11267            if (invalidate) {
11268                // Invalidate to show the scrollbars
11269                postInvalidateOnAnimation();
11270            }
11271
11272            if (scrollCache.state == ScrollabilityCache.OFF) {
11273                // FIXME: this is copied from WindowManagerService.
11274                // We should get this value from the system when it
11275                // is possible to do so.
11276                final int KEY_REPEAT_FIRST_DELAY = 750;
11277                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11278            }
11279
11280            // Tell mScrollCache when we should start fading. This may
11281            // extend the fade start time if one was already scheduled
11282            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11283            scrollCache.fadeStartTime = fadeStartTime;
11284            scrollCache.state = ScrollabilityCache.ON;
11285
11286            // Schedule our fader to run, unscheduling any old ones first
11287            if (mAttachInfo != null) {
11288                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11289                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11290            }
11291
11292            return true;
11293        }
11294
11295        return false;
11296    }
11297
11298    /**
11299     * Do not invalidate views which are not visible and which are not running an animation. They
11300     * will not get drawn and they should not set dirty flags as if they will be drawn
11301     */
11302    private boolean skipInvalidate() {
11303        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11304                (!(mParent instanceof ViewGroup) ||
11305                        !((ViewGroup) mParent).isViewTransitioning(this));
11306    }
11307
11308    /**
11309     * Mark the area defined by dirty as needing to be drawn. If the view is
11310     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11311     * point in the future.
11312     * <p>
11313     * This must be called from a UI thread. To call from a non-UI thread, call
11314     * {@link #postInvalidate()}.
11315     * <p>
11316     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11317     * {@code dirty}.
11318     *
11319     * @param dirty the rectangle representing the bounds of the dirty region
11320     */
11321    public void invalidate(Rect dirty) {
11322        final int scrollX = mScrollX;
11323        final int scrollY = mScrollY;
11324        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11325                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11326    }
11327
11328    /**
11329     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11330     * coordinates of the dirty rect are relative to the view. If the view is
11331     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11332     * point in the future.
11333     * <p>
11334     * This must be called from a UI thread. To call from a non-UI thread, call
11335     * {@link #postInvalidate()}.
11336     *
11337     * @param l the left position of the dirty region
11338     * @param t the top position of the dirty region
11339     * @param r the right position of the dirty region
11340     * @param b the bottom position of the dirty region
11341     */
11342    public void invalidate(int l, int t, int r, int b) {
11343        final int scrollX = mScrollX;
11344        final int scrollY = mScrollY;
11345        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11346    }
11347
11348    /**
11349     * Invalidate the whole view. If the view is visible,
11350     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11351     * the future.
11352     * <p>
11353     * This must be called from a UI thread. To call from a non-UI thread, call
11354     * {@link #postInvalidate()}.
11355     */
11356    public void invalidate() {
11357        invalidate(true);
11358    }
11359
11360    /**
11361     * This is where the invalidate() work actually happens. A full invalidate()
11362     * causes the drawing cache to be invalidated, but this function can be
11363     * called with invalidateCache set to false to skip that invalidation step
11364     * for cases that do not need it (for example, a component that remains at
11365     * the same dimensions with the same content).
11366     *
11367     * @param invalidateCache Whether the drawing cache for this view should be
11368     *            invalidated as well. This is usually true for a full
11369     *            invalidate, but may be set to false if the View's contents or
11370     *            dimensions have not changed.
11371     */
11372    void invalidate(boolean invalidateCache) {
11373        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11374    }
11375
11376    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11377            boolean fullInvalidate) {
11378        if (skipInvalidate()) {
11379            return;
11380        }
11381
11382        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11383                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11384                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11385                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11386            if (fullInvalidate) {
11387                mLastIsOpaque = isOpaque();
11388                mPrivateFlags &= ~PFLAG_DRAWN;
11389            }
11390
11391            mPrivateFlags |= PFLAG_DIRTY;
11392
11393            if (invalidateCache) {
11394                mPrivateFlags |= PFLAG_INVALIDATED;
11395                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11396            }
11397
11398            // Propagate the damage rectangle to the parent view.
11399            final AttachInfo ai = mAttachInfo;
11400            final ViewParent p = mParent;
11401            if (p != null && ai != null && l < r && t < b) {
11402                final Rect damage = ai.mTmpInvalRect;
11403                damage.set(l, t, r, b);
11404                p.invalidateChild(this, damage);
11405            }
11406
11407            // Damage the entire projection receiver, if necessary.
11408            if (mBackground != null && mBackground.isProjected()) {
11409                final View receiver = getProjectionReceiver();
11410                if (receiver != null) {
11411                    receiver.damageInParent();
11412                }
11413            }
11414
11415            // Damage the entire IsolatedZVolume recieving this view's shadow.
11416            if (isHardwareAccelerated() && getZ() != 0) {
11417                damageShadowReceiver();
11418            }
11419        }
11420    }
11421
11422    /**
11423     * @return this view's projection receiver, or {@code null} if none exists
11424     */
11425    private View getProjectionReceiver() {
11426        ViewParent p = getParent();
11427        while (p != null && p instanceof View) {
11428            final View v = (View) p;
11429            if (v.isProjectionReceiver()) {
11430                return v;
11431            }
11432            p = p.getParent();
11433        }
11434
11435        return null;
11436    }
11437
11438    /**
11439     * @return whether the view is a projection receiver
11440     */
11441    private boolean isProjectionReceiver() {
11442        return mBackground != null;
11443    }
11444
11445    /**
11446     * Damage area of the screen that can be covered by this View's shadow.
11447     *
11448     * This method will guarantee that any changes to shadows cast by a View
11449     * are damaged on the screen for future redraw.
11450     */
11451    private void damageShadowReceiver() {
11452        final AttachInfo ai = mAttachInfo;
11453        if (ai != null) {
11454            ViewParent p = getParent();
11455            if (p != null && p instanceof ViewGroup) {
11456                final ViewGroup vg = (ViewGroup) p;
11457                vg.damageInParent();
11458            }
11459        }
11460    }
11461
11462    /**
11463     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11464     * set any flags or handle all of the cases handled by the default invalidation methods.
11465     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11466     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11467     * walk up the hierarchy, transforming the dirty rect as necessary.
11468     *
11469     * The method also handles normal invalidation logic if display list properties are not
11470     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11471     * backup approach, to handle these cases used in the various property-setting methods.
11472     *
11473     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11474     * are not being used in this view
11475     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11476     * list properties are not being used in this view
11477     */
11478    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11479        if (!isHardwareAccelerated()
11480                || !mRenderNode.isValid()
11481                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11482            if (invalidateParent) {
11483                invalidateParentCaches();
11484            }
11485            if (forceRedraw) {
11486                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11487            }
11488            invalidate(false);
11489        } else {
11490            damageInParent();
11491        }
11492        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11493            damageShadowReceiver();
11494        }
11495    }
11496
11497    /**
11498     * Tells the parent view to damage this view's bounds.
11499     *
11500     * @hide
11501     */
11502    protected void damageInParent() {
11503        final AttachInfo ai = mAttachInfo;
11504        final ViewParent p = mParent;
11505        if (p != null && ai != null) {
11506            final Rect r = ai.mTmpInvalRect;
11507            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11508            if (mParent instanceof ViewGroup) {
11509                ((ViewGroup) mParent).damageChild(this, r);
11510            } else {
11511                mParent.invalidateChild(this, r);
11512            }
11513        }
11514    }
11515
11516    /**
11517     * Utility method to transform a given Rect by the current matrix of this view.
11518     */
11519    void transformRect(final Rect rect) {
11520        if (!getMatrix().isIdentity()) {
11521            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11522            boundingRect.set(rect);
11523            getMatrix().mapRect(boundingRect);
11524            rect.set((int) Math.floor(boundingRect.left),
11525                    (int) Math.floor(boundingRect.top),
11526                    (int) Math.ceil(boundingRect.right),
11527                    (int) Math.ceil(boundingRect.bottom));
11528        }
11529    }
11530
11531    /**
11532     * Used to indicate that the parent of this view should clear its caches. This functionality
11533     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11534     * which is necessary when various parent-managed properties of the view change, such as
11535     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11536     * clears the parent caches and does not causes an invalidate event.
11537     *
11538     * @hide
11539     */
11540    protected void invalidateParentCaches() {
11541        if (mParent instanceof View) {
11542            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11543        }
11544    }
11545
11546    /**
11547     * Used to indicate that the parent of this view should be invalidated. This functionality
11548     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11549     * which is necessary when various parent-managed properties of the view change, such as
11550     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11551     * an invalidation event to the parent.
11552     *
11553     * @hide
11554     */
11555    protected void invalidateParentIfNeeded() {
11556        if (isHardwareAccelerated() && mParent instanceof View) {
11557            ((View) mParent).invalidate(true);
11558        }
11559    }
11560
11561    /**
11562     * @hide
11563     */
11564    protected void invalidateParentIfNeededAndWasQuickRejected() {
11565        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11566            // View was rejected last time it was drawn by its parent; this may have changed
11567            invalidateParentIfNeeded();
11568        }
11569    }
11570
11571    /**
11572     * Indicates whether this View is opaque. An opaque View guarantees that it will
11573     * draw all the pixels overlapping its bounds using a fully opaque color.
11574     *
11575     * Subclasses of View should override this method whenever possible to indicate
11576     * whether an instance is opaque. Opaque Views are treated in a special way by
11577     * the View hierarchy, possibly allowing it to perform optimizations during
11578     * invalidate/draw passes.
11579     *
11580     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11581     */
11582    @ViewDebug.ExportedProperty(category = "drawing")
11583    public boolean isOpaque() {
11584        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11585                getFinalAlpha() >= 1.0f;
11586    }
11587
11588    /**
11589     * @hide
11590     */
11591    protected void computeOpaqueFlags() {
11592        // Opaque if:
11593        //   - Has a background
11594        //   - Background is opaque
11595        //   - Doesn't have scrollbars or scrollbars overlay
11596
11597        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11598            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11599        } else {
11600            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11601        }
11602
11603        final int flags = mViewFlags;
11604        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11605                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11606                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11607            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11608        } else {
11609            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11610        }
11611    }
11612
11613    /**
11614     * @hide
11615     */
11616    protected boolean hasOpaqueScrollbars() {
11617        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11618    }
11619
11620    /**
11621     * @return A handler associated with the thread running the View. This
11622     * handler can be used to pump events in the UI events queue.
11623     */
11624    public Handler getHandler() {
11625        final AttachInfo attachInfo = mAttachInfo;
11626        if (attachInfo != null) {
11627            return attachInfo.mHandler;
11628        }
11629        return null;
11630    }
11631
11632    /**
11633     * Gets the view root associated with the View.
11634     * @return The view root, or null if none.
11635     * @hide
11636     */
11637    public ViewRootImpl getViewRootImpl() {
11638        if (mAttachInfo != null) {
11639            return mAttachInfo.mViewRootImpl;
11640        }
11641        return null;
11642    }
11643
11644    /**
11645     * @hide
11646     */
11647    public HardwareRenderer getHardwareRenderer() {
11648        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11649    }
11650
11651    /**
11652     * <p>Causes the Runnable to be added to the message queue.
11653     * The runnable will be run on the user interface thread.</p>
11654     *
11655     * @param action The Runnable that will be executed.
11656     *
11657     * @return Returns true if the Runnable was successfully placed in to the
11658     *         message queue.  Returns false on failure, usually because the
11659     *         looper processing the message queue is exiting.
11660     *
11661     * @see #postDelayed
11662     * @see #removeCallbacks
11663     */
11664    public boolean post(Runnable action) {
11665        final AttachInfo attachInfo = mAttachInfo;
11666        if (attachInfo != null) {
11667            return attachInfo.mHandler.post(action);
11668        }
11669        // Assume that post will succeed later
11670        ViewRootImpl.getRunQueue().post(action);
11671        return true;
11672    }
11673
11674    /**
11675     * <p>Causes the Runnable to be added to the message queue, to be run
11676     * after the specified amount of time elapses.
11677     * The runnable will be run on the user interface thread.</p>
11678     *
11679     * @param action The Runnable that will be executed.
11680     * @param delayMillis The delay (in milliseconds) until the Runnable
11681     *        will be executed.
11682     *
11683     * @return true if the Runnable was successfully placed in to the
11684     *         message queue.  Returns false on failure, usually because the
11685     *         looper processing the message queue is exiting.  Note that a
11686     *         result of true does not mean the Runnable will be processed --
11687     *         if the looper is quit before the delivery time of the message
11688     *         occurs then the message will be dropped.
11689     *
11690     * @see #post
11691     * @see #removeCallbacks
11692     */
11693    public boolean postDelayed(Runnable action, long delayMillis) {
11694        final AttachInfo attachInfo = mAttachInfo;
11695        if (attachInfo != null) {
11696            return attachInfo.mHandler.postDelayed(action, delayMillis);
11697        }
11698        // Assume that post will succeed later
11699        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11700        return true;
11701    }
11702
11703    /**
11704     * <p>Causes the Runnable to execute on the next animation time step.
11705     * The runnable will be run on the user interface thread.</p>
11706     *
11707     * @param action The Runnable that will be executed.
11708     *
11709     * @see #postOnAnimationDelayed
11710     * @see #removeCallbacks
11711     */
11712    public void postOnAnimation(Runnable action) {
11713        final AttachInfo attachInfo = mAttachInfo;
11714        if (attachInfo != null) {
11715            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11716                    Choreographer.CALLBACK_ANIMATION, action, null);
11717        } else {
11718            // Assume that post will succeed later
11719            ViewRootImpl.getRunQueue().post(action);
11720        }
11721    }
11722
11723    /**
11724     * <p>Causes the Runnable to execute on the next animation time step,
11725     * after the specified amount of time elapses.
11726     * The runnable will be run on the user interface thread.</p>
11727     *
11728     * @param action The Runnable that will be executed.
11729     * @param delayMillis The delay (in milliseconds) until the Runnable
11730     *        will be executed.
11731     *
11732     * @see #postOnAnimation
11733     * @see #removeCallbacks
11734     */
11735    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11736        final AttachInfo attachInfo = mAttachInfo;
11737        if (attachInfo != null) {
11738            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11739                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11740        } else {
11741            // Assume that post will succeed later
11742            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11743        }
11744    }
11745
11746    /**
11747     * <p>Removes the specified Runnable from the message queue.</p>
11748     *
11749     * @param action The Runnable to remove from the message handling queue
11750     *
11751     * @return true if this view could ask the Handler to remove the Runnable,
11752     *         false otherwise. When the returned value is true, the Runnable
11753     *         may or may not have been actually removed from the message queue
11754     *         (for instance, if the Runnable was not in the queue already.)
11755     *
11756     * @see #post
11757     * @see #postDelayed
11758     * @see #postOnAnimation
11759     * @see #postOnAnimationDelayed
11760     */
11761    public boolean removeCallbacks(Runnable action) {
11762        if (action != null) {
11763            final AttachInfo attachInfo = mAttachInfo;
11764            if (attachInfo != null) {
11765                attachInfo.mHandler.removeCallbacks(action);
11766                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11767                        Choreographer.CALLBACK_ANIMATION, action, null);
11768            }
11769            // Assume that post will succeed later
11770            ViewRootImpl.getRunQueue().removeCallbacks(action);
11771        }
11772        return true;
11773    }
11774
11775    /**
11776     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11777     * Use this to invalidate the View from a non-UI thread.</p>
11778     *
11779     * <p>This method can be invoked from outside of the UI thread
11780     * only when this View is attached to a window.</p>
11781     *
11782     * @see #invalidate()
11783     * @see #postInvalidateDelayed(long)
11784     */
11785    public void postInvalidate() {
11786        postInvalidateDelayed(0);
11787    }
11788
11789    /**
11790     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11791     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11792     *
11793     * <p>This method can be invoked from outside of the UI thread
11794     * only when this View is attached to a window.</p>
11795     *
11796     * @param left The left coordinate of the rectangle to invalidate.
11797     * @param top The top coordinate of the rectangle to invalidate.
11798     * @param right The right coordinate of the rectangle to invalidate.
11799     * @param bottom The bottom coordinate of the rectangle to invalidate.
11800     *
11801     * @see #invalidate(int, int, int, int)
11802     * @see #invalidate(Rect)
11803     * @see #postInvalidateDelayed(long, int, int, int, int)
11804     */
11805    public void postInvalidate(int left, int top, int right, int bottom) {
11806        postInvalidateDelayed(0, left, top, right, bottom);
11807    }
11808
11809    /**
11810     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11811     * loop. Waits for the specified amount of time.</p>
11812     *
11813     * <p>This method can be invoked from outside of the UI thread
11814     * only when this View is attached to a window.</p>
11815     *
11816     * @param delayMilliseconds the duration in milliseconds to delay the
11817     *         invalidation by
11818     *
11819     * @see #invalidate()
11820     * @see #postInvalidate()
11821     */
11822    public void postInvalidateDelayed(long delayMilliseconds) {
11823        // We try only with the AttachInfo because there's no point in invalidating
11824        // if we are not attached to our window
11825        final AttachInfo attachInfo = mAttachInfo;
11826        if (attachInfo != null) {
11827            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11828        }
11829    }
11830
11831    /**
11832     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11833     * through the event loop. Waits for the specified amount of time.</p>
11834     *
11835     * <p>This method can be invoked from outside of the UI thread
11836     * only when this View is attached to a window.</p>
11837     *
11838     * @param delayMilliseconds the duration in milliseconds to delay the
11839     *         invalidation by
11840     * @param left The left coordinate of the rectangle to invalidate.
11841     * @param top The top coordinate of the rectangle to invalidate.
11842     * @param right The right coordinate of the rectangle to invalidate.
11843     * @param bottom The bottom coordinate of the rectangle to invalidate.
11844     *
11845     * @see #invalidate(int, int, int, int)
11846     * @see #invalidate(Rect)
11847     * @see #postInvalidate(int, int, int, int)
11848     */
11849    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11850            int right, int bottom) {
11851
11852        // We try only with the AttachInfo because there's no point in invalidating
11853        // if we are not attached to our window
11854        final AttachInfo attachInfo = mAttachInfo;
11855        if (attachInfo != null) {
11856            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11857            info.target = this;
11858            info.left = left;
11859            info.top = top;
11860            info.right = right;
11861            info.bottom = bottom;
11862
11863            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11864        }
11865    }
11866
11867    /**
11868     * <p>Cause an invalidate to happen on the next animation time step, typically the
11869     * next display frame.</p>
11870     *
11871     * <p>This method can be invoked from outside of the UI thread
11872     * only when this View is attached to a window.</p>
11873     *
11874     * @see #invalidate()
11875     */
11876    public void postInvalidateOnAnimation() {
11877        // We try only with the AttachInfo because there's no point in invalidating
11878        // if we are not attached to our window
11879        final AttachInfo attachInfo = mAttachInfo;
11880        if (attachInfo != null) {
11881            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11882        }
11883    }
11884
11885    /**
11886     * <p>Cause an invalidate of the specified area to happen on the next animation
11887     * time step, typically the next display frame.</p>
11888     *
11889     * <p>This method can be invoked from outside of the UI thread
11890     * only when this View is attached to a window.</p>
11891     *
11892     * @param left The left coordinate of the rectangle to invalidate.
11893     * @param top The top coordinate of the rectangle to invalidate.
11894     * @param right The right coordinate of the rectangle to invalidate.
11895     * @param bottom The bottom coordinate of the rectangle to invalidate.
11896     *
11897     * @see #invalidate(int, int, int, int)
11898     * @see #invalidate(Rect)
11899     */
11900    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11901        // We try only with the AttachInfo because there's no point in invalidating
11902        // if we are not attached to our window
11903        final AttachInfo attachInfo = mAttachInfo;
11904        if (attachInfo != null) {
11905            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11906            info.target = this;
11907            info.left = left;
11908            info.top = top;
11909            info.right = right;
11910            info.bottom = bottom;
11911
11912            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11913        }
11914    }
11915
11916    /**
11917     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11918     * This event is sent at most once every
11919     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11920     */
11921    private void postSendViewScrolledAccessibilityEventCallback() {
11922        if (mSendViewScrolledAccessibilityEvent == null) {
11923            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11924        }
11925        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11926            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11927            postDelayed(mSendViewScrolledAccessibilityEvent,
11928                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11929        }
11930    }
11931
11932    /**
11933     * Called by a parent to request that a child update its values for mScrollX
11934     * and mScrollY if necessary. This will typically be done if the child is
11935     * animating a scroll using a {@link android.widget.Scroller Scroller}
11936     * object.
11937     */
11938    public void computeScroll() {
11939    }
11940
11941    /**
11942     * <p>Indicate whether the horizontal edges are faded when the view is
11943     * scrolled horizontally.</p>
11944     *
11945     * @return true if the horizontal edges should are faded on scroll, false
11946     *         otherwise
11947     *
11948     * @see #setHorizontalFadingEdgeEnabled(boolean)
11949     *
11950     * @attr ref android.R.styleable#View_requiresFadingEdge
11951     */
11952    public boolean isHorizontalFadingEdgeEnabled() {
11953        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11954    }
11955
11956    /**
11957     * <p>Define whether the horizontal edges should be faded when this view
11958     * is scrolled horizontally.</p>
11959     *
11960     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11961     *                                    be faded when the view is scrolled
11962     *                                    horizontally
11963     *
11964     * @see #isHorizontalFadingEdgeEnabled()
11965     *
11966     * @attr ref android.R.styleable#View_requiresFadingEdge
11967     */
11968    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11969        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11970            if (horizontalFadingEdgeEnabled) {
11971                initScrollCache();
11972            }
11973
11974            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11975        }
11976    }
11977
11978    /**
11979     * <p>Indicate whether the vertical edges are faded when the view is
11980     * scrolled horizontally.</p>
11981     *
11982     * @return true if the vertical edges should are faded on scroll, false
11983     *         otherwise
11984     *
11985     * @see #setVerticalFadingEdgeEnabled(boolean)
11986     *
11987     * @attr ref android.R.styleable#View_requiresFadingEdge
11988     */
11989    public boolean isVerticalFadingEdgeEnabled() {
11990        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11991    }
11992
11993    /**
11994     * <p>Define whether the vertical edges should be faded when this view
11995     * is scrolled vertically.</p>
11996     *
11997     * @param verticalFadingEdgeEnabled true if the vertical edges should
11998     *                                  be faded when the view is scrolled
11999     *                                  vertically
12000     *
12001     * @see #isVerticalFadingEdgeEnabled()
12002     *
12003     * @attr ref android.R.styleable#View_requiresFadingEdge
12004     */
12005    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12006        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12007            if (verticalFadingEdgeEnabled) {
12008                initScrollCache();
12009            }
12010
12011            mViewFlags ^= FADING_EDGE_VERTICAL;
12012        }
12013    }
12014
12015    /**
12016     * Returns the strength, or intensity, of the top faded edge. The strength is
12017     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12018     * returns 0.0 or 1.0 but no value in between.
12019     *
12020     * Subclasses should override this method to provide a smoother fade transition
12021     * when scrolling occurs.
12022     *
12023     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12024     */
12025    protected float getTopFadingEdgeStrength() {
12026        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12027    }
12028
12029    /**
12030     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12031     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12032     * returns 0.0 or 1.0 but no value in between.
12033     *
12034     * Subclasses should override this method to provide a smoother fade transition
12035     * when scrolling occurs.
12036     *
12037     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12038     */
12039    protected float getBottomFadingEdgeStrength() {
12040        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12041                computeVerticalScrollRange() ? 1.0f : 0.0f;
12042    }
12043
12044    /**
12045     * Returns the strength, or intensity, of the left faded edge. The strength is
12046     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12047     * returns 0.0 or 1.0 but no value in between.
12048     *
12049     * Subclasses should override this method to provide a smoother fade transition
12050     * when scrolling occurs.
12051     *
12052     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12053     */
12054    protected float getLeftFadingEdgeStrength() {
12055        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12056    }
12057
12058    /**
12059     * Returns the strength, or intensity, of the right faded edge. The strength is
12060     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12061     * returns 0.0 or 1.0 but no value in between.
12062     *
12063     * Subclasses should override this method to provide a smoother fade transition
12064     * when scrolling occurs.
12065     *
12066     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12067     */
12068    protected float getRightFadingEdgeStrength() {
12069        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12070                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12071    }
12072
12073    /**
12074     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12075     * scrollbar is not drawn by default.</p>
12076     *
12077     * @return true if the horizontal scrollbar should be painted, false
12078     *         otherwise
12079     *
12080     * @see #setHorizontalScrollBarEnabled(boolean)
12081     */
12082    public boolean isHorizontalScrollBarEnabled() {
12083        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12084    }
12085
12086    /**
12087     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12088     * scrollbar is not drawn by default.</p>
12089     *
12090     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12091     *                                   be painted
12092     *
12093     * @see #isHorizontalScrollBarEnabled()
12094     */
12095    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12096        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12097            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12098            computeOpaqueFlags();
12099            resolvePadding();
12100        }
12101    }
12102
12103    /**
12104     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12105     * scrollbar is not drawn by default.</p>
12106     *
12107     * @return true if the vertical scrollbar should be painted, false
12108     *         otherwise
12109     *
12110     * @see #setVerticalScrollBarEnabled(boolean)
12111     */
12112    public boolean isVerticalScrollBarEnabled() {
12113        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12114    }
12115
12116    /**
12117     * <p>Define whether the vertical scrollbar should be drawn or not. The
12118     * scrollbar is not drawn by default.</p>
12119     *
12120     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12121     *                                 be painted
12122     *
12123     * @see #isVerticalScrollBarEnabled()
12124     */
12125    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12126        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12127            mViewFlags ^= SCROLLBARS_VERTICAL;
12128            computeOpaqueFlags();
12129            resolvePadding();
12130        }
12131    }
12132
12133    /**
12134     * @hide
12135     */
12136    protected void recomputePadding() {
12137        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12138    }
12139
12140    /**
12141     * Define whether scrollbars will fade when the view is not scrolling.
12142     *
12143     * @param fadeScrollbars wheter to enable fading
12144     *
12145     * @attr ref android.R.styleable#View_fadeScrollbars
12146     */
12147    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12148        initScrollCache();
12149        final ScrollabilityCache scrollabilityCache = mScrollCache;
12150        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12151        if (fadeScrollbars) {
12152            scrollabilityCache.state = ScrollabilityCache.OFF;
12153        } else {
12154            scrollabilityCache.state = ScrollabilityCache.ON;
12155        }
12156    }
12157
12158    /**
12159     *
12160     * Returns true if scrollbars will fade when this view is not scrolling
12161     *
12162     * @return true if scrollbar fading is enabled
12163     *
12164     * @attr ref android.R.styleable#View_fadeScrollbars
12165     */
12166    public boolean isScrollbarFadingEnabled() {
12167        return mScrollCache != null && mScrollCache.fadeScrollBars;
12168    }
12169
12170    /**
12171     *
12172     * Returns the delay before scrollbars fade.
12173     *
12174     * @return the delay before scrollbars fade
12175     *
12176     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12177     */
12178    public int getScrollBarDefaultDelayBeforeFade() {
12179        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12180                mScrollCache.scrollBarDefaultDelayBeforeFade;
12181    }
12182
12183    /**
12184     * Define the delay before scrollbars fade.
12185     *
12186     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12187     *
12188     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12189     */
12190    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12191        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12192    }
12193
12194    /**
12195     *
12196     * Returns the scrollbar fade duration.
12197     *
12198     * @return the scrollbar fade duration
12199     *
12200     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12201     */
12202    public int getScrollBarFadeDuration() {
12203        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12204                mScrollCache.scrollBarFadeDuration;
12205    }
12206
12207    /**
12208     * Define the scrollbar fade duration.
12209     *
12210     * @param scrollBarFadeDuration - the scrollbar fade duration
12211     *
12212     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12213     */
12214    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12215        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12216    }
12217
12218    /**
12219     *
12220     * Returns the scrollbar size.
12221     *
12222     * @return the scrollbar size
12223     *
12224     * @attr ref android.R.styleable#View_scrollbarSize
12225     */
12226    public int getScrollBarSize() {
12227        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12228                mScrollCache.scrollBarSize;
12229    }
12230
12231    /**
12232     * Define the scrollbar size.
12233     *
12234     * @param scrollBarSize - the scrollbar size
12235     *
12236     * @attr ref android.R.styleable#View_scrollbarSize
12237     */
12238    public void setScrollBarSize(int scrollBarSize) {
12239        getScrollCache().scrollBarSize = scrollBarSize;
12240    }
12241
12242    /**
12243     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12244     * inset. When inset, they add to the padding of the view. And the scrollbars
12245     * can be drawn inside the padding area or on the edge of the view. For example,
12246     * if a view has a background drawable and you want to draw the scrollbars
12247     * inside the padding specified by the drawable, you can use
12248     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12249     * appear at the edge of the view, ignoring the padding, then you can use
12250     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12251     * @param style the style of the scrollbars. Should be one of
12252     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12253     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12254     * @see #SCROLLBARS_INSIDE_OVERLAY
12255     * @see #SCROLLBARS_INSIDE_INSET
12256     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12257     * @see #SCROLLBARS_OUTSIDE_INSET
12258     *
12259     * @attr ref android.R.styleable#View_scrollbarStyle
12260     */
12261    public void setScrollBarStyle(@ScrollBarStyle int style) {
12262        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12263            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12264            computeOpaqueFlags();
12265            resolvePadding();
12266        }
12267    }
12268
12269    /**
12270     * <p>Returns the current scrollbar style.</p>
12271     * @return the current scrollbar style
12272     * @see #SCROLLBARS_INSIDE_OVERLAY
12273     * @see #SCROLLBARS_INSIDE_INSET
12274     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12275     * @see #SCROLLBARS_OUTSIDE_INSET
12276     *
12277     * @attr ref android.R.styleable#View_scrollbarStyle
12278     */
12279    @ViewDebug.ExportedProperty(mapping = {
12280            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12281            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12282            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12283            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12284    })
12285    @ScrollBarStyle
12286    public int getScrollBarStyle() {
12287        return mViewFlags & SCROLLBARS_STYLE_MASK;
12288    }
12289
12290    /**
12291     * <p>Compute the horizontal range that the horizontal scrollbar
12292     * represents.</p>
12293     *
12294     * <p>The range is expressed in arbitrary units that must be the same as the
12295     * units used by {@link #computeHorizontalScrollExtent()} and
12296     * {@link #computeHorizontalScrollOffset()}.</p>
12297     *
12298     * <p>The default range is the drawing width of this view.</p>
12299     *
12300     * @return the total horizontal range represented by the horizontal
12301     *         scrollbar
12302     *
12303     * @see #computeHorizontalScrollExtent()
12304     * @see #computeHorizontalScrollOffset()
12305     * @see android.widget.ScrollBarDrawable
12306     */
12307    protected int computeHorizontalScrollRange() {
12308        return getWidth();
12309    }
12310
12311    /**
12312     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12313     * within the horizontal range. This value is used to compute the position
12314     * of the thumb within the scrollbar's track.</p>
12315     *
12316     * <p>The range is expressed in arbitrary units that must be the same as the
12317     * units used by {@link #computeHorizontalScrollRange()} and
12318     * {@link #computeHorizontalScrollExtent()}.</p>
12319     *
12320     * <p>The default offset is the scroll offset of this view.</p>
12321     *
12322     * @return the horizontal offset of the scrollbar's thumb
12323     *
12324     * @see #computeHorizontalScrollRange()
12325     * @see #computeHorizontalScrollExtent()
12326     * @see android.widget.ScrollBarDrawable
12327     */
12328    protected int computeHorizontalScrollOffset() {
12329        return mScrollX;
12330    }
12331
12332    /**
12333     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12334     * within the horizontal range. This value is used to compute the length
12335     * of the thumb within the scrollbar's track.</p>
12336     *
12337     * <p>The range is expressed in arbitrary units that must be the same as the
12338     * units used by {@link #computeHorizontalScrollRange()} and
12339     * {@link #computeHorizontalScrollOffset()}.</p>
12340     *
12341     * <p>The default extent is the drawing width of this view.</p>
12342     *
12343     * @return the horizontal extent of the scrollbar's thumb
12344     *
12345     * @see #computeHorizontalScrollRange()
12346     * @see #computeHorizontalScrollOffset()
12347     * @see android.widget.ScrollBarDrawable
12348     */
12349    protected int computeHorizontalScrollExtent() {
12350        return getWidth();
12351    }
12352
12353    /**
12354     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12355     *
12356     * <p>The range is expressed in arbitrary units that must be the same as the
12357     * units used by {@link #computeVerticalScrollExtent()} and
12358     * {@link #computeVerticalScrollOffset()}.</p>
12359     *
12360     * @return the total vertical range represented by the vertical scrollbar
12361     *
12362     * <p>The default range is the drawing height of this view.</p>
12363     *
12364     * @see #computeVerticalScrollExtent()
12365     * @see #computeVerticalScrollOffset()
12366     * @see android.widget.ScrollBarDrawable
12367     */
12368    protected int computeVerticalScrollRange() {
12369        return getHeight();
12370    }
12371
12372    /**
12373     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12374     * within the horizontal range. This value is used to compute the position
12375     * of the thumb within the scrollbar's track.</p>
12376     *
12377     * <p>The range is expressed in arbitrary units that must be the same as the
12378     * units used by {@link #computeVerticalScrollRange()} and
12379     * {@link #computeVerticalScrollExtent()}.</p>
12380     *
12381     * <p>The default offset is the scroll offset of this view.</p>
12382     *
12383     * @return the vertical offset of the scrollbar's thumb
12384     *
12385     * @see #computeVerticalScrollRange()
12386     * @see #computeVerticalScrollExtent()
12387     * @see android.widget.ScrollBarDrawable
12388     */
12389    protected int computeVerticalScrollOffset() {
12390        return mScrollY;
12391    }
12392
12393    /**
12394     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12395     * within the vertical range. This value is used to compute the length
12396     * of the thumb within the scrollbar's track.</p>
12397     *
12398     * <p>The range is expressed in arbitrary units that must be the same as the
12399     * units used by {@link #computeVerticalScrollRange()} and
12400     * {@link #computeVerticalScrollOffset()}.</p>
12401     *
12402     * <p>The default extent is the drawing height of this view.</p>
12403     *
12404     * @return the vertical extent of the scrollbar's thumb
12405     *
12406     * @see #computeVerticalScrollRange()
12407     * @see #computeVerticalScrollOffset()
12408     * @see android.widget.ScrollBarDrawable
12409     */
12410    protected int computeVerticalScrollExtent() {
12411        return getHeight();
12412    }
12413
12414    /**
12415     * Check if this view can be scrolled horizontally in a certain direction.
12416     *
12417     * @param direction Negative to check scrolling left, positive to check scrolling right.
12418     * @return true if this view can be scrolled in the specified direction, false otherwise.
12419     */
12420    public boolean canScrollHorizontally(int direction) {
12421        final int offset = computeHorizontalScrollOffset();
12422        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12423        if (range == 0) return false;
12424        if (direction < 0) {
12425            return offset > 0;
12426        } else {
12427            return offset < range - 1;
12428        }
12429    }
12430
12431    /**
12432     * Check if this view can be scrolled vertically in a certain direction.
12433     *
12434     * @param direction Negative to check scrolling up, positive to check scrolling down.
12435     * @return true if this view can be scrolled in the specified direction, false otherwise.
12436     */
12437    public boolean canScrollVertically(int direction) {
12438        final int offset = computeVerticalScrollOffset();
12439        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12440        if (range == 0) return false;
12441        if (direction < 0) {
12442            return offset > 0;
12443        } else {
12444            return offset < range - 1;
12445        }
12446    }
12447
12448    /**
12449     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12450     * scrollbars are painted only if they have been awakened first.</p>
12451     *
12452     * @param canvas the canvas on which to draw the scrollbars
12453     *
12454     * @see #awakenScrollBars(int)
12455     */
12456    protected final void onDrawScrollBars(Canvas canvas) {
12457        // scrollbars are drawn only when the animation is running
12458        final ScrollabilityCache cache = mScrollCache;
12459        if (cache != null) {
12460
12461            int state = cache.state;
12462
12463            if (state == ScrollabilityCache.OFF) {
12464                return;
12465            }
12466
12467            boolean invalidate = false;
12468
12469            if (state == ScrollabilityCache.FADING) {
12470                // We're fading -- get our fade interpolation
12471                if (cache.interpolatorValues == null) {
12472                    cache.interpolatorValues = new float[1];
12473                }
12474
12475                float[] values = cache.interpolatorValues;
12476
12477                // Stops the animation if we're done
12478                if (cache.scrollBarInterpolator.timeToValues(values) ==
12479                        Interpolator.Result.FREEZE_END) {
12480                    cache.state = ScrollabilityCache.OFF;
12481                } else {
12482                    cache.scrollBar.setAlpha(Math.round(values[0]));
12483                }
12484
12485                // This will make the scroll bars inval themselves after
12486                // drawing. We only want this when we're fading so that
12487                // we prevent excessive redraws
12488                invalidate = true;
12489            } else {
12490                // We're just on -- but we may have been fading before so
12491                // reset alpha
12492                cache.scrollBar.setAlpha(255);
12493            }
12494
12495
12496            final int viewFlags = mViewFlags;
12497
12498            final boolean drawHorizontalScrollBar =
12499                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12500            final boolean drawVerticalScrollBar =
12501                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12502                && !isVerticalScrollBarHidden();
12503
12504            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12505                final int width = mRight - mLeft;
12506                final int height = mBottom - mTop;
12507
12508                final ScrollBarDrawable scrollBar = cache.scrollBar;
12509
12510                final int scrollX = mScrollX;
12511                final int scrollY = mScrollY;
12512                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12513
12514                int left;
12515                int top;
12516                int right;
12517                int bottom;
12518
12519                if (drawHorizontalScrollBar) {
12520                    int size = scrollBar.getSize(false);
12521                    if (size <= 0) {
12522                        size = cache.scrollBarSize;
12523                    }
12524
12525                    scrollBar.setParameters(computeHorizontalScrollRange(),
12526                                            computeHorizontalScrollOffset(),
12527                                            computeHorizontalScrollExtent(), false);
12528                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12529                            getVerticalScrollbarWidth() : 0;
12530                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12531                    left = scrollX + (mPaddingLeft & inside);
12532                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12533                    bottom = top + size;
12534                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12535                    if (invalidate) {
12536                        invalidate(left, top, right, bottom);
12537                    }
12538                }
12539
12540                if (drawVerticalScrollBar) {
12541                    int size = scrollBar.getSize(true);
12542                    if (size <= 0) {
12543                        size = cache.scrollBarSize;
12544                    }
12545
12546                    scrollBar.setParameters(computeVerticalScrollRange(),
12547                                            computeVerticalScrollOffset(),
12548                                            computeVerticalScrollExtent(), true);
12549                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12550                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12551                        verticalScrollbarPosition = isLayoutRtl() ?
12552                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12553                    }
12554                    switch (verticalScrollbarPosition) {
12555                        default:
12556                        case SCROLLBAR_POSITION_RIGHT:
12557                            left = scrollX + width - size - (mUserPaddingRight & inside);
12558                            break;
12559                        case SCROLLBAR_POSITION_LEFT:
12560                            left = scrollX + (mUserPaddingLeft & inside);
12561                            break;
12562                    }
12563                    top = scrollY + (mPaddingTop & inside);
12564                    right = left + size;
12565                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12566                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12567                    if (invalidate) {
12568                        invalidate(left, top, right, bottom);
12569                    }
12570                }
12571            }
12572        }
12573    }
12574
12575    /**
12576     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12577     * FastScroller is visible.
12578     * @return whether to temporarily hide the vertical scrollbar
12579     * @hide
12580     */
12581    protected boolean isVerticalScrollBarHidden() {
12582        return false;
12583    }
12584
12585    /**
12586     * <p>Draw the horizontal scrollbar if
12587     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12588     *
12589     * @param canvas the canvas on which to draw the scrollbar
12590     * @param scrollBar the scrollbar's drawable
12591     *
12592     * @see #isHorizontalScrollBarEnabled()
12593     * @see #computeHorizontalScrollRange()
12594     * @see #computeHorizontalScrollExtent()
12595     * @see #computeHorizontalScrollOffset()
12596     * @see android.widget.ScrollBarDrawable
12597     * @hide
12598     */
12599    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12600            int l, int t, int r, int b) {
12601        scrollBar.setBounds(l, t, r, b);
12602        scrollBar.draw(canvas);
12603    }
12604
12605    /**
12606     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12607     * returns true.</p>
12608     *
12609     * @param canvas the canvas on which to draw the scrollbar
12610     * @param scrollBar the scrollbar's drawable
12611     *
12612     * @see #isVerticalScrollBarEnabled()
12613     * @see #computeVerticalScrollRange()
12614     * @see #computeVerticalScrollExtent()
12615     * @see #computeVerticalScrollOffset()
12616     * @see android.widget.ScrollBarDrawable
12617     * @hide
12618     */
12619    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12620            int l, int t, int r, int b) {
12621        scrollBar.setBounds(l, t, r, b);
12622        scrollBar.draw(canvas);
12623    }
12624
12625    /**
12626     * Implement this to do your drawing.
12627     *
12628     * @param canvas the canvas on which the background will be drawn
12629     */
12630    protected void onDraw(Canvas canvas) {
12631    }
12632
12633    /*
12634     * Caller is responsible for calling requestLayout if necessary.
12635     * (This allows addViewInLayout to not request a new layout.)
12636     */
12637    void assignParent(ViewParent parent) {
12638        if (mParent == null) {
12639            mParent = parent;
12640        } else if (parent == null) {
12641            mParent = null;
12642        } else {
12643            throw new RuntimeException("view " + this + " being added, but"
12644                    + " it already has a parent");
12645        }
12646    }
12647
12648    /**
12649     * This is called when the view is attached to a window.  At this point it
12650     * has a Surface and will start drawing.  Note that this function is
12651     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12652     * however it may be called any time before the first onDraw -- including
12653     * before or after {@link #onMeasure(int, int)}.
12654     *
12655     * @see #onDetachedFromWindow()
12656     */
12657    protected void onAttachedToWindow() {
12658        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12659            mParent.requestTransparentRegion(this);
12660        }
12661
12662        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12663            initialAwakenScrollBars();
12664            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12665        }
12666
12667        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12668
12669        jumpDrawablesToCurrentState();
12670
12671        resetSubtreeAccessibilityStateChanged();
12672
12673        if (isFocused()) {
12674            InputMethodManager imm = InputMethodManager.peekInstance();
12675            imm.focusIn(this);
12676        }
12677    }
12678
12679    /**
12680     * Resolve all RTL related properties.
12681     *
12682     * @return true if resolution of RTL properties has been done
12683     *
12684     * @hide
12685     */
12686    public boolean resolveRtlPropertiesIfNeeded() {
12687        if (!needRtlPropertiesResolution()) return false;
12688
12689        // Order is important here: LayoutDirection MUST be resolved first
12690        if (!isLayoutDirectionResolved()) {
12691            resolveLayoutDirection();
12692            resolveLayoutParams();
12693        }
12694        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12695        if (!isTextDirectionResolved()) {
12696            resolveTextDirection();
12697        }
12698        if (!isTextAlignmentResolved()) {
12699            resolveTextAlignment();
12700        }
12701        // Should resolve Drawables before Padding because we need the layout direction of the
12702        // Drawable to correctly resolve Padding.
12703        if (!isDrawablesResolved()) {
12704            resolveDrawables();
12705        }
12706        if (!isPaddingResolved()) {
12707            resolvePadding();
12708        }
12709        onRtlPropertiesChanged(getLayoutDirection());
12710        return true;
12711    }
12712
12713    /**
12714     * Reset resolution of all RTL related properties.
12715     *
12716     * @hide
12717     */
12718    public void resetRtlProperties() {
12719        resetResolvedLayoutDirection();
12720        resetResolvedTextDirection();
12721        resetResolvedTextAlignment();
12722        resetResolvedPadding();
12723        resetResolvedDrawables();
12724    }
12725
12726    /**
12727     * @see #onScreenStateChanged(int)
12728     */
12729    void dispatchScreenStateChanged(int screenState) {
12730        onScreenStateChanged(screenState);
12731    }
12732
12733    /**
12734     * This method is called whenever the state of the screen this view is
12735     * attached to changes. A state change will usually occurs when the screen
12736     * turns on or off (whether it happens automatically or the user does it
12737     * manually.)
12738     *
12739     * @param screenState The new state of the screen. Can be either
12740     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12741     */
12742    public void onScreenStateChanged(int screenState) {
12743    }
12744
12745    /**
12746     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12747     */
12748    private boolean hasRtlSupport() {
12749        return mContext.getApplicationInfo().hasRtlSupport();
12750    }
12751
12752    /**
12753     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12754     * RTL not supported)
12755     */
12756    private boolean isRtlCompatibilityMode() {
12757        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12758        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12759    }
12760
12761    /**
12762     * @return true if RTL properties need resolution.
12763     *
12764     */
12765    private boolean needRtlPropertiesResolution() {
12766        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12767    }
12768
12769    /**
12770     * Called when any RTL property (layout direction or text direction or text alignment) has
12771     * been changed.
12772     *
12773     * Subclasses need to override this method to take care of cached information that depends on the
12774     * resolved layout direction, or to inform child views that inherit their layout direction.
12775     *
12776     * The default implementation does nothing.
12777     *
12778     * @param layoutDirection the direction of the layout
12779     *
12780     * @see #LAYOUT_DIRECTION_LTR
12781     * @see #LAYOUT_DIRECTION_RTL
12782     */
12783    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12784    }
12785
12786    /**
12787     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12788     * that the parent directionality can and will be resolved before its children.
12789     *
12790     * @return true if resolution has been done, false otherwise.
12791     *
12792     * @hide
12793     */
12794    public boolean resolveLayoutDirection() {
12795        // Clear any previous layout direction resolution
12796        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12797
12798        if (hasRtlSupport()) {
12799            // Set resolved depending on layout direction
12800            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12801                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12802                case LAYOUT_DIRECTION_INHERIT:
12803                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12804                    // later to get the correct resolved value
12805                    if (!canResolveLayoutDirection()) return false;
12806
12807                    // Parent has not yet resolved, LTR is still the default
12808                    try {
12809                        if (!mParent.isLayoutDirectionResolved()) return false;
12810
12811                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12812                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12813                        }
12814                    } catch (AbstractMethodError e) {
12815                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12816                                " does not fully implement ViewParent", e);
12817                    }
12818                    break;
12819                case LAYOUT_DIRECTION_RTL:
12820                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12821                    break;
12822                case LAYOUT_DIRECTION_LOCALE:
12823                    if((LAYOUT_DIRECTION_RTL ==
12824                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12825                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12826                    }
12827                    break;
12828                default:
12829                    // Nothing to do, LTR by default
12830            }
12831        }
12832
12833        // Set to resolved
12834        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12835        return true;
12836    }
12837
12838    /**
12839     * Check if layout direction resolution can be done.
12840     *
12841     * @return true if layout direction resolution can be done otherwise return false.
12842     */
12843    public boolean canResolveLayoutDirection() {
12844        switch (getRawLayoutDirection()) {
12845            case LAYOUT_DIRECTION_INHERIT:
12846                if (mParent != null) {
12847                    try {
12848                        return mParent.canResolveLayoutDirection();
12849                    } catch (AbstractMethodError e) {
12850                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12851                                " does not fully implement ViewParent", e);
12852                    }
12853                }
12854                return false;
12855
12856            default:
12857                return true;
12858        }
12859    }
12860
12861    /**
12862     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12863     * {@link #onMeasure(int, int)}.
12864     *
12865     * @hide
12866     */
12867    public void resetResolvedLayoutDirection() {
12868        // Reset the current resolved bits
12869        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12870    }
12871
12872    /**
12873     * @return true if the layout direction is inherited.
12874     *
12875     * @hide
12876     */
12877    public boolean isLayoutDirectionInherited() {
12878        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12879    }
12880
12881    /**
12882     * @return true if layout direction has been resolved.
12883     */
12884    public boolean isLayoutDirectionResolved() {
12885        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12886    }
12887
12888    /**
12889     * Return if padding has been resolved
12890     *
12891     * @hide
12892     */
12893    boolean isPaddingResolved() {
12894        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12895    }
12896
12897    /**
12898     * Resolves padding depending on layout direction, if applicable, and
12899     * recomputes internal padding values to adjust for scroll bars.
12900     *
12901     * @hide
12902     */
12903    public void resolvePadding() {
12904        final int resolvedLayoutDirection = getLayoutDirection();
12905
12906        if (!isRtlCompatibilityMode()) {
12907            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12908            // If start / end padding are defined, they will be resolved (hence overriding) to
12909            // left / right or right / left depending on the resolved layout direction.
12910            // If start / end padding are not defined, use the left / right ones.
12911            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12912                Rect padding = sThreadLocal.get();
12913                if (padding == null) {
12914                    padding = new Rect();
12915                    sThreadLocal.set(padding);
12916                }
12917                mBackground.getPadding(padding);
12918                if (!mLeftPaddingDefined) {
12919                    mUserPaddingLeftInitial = padding.left;
12920                }
12921                if (!mRightPaddingDefined) {
12922                    mUserPaddingRightInitial = padding.right;
12923                }
12924            }
12925            switch (resolvedLayoutDirection) {
12926                case LAYOUT_DIRECTION_RTL:
12927                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12928                        mUserPaddingRight = mUserPaddingStart;
12929                    } else {
12930                        mUserPaddingRight = mUserPaddingRightInitial;
12931                    }
12932                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12933                        mUserPaddingLeft = mUserPaddingEnd;
12934                    } else {
12935                        mUserPaddingLeft = mUserPaddingLeftInitial;
12936                    }
12937                    break;
12938                case LAYOUT_DIRECTION_LTR:
12939                default:
12940                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12941                        mUserPaddingLeft = mUserPaddingStart;
12942                    } else {
12943                        mUserPaddingLeft = mUserPaddingLeftInitial;
12944                    }
12945                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12946                        mUserPaddingRight = mUserPaddingEnd;
12947                    } else {
12948                        mUserPaddingRight = mUserPaddingRightInitial;
12949                    }
12950            }
12951
12952            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12953        }
12954
12955        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12956        onRtlPropertiesChanged(resolvedLayoutDirection);
12957
12958        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12959    }
12960
12961    /**
12962     * Reset the resolved layout direction.
12963     *
12964     * @hide
12965     */
12966    public void resetResolvedPadding() {
12967        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12968    }
12969
12970    /**
12971     * This is called when the view is detached from a window.  At this point it
12972     * no longer has a surface for drawing.
12973     *
12974     * @see #onAttachedToWindow()
12975     */
12976    protected void onDetachedFromWindow() {
12977    }
12978
12979    /**
12980     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12981     * after onDetachedFromWindow().
12982     *
12983     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12984     * The super method should be called at the end of the overriden method to ensure
12985     * subclasses are destroyed first
12986     *
12987     * @hide
12988     */
12989    protected void onDetachedFromWindowInternal() {
12990        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12991        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12992
12993        removeUnsetPressCallback();
12994        removeLongPressCallback();
12995        removePerformClickCallback();
12996        removeSendViewScrolledAccessibilityEventCallback();
12997        stopNestedScroll();
12998
12999        destroyDrawingCache();
13000
13001        cleanupDraw();
13002        mCurrentAnimation = null;
13003    }
13004
13005    private void cleanupDraw() {
13006        resetDisplayList();
13007        if (mAttachInfo != null) {
13008            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13009        }
13010    }
13011
13012    /**
13013     * This method ensures the hardware renderer is in a valid state
13014     * before executing the specified action.
13015     *
13016     * This method will attempt to set a valid state even if the window
13017     * the renderer is attached to was destroyed.
13018     *
13019     * This method is not guaranteed to work. If the hardware renderer
13020     * does not exist or cannot be put in a valid state, this method
13021     * will not executed the specified action.
13022     *
13023     * The specified action is executed synchronously.
13024     *
13025     * @param action The action to execute after the renderer is in a valid state
13026     *
13027     * @return True if the specified Runnable was executed, false otherwise
13028     *
13029     * @hide
13030     */
13031    public boolean executeHardwareAction(Runnable action) {
13032        //noinspection SimplifiableIfStatement
13033        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
13034            return mAttachInfo.mHardwareRenderer.safelyRun(action);
13035        }
13036        return false;
13037    }
13038
13039    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13040    }
13041
13042    /**
13043     * @return The number of times this view has been attached to a window
13044     */
13045    protected int getWindowAttachCount() {
13046        return mWindowAttachCount;
13047    }
13048
13049    /**
13050     * Retrieve a unique token identifying the window this view is attached to.
13051     * @return Return the window's token for use in
13052     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13053     */
13054    public IBinder getWindowToken() {
13055        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13056    }
13057
13058    /**
13059     * Retrieve the {@link WindowId} for the window this view is
13060     * currently attached to.
13061     */
13062    public WindowId getWindowId() {
13063        if (mAttachInfo == null) {
13064            return null;
13065        }
13066        if (mAttachInfo.mWindowId == null) {
13067            try {
13068                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13069                        mAttachInfo.mWindowToken);
13070                mAttachInfo.mWindowId = new WindowId(
13071                        mAttachInfo.mIWindowId);
13072            } catch (RemoteException e) {
13073            }
13074        }
13075        return mAttachInfo.mWindowId;
13076    }
13077
13078    /**
13079     * Retrieve a unique token identifying the top-level "real" window of
13080     * the window that this view is attached to.  That is, this is like
13081     * {@link #getWindowToken}, except if the window this view in is a panel
13082     * window (attached to another containing window), then the token of
13083     * the containing window is returned instead.
13084     *
13085     * @return Returns the associated window token, either
13086     * {@link #getWindowToken()} or the containing window's token.
13087     */
13088    public IBinder getApplicationWindowToken() {
13089        AttachInfo ai = mAttachInfo;
13090        if (ai != null) {
13091            IBinder appWindowToken = ai.mPanelParentWindowToken;
13092            if (appWindowToken == null) {
13093                appWindowToken = ai.mWindowToken;
13094            }
13095            return appWindowToken;
13096        }
13097        return null;
13098    }
13099
13100    /**
13101     * Gets the logical display to which the view's window has been attached.
13102     *
13103     * @return The logical display, or null if the view is not currently attached to a window.
13104     */
13105    public Display getDisplay() {
13106        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13107    }
13108
13109    /**
13110     * Retrieve private session object this view hierarchy is using to
13111     * communicate with the window manager.
13112     * @return the session object to communicate with the window manager
13113     */
13114    /*package*/ IWindowSession getWindowSession() {
13115        return mAttachInfo != null ? mAttachInfo.mSession : null;
13116    }
13117
13118    /**
13119     * @param info the {@link android.view.View.AttachInfo} to associated with
13120     *        this view
13121     */
13122    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13123        //System.out.println("Attached! " + this);
13124        mAttachInfo = info;
13125        if (mOverlay != null) {
13126            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13127        }
13128        mWindowAttachCount++;
13129        // We will need to evaluate the drawable state at least once.
13130        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13131        if (mFloatingTreeObserver != null) {
13132            info.mTreeObserver.merge(mFloatingTreeObserver);
13133            mFloatingTreeObserver = null;
13134        }
13135        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13136            mAttachInfo.mScrollContainers.add(this);
13137            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13138        }
13139        performCollectViewAttributes(mAttachInfo, visibility);
13140        onAttachedToWindow();
13141
13142        ListenerInfo li = mListenerInfo;
13143        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13144                li != null ? li.mOnAttachStateChangeListeners : null;
13145        if (listeners != null && listeners.size() > 0) {
13146            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13147            // perform the dispatching. The iterator is a safe guard against listeners that
13148            // could mutate the list by calling the various add/remove methods. This prevents
13149            // the array from being modified while we iterate it.
13150            for (OnAttachStateChangeListener listener : listeners) {
13151                listener.onViewAttachedToWindow(this);
13152            }
13153        }
13154
13155        int vis = info.mWindowVisibility;
13156        if (vis != GONE) {
13157            onWindowVisibilityChanged(vis);
13158        }
13159        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13160            // If nobody has evaluated the drawable state yet, then do it now.
13161            refreshDrawableState();
13162        }
13163        needGlobalAttributesUpdate(false);
13164    }
13165
13166    void dispatchDetachedFromWindow() {
13167        AttachInfo info = mAttachInfo;
13168        if (info != null) {
13169            int vis = info.mWindowVisibility;
13170            if (vis != GONE) {
13171                onWindowVisibilityChanged(GONE);
13172            }
13173        }
13174
13175        onDetachedFromWindow();
13176        onDetachedFromWindowInternal();
13177
13178        ListenerInfo li = mListenerInfo;
13179        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13180                li != null ? li.mOnAttachStateChangeListeners : null;
13181        if (listeners != null && listeners.size() > 0) {
13182            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13183            // perform the dispatching. The iterator is a safe guard against listeners that
13184            // could mutate the list by calling the various add/remove methods. This prevents
13185            // the array from being modified while we iterate it.
13186            for (OnAttachStateChangeListener listener : listeners) {
13187                listener.onViewDetachedFromWindow(this);
13188            }
13189        }
13190
13191        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13192            mAttachInfo.mScrollContainers.remove(this);
13193            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13194        }
13195
13196        mAttachInfo = null;
13197        if (mOverlay != null) {
13198            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13199        }
13200    }
13201
13202    /**
13203     * Cancel any deferred high-level input events that were previously posted to the event queue.
13204     *
13205     * <p>Many views post high-level events such as click handlers to the event queue
13206     * to run deferred in order to preserve a desired user experience - clearing visible
13207     * pressed states before executing, etc. This method will abort any events of this nature
13208     * that are currently in flight.</p>
13209     *
13210     * <p>Custom views that generate their own high-level deferred input events should override
13211     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13212     *
13213     * <p>This will also cancel pending input events for any child views.</p>
13214     *
13215     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13216     * This will not impact newer events posted after this call that may occur as a result of
13217     * lower-level input events still waiting in the queue. If you are trying to prevent
13218     * double-submitted  events for the duration of some sort of asynchronous transaction
13219     * you should also take other steps to protect against unexpected double inputs e.g. calling
13220     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13221     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13222     */
13223    public final void cancelPendingInputEvents() {
13224        dispatchCancelPendingInputEvents();
13225    }
13226
13227    /**
13228     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13229     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13230     */
13231    void dispatchCancelPendingInputEvents() {
13232        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13233        onCancelPendingInputEvents();
13234        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13235            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13236                    " did not call through to super.onCancelPendingInputEvents()");
13237        }
13238    }
13239
13240    /**
13241     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13242     * a parent view.
13243     *
13244     * <p>This method is responsible for removing any pending high-level input events that were
13245     * posted to the event queue to run later. Custom view classes that post their own deferred
13246     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13247     * {@link android.os.Handler} should override this method, call
13248     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13249     * </p>
13250     */
13251    public void onCancelPendingInputEvents() {
13252        removePerformClickCallback();
13253        cancelLongPress();
13254        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13255    }
13256
13257    /**
13258     * Store this view hierarchy's frozen state into the given container.
13259     *
13260     * @param container The SparseArray in which to save the view's state.
13261     *
13262     * @see #restoreHierarchyState(android.util.SparseArray)
13263     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13264     * @see #onSaveInstanceState()
13265     */
13266    public void saveHierarchyState(SparseArray<Parcelable> container) {
13267        dispatchSaveInstanceState(container);
13268    }
13269
13270    /**
13271     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13272     * this view and its children. May be overridden to modify how freezing happens to a
13273     * view's children; for example, some views may want to not store state for their children.
13274     *
13275     * @param container The SparseArray in which to save the view's state.
13276     *
13277     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13278     * @see #saveHierarchyState(android.util.SparseArray)
13279     * @see #onSaveInstanceState()
13280     */
13281    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13282        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13283            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13284            Parcelable state = onSaveInstanceState();
13285            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13286                throw new IllegalStateException(
13287                        "Derived class did not call super.onSaveInstanceState()");
13288            }
13289            if (state != null) {
13290                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13291                // + ": " + state);
13292                container.put(mID, state);
13293            }
13294        }
13295    }
13296
13297    /**
13298     * Hook allowing a view to generate a representation of its internal state
13299     * that can later be used to create a new instance with that same state.
13300     * This state should only contain information that is not persistent or can
13301     * not be reconstructed later. For example, you will never store your
13302     * current position on screen because that will be computed again when a
13303     * new instance of the view is placed in its view hierarchy.
13304     * <p>
13305     * Some examples of things you may store here: the current cursor position
13306     * in a text view (but usually not the text itself since that is stored in a
13307     * content provider or other persistent storage), the currently selected
13308     * item in a list view.
13309     *
13310     * @return Returns a Parcelable object containing the view's current dynamic
13311     *         state, or null if there is nothing interesting to save. The
13312     *         default implementation returns null.
13313     * @see #onRestoreInstanceState(android.os.Parcelable)
13314     * @see #saveHierarchyState(android.util.SparseArray)
13315     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13316     * @see #setSaveEnabled(boolean)
13317     */
13318    protected Parcelable onSaveInstanceState() {
13319        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13320        return BaseSavedState.EMPTY_STATE;
13321    }
13322
13323    /**
13324     * Restore this view hierarchy's frozen state from the given container.
13325     *
13326     * @param container The SparseArray which holds previously frozen states.
13327     *
13328     * @see #saveHierarchyState(android.util.SparseArray)
13329     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13330     * @see #onRestoreInstanceState(android.os.Parcelable)
13331     */
13332    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13333        dispatchRestoreInstanceState(container);
13334    }
13335
13336    /**
13337     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13338     * state for this view and its children. May be overridden to modify how restoring
13339     * happens to a view's children; for example, some views may want to not store state
13340     * for their children.
13341     *
13342     * @param container The SparseArray which holds previously saved state.
13343     *
13344     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13345     * @see #restoreHierarchyState(android.util.SparseArray)
13346     * @see #onRestoreInstanceState(android.os.Parcelable)
13347     */
13348    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13349        if (mID != NO_ID) {
13350            Parcelable state = container.get(mID);
13351            if (state != null) {
13352                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13353                // + ": " + state);
13354                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13355                onRestoreInstanceState(state);
13356                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13357                    throw new IllegalStateException(
13358                            "Derived class did not call super.onRestoreInstanceState()");
13359                }
13360            }
13361        }
13362    }
13363
13364    /**
13365     * Hook allowing a view to re-apply a representation of its internal state that had previously
13366     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13367     * null state.
13368     *
13369     * @param state The frozen state that had previously been returned by
13370     *        {@link #onSaveInstanceState}.
13371     *
13372     * @see #onSaveInstanceState()
13373     * @see #restoreHierarchyState(android.util.SparseArray)
13374     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13375     */
13376    protected void onRestoreInstanceState(Parcelable state) {
13377        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13378        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13379            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13380                    + "received " + state.getClass().toString() + " instead. This usually happens "
13381                    + "when two views of different type have the same id in the same hierarchy. "
13382                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13383                    + "other views do not use the same id.");
13384        }
13385    }
13386
13387    /**
13388     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13389     *
13390     * @return the drawing start time in milliseconds
13391     */
13392    public long getDrawingTime() {
13393        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13394    }
13395
13396    /**
13397     * <p>Enables or disables the duplication of the parent's state into this view. When
13398     * duplication is enabled, this view gets its drawable state from its parent rather
13399     * than from its own internal properties.</p>
13400     *
13401     * <p>Note: in the current implementation, setting this property to true after the
13402     * view was added to a ViewGroup might have no effect at all. This property should
13403     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13404     *
13405     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13406     * property is enabled, an exception will be thrown.</p>
13407     *
13408     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13409     * parent, these states should not be affected by this method.</p>
13410     *
13411     * @param enabled True to enable duplication of the parent's drawable state, false
13412     *                to disable it.
13413     *
13414     * @see #getDrawableState()
13415     * @see #isDuplicateParentStateEnabled()
13416     */
13417    public void setDuplicateParentStateEnabled(boolean enabled) {
13418        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13419    }
13420
13421    /**
13422     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13423     *
13424     * @return True if this view's drawable state is duplicated from the parent,
13425     *         false otherwise
13426     *
13427     * @see #getDrawableState()
13428     * @see #setDuplicateParentStateEnabled(boolean)
13429     */
13430    public boolean isDuplicateParentStateEnabled() {
13431        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13432    }
13433
13434    /**
13435     * <p>Specifies the type of layer backing this view. The layer can be
13436     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13437     * {@link #LAYER_TYPE_HARDWARE}.</p>
13438     *
13439     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13440     * instance that controls how the layer is composed on screen. The following
13441     * properties of the paint are taken into account when composing the layer:</p>
13442     * <ul>
13443     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13444     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13445     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13446     * </ul>
13447     *
13448     * <p>If this view has an alpha value set to < 1.0 by calling
13449     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13450     * by this view's alpha value.</p>
13451     *
13452     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13453     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13454     * for more information on when and how to use layers.</p>
13455     *
13456     * @param layerType The type of layer to use with this view, must be one of
13457     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13458     *        {@link #LAYER_TYPE_HARDWARE}
13459     * @param paint The paint used to compose the layer. This argument is optional
13460     *        and can be null. It is ignored when the layer type is
13461     *        {@link #LAYER_TYPE_NONE}
13462     *
13463     * @see #getLayerType()
13464     * @see #LAYER_TYPE_NONE
13465     * @see #LAYER_TYPE_SOFTWARE
13466     * @see #LAYER_TYPE_HARDWARE
13467     * @see #setAlpha(float)
13468     *
13469     * @attr ref android.R.styleable#View_layerType
13470     */
13471    public void setLayerType(int layerType, Paint paint) {
13472        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13473            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13474                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13475        }
13476
13477        boolean typeChanged = mRenderNode.setLayerType(layerType);
13478
13479        if (!typeChanged) {
13480            setLayerPaint(paint);
13481            return;
13482        }
13483
13484        // Destroy any previous software drawing cache if needed
13485        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13486            destroyDrawingCache();
13487        }
13488
13489        mLayerType = layerType;
13490        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13491        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13492        mRenderNode.setLayerPaint(mLayerPaint);
13493
13494        // draw() behaves differently if we are on a layer, so we need to
13495        // invalidate() here
13496        invalidateParentCaches();
13497        invalidate(true);
13498    }
13499
13500    /**
13501     * Updates the {@link Paint} object used with the current layer (used only if the current
13502     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13503     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13504     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13505     * ensure that the view gets redrawn immediately.
13506     *
13507     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13508     * instance that controls how the layer is composed on screen. The following
13509     * properties of the paint are taken into account when composing the layer:</p>
13510     * <ul>
13511     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13512     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13513     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13514     * </ul>
13515     *
13516     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13517     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13518     *
13519     * @param paint The paint used to compose the layer. This argument is optional
13520     *        and can be null. It is ignored when the layer type is
13521     *        {@link #LAYER_TYPE_NONE}
13522     *
13523     * @see #setLayerType(int, android.graphics.Paint)
13524     */
13525    public void setLayerPaint(Paint paint) {
13526        int layerType = getLayerType();
13527        if (layerType != LAYER_TYPE_NONE) {
13528            mLayerPaint = paint == null ? new Paint() : paint;
13529            if (layerType == LAYER_TYPE_HARDWARE) {
13530                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13531                    invalidateViewProperty(false, false);
13532                }
13533            } else {
13534                invalidate();
13535            }
13536        }
13537    }
13538
13539    /**
13540     * Indicates whether this view has a static layer. A view with layer type
13541     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13542     * dynamic.
13543     */
13544    boolean hasStaticLayer() {
13545        return true;
13546    }
13547
13548    /**
13549     * Indicates what type of layer is currently associated with this view. By default
13550     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13551     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13552     * for more information on the different types of layers.
13553     *
13554     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13555     *         {@link #LAYER_TYPE_HARDWARE}
13556     *
13557     * @see #setLayerType(int, android.graphics.Paint)
13558     * @see #buildLayer()
13559     * @see #LAYER_TYPE_NONE
13560     * @see #LAYER_TYPE_SOFTWARE
13561     * @see #LAYER_TYPE_HARDWARE
13562     */
13563    public int getLayerType() {
13564        return mLayerType;
13565    }
13566
13567    /**
13568     * Forces this view's layer to be created and this view to be rendered
13569     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13570     * invoking this method will have no effect.
13571     *
13572     * This method can for instance be used to render a view into its layer before
13573     * starting an animation. If this view is complex, rendering into the layer
13574     * before starting the animation will avoid skipping frames.
13575     *
13576     * @throws IllegalStateException If this view is not attached to a window
13577     *
13578     * @see #setLayerType(int, android.graphics.Paint)
13579     */
13580    public void buildLayer() {
13581        if (mLayerType == LAYER_TYPE_NONE) return;
13582
13583        final AttachInfo attachInfo = mAttachInfo;
13584        if (attachInfo == null) {
13585            throw new IllegalStateException("This view must be attached to a window first");
13586        }
13587
13588        if (getWidth() == 0 || getHeight() == 0) {
13589            return;
13590        }
13591
13592        switch (mLayerType) {
13593            case LAYER_TYPE_HARDWARE:
13594                // The only part of a hardware layer we can build in response to
13595                // this call is to ensure the display list is up to date.
13596                // The actual rendering of the display list into the layer must
13597                // be done at playback time
13598                updateDisplayListIfDirty();
13599                break;
13600            case LAYER_TYPE_SOFTWARE:
13601                buildDrawingCache(true);
13602                break;
13603        }
13604    }
13605
13606    /**
13607     * If this View draws with a HardwareLayer, returns it.
13608     * Otherwise returns null
13609     *
13610     * TODO: Only TextureView uses this, can we eliminate it?
13611     */
13612    HardwareLayer getHardwareLayer() {
13613        return null;
13614    }
13615
13616    /**
13617     * Destroys all hardware rendering resources. This method is invoked
13618     * when the system needs to reclaim resources. Upon execution of this
13619     * method, you should free any OpenGL resources created by the view.
13620     *
13621     * Note: you <strong>must</strong> call
13622     * <code>super.destroyHardwareResources()</code> when overriding
13623     * this method.
13624     *
13625     * @hide
13626     */
13627    protected void destroyHardwareResources() {
13628        resetDisplayList();
13629    }
13630
13631    /**
13632     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13633     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13634     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13635     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13636     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13637     * null.</p>
13638     *
13639     * <p>Enabling the drawing cache is similar to
13640     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13641     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13642     * drawing cache has no effect on rendering because the system uses a different mechanism
13643     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13644     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13645     * for information on how to enable software and hardware layers.</p>
13646     *
13647     * <p>This API can be used to manually generate
13648     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13649     * {@link #getDrawingCache()}.</p>
13650     *
13651     * @param enabled true to enable the drawing cache, false otherwise
13652     *
13653     * @see #isDrawingCacheEnabled()
13654     * @see #getDrawingCache()
13655     * @see #buildDrawingCache()
13656     * @see #setLayerType(int, android.graphics.Paint)
13657     */
13658    public void setDrawingCacheEnabled(boolean enabled) {
13659        mCachingFailed = false;
13660        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13661    }
13662
13663    /**
13664     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13665     *
13666     * @return true if the drawing cache is enabled
13667     *
13668     * @see #setDrawingCacheEnabled(boolean)
13669     * @see #getDrawingCache()
13670     */
13671    @ViewDebug.ExportedProperty(category = "drawing")
13672    public boolean isDrawingCacheEnabled() {
13673        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13674    }
13675
13676    /**
13677     * Debugging utility which recursively outputs the dirty state of a view and its
13678     * descendants.
13679     *
13680     * @hide
13681     */
13682    @SuppressWarnings({"UnusedDeclaration"})
13683    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13684        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13685                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13686                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13687                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13688        if (clear) {
13689            mPrivateFlags &= clearMask;
13690        }
13691        if (this instanceof ViewGroup) {
13692            ViewGroup parent = (ViewGroup) this;
13693            final int count = parent.getChildCount();
13694            for (int i = 0; i < count; i++) {
13695                final View child = parent.getChildAt(i);
13696                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13697            }
13698        }
13699    }
13700
13701    /**
13702     * This method is used by ViewGroup to cause its children to restore or recreate their
13703     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13704     * to recreate its own display list, which would happen if it went through the normal
13705     * draw/dispatchDraw mechanisms.
13706     *
13707     * @hide
13708     */
13709    protected void dispatchGetDisplayList() {}
13710
13711    /**
13712     * A view that is not attached or hardware accelerated cannot create a display list.
13713     * This method checks these conditions and returns the appropriate result.
13714     *
13715     * @return true if view has the ability to create a display list, false otherwise.
13716     *
13717     * @hide
13718     */
13719    public boolean canHaveDisplayList() {
13720        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13721    }
13722
13723    private void updateDisplayListIfDirty() {
13724        final RenderNode renderNode = mRenderNode;
13725        if (!canHaveDisplayList()) {
13726            // can't populate RenderNode, don't try
13727            return;
13728        }
13729
13730        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13731                || !renderNode.isValid()
13732                || (mRecreateDisplayList)) {
13733            // Don't need to recreate the display list, just need to tell our
13734            // children to restore/recreate theirs
13735            if (renderNode.isValid()
13736                    && !mRecreateDisplayList) {
13737                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13738                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13739                dispatchGetDisplayList();
13740
13741                return; // no work needed
13742            }
13743
13744            // If we got here, we're recreating it. Mark it as such to ensure that
13745            // we copy in child display lists into ours in drawChild()
13746            mRecreateDisplayList = true;
13747
13748            int width = mRight - mLeft;
13749            int height = mBottom - mTop;
13750            int layerType = getLayerType();
13751
13752            final HardwareCanvas canvas = renderNode.start(width, height);
13753
13754            try {
13755                final HardwareLayer layer = getHardwareLayer();
13756                if (layer != null && layer.isValid()) {
13757                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13758                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13759                    buildDrawingCache(true);
13760                    Bitmap cache = getDrawingCache(true);
13761                    if (cache != null) {
13762                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13763                    }
13764                } else {
13765                    computeScroll();
13766
13767                    canvas.translate(-mScrollX, -mScrollY);
13768                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13769                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13770
13771                    // Fast path for layouts with no backgrounds
13772                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13773                        dispatchDraw(canvas);
13774                        if (mOverlay != null && !mOverlay.isEmpty()) {
13775                            mOverlay.getOverlayView().draw(canvas);
13776                        }
13777                    } else {
13778                        draw(canvas);
13779                    }
13780                }
13781            } finally {
13782                renderNode.end(canvas);
13783                setDisplayListProperties(renderNode);
13784            }
13785        } else {
13786            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13787            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13788        }
13789    }
13790
13791    /**
13792     * Returns a RenderNode with View draw content recorded, which can be
13793     * used to draw this view again without executing its draw method.
13794     *
13795     * @return A RenderNode ready to replay, or null if caching is not enabled.
13796     *
13797     * @hide
13798     */
13799    public RenderNode getDisplayList() {
13800        updateDisplayListIfDirty();
13801        return mRenderNode;
13802    }
13803
13804    private void resetDisplayList() {
13805        if (mRenderNode.isValid()) {
13806            mRenderNode.destroyDisplayListData();
13807        }
13808
13809        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13810            mBackgroundRenderNode.destroyDisplayListData();
13811        }
13812    }
13813
13814    /**
13815     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13816     *
13817     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13818     *
13819     * @see #getDrawingCache(boolean)
13820     */
13821    public Bitmap getDrawingCache() {
13822        return getDrawingCache(false);
13823    }
13824
13825    /**
13826     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13827     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13828     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13829     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13830     * request the drawing cache by calling this method and draw it on screen if the
13831     * returned bitmap is not null.</p>
13832     *
13833     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13834     * this method will create a bitmap of the same size as this view. Because this bitmap
13835     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13836     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13837     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13838     * size than the view. This implies that your application must be able to handle this
13839     * size.</p>
13840     *
13841     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13842     *        the current density of the screen when the application is in compatibility
13843     *        mode.
13844     *
13845     * @return A bitmap representing this view or null if cache is disabled.
13846     *
13847     * @see #setDrawingCacheEnabled(boolean)
13848     * @see #isDrawingCacheEnabled()
13849     * @see #buildDrawingCache(boolean)
13850     * @see #destroyDrawingCache()
13851     */
13852    public Bitmap getDrawingCache(boolean autoScale) {
13853        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13854            return null;
13855        }
13856        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13857            buildDrawingCache(autoScale);
13858        }
13859        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13860    }
13861
13862    /**
13863     * <p>Frees the resources used by the drawing cache. If you call
13864     * {@link #buildDrawingCache()} manually without calling
13865     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13866     * should cleanup the cache with this method afterwards.</p>
13867     *
13868     * @see #setDrawingCacheEnabled(boolean)
13869     * @see #buildDrawingCache()
13870     * @see #getDrawingCache()
13871     */
13872    public void destroyDrawingCache() {
13873        if (mDrawingCache != null) {
13874            mDrawingCache.recycle();
13875            mDrawingCache = null;
13876        }
13877        if (mUnscaledDrawingCache != null) {
13878            mUnscaledDrawingCache.recycle();
13879            mUnscaledDrawingCache = null;
13880        }
13881    }
13882
13883    /**
13884     * Setting a solid background color for the drawing cache's bitmaps will improve
13885     * performance and memory usage. Note, though that this should only be used if this
13886     * view will always be drawn on top of a solid color.
13887     *
13888     * @param color The background color to use for the drawing cache's bitmap
13889     *
13890     * @see #setDrawingCacheEnabled(boolean)
13891     * @see #buildDrawingCache()
13892     * @see #getDrawingCache()
13893     */
13894    public void setDrawingCacheBackgroundColor(int color) {
13895        if (color != mDrawingCacheBackgroundColor) {
13896            mDrawingCacheBackgroundColor = color;
13897            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13898        }
13899    }
13900
13901    /**
13902     * @see #setDrawingCacheBackgroundColor(int)
13903     *
13904     * @return The background color to used for the drawing cache's bitmap
13905     */
13906    public int getDrawingCacheBackgroundColor() {
13907        return mDrawingCacheBackgroundColor;
13908    }
13909
13910    /**
13911     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13912     *
13913     * @see #buildDrawingCache(boolean)
13914     */
13915    public void buildDrawingCache() {
13916        buildDrawingCache(false);
13917    }
13918
13919    /**
13920     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13921     *
13922     * <p>If you call {@link #buildDrawingCache()} manually without calling
13923     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13924     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13925     *
13926     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13927     * this method will create a bitmap of the same size as this view. Because this bitmap
13928     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13929     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13930     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13931     * size than the view. This implies that your application must be able to handle this
13932     * size.</p>
13933     *
13934     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13935     * you do not need the drawing cache bitmap, calling this method will increase memory
13936     * usage and cause the view to be rendered in software once, thus negatively impacting
13937     * performance.</p>
13938     *
13939     * @see #getDrawingCache()
13940     * @see #destroyDrawingCache()
13941     */
13942    public void buildDrawingCache(boolean autoScale) {
13943        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13944                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13945            mCachingFailed = false;
13946
13947            int width = mRight - mLeft;
13948            int height = mBottom - mTop;
13949
13950            final AttachInfo attachInfo = mAttachInfo;
13951            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13952
13953            if (autoScale && scalingRequired) {
13954                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13955                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13956            }
13957
13958            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13959            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13960            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13961
13962            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13963            final long drawingCacheSize =
13964                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13965            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13966                if (width > 0 && height > 0) {
13967                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13968                            + projectedBitmapSize + " bytes, only "
13969                            + drawingCacheSize + " available");
13970                }
13971                destroyDrawingCache();
13972                mCachingFailed = true;
13973                return;
13974            }
13975
13976            boolean clear = true;
13977            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13978
13979            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13980                Bitmap.Config quality;
13981                if (!opaque) {
13982                    // Never pick ARGB_4444 because it looks awful
13983                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13984                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13985                        case DRAWING_CACHE_QUALITY_AUTO:
13986                        case DRAWING_CACHE_QUALITY_LOW:
13987                        case DRAWING_CACHE_QUALITY_HIGH:
13988                        default:
13989                            quality = Bitmap.Config.ARGB_8888;
13990                            break;
13991                    }
13992                } else {
13993                    // Optimization for translucent windows
13994                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13995                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13996                }
13997
13998                // Try to cleanup memory
13999                if (bitmap != null) bitmap.recycle();
14000
14001                try {
14002                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14003                            width, height, quality);
14004                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14005                    if (autoScale) {
14006                        mDrawingCache = bitmap;
14007                    } else {
14008                        mUnscaledDrawingCache = bitmap;
14009                    }
14010                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14011                } catch (OutOfMemoryError e) {
14012                    // If there is not enough memory to create the bitmap cache, just
14013                    // ignore the issue as bitmap caches are not required to draw the
14014                    // view hierarchy
14015                    if (autoScale) {
14016                        mDrawingCache = null;
14017                    } else {
14018                        mUnscaledDrawingCache = null;
14019                    }
14020                    mCachingFailed = true;
14021                    return;
14022                }
14023
14024                clear = drawingCacheBackgroundColor != 0;
14025            }
14026
14027            Canvas canvas;
14028            if (attachInfo != null) {
14029                canvas = attachInfo.mCanvas;
14030                if (canvas == null) {
14031                    canvas = new Canvas();
14032                }
14033                canvas.setBitmap(bitmap);
14034                // Temporarily clobber the cached Canvas in case one of our children
14035                // is also using a drawing cache. Without this, the children would
14036                // steal the canvas by attaching their own bitmap to it and bad, bad
14037                // thing would happen (invisible views, corrupted drawings, etc.)
14038                attachInfo.mCanvas = null;
14039            } else {
14040                // This case should hopefully never or seldom happen
14041                canvas = new Canvas(bitmap);
14042            }
14043
14044            if (clear) {
14045                bitmap.eraseColor(drawingCacheBackgroundColor);
14046            }
14047
14048            computeScroll();
14049            final int restoreCount = canvas.save();
14050
14051            if (autoScale && scalingRequired) {
14052                final float scale = attachInfo.mApplicationScale;
14053                canvas.scale(scale, scale);
14054            }
14055
14056            canvas.translate(-mScrollX, -mScrollY);
14057
14058            mPrivateFlags |= PFLAG_DRAWN;
14059            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14060                    mLayerType != LAYER_TYPE_NONE) {
14061                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14062            }
14063
14064            // Fast path for layouts with no backgrounds
14065            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14066                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14067                dispatchDraw(canvas);
14068                if (mOverlay != null && !mOverlay.isEmpty()) {
14069                    mOverlay.getOverlayView().draw(canvas);
14070                }
14071            } else {
14072                draw(canvas);
14073            }
14074
14075            canvas.restoreToCount(restoreCount);
14076            canvas.setBitmap(null);
14077
14078            if (attachInfo != null) {
14079                // Restore the cached Canvas for our siblings
14080                attachInfo.mCanvas = canvas;
14081            }
14082        }
14083    }
14084
14085    /**
14086     * Create a snapshot of the view into a bitmap.  We should probably make
14087     * some form of this public, but should think about the API.
14088     */
14089    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14090        int width = mRight - mLeft;
14091        int height = mBottom - mTop;
14092
14093        final AttachInfo attachInfo = mAttachInfo;
14094        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14095        width = (int) ((width * scale) + 0.5f);
14096        height = (int) ((height * scale) + 0.5f);
14097
14098        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14099                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14100        if (bitmap == null) {
14101            throw new OutOfMemoryError();
14102        }
14103
14104        Resources resources = getResources();
14105        if (resources != null) {
14106            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14107        }
14108
14109        Canvas canvas;
14110        if (attachInfo != null) {
14111            canvas = attachInfo.mCanvas;
14112            if (canvas == null) {
14113                canvas = new Canvas();
14114            }
14115            canvas.setBitmap(bitmap);
14116            // Temporarily clobber the cached Canvas in case one of our children
14117            // is also using a drawing cache. Without this, the children would
14118            // steal the canvas by attaching their own bitmap to it and bad, bad
14119            // things would happen (invisible views, corrupted drawings, etc.)
14120            attachInfo.mCanvas = null;
14121        } else {
14122            // This case should hopefully never or seldom happen
14123            canvas = new Canvas(bitmap);
14124        }
14125
14126        if ((backgroundColor & 0xff000000) != 0) {
14127            bitmap.eraseColor(backgroundColor);
14128        }
14129
14130        computeScroll();
14131        final int restoreCount = canvas.save();
14132        canvas.scale(scale, scale);
14133        canvas.translate(-mScrollX, -mScrollY);
14134
14135        // Temporarily remove the dirty mask
14136        int flags = mPrivateFlags;
14137        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14138
14139        // Fast path for layouts with no backgrounds
14140        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14141            dispatchDraw(canvas);
14142            if (mOverlay != null && !mOverlay.isEmpty()) {
14143                mOverlay.getOverlayView().draw(canvas);
14144            }
14145        } else {
14146            draw(canvas);
14147        }
14148
14149        mPrivateFlags = flags;
14150
14151        canvas.restoreToCount(restoreCount);
14152        canvas.setBitmap(null);
14153
14154        if (attachInfo != null) {
14155            // Restore the cached Canvas for our siblings
14156            attachInfo.mCanvas = canvas;
14157        }
14158
14159        return bitmap;
14160    }
14161
14162    /**
14163     * Indicates whether this View is currently in edit mode. A View is usually
14164     * in edit mode when displayed within a developer tool. For instance, if
14165     * this View is being drawn by a visual user interface builder, this method
14166     * should return true.
14167     *
14168     * Subclasses should check the return value of this method to provide
14169     * different behaviors if their normal behavior might interfere with the
14170     * host environment. For instance: the class spawns a thread in its
14171     * constructor, the drawing code relies on device-specific features, etc.
14172     *
14173     * This method is usually checked in the drawing code of custom widgets.
14174     *
14175     * @return True if this View is in edit mode, false otherwise.
14176     */
14177    public boolean isInEditMode() {
14178        return false;
14179    }
14180
14181    /**
14182     * If the View draws content inside its padding and enables fading edges,
14183     * it needs to support padding offsets. Padding offsets are added to the
14184     * fading edges to extend the length of the fade so that it covers pixels
14185     * drawn inside the padding.
14186     *
14187     * Subclasses of this class should override this method if they need
14188     * to draw content inside the padding.
14189     *
14190     * @return True if padding offset must be applied, false otherwise.
14191     *
14192     * @see #getLeftPaddingOffset()
14193     * @see #getRightPaddingOffset()
14194     * @see #getTopPaddingOffset()
14195     * @see #getBottomPaddingOffset()
14196     *
14197     * @since CURRENT
14198     */
14199    protected boolean isPaddingOffsetRequired() {
14200        return false;
14201    }
14202
14203    /**
14204     * Amount by which to extend the left fading region. Called only when
14205     * {@link #isPaddingOffsetRequired()} returns true.
14206     *
14207     * @return The left padding offset in pixels.
14208     *
14209     * @see #isPaddingOffsetRequired()
14210     *
14211     * @since CURRENT
14212     */
14213    protected int getLeftPaddingOffset() {
14214        return 0;
14215    }
14216
14217    /**
14218     * Amount by which to extend the right fading region. Called only when
14219     * {@link #isPaddingOffsetRequired()} returns true.
14220     *
14221     * @return The right padding offset in pixels.
14222     *
14223     * @see #isPaddingOffsetRequired()
14224     *
14225     * @since CURRENT
14226     */
14227    protected int getRightPaddingOffset() {
14228        return 0;
14229    }
14230
14231    /**
14232     * Amount by which to extend the top fading region. Called only when
14233     * {@link #isPaddingOffsetRequired()} returns true.
14234     *
14235     * @return The top padding offset in pixels.
14236     *
14237     * @see #isPaddingOffsetRequired()
14238     *
14239     * @since CURRENT
14240     */
14241    protected int getTopPaddingOffset() {
14242        return 0;
14243    }
14244
14245    /**
14246     * Amount by which to extend the bottom fading region. Called only when
14247     * {@link #isPaddingOffsetRequired()} returns true.
14248     *
14249     * @return The bottom padding offset in pixels.
14250     *
14251     * @see #isPaddingOffsetRequired()
14252     *
14253     * @since CURRENT
14254     */
14255    protected int getBottomPaddingOffset() {
14256        return 0;
14257    }
14258
14259    /**
14260     * @hide
14261     * @param offsetRequired
14262     */
14263    protected int getFadeTop(boolean offsetRequired) {
14264        int top = mPaddingTop;
14265        if (offsetRequired) top += getTopPaddingOffset();
14266        return top;
14267    }
14268
14269    /**
14270     * @hide
14271     * @param offsetRequired
14272     */
14273    protected int getFadeHeight(boolean offsetRequired) {
14274        int padding = mPaddingTop;
14275        if (offsetRequired) padding += getTopPaddingOffset();
14276        return mBottom - mTop - mPaddingBottom - padding;
14277    }
14278
14279    /**
14280     * <p>Indicates whether this view is attached to a hardware accelerated
14281     * window or not.</p>
14282     *
14283     * <p>Even if this method returns true, it does not mean that every call
14284     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14285     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14286     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14287     * window is hardware accelerated,
14288     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14289     * return false, and this method will return true.</p>
14290     *
14291     * @return True if the view is attached to a window and the window is
14292     *         hardware accelerated; false in any other case.
14293     */
14294    @ViewDebug.ExportedProperty(category = "drawing")
14295    public boolean isHardwareAccelerated() {
14296        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14297    }
14298
14299    /**
14300     * Sets a rectangular area on this view to which the view will be clipped
14301     * when it is drawn. Setting the value to null will remove the clip bounds
14302     * and the view will draw normally, using its full bounds.
14303     *
14304     * @param clipBounds The rectangular area, in the local coordinates of
14305     * this view, to which future drawing operations will be clipped.
14306     */
14307    public void setClipBounds(Rect clipBounds) {
14308        if (clipBounds != null) {
14309            if (clipBounds.equals(mClipBounds)) {
14310                return;
14311            }
14312            if (mClipBounds == null) {
14313                invalidate();
14314                mClipBounds = new Rect(clipBounds);
14315            } else {
14316                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14317                        Math.min(mClipBounds.top, clipBounds.top),
14318                        Math.max(mClipBounds.right, clipBounds.right),
14319                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14320                mClipBounds.set(clipBounds);
14321            }
14322        } else {
14323            if (mClipBounds != null) {
14324                invalidate();
14325                mClipBounds = null;
14326            }
14327        }
14328    }
14329
14330    /**
14331     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14332     *
14333     * @return A copy of the current clip bounds if clip bounds are set,
14334     * otherwise null.
14335     */
14336    public Rect getClipBounds() {
14337        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14338    }
14339
14340    /**
14341     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14342     * case of an active Animation being run on the view.
14343     */
14344    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14345            Animation a, boolean scalingRequired) {
14346        Transformation invalidationTransform;
14347        final int flags = parent.mGroupFlags;
14348        final boolean initialized = a.isInitialized();
14349        if (!initialized) {
14350            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14351            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14352            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14353            onAnimationStart();
14354        }
14355
14356        final Transformation t = parent.getChildTransformation();
14357        boolean more = a.getTransformation(drawingTime, t, 1f);
14358        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14359            if (parent.mInvalidationTransformation == null) {
14360                parent.mInvalidationTransformation = new Transformation();
14361            }
14362            invalidationTransform = parent.mInvalidationTransformation;
14363            a.getTransformation(drawingTime, invalidationTransform, 1f);
14364        } else {
14365            invalidationTransform = t;
14366        }
14367
14368        if (more) {
14369            if (!a.willChangeBounds()) {
14370                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14371                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14372                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14373                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14374                    // The child need to draw an animation, potentially offscreen, so
14375                    // make sure we do not cancel invalidate requests
14376                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14377                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14378                }
14379            } else {
14380                if (parent.mInvalidateRegion == null) {
14381                    parent.mInvalidateRegion = new RectF();
14382                }
14383                final RectF region = parent.mInvalidateRegion;
14384                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14385                        invalidationTransform);
14386
14387                // The child need to draw an animation, potentially offscreen, so
14388                // make sure we do not cancel invalidate requests
14389                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14390
14391                final int left = mLeft + (int) region.left;
14392                final int top = mTop + (int) region.top;
14393                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14394                        top + (int) (region.height() + .5f));
14395            }
14396        }
14397        return more;
14398    }
14399
14400    /**
14401     * This method is called by getDisplayList() when a display list is recorded for a View.
14402     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14403     */
14404    void setDisplayListProperties(RenderNode renderNode) {
14405        if (renderNode != null) {
14406            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14407            if (mParent instanceof ViewGroup) {
14408                renderNode.setClipToBounds(
14409                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14410            }
14411            float alpha = 1;
14412            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14413                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14414                ViewGroup parentVG = (ViewGroup) mParent;
14415                final Transformation t = parentVG.getChildTransformation();
14416                if (parentVG.getChildStaticTransformation(this, t)) {
14417                    final int transformType = t.getTransformationType();
14418                    if (transformType != Transformation.TYPE_IDENTITY) {
14419                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14420                            alpha = t.getAlpha();
14421                        }
14422                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14423                            renderNode.setStaticMatrix(t.getMatrix());
14424                        }
14425                    }
14426                }
14427            }
14428            if (mTransformationInfo != null) {
14429                alpha *= getFinalAlpha();
14430                if (alpha < 1) {
14431                    final int multipliedAlpha = (int) (255 * alpha);
14432                    if (onSetAlpha(multipliedAlpha)) {
14433                        alpha = 1;
14434                    }
14435                }
14436                renderNode.setAlpha(alpha);
14437            } else if (alpha < 1) {
14438                renderNode.setAlpha(alpha);
14439            }
14440        }
14441    }
14442
14443    /**
14444     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14445     * This draw() method is an implementation detail and is not intended to be overridden or
14446     * to be called from anywhere else other than ViewGroup.drawChild().
14447     */
14448    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14449        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14450        boolean more = false;
14451        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14452        final int flags = parent.mGroupFlags;
14453
14454        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14455            parent.getChildTransformation().clear();
14456            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14457        }
14458
14459        Transformation transformToApply = null;
14460        boolean concatMatrix = false;
14461
14462        boolean scalingRequired = false;
14463        boolean caching;
14464        int layerType = getLayerType();
14465
14466        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14467        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14468                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14469            caching = true;
14470            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14471            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14472        } else {
14473            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14474        }
14475
14476        final Animation a = getAnimation();
14477        if (a != null) {
14478            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14479            concatMatrix = a.willChangeTransformationMatrix();
14480            if (concatMatrix) {
14481                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14482            }
14483            transformToApply = parent.getChildTransformation();
14484        } else {
14485            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14486                // No longer animating: clear out old animation matrix
14487                mRenderNode.setAnimationMatrix(null);
14488                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14489            }
14490            if (!useDisplayListProperties &&
14491                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14492                final Transformation t = parent.getChildTransformation();
14493                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14494                if (hasTransform) {
14495                    final int transformType = t.getTransformationType();
14496                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14497                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14498                }
14499            }
14500        }
14501
14502        concatMatrix |= !childHasIdentityMatrix;
14503
14504        // Sets the flag as early as possible to allow draw() implementations
14505        // to call invalidate() successfully when doing animations
14506        mPrivateFlags |= PFLAG_DRAWN;
14507
14508        if (!concatMatrix &&
14509                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14510                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14511                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14512                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14513            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14514            return more;
14515        }
14516        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14517
14518        if (hardwareAccelerated) {
14519            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14520            // retain the flag's value temporarily in the mRecreateDisplayList flag
14521            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14522            mPrivateFlags &= ~PFLAG_INVALIDATED;
14523        }
14524
14525        RenderNode renderNode = null;
14526        Bitmap cache = null;
14527        boolean hasDisplayList = false;
14528        if (caching) {
14529            if (!hardwareAccelerated) {
14530                if (layerType != LAYER_TYPE_NONE) {
14531                    layerType = LAYER_TYPE_SOFTWARE;
14532                    buildDrawingCache(true);
14533                }
14534                cache = getDrawingCache(true);
14535            } else {
14536                switch (layerType) {
14537                    case LAYER_TYPE_SOFTWARE:
14538                        if (useDisplayListProperties) {
14539                            hasDisplayList = canHaveDisplayList();
14540                        } else {
14541                            buildDrawingCache(true);
14542                            cache = getDrawingCache(true);
14543                        }
14544                        break;
14545                    case LAYER_TYPE_HARDWARE:
14546                        if (useDisplayListProperties) {
14547                            hasDisplayList = canHaveDisplayList();
14548                        }
14549                        break;
14550                    case LAYER_TYPE_NONE:
14551                        // Delay getting the display list until animation-driven alpha values are
14552                        // set up and possibly passed on to the view
14553                        hasDisplayList = canHaveDisplayList();
14554                        break;
14555                }
14556            }
14557        }
14558        useDisplayListProperties &= hasDisplayList;
14559        if (useDisplayListProperties) {
14560            renderNode = getDisplayList();
14561            if (!renderNode.isValid()) {
14562                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14563                // to getDisplayList(), the display list will be marked invalid and we should not
14564                // try to use it again.
14565                renderNode = null;
14566                hasDisplayList = false;
14567                useDisplayListProperties = false;
14568            }
14569        }
14570
14571        int sx = 0;
14572        int sy = 0;
14573        if (!hasDisplayList) {
14574            computeScroll();
14575            sx = mScrollX;
14576            sy = mScrollY;
14577        }
14578
14579        final boolean hasNoCache = cache == null || hasDisplayList;
14580        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14581                layerType != LAYER_TYPE_HARDWARE;
14582
14583        int restoreTo = -1;
14584        if (!useDisplayListProperties || transformToApply != null) {
14585            restoreTo = canvas.save();
14586        }
14587        if (offsetForScroll) {
14588            canvas.translate(mLeft - sx, mTop - sy);
14589        } else {
14590            if (!useDisplayListProperties) {
14591                canvas.translate(mLeft, mTop);
14592            }
14593            if (scalingRequired) {
14594                if (useDisplayListProperties) {
14595                    // TODO: Might not need this if we put everything inside the DL
14596                    restoreTo = canvas.save();
14597                }
14598                // mAttachInfo cannot be null, otherwise scalingRequired == false
14599                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14600                canvas.scale(scale, scale);
14601            }
14602        }
14603
14604        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14605        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14606                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14607            if (transformToApply != null || !childHasIdentityMatrix) {
14608                int transX = 0;
14609                int transY = 0;
14610
14611                if (offsetForScroll) {
14612                    transX = -sx;
14613                    transY = -sy;
14614                }
14615
14616                if (transformToApply != null) {
14617                    if (concatMatrix) {
14618                        if (useDisplayListProperties) {
14619                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14620                        } else {
14621                            // Undo the scroll translation, apply the transformation matrix,
14622                            // then redo the scroll translate to get the correct result.
14623                            canvas.translate(-transX, -transY);
14624                            canvas.concat(transformToApply.getMatrix());
14625                            canvas.translate(transX, transY);
14626                        }
14627                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14628                    }
14629
14630                    float transformAlpha = transformToApply.getAlpha();
14631                    if (transformAlpha < 1) {
14632                        alpha *= transformAlpha;
14633                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14634                    }
14635                }
14636
14637                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14638                    canvas.translate(-transX, -transY);
14639                    canvas.concat(getMatrix());
14640                    canvas.translate(transX, transY);
14641                }
14642            }
14643
14644            // Deal with alpha if it is or used to be <1
14645            if (alpha < 1 ||
14646                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14647                if (alpha < 1) {
14648                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14649                } else {
14650                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14651                }
14652                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14653                if (hasNoCache) {
14654                    final int multipliedAlpha = (int) (255 * alpha);
14655                    if (!onSetAlpha(multipliedAlpha)) {
14656                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14657                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14658                                layerType != LAYER_TYPE_NONE) {
14659                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14660                        }
14661                        if (useDisplayListProperties) {
14662                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14663                        } else  if (layerType == LAYER_TYPE_NONE) {
14664                            final int scrollX = hasDisplayList ? 0 : sx;
14665                            final int scrollY = hasDisplayList ? 0 : sy;
14666                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14667                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14668                        }
14669                    } else {
14670                        // Alpha is handled by the child directly, clobber the layer's alpha
14671                        mPrivateFlags |= PFLAG_ALPHA_SET;
14672                    }
14673                }
14674            }
14675        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14676            onSetAlpha(255);
14677            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14678        }
14679
14680        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14681                !useDisplayListProperties && cache == null) {
14682            if (offsetForScroll) {
14683                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14684            } else {
14685                if (!scalingRequired || cache == null) {
14686                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14687                } else {
14688                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14689                }
14690            }
14691        }
14692
14693        if (!useDisplayListProperties && hasDisplayList) {
14694            renderNode = getDisplayList();
14695            if (!renderNode.isValid()) {
14696                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14697                // to getDisplayList(), the display list will be marked invalid and we should not
14698                // try to use it again.
14699                renderNode = null;
14700                hasDisplayList = false;
14701            }
14702        }
14703
14704        if (hasNoCache) {
14705            boolean layerRendered = false;
14706            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14707                final HardwareLayer layer = getHardwareLayer();
14708                if (layer != null && layer.isValid()) {
14709                    mLayerPaint.setAlpha((int) (alpha * 255));
14710                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14711                    layerRendered = true;
14712                } else {
14713                    final int scrollX = hasDisplayList ? 0 : sx;
14714                    final int scrollY = hasDisplayList ? 0 : sy;
14715                    canvas.saveLayer(scrollX, scrollY,
14716                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14717                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14718                }
14719            }
14720
14721            if (!layerRendered) {
14722                if (!hasDisplayList) {
14723                    // Fast path for layouts with no backgrounds
14724                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14725                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14726                        dispatchDraw(canvas);
14727                    } else {
14728                        draw(canvas);
14729                    }
14730                } else {
14731                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14732                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14733                }
14734            }
14735        } else if (cache != null) {
14736            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14737            Paint cachePaint;
14738
14739            if (layerType == LAYER_TYPE_NONE) {
14740                cachePaint = parent.mCachePaint;
14741                if (cachePaint == null) {
14742                    cachePaint = new Paint();
14743                    cachePaint.setDither(false);
14744                    parent.mCachePaint = cachePaint;
14745                }
14746                if (alpha < 1) {
14747                    cachePaint.setAlpha((int) (alpha * 255));
14748                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14749                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14750                    cachePaint.setAlpha(255);
14751                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14752                }
14753            } else {
14754                cachePaint = mLayerPaint;
14755                cachePaint.setAlpha((int) (alpha * 255));
14756            }
14757            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14758        }
14759
14760        if (restoreTo >= 0) {
14761            canvas.restoreToCount(restoreTo);
14762        }
14763
14764        if (a != null && !more) {
14765            if (!hardwareAccelerated && !a.getFillAfter()) {
14766                onSetAlpha(255);
14767            }
14768            parent.finishAnimatingView(this, a);
14769        }
14770
14771        if (more && hardwareAccelerated) {
14772            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14773                // alpha animations should cause the child to recreate its display list
14774                invalidate(true);
14775            }
14776        }
14777
14778        mRecreateDisplayList = false;
14779
14780        return more;
14781    }
14782
14783    /**
14784     * Manually render this view (and all of its children) to the given Canvas.
14785     * The view must have already done a full layout before this function is
14786     * called.  When implementing a view, implement
14787     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14788     * If you do need to override this method, call the superclass version.
14789     *
14790     * @param canvas The Canvas to which the View is rendered.
14791     */
14792    public void draw(Canvas canvas) {
14793        if (mClipBounds != null) {
14794            canvas.clipRect(mClipBounds);
14795        }
14796        final int privateFlags = mPrivateFlags;
14797        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14798                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14799        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14800
14801        /*
14802         * Draw traversal performs several drawing steps which must be executed
14803         * in the appropriate order:
14804         *
14805         *      1. Draw the background
14806         *      2. If necessary, save the canvas' layers to prepare for fading
14807         *      3. Draw view's content
14808         *      4. Draw children
14809         *      5. If necessary, draw the fading edges and restore layers
14810         *      6. Draw decorations (scrollbars for instance)
14811         */
14812
14813        // Step 1, draw the background, if needed
14814        int saveCount;
14815
14816        if (!dirtyOpaque) {
14817            drawBackground(canvas);
14818        }
14819
14820        // skip step 2 & 5 if possible (common case)
14821        final int viewFlags = mViewFlags;
14822        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14823        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14824        if (!verticalEdges && !horizontalEdges) {
14825            // Step 3, draw the content
14826            if (!dirtyOpaque) onDraw(canvas);
14827
14828            // Step 4, draw the children
14829            dispatchDraw(canvas);
14830
14831            // Step 6, draw decorations (scrollbars)
14832            onDrawScrollBars(canvas);
14833
14834            if (mOverlay != null && !mOverlay.isEmpty()) {
14835                mOverlay.getOverlayView().dispatchDraw(canvas);
14836            }
14837
14838            // we're done...
14839            return;
14840        }
14841
14842        /*
14843         * Here we do the full fledged routine...
14844         * (this is an uncommon case where speed matters less,
14845         * this is why we repeat some of the tests that have been
14846         * done above)
14847         */
14848
14849        boolean drawTop = false;
14850        boolean drawBottom = false;
14851        boolean drawLeft = false;
14852        boolean drawRight = false;
14853
14854        float topFadeStrength = 0.0f;
14855        float bottomFadeStrength = 0.0f;
14856        float leftFadeStrength = 0.0f;
14857        float rightFadeStrength = 0.0f;
14858
14859        // Step 2, save the canvas' layers
14860        int paddingLeft = mPaddingLeft;
14861
14862        final boolean offsetRequired = isPaddingOffsetRequired();
14863        if (offsetRequired) {
14864            paddingLeft += getLeftPaddingOffset();
14865        }
14866
14867        int left = mScrollX + paddingLeft;
14868        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14869        int top = mScrollY + getFadeTop(offsetRequired);
14870        int bottom = top + getFadeHeight(offsetRequired);
14871
14872        if (offsetRequired) {
14873            right += getRightPaddingOffset();
14874            bottom += getBottomPaddingOffset();
14875        }
14876
14877        final ScrollabilityCache scrollabilityCache = mScrollCache;
14878        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14879        int length = (int) fadeHeight;
14880
14881        // clip the fade length if top and bottom fades overlap
14882        // overlapping fades produce odd-looking artifacts
14883        if (verticalEdges && (top + length > bottom - length)) {
14884            length = (bottom - top) / 2;
14885        }
14886
14887        // also clip horizontal fades if necessary
14888        if (horizontalEdges && (left + length > right - length)) {
14889            length = (right - left) / 2;
14890        }
14891
14892        if (verticalEdges) {
14893            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14894            drawTop = topFadeStrength * fadeHeight > 1.0f;
14895            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14896            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14897        }
14898
14899        if (horizontalEdges) {
14900            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14901            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14902            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14903            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14904        }
14905
14906        saveCount = canvas.getSaveCount();
14907
14908        int solidColor = getSolidColor();
14909        if (solidColor == 0) {
14910            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14911
14912            if (drawTop) {
14913                canvas.saveLayer(left, top, right, top + length, null, flags);
14914            }
14915
14916            if (drawBottom) {
14917                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14918            }
14919
14920            if (drawLeft) {
14921                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14922            }
14923
14924            if (drawRight) {
14925                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14926            }
14927        } else {
14928            scrollabilityCache.setFadeColor(solidColor);
14929        }
14930
14931        // Step 3, draw the content
14932        if (!dirtyOpaque) onDraw(canvas);
14933
14934        // Step 4, draw the children
14935        dispatchDraw(canvas);
14936
14937        // Step 5, draw the fade effect and restore layers
14938        final Paint p = scrollabilityCache.paint;
14939        final Matrix matrix = scrollabilityCache.matrix;
14940        final Shader fade = scrollabilityCache.shader;
14941
14942        if (drawTop) {
14943            matrix.setScale(1, fadeHeight * topFadeStrength);
14944            matrix.postTranslate(left, top);
14945            fade.setLocalMatrix(matrix);
14946            canvas.drawRect(left, top, right, top + length, p);
14947        }
14948
14949        if (drawBottom) {
14950            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14951            matrix.postRotate(180);
14952            matrix.postTranslate(left, bottom);
14953            fade.setLocalMatrix(matrix);
14954            canvas.drawRect(left, bottom - length, right, bottom, p);
14955        }
14956
14957        if (drawLeft) {
14958            matrix.setScale(1, fadeHeight * leftFadeStrength);
14959            matrix.postRotate(-90);
14960            matrix.postTranslate(left, top);
14961            fade.setLocalMatrix(matrix);
14962            canvas.drawRect(left, top, left + length, bottom, p);
14963        }
14964
14965        if (drawRight) {
14966            matrix.setScale(1, fadeHeight * rightFadeStrength);
14967            matrix.postRotate(90);
14968            matrix.postTranslate(right, top);
14969            fade.setLocalMatrix(matrix);
14970            canvas.drawRect(right - length, top, right, bottom, p);
14971        }
14972
14973        canvas.restoreToCount(saveCount);
14974
14975        // Step 6, draw decorations (scrollbars)
14976        onDrawScrollBars(canvas);
14977
14978        if (mOverlay != null && !mOverlay.isEmpty()) {
14979            mOverlay.getOverlayView().dispatchDraw(canvas);
14980        }
14981    }
14982
14983    /**
14984     * Draws the background onto the specified canvas.
14985     *
14986     * @param canvas Canvas on which to draw the background
14987     */
14988    private void drawBackground(Canvas canvas) {
14989        final Drawable background = mBackground;
14990        if (background == null) {
14991            return;
14992        }
14993
14994        if (mBackgroundSizeChanged) {
14995            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14996            mBackgroundSizeChanged = false;
14997            queryOutlineFromBackgroundIfUndefined();
14998        }
14999
15000        // Attempt to use a display list if requested.
15001        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15002                && mAttachInfo.mHardwareRenderer != null) {
15003            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15004
15005            final RenderNode displayList = mBackgroundRenderNode;
15006            if (displayList != null && displayList.isValid()) {
15007                setBackgroundDisplayListProperties(displayList);
15008                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15009                return;
15010            }
15011        }
15012
15013        final int scrollX = mScrollX;
15014        final int scrollY = mScrollY;
15015        if ((scrollX | scrollY) == 0) {
15016            background.draw(canvas);
15017        } else {
15018            canvas.translate(scrollX, scrollY);
15019            background.draw(canvas);
15020            canvas.translate(-scrollX, -scrollY);
15021        }
15022    }
15023
15024    /**
15025     * Set up background drawable display list properties.
15026     *
15027     * @param displayList Valid display list for the background drawable
15028     */
15029    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15030        displayList.setTranslationX(mScrollX);
15031        displayList.setTranslationY(mScrollY);
15032    }
15033
15034    /**
15035     * Creates a new display list or updates the existing display list for the
15036     * specified Drawable.
15037     *
15038     * @param drawable Drawable for which to create a display list
15039     * @param renderNode Existing RenderNode, or {@code null}
15040     * @return A valid display list for the specified drawable
15041     */
15042    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15043        if (renderNode == null) {
15044            renderNode = RenderNode.create(drawable.getClass().getName());
15045        }
15046
15047        final Rect bounds = drawable.getBounds();
15048        final int width = bounds.width();
15049        final int height = bounds.height();
15050        final HardwareCanvas canvas = renderNode.start(width, height);
15051        try {
15052            drawable.draw(canvas);
15053        } finally {
15054            renderNode.end(canvas);
15055        }
15056
15057        // Set up drawable properties that are view-independent.
15058        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15059        renderNode.setProjectBackwards(drawable.isProjected());
15060        renderNode.setProjectionReceiver(true);
15061        renderNode.setClipToBounds(false);
15062        return renderNode;
15063    }
15064
15065    /**
15066     * Returns the overlay for this view, creating it if it does not yet exist.
15067     * Adding drawables to the overlay will cause them to be displayed whenever
15068     * the view itself is redrawn. Objects in the overlay should be actively
15069     * managed: remove them when they should not be displayed anymore. The
15070     * overlay will always have the same size as its host view.
15071     *
15072     * <p>Note: Overlays do not currently work correctly with {@link
15073     * SurfaceView} or {@link TextureView}; contents in overlays for these
15074     * types of views may not display correctly.</p>
15075     *
15076     * @return The ViewOverlay object for this view.
15077     * @see ViewOverlay
15078     */
15079    public ViewOverlay getOverlay() {
15080        if (mOverlay == null) {
15081            mOverlay = new ViewOverlay(mContext, this);
15082        }
15083        return mOverlay;
15084    }
15085
15086    /**
15087     * Override this if your view is known to always be drawn on top of a solid color background,
15088     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15089     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15090     * should be set to 0xFF.
15091     *
15092     * @see #setVerticalFadingEdgeEnabled(boolean)
15093     * @see #setHorizontalFadingEdgeEnabled(boolean)
15094     *
15095     * @return The known solid color background for this view, or 0 if the color may vary
15096     */
15097    @ViewDebug.ExportedProperty(category = "drawing")
15098    public int getSolidColor() {
15099        return 0;
15100    }
15101
15102    /**
15103     * Build a human readable string representation of the specified view flags.
15104     *
15105     * @param flags the view flags to convert to a string
15106     * @return a String representing the supplied flags
15107     */
15108    private static String printFlags(int flags) {
15109        String output = "";
15110        int numFlags = 0;
15111        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15112            output += "TAKES_FOCUS";
15113            numFlags++;
15114        }
15115
15116        switch (flags & VISIBILITY_MASK) {
15117        case INVISIBLE:
15118            if (numFlags > 0) {
15119                output += " ";
15120            }
15121            output += "INVISIBLE";
15122            // USELESS HERE numFlags++;
15123            break;
15124        case GONE:
15125            if (numFlags > 0) {
15126                output += " ";
15127            }
15128            output += "GONE";
15129            // USELESS HERE numFlags++;
15130            break;
15131        default:
15132            break;
15133        }
15134        return output;
15135    }
15136
15137    /**
15138     * Build a human readable string representation of the specified private
15139     * view flags.
15140     *
15141     * @param privateFlags the private view flags to convert to a string
15142     * @return a String representing the supplied flags
15143     */
15144    private static String printPrivateFlags(int privateFlags) {
15145        String output = "";
15146        int numFlags = 0;
15147
15148        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15149            output += "WANTS_FOCUS";
15150            numFlags++;
15151        }
15152
15153        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15154            if (numFlags > 0) {
15155                output += " ";
15156            }
15157            output += "FOCUSED";
15158            numFlags++;
15159        }
15160
15161        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15162            if (numFlags > 0) {
15163                output += " ";
15164            }
15165            output += "SELECTED";
15166            numFlags++;
15167        }
15168
15169        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15170            if (numFlags > 0) {
15171                output += " ";
15172            }
15173            output += "IS_ROOT_NAMESPACE";
15174            numFlags++;
15175        }
15176
15177        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15178            if (numFlags > 0) {
15179                output += " ";
15180            }
15181            output += "HAS_BOUNDS";
15182            numFlags++;
15183        }
15184
15185        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15186            if (numFlags > 0) {
15187                output += " ";
15188            }
15189            output += "DRAWN";
15190            // USELESS HERE numFlags++;
15191        }
15192        return output;
15193    }
15194
15195    /**
15196     * <p>Indicates whether or not this view's layout will be requested during
15197     * the next hierarchy layout pass.</p>
15198     *
15199     * @return true if the layout will be forced during next layout pass
15200     */
15201    public boolean isLayoutRequested() {
15202        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15203    }
15204
15205    /**
15206     * Return true if o is a ViewGroup that is laying out using optical bounds.
15207     * @hide
15208     */
15209    public static boolean isLayoutModeOptical(Object o) {
15210        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15211    }
15212
15213    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15214        Insets parentInsets = mParent instanceof View ?
15215                ((View) mParent).getOpticalInsets() : Insets.NONE;
15216        Insets childInsets = getOpticalInsets();
15217        return setFrame(
15218                left   + parentInsets.left - childInsets.left,
15219                top    + parentInsets.top  - childInsets.top,
15220                right  + parentInsets.left + childInsets.right,
15221                bottom + parentInsets.top  + childInsets.bottom);
15222    }
15223
15224    /**
15225     * Assign a size and position to a view and all of its
15226     * descendants
15227     *
15228     * <p>This is the second phase of the layout mechanism.
15229     * (The first is measuring). In this phase, each parent calls
15230     * layout on all of its children to position them.
15231     * This is typically done using the child measurements
15232     * that were stored in the measure pass().</p>
15233     *
15234     * <p>Derived classes should not override this method.
15235     * Derived classes with children should override
15236     * onLayout. In that method, they should
15237     * call layout on each of their children.</p>
15238     *
15239     * @param l Left position, relative to parent
15240     * @param t Top position, relative to parent
15241     * @param r Right position, relative to parent
15242     * @param b Bottom position, relative to parent
15243     */
15244    @SuppressWarnings({"unchecked"})
15245    public void layout(int l, int t, int r, int b) {
15246        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15247            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15248            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15249        }
15250
15251        int oldL = mLeft;
15252        int oldT = mTop;
15253        int oldB = mBottom;
15254        int oldR = mRight;
15255
15256        boolean changed = isLayoutModeOptical(mParent) ?
15257                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15258
15259        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15260            onLayout(changed, l, t, r, b);
15261            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15262
15263            ListenerInfo li = mListenerInfo;
15264            if (li != null && li.mOnLayoutChangeListeners != null) {
15265                ArrayList<OnLayoutChangeListener> listenersCopy =
15266                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15267                int numListeners = listenersCopy.size();
15268                for (int i = 0; i < numListeners; ++i) {
15269                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15270                }
15271            }
15272        }
15273
15274        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15275        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15276    }
15277
15278    /**
15279     * Called from layout when this view should
15280     * assign a size and position to each of its children.
15281     *
15282     * Derived classes with children should override
15283     * this method and call layout on each of
15284     * their children.
15285     * @param changed This is a new size or position for this view
15286     * @param left Left position, relative to parent
15287     * @param top Top position, relative to parent
15288     * @param right Right position, relative to parent
15289     * @param bottom Bottom position, relative to parent
15290     */
15291    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15292    }
15293
15294    /**
15295     * Assign a size and position to this view.
15296     *
15297     * This is called from layout.
15298     *
15299     * @param left Left position, relative to parent
15300     * @param top Top position, relative to parent
15301     * @param right Right position, relative to parent
15302     * @param bottom Bottom position, relative to parent
15303     * @return true if the new size and position are different than the
15304     *         previous ones
15305     * {@hide}
15306     */
15307    protected boolean setFrame(int left, int top, int right, int bottom) {
15308        boolean changed = false;
15309
15310        if (DBG) {
15311            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15312                    + right + "," + bottom + ")");
15313        }
15314
15315        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15316            changed = true;
15317
15318            // Remember our drawn bit
15319            int drawn = mPrivateFlags & PFLAG_DRAWN;
15320
15321            int oldWidth = mRight - mLeft;
15322            int oldHeight = mBottom - mTop;
15323            int newWidth = right - left;
15324            int newHeight = bottom - top;
15325            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15326
15327            // Invalidate our old position
15328            invalidate(sizeChanged);
15329
15330            mLeft = left;
15331            mTop = top;
15332            mRight = right;
15333            mBottom = bottom;
15334            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15335
15336            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15337
15338
15339            if (sizeChanged) {
15340                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15341            }
15342
15343            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15344                // If we are visible, force the DRAWN bit to on so that
15345                // this invalidate will go through (at least to our parent).
15346                // This is because someone may have invalidated this view
15347                // before this call to setFrame came in, thereby clearing
15348                // the DRAWN bit.
15349                mPrivateFlags |= PFLAG_DRAWN;
15350                invalidate(sizeChanged);
15351                // parent display list may need to be recreated based on a change in the bounds
15352                // of any child
15353                invalidateParentCaches();
15354            }
15355
15356            // Reset drawn bit to original value (invalidate turns it off)
15357            mPrivateFlags |= drawn;
15358
15359            mBackgroundSizeChanged = true;
15360
15361            notifySubtreeAccessibilityStateChangedIfNeeded();
15362        }
15363        return changed;
15364    }
15365
15366    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15367        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15368        if (mOverlay != null) {
15369            mOverlay.getOverlayView().setRight(newWidth);
15370            mOverlay.getOverlayView().setBottom(newHeight);
15371        }
15372    }
15373
15374    /**
15375     * Finalize inflating a view from XML.  This is called as the last phase
15376     * of inflation, after all child views have been added.
15377     *
15378     * <p>Even if the subclass overrides onFinishInflate, they should always be
15379     * sure to call the super method, so that we get called.
15380     */
15381    protected void onFinishInflate() {
15382    }
15383
15384    /**
15385     * Returns the resources associated with this view.
15386     *
15387     * @return Resources object.
15388     */
15389    public Resources getResources() {
15390        return mResources;
15391    }
15392
15393    /**
15394     * Invalidates the specified Drawable.
15395     *
15396     * @param drawable the drawable to invalidate
15397     */
15398    @Override
15399    public void invalidateDrawable(@NonNull Drawable drawable) {
15400        if (verifyDrawable(drawable)) {
15401            final Rect dirty = drawable.getDirtyBounds();
15402            final int scrollX = mScrollX;
15403            final int scrollY = mScrollY;
15404
15405            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15406                    dirty.right + scrollX, dirty.bottom + scrollY);
15407
15408            if (drawable == mBackground) {
15409                queryOutlineFromBackgroundIfUndefined();
15410            }
15411        }
15412    }
15413
15414    /**
15415     * Schedules an action on a drawable to occur at a specified time.
15416     *
15417     * @param who the recipient of the action
15418     * @param what the action to run on the drawable
15419     * @param when the time at which the action must occur. Uses the
15420     *        {@link SystemClock#uptimeMillis} timebase.
15421     */
15422    @Override
15423    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15424        if (verifyDrawable(who) && what != null) {
15425            final long delay = when - SystemClock.uptimeMillis();
15426            if (mAttachInfo != null) {
15427                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15428                        Choreographer.CALLBACK_ANIMATION, what, who,
15429                        Choreographer.subtractFrameDelay(delay));
15430            } else {
15431                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15432            }
15433        }
15434    }
15435
15436    /**
15437     * Cancels a scheduled action on a drawable.
15438     *
15439     * @param who the recipient of the action
15440     * @param what the action to cancel
15441     */
15442    @Override
15443    public void unscheduleDrawable(Drawable who, Runnable what) {
15444        if (verifyDrawable(who) && what != null) {
15445            if (mAttachInfo != null) {
15446                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15447                        Choreographer.CALLBACK_ANIMATION, what, who);
15448            }
15449            ViewRootImpl.getRunQueue().removeCallbacks(what);
15450        }
15451    }
15452
15453    /**
15454     * Unschedule any events associated with the given Drawable.  This can be
15455     * used when selecting a new Drawable into a view, so that the previous
15456     * one is completely unscheduled.
15457     *
15458     * @param who The Drawable to unschedule.
15459     *
15460     * @see #drawableStateChanged
15461     */
15462    public void unscheduleDrawable(Drawable who) {
15463        if (mAttachInfo != null && who != null) {
15464            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15465                    Choreographer.CALLBACK_ANIMATION, null, who);
15466        }
15467    }
15468
15469    /**
15470     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15471     * that the View directionality can and will be resolved before its Drawables.
15472     *
15473     * Will call {@link View#onResolveDrawables} when resolution is done.
15474     *
15475     * @hide
15476     */
15477    protected void resolveDrawables() {
15478        // Drawables resolution may need to happen before resolving the layout direction (which is
15479        // done only during the measure() call).
15480        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15481        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15482        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15483        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15484        // direction to be resolved as its resolved value will be the same as its raw value.
15485        if (!isLayoutDirectionResolved() &&
15486                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15487            return;
15488        }
15489
15490        final int layoutDirection = isLayoutDirectionResolved() ?
15491                getLayoutDirection() : getRawLayoutDirection();
15492
15493        if (mBackground != null) {
15494            mBackground.setLayoutDirection(layoutDirection);
15495        }
15496        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15497        onResolveDrawables(layoutDirection);
15498    }
15499
15500    /**
15501     * Called when layout direction has been resolved.
15502     *
15503     * The default implementation does nothing.
15504     *
15505     * @param layoutDirection The resolved layout direction.
15506     *
15507     * @see #LAYOUT_DIRECTION_LTR
15508     * @see #LAYOUT_DIRECTION_RTL
15509     *
15510     * @hide
15511     */
15512    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15513    }
15514
15515    /**
15516     * @hide
15517     */
15518    protected void resetResolvedDrawables() {
15519        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15520    }
15521
15522    private boolean isDrawablesResolved() {
15523        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15524    }
15525
15526    /**
15527     * If your view subclass is displaying its own Drawable objects, it should
15528     * override this function and return true for any Drawable it is
15529     * displaying.  This allows animations for those drawables to be
15530     * scheduled.
15531     *
15532     * <p>Be sure to call through to the super class when overriding this
15533     * function.
15534     *
15535     * @param who The Drawable to verify.  Return true if it is one you are
15536     *            displaying, else return the result of calling through to the
15537     *            super class.
15538     *
15539     * @return boolean If true than the Drawable is being displayed in the
15540     *         view; else false and it is not allowed to animate.
15541     *
15542     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15543     * @see #drawableStateChanged()
15544     */
15545    protected boolean verifyDrawable(Drawable who) {
15546        return who == mBackground;
15547    }
15548
15549    /**
15550     * This function is called whenever the state of the view changes in such
15551     * a way that it impacts the state of drawables being shown.
15552     * <p>
15553     * If the View has a StateListAnimator, it will also be called to run necessary state
15554     * change animations.
15555     * <p>
15556     * Be sure to call through to the superclass when overriding this function.
15557     *
15558     * @see Drawable#setState(int[])
15559     */
15560    protected void drawableStateChanged() {
15561        final Drawable d = mBackground;
15562        if (d != null && d.isStateful()) {
15563            d.setState(getDrawableState());
15564        }
15565
15566        if (mStateListAnimator != null) {
15567            mStateListAnimator.setState(getDrawableState());
15568        }
15569    }
15570
15571    /**
15572     * This function is called whenever the drawable hotspot changes.
15573     * <p>
15574     * Be sure to call through to the superclass when overriding this function.
15575     *
15576     * @param x hotspot x coordinate
15577     * @param y hotspot y coordinate
15578     */
15579    public void drawableHotspotChanged(float x, float y) {
15580        if (mBackground != null) {
15581            mBackground.setHotspot(x, y);
15582        }
15583    }
15584
15585    /**
15586     * Call this to force a view to update its drawable state. This will cause
15587     * drawableStateChanged to be called on this view. Views that are interested
15588     * in the new state should call getDrawableState.
15589     *
15590     * @see #drawableStateChanged
15591     * @see #getDrawableState
15592     */
15593    public void refreshDrawableState() {
15594        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15595        drawableStateChanged();
15596
15597        ViewParent parent = mParent;
15598        if (parent != null) {
15599            parent.childDrawableStateChanged(this);
15600        }
15601    }
15602
15603    /**
15604     * Return an array of resource IDs of the drawable states representing the
15605     * current state of the view.
15606     *
15607     * @return The current drawable state
15608     *
15609     * @see Drawable#setState(int[])
15610     * @see #drawableStateChanged()
15611     * @see #onCreateDrawableState(int)
15612     */
15613    public final int[] getDrawableState() {
15614        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15615            return mDrawableState;
15616        } else {
15617            mDrawableState = onCreateDrawableState(0);
15618            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15619            return mDrawableState;
15620        }
15621    }
15622
15623    /**
15624     * Generate the new {@link android.graphics.drawable.Drawable} state for
15625     * this view. This is called by the view
15626     * system when the cached Drawable state is determined to be invalid.  To
15627     * retrieve the current state, you should use {@link #getDrawableState}.
15628     *
15629     * @param extraSpace if non-zero, this is the number of extra entries you
15630     * would like in the returned array in which you can place your own
15631     * states.
15632     *
15633     * @return Returns an array holding the current {@link Drawable} state of
15634     * the view.
15635     *
15636     * @see #mergeDrawableStates(int[], int[])
15637     */
15638    protected int[] onCreateDrawableState(int extraSpace) {
15639        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15640                mParent instanceof View) {
15641            return ((View) mParent).onCreateDrawableState(extraSpace);
15642        }
15643
15644        int[] drawableState;
15645
15646        int privateFlags = mPrivateFlags;
15647
15648        int viewStateIndex = 0;
15649        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15650        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15651        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15652        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15653        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15654        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15655        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15656                HardwareRenderer.isAvailable()) {
15657            // This is set if HW acceleration is requested, even if the current
15658            // process doesn't allow it.  This is just to allow app preview
15659            // windows to better match their app.
15660            viewStateIndex |= VIEW_STATE_ACCELERATED;
15661        }
15662        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15663
15664        final int privateFlags2 = mPrivateFlags2;
15665        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15666        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15667
15668        drawableState = VIEW_STATE_SETS[viewStateIndex];
15669
15670        //noinspection ConstantIfStatement
15671        if (false) {
15672            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15673            Log.i("View", toString()
15674                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15675                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15676                    + " fo=" + hasFocus()
15677                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15678                    + " wf=" + hasWindowFocus()
15679                    + ": " + Arrays.toString(drawableState));
15680        }
15681
15682        if (extraSpace == 0) {
15683            return drawableState;
15684        }
15685
15686        final int[] fullState;
15687        if (drawableState != null) {
15688            fullState = new int[drawableState.length + extraSpace];
15689            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15690        } else {
15691            fullState = new int[extraSpace];
15692        }
15693
15694        return fullState;
15695    }
15696
15697    /**
15698     * Merge your own state values in <var>additionalState</var> into the base
15699     * state values <var>baseState</var> that were returned by
15700     * {@link #onCreateDrawableState(int)}.
15701     *
15702     * @param baseState The base state values returned by
15703     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15704     * own additional state values.
15705     *
15706     * @param additionalState The additional state values you would like
15707     * added to <var>baseState</var>; this array is not modified.
15708     *
15709     * @return As a convenience, the <var>baseState</var> array you originally
15710     * passed into the function is returned.
15711     *
15712     * @see #onCreateDrawableState(int)
15713     */
15714    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15715        final int N = baseState.length;
15716        int i = N - 1;
15717        while (i >= 0 && baseState[i] == 0) {
15718            i--;
15719        }
15720        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15721        return baseState;
15722    }
15723
15724    /**
15725     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15726     * on all Drawable objects associated with this view.
15727     * <p>
15728     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15729     * attached to this view.
15730     */
15731    public void jumpDrawablesToCurrentState() {
15732        if (mBackground != null) {
15733            mBackground.jumpToCurrentState();
15734        }
15735        if (mStateListAnimator != null) {
15736            mStateListAnimator.jumpToCurrentState();
15737        }
15738    }
15739
15740    /**
15741     * Sets the background color for this view.
15742     * @param color the color of the background
15743     */
15744    @RemotableViewMethod
15745    public void setBackgroundColor(int color) {
15746        if (mBackground instanceof ColorDrawable) {
15747            ((ColorDrawable) mBackground.mutate()).setColor(color);
15748            computeOpaqueFlags();
15749            mBackgroundResource = 0;
15750        } else {
15751            setBackground(new ColorDrawable(color));
15752        }
15753    }
15754
15755    /**
15756     * Set the background to a given resource. The resource should refer to
15757     * a Drawable object or 0 to remove the background.
15758     * @param resid The identifier of the resource.
15759     *
15760     * @attr ref android.R.styleable#View_background
15761     */
15762    @RemotableViewMethod
15763    public void setBackgroundResource(int resid) {
15764        if (resid != 0 && resid == mBackgroundResource) {
15765            return;
15766        }
15767
15768        Drawable d = null;
15769        if (resid != 0) {
15770            d = mContext.getDrawable(resid);
15771        }
15772        setBackground(d);
15773
15774        mBackgroundResource = resid;
15775    }
15776
15777    /**
15778     * Set the background to a given Drawable, or remove the background. If the
15779     * background has padding, this View's padding is set to the background's
15780     * padding. However, when a background is removed, this View's padding isn't
15781     * touched. If setting the padding is desired, please use
15782     * {@link #setPadding(int, int, int, int)}.
15783     *
15784     * @param background The Drawable to use as the background, or null to remove the
15785     *        background
15786     */
15787    public void setBackground(Drawable background) {
15788        //noinspection deprecation
15789        setBackgroundDrawable(background);
15790    }
15791
15792    /**
15793     * @deprecated use {@link #setBackground(Drawable)} instead
15794     */
15795    @Deprecated
15796    public void setBackgroundDrawable(Drawable background) {
15797        computeOpaqueFlags();
15798
15799        if (background == mBackground) {
15800            return;
15801        }
15802
15803        boolean requestLayout = false;
15804
15805        mBackgroundResource = 0;
15806
15807        /*
15808         * Regardless of whether we're setting a new background or not, we want
15809         * to clear the previous drawable.
15810         */
15811        if (mBackground != null) {
15812            mBackground.setCallback(null);
15813            unscheduleDrawable(mBackground);
15814        }
15815
15816        if (background != null) {
15817            Rect padding = sThreadLocal.get();
15818            if (padding == null) {
15819                padding = new Rect();
15820                sThreadLocal.set(padding);
15821            }
15822            resetResolvedDrawables();
15823            background.setLayoutDirection(getLayoutDirection());
15824            if (background.getPadding(padding)) {
15825                resetResolvedPadding();
15826                switch (background.getLayoutDirection()) {
15827                    case LAYOUT_DIRECTION_RTL:
15828                        mUserPaddingLeftInitial = padding.right;
15829                        mUserPaddingRightInitial = padding.left;
15830                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15831                        break;
15832                    case LAYOUT_DIRECTION_LTR:
15833                    default:
15834                        mUserPaddingLeftInitial = padding.left;
15835                        mUserPaddingRightInitial = padding.right;
15836                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15837                }
15838                mLeftPaddingDefined = false;
15839                mRightPaddingDefined = false;
15840            }
15841
15842            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15843            // if it has a different minimum size, we should layout again
15844            if (mBackground == null
15845                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15846                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15847                requestLayout = true;
15848            }
15849
15850            background.setCallback(this);
15851            if (background.isStateful()) {
15852                background.setState(getDrawableState());
15853            }
15854            background.setVisible(getVisibility() == VISIBLE, false);
15855            mBackground = background;
15856
15857            applyBackgroundTint();
15858
15859            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15860                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15861                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15862                requestLayout = true;
15863            }
15864        } else {
15865            /* Remove the background */
15866            mBackground = null;
15867
15868            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15869                /*
15870                 * This view ONLY drew the background before and we're removing
15871                 * the background, so now it won't draw anything
15872                 * (hence we SKIP_DRAW)
15873                 */
15874                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15875                mPrivateFlags |= PFLAG_SKIP_DRAW;
15876            }
15877
15878            /*
15879             * When the background is set, we try to apply its padding to this
15880             * View. When the background is removed, we don't touch this View's
15881             * padding. This is noted in the Javadocs. Hence, we don't need to
15882             * requestLayout(), the invalidate() below is sufficient.
15883             */
15884
15885            // The old background's minimum size could have affected this
15886            // View's layout, so let's requestLayout
15887            requestLayout = true;
15888        }
15889
15890        computeOpaqueFlags();
15891
15892        if (requestLayout) {
15893            requestLayout();
15894        }
15895
15896        mBackgroundSizeChanged = true;
15897        invalidate(true);
15898    }
15899
15900    /**
15901     * Gets the background drawable
15902     *
15903     * @return The drawable used as the background for this view, if any.
15904     *
15905     * @see #setBackground(Drawable)
15906     *
15907     * @attr ref android.R.styleable#View_background
15908     */
15909    public Drawable getBackground() {
15910        return mBackground;
15911    }
15912
15913    /**
15914     * Applies a tint to the background drawable.
15915     * <p>
15916     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15917     * mutate the drawable and apply the specified tint and tint mode using
15918     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15919     *
15920     * @param tint the tint to apply, may be {@code null} to clear tint
15921     * @param tintMode the blending mode used to apply the tint, may be
15922     *                 {@code null} to clear tint
15923     *
15924     * @attr ref android.R.styleable#View_backgroundTint
15925     * @attr ref android.R.styleable#View_backgroundTintMode
15926     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15927     */
15928    private void setBackgroundTint(@Nullable ColorStateList tint,
15929            @Nullable PorterDuff.Mode tintMode) {
15930        mBackgroundTint = tint;
15931        mBackgroundTintMode = tintMode;
15932        mHasBackgroundTint = true;
15933
15934        applyBackgroundTint();
15935    }
15936
15937    /**
15938     * Applies a tint to the background drawable. Does not modify the current tint
15939     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15940     * <p>
15941     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15942     * mutate the drawable and apply the specified tint and tint mode using
15943     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15944     *
15945     * @param tint the tint to apply, may be {@code null} to clear tint
15946     *
15947     * @attr ref android.R.styleable#View_backgroundTint
15948     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15949     */
15950    public void setBackgroundTint(@Nullable ColorStateList tint) {
15951        setBackgroundTint(tint, mBackgroundTintMode);
15952    }
15953
15954    /**
15955     * @return the tint applied to the background drawable
15956     * @attr ref android.R.styleable#View_backgroundTint
15957     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15958     */
15959    @Nullable
15960    public ColorStateList getBackgroundTint() {
15961        return mBackgroundTint;
15962    }
15963
15964    /**
15965     * Specifies the blending mode used to apply the tint specified by
15966     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15967     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15968     *
15969     * @param tintMode the blending mode used to apply the tint, may be
15970     *                 {@code null} to clear tint
15971     * @attr ref android.R.styleable#View_backgroundTintMode
15972     * @see #setBackgroundTint(ColorStateList)
15973     */
15974    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15975        setBackgroundTint(mBackgroundTint, tintMode);
15976    }
15977
15978    /**
15979     * @return the blending mode used to apply the tint to the background drawable
15980     * @attr ref android.R.styleable#View_backgroundTintMode
15981     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15982     */
15983    @Nullable
15984    public PorterDuff.Mode getBackgroundTintMode() {
15985        return mBackgroundTintMode;
15986    }
15987
15988    private void applyBackgroundTint() {
15989        if (mBackground != null && mHasBackgroundTint) {
15990            mBackground = mBackground.mutate();
15991            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15992        }
15993    }
15994
15995    /**
15996     * Sets the padding. The view may add on the space required to display
15997     * the scrollbars, depending on the style and visibility of the scrollbars.
15998     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15999     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16000     * from the values set in this call.
16001     *
16002     * @attr ref android.R.styleable#View_padding
16003     * @attr ref android.R.styleable#View_paddingBottom
16004     * @attr ref android.R.styleable#View_paddingLeft
16005     * @attr ref android.R.styleable#View_paddingRight
16006     * @attr ref android.R.styleable#View_paddingTop
16007     * @param left the left padding in pixels
16008     * @param top the top padding in pixels
16009     * @param right the right padding in pixels
16010     * @param bottom the bottom padding in pixels
16011     */
16012    public void setPadding(int left, int top, int right, int bottom) {
16013        resetResolvedPadding();
16014
16015        mUserPaddingStart = UNDEFINED_PADDING;
16016        mUserPaddingEnd = UNDEFINED_PADDING;
16017
16018        mUserPaddingLeftInitial = left;
16019        mUserPaddingRightInitial = right;
16020
16021        mLeftPaddingDefined = true;
16022        mRightPaddingDefined = true;
16023
16024        internalSetPadding(left, top, right, bottom);
16025    }
16026
16027    /**
16028     * @hide
16029     */
16030    protected void internalSetPadding(int left, int top, int right, int bottom) {
16031        mUserPaddingLeft = left;
16032        mUserPaddingRight = right;
16033        mUserPaddingBottom = bottom;
16034
16035        final int viewFlags = mViewFlags;
16036        boolean changed = false;
16037
16038        // Common case is there are no scroll bars.
16039        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16040            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16041                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16042                        ? 0 : getVerticalScrollbarWidth();
16043                switch (mVerticalScrollbarPosition) {
16044                    case SCROLLBAR_POSITION_DEFAULT:
16045                        if (isLayoutRtl()) {
16046                            left += offset;
16047                        } else {
16048                            right += offset;
16049                        }
16050                        break;
16051                    case SCROLLBAR_POSITION_RIGHT:
16052                        right += offset;
16053                        break;
16054                    case SCROLLBAR_POSITION_LEFT:
16055                        left += offset;
16056                        break;
16057                }
16058            }
16059            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16060                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16061                        ? 0 : getHorizontalScrollbarHeight();
16062            }
16063        }
16064
16065        if (mPaddingLeft != left) {
16066            changed = true;
16067            mPaddingLeft = left;
16068        }
16069        if (mPaddingTop != top) {
16070            changed = true;
16071            mPaddingTop = top;
16072        }
16073        if (mPaddingRight != right) {
16074            changed = true;
16075            mPaddingRight = right;
16076        }
16077        if (mPaddingBottom != bottom) {
16078            changed = true;
16079            mPaddingBottom = bottom;
16080        }
16081
16082        if (changed) {
16083            requestLayout();
16084        }
16085    }
16086
16087    /**
16088     * Sets the relative padding. The view may add on the space required to display
16089     * the scrollbars, depending on the style and visibility of the scrollbars.
16090     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16091     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16092     * from the values set in this call.
16093     *
16094     * @attr ref android.R.styleable#View_padding
16095     * @attr ref android.R.styleable#View_paddingBottom
16096     * @attr ref android.R.styleable#View_paddingStart
16097     * @attr ref android.R.styleable#View_paddingEnd
16098     * @attr ref android.R.styleable#View_paddingTop
16099     * @param start the start padding in pixels
16100     * @param top the top padding in pixels
16101     * @param end the end padding in pixels
16102     * @param bottom the bottom padding in pixels
16103     */
16104    public void setPaddingRelative(int start, int top, int end, int bottom) {
16105        resetResolvedPadding();
16106
16107        mUserPaddingStart = start;
16108        mUserPaddingEnd = end;
16109        mLeftPaddingDefined = true;
16110        mRightPaddingDefined = true;
16111
16112        switch(getLayoutDirection()) {
16113            case LAYOUT_DIRECTION_RTL:
16114                mUserPaddingLeftInitial = end;
16115                mUserPaddingRightInitial = start;
16116                internalSetPadding(end, top, start, bottom);
16117                break;
16118            case LAYOUT_DIRECTION_LTR:
16119            default:
16120                mUserPaddingLeftInitial = start;
16121                mUserPaddingRightInitial = end;
16122                internalSetPadding(start, top, end, bottom);
16123        }
16124    }
16125
16126    /**
16127     * Returns the top padding of this view.
16128     *
16129     * @return the top padding in pixels
16130     */
16131    public int getPaddingTop() {
16132        return mPaddingTop;
16133    }
16134
16135    /**
16136     * Returns the bottom padding of this view. If there are inset and enabled
16137     * scrollbars, this value may include the space required to display the
16138     * scrollbars as well.
16139     *
16140     * @return the bottom padding in pixels
16141     */
16142    public int getPaddingBottom() {
16143        return mPaddingBottom;
16144    }
16145
16146    /**
16147     * Returns the left padding of this view. If there are inset and enabled
16148     * scrollbars, this value may include the space required to display the
16149     * scrollbars as well.
16150     *
16151     * @return the left padding in pixels
16152     */
16153    public int getPaddingLeft() {
16154        if (!isPaddingResolved()) {
16155            resolvePadding();
16156        }
16157        return mPaddingLeft;
16158    }
16159
16160    /**
16161     * Returns the start padding of this view depending on its resolved layout direction.
16162     * If there are inset and enabled scrollbars, this value may include the space
16163     * required to display the scrollbars as well.
16164     *
16165     * @return the start padding in pixels
16166     */
16167    public int getPaddingStart() {
16168        if (!isPaddingResolved()) {
16169            resolvePadding();
16170        }
16171        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16172                mPaddingRight : mPaddingLeft;
16173    }
16174
16175    /**
16176     * Returns the right padding of this view. If there are inset and enabled
16177     * scrollbars, this value may include the space required to display the
16178     * scrollbars as well.
16179     *
16180     * @return the right padding in pixels
16181     */
16182    public int getPaddingRight() {
16183        if (!isPaddingResolved()) {
16184            resolvePadding();
16185        }
16186        return mPaddingRight;
16187    }
16188
16189    /**
16190     * Returns the end padding of this view depending on its resolved layout direction.
16191     * If there are inset and enabled scrollbars, this value may include the space
16192     * required to display the scrollbars as well.
16193     *
16194     * @return the end padding in pixels
16195     */
16196    public int getPaddingEnd() {
16197        if (!isPaddingResolved()) {
16198            resolvePadding();
16199        }
16200        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16201                mPaddingLeft : mPaddingRight;
16202    }
16203
16204    /**
16205     * Return if the padding as been set thru relative values
16206     * {@link #setPaddingRelative(int, int, int, int)} or thru
16207     * @attr ref android.R.styleable#View_paddingStart or
16208     * @attr ref android.R.styleable#View_paddingEnd
16209     *
16210     * @return true if the padding is relative or false if it is not.
16211     */
16212    public boolean isPaddingRelative() {
16213        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16214    }
16215
16216    Insets computeOpticalInsets() {
16217        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16218    }
16219
16220    /**
16221     * @hide
16222     */
16223    public void resetPaddingToInitialValues() {
16224        if (isRtlCompatibilityMode()) {
16225            mPaddingLeft = mUserPaddingLeftInitial;
16226            mPaddingRight = mUserPaddingRightInitial;
16227            return;
16228        }
16229        if (isLayoutRtl()) {
16230            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16231            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16232        } else {
16233            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16234            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16235        }
16236    }
16237
16238    /**
16239     * @hide
16240     */
16241    public Insets getOpticalInsets() {
16242        if (mLayoutInsets == null) {
16243            mLayoutInsets = computeOpticalInsets();
16244        }
16245        return mLayoutInsets;
16246    }
16247
16248    /**
16249     * Set this view's optical insets.
16250     *
16251     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16252     * property. Views that compute their own optical insets should call it as part of measurement.
16253     * This method does not request layout. If you are setting optical insets outside of
16254     * measure/layout itself you will want to call requestLayout() yourself.
16255     * </p>
16256     * @hide
16257     */
16258    public void setOpticalInsets(Insets insets) {
16259        mLayoutInsets = insets;
16260    }
16261
16262    /**
16263     * Changes the selection state of this view. A view can be selected or not.
16264     * Note that selection is not the same as focus. Views are typically
16265     * selected in the context of an AdapterView like ListView or GridView;
16266     * the selected view is the view that is highlighted.
16267     *
16268     * @param selected true if the view must be selected, false otherwise
16269     */
16270    public void setSelected(boolean selected) {
16271        //noinspection DoubleNegation
16272        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16273            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16274            if (!selected) resetPressedState();
16275            invalidate(true);
16276            refreshDrawableState();
16277            dispatchSetSelected(selected);
16278            notifyViewAccessibilityStateChangedIfNeeded(
16279                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16280        }
16281    }
16282
16283    /**
16284     * Dispatch setSelected to all of this View's children.
16285     *
16286     * @see #setSelected(boolean)
16287     *
16288     * @param selected The new selected state
16289     */
16290    protected void dispatchSetSelected(boolean selected) {
16291    }
16292
16293    /**
16294     * Indicates the selection state of this view.
16295     *
16296     * @return true if the view is selected, false otherwise
16297     */
16298    @ViewDebug.ExportedProperty
16299    public boolean isSelected() {
16300        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16301    }
16302
16303    /**
16304     * Changes the activated state of this view. A view can be activated or not.
16305     * Note that activation is not the same as selection.  Selection is
16306     * a transient property, representing the view (hierarchy) the user is
16307     * currently interacting with.  Activation is a longer-term state that the
16308     * user can move views in and out of.  For example, in a list view with
16309     * single or multiple selection enabled, the views in the current selection
16310     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16311     * here.)  The activated state is propagated down to children of the view it
16312     * is set on.
16313     *
16314     * @param activated true if the view must be activated, false otherwise
16315     */
16316    public void setActivated(boolean activated) {
16317        //noinspection DoubleNegation
16318        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16319            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16320            invalidate(true);
16321            refreshDrawableState();
16322            dispatchSetActivated(activated);
16323        }
16324    }
16325
16326    /**
16327     * Dispatch setActivated to all of this View's children.
16328     *
16329     * @see #setActivated(boolean)
16330     *
16331     * @param activated The new activated state
16332     */
16333    protected void dispatchSetActivated(boolean activated) {
16334    }
16335
16336    /**
16337     * Indicates the activation state of this view.
16338     *
16339     * @return true if the view is activated, false otherwise
16340     */
16341    @ViewDebug.ExportedProperty
16342    public boolean isActivated() {
16343        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16344    }
16345
16346    /**
16347     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16348     * observer can be used to get notifications when global events, like
16349     * layout, happen.
16350     *
16351     * The returned ViewTreeObserver observer is not guaranteed to remain
16352     * valid for the lifetime of this View. If the caller of this method keeps
16353     * a long-lived reference to ViewTreeObserver, it should always check for
16354     * the return value of {@link ViewTreeObserver#isAlive()}.
16355     *
16356     * @return The ViewTreeObserver for this view's hierarchy.
16357     */
16358    public ViewTreeObserver getViewTreeObserver() {
16359        if (mAttachInfo != null) {
16360            return mAttachInfo.mTreeObserver;
16361        }
16362        if (mFloatingTreeObserver == null) {
16363            mFloatingTreeObserver = new ViewTreeObserver();
16364        }
16365        return mFloatingTreeObserver;
16366    }
16367
16368    /**
16369     * <p>Finds the topmost view in the current view hierarchy.</p>
16370     *
16371     * @return the topmost view containing this view
16372     */
16373    public View getRootView() {
16374        if (mAttachInfo != null) {
16375            final View v = mAttachInfo.mRootView;
16376            if (v != null) {
16377                return v;
16378            }
16379        }
16380
16381        View parent = this;
16382
16383        while (parent.mParent != null && parent.mParent instanceof View) {
16384            parent = (View) parent.mParent;
16385        }
16386
16387        return parent;
16388    }
16389
16390    /**
16391     * Transforms a motion event from view-local coordinates to on-screen
16392     * coordinates.
16393     *
16394     * @param ev the view-local motion event
16395     * @return false if the transformation could not be applied
16396     * @hide
16397     */
16398    public boolean toGlobalMotionEvent(MotionEvent ev) {
16399        final AttachInfo info = mAttachInfo;
16400        if (info == null) {
16401            return false;
16402        }
16403
16404        final Matrix m = info.mTmpMatrix;
16405        m.set(Matrix.IDENTITY_MATRIX);
16406        transformMatrixToGlobal(m);
16407        ev.transform(m);
16408        return true;
16409    }
16410
16411    /**
16412     * Transforms a motion event from on-screen coordinates to view-local
16413     * coordinates.
16414     *
16415     * @param ev the on-screen motion event
16416     * @return false if the transformation could not be applied
16417     * @hide
16418     */
16419    public boolean toLocalMotionEvent(MotionEvent ev) {
16420        final AttachInfo info = mAttachInfo;
16421        if (info == null) {
16422            return false;
16423        }
16424
16425        final Matrix m = info.mTmpMatrix;
16426        m.set(Matrix.IDENTITY_MATRIX);
16427        transformMatrixToLocal(m);
16428        ev.transform(m);
16429        return true;
16430    }
16431
16432    /**
16433     * Modifies the input matrix such that it maps view-local coordinates to
16434     * on-screen coordinates.
16435     *
16436     * @param m input matrix to modify
16437     */
16438    void transformMatrixToGlobal(Matrix m) {
16439        final ViewParent parent = mParent;
16440        if (parent instanceof View) {
16441            final View vp = (View) parent;
16442            vp.transformMatrixToGlobal(m);
16443            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16444        } else if (parent instanceof ViewRootImpl) {
16445            final ViewRootImpl vr = (ViewRootImpl) parent;
16446            vr.transformMatrixToGlobal(m);
16447            m.postTranslate(0, -vr.mCurScrollY);
16448        }
16449
16450        m.postTranslate(mLeft, mTop);
16451
16452        if (!hasIdentityMatrix()) {
16453            m.postConcat(getMatrix());
16454        }
16455    }
16456
16457    /**
16458     * Modifies the input matrix such that it maps on-screen coordinates to
16459     * view-local coordinates.
16460     *
16461     * @param m input matrix to modify
16462     */
16463    void transformMatrixToLocal(Matrix m) {
16464        final ViewParent parent = mParent;
16465        if (parent instanceof View) {
16466            final View vp = (View) parent;
16467            vp.transformMatrixToLocal(m);
16468            m.preTranslate(vp.mScrollX, vp.mScrollY);
16469        } else if (parent instanceof ViewRootImpl) {
16470            final ViewRootImpl vr = (ViewRootImpl) parent;
16471            vr.transformMatrixToLocal(m);
16472            m.preTranslate(0, vr.mCurScrollY);
16473        }
16474
16475        m.preTranslate(-mLeft, -mTop);
16476
16477        if (!hasIdentityMatrix()) {
16478            m.preConcat(getInverseMatrix());
16479        }
16480    }
16481
16482    /**
16483     * <p>Computes the coordinates of this view on the screen. The argument
16484     * must be an array of two integers. After the method returns, the array
16485     * contains the x and y location in that order.</p>
16486     *
16487     * @param location an array of two integers in which to hold the coordinates
16488     */
16489    public void getLocationOnScreen(int[] location) {
16490        getLocationInWindow(location);
16491
16492        final AttachInfo info = mAttachInfo;
16493        if (info != null) {
16494            location[0] += info.mWindowLeft;
16495            location[1] += info.mWindowTop;
16496        }
16497    }
16498
16499    /**
16500     * <p>Computes the coordinates of this view in its window. The argument
16501     * must be an array of two integers. After the method returns, the array
16502     * contains the x and y location in that order.</p>
16503     *
16504     * @param location an array of two integers in which to hold the coordinates
16505     */
16506    public void getLocationInWindow(int[] location) {
16507        if (location == null || location.length < 2) {
16508            throw new IllegalArgumentException("location must be an array of two integers");
16509        }
16510
16511        if (mAttachInfo == null) {
16512            // When the view is not attached to a window, this method does not make sense
16513            location[0] = location[1] = 0;
16514            return;
16515        }
16516
16517        float[] position = mAttachInfo.mTmpTransformLocation;
16518        position[0] = position[1] = 0.0f;
16519
16520        if (!hasIdentityMatrix()) {
16521            getMatrix().mapPoints(position);
16522        }
16523
16524        position[0] += mLeft;
16525        position[1] += mTop;
16526
16527        ViewParent viewParent = mParent;
16528        while (viewParent instanceof View) {
16529            final View view = (View) viewParent;
16530
16531            position[0] -= view.mScrollX;
16532            position[1] -= view.mScrollY;
16533
16534            if (!view.hasIdentityMatrix()) {
16535                view.getMatrix().mapPoints(position);
16536            }
16537
16538            position[0] += view.mLeft;
16539            position[1] += view.mTop;
16540
16541            viewParent = view.mParent;
16542         }
16543
16544        if (viewParent instanceof ViewRootImpl) {
16545            // *cough*
16546            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16547            position[1] -= vr.mCurScrollY;
16548        }
16549
16550        location[0] = (int) (position[0] + 0.5f);
16551        location[1] = (int) (position[1] + 0.5f);
16552    }
16553
16554    /**
16555     * {@hide}
16556     * @param id the id of the view to be found
16557     * @return the view of the specified id, null if cannot be found
16558     */
16559    protected View findViewTraversal(int id) {
16560        if (id == mID) {
16561            return this;
16562        }
16563        return null;
16564    }
16565
16566    /**
16567     * {@hide}
16568     * @param tag the tag of the view to be found
16569     * @return the view of specified tag, null if cannot be found
16570     */
16571    protected View findViewWithTagTraversal(Object tag) {
16572        if (tag != null && tag.equals(mTag)) {
16573            return this;
16574        }
16575        return null;
16576    }
16577
16578    /**
16579     * {@hide}
16580     * @param predicate The predicate to evaluate.
16581     * @param childToSkip If not null, ignores this child during the recursive traversal.
16582     * @return The first view that matches the predicate or null.
16583     */
16584    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16585        if (predicate.apply(this)) {
16586            return this;
16587        }
16588        return null;
16589    }
16590
16591    /**
16592     * Look for a child view with the given id.  If this view has the given
16593     * id, return this view.
16594     *
16595     * @param id The id to search for.
16596     * @return The view that has the given id in the hierarchy or null
16597     */
16598    public final View findViewById(int id) {
16599        if (id < 0) {
16600            return null;
16601        }
16602        return findViewTraversal(id);
16603    }
16604
16605    /**
16606     * Finds a view by its unuque and stable accessibility id.
16607     *
16608     * @param accessibilityId The searched accessibility id.
16609     * @return The found view.
16610     */
16611    final View findViewByAccessibilityId(int accessibilityId) {
16612        if (accessibilityId < 0) {
16613            return null;
16614        }
16615        return findViewByAccessibilityIdTraversal(accessibilityId);
16616    }
16617
16618    /**
16619     * Performs the traversal to find a view by its unuque and stable accessibility id.
16620     *
16621     * <strong>Note:</strong>This method does not stop at the root namespace
16622     * boundary since the user can touch the screen at an arbitrary location
16623     * potentially crossing the root namespace bounday which will send an
16624     * accessibility event to accessibility services and they should be able
16625     * to obtain the event source. Also accessibility ids are guaranteed to be
16626     * unique in the window.
16627     *
16628     * @param accessibilityId The accessibility id.
16629     * @return The found view.
16630     *
16631     * @hide
16632     */
16633    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16634        if (getAccessibilityViewId() == accessibilityId) {
16635            return this;
16636        }
16637        return null;
16638    }
16639
16640    /**
16641     * Look for a child view with the given tag.  If this view has the given
16642     * tag, return this view.
16643     *
16644     * @param tag The tag to search for, using "tag.equals(getTag())".
16645     * @return The View that has the given tag in the hierarchy or null
16646     */
16647    public final View findViewWithTag(Object tag) {
16648        if (tag == null) {
16649            return null;
16650        }
16651        return findViewWithTagTraversal(tag);
16652    }
16653
16654    /**
16655     * {@hide}
16656     * Look for a child view that matches the specified predicate.
16657     * If this view matches the predicate, return this view.
16658     *
16659     * @param predicate The predicate to evaluate.
16660     * @return The first view that matches the predicate or null.
16661     */
16662    public final View findViewByPredicate(Predicate<View> predicate) {
16663        return findViewByPredicateTraversal(predicate, null);
16664    }
16665
16666    /**
16667     * {@hide}
16668     * Look for a child view that matches the specified predicate,
16669     * starting with the specified view and its descendents and then
16670     * recusively searching the ancestors and siblings of that view
16671     * until this view is reached.
16672     *
16673     * This method is useful in cases where the predicate does not match
16674     * a single unique view (perhaps multiple views use the same id)
16675     * and we are trying to find the view that is "closest" in scope to the
16676     * starting view.
16677     *
16678     * @param start The view to start from.
16679     * @param predicate The predicate to evaluate.
16680     * @return The first view that matches the predicate or null.
16681     */
16682    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16683        View childToSkip = null;
16684        for (;;) {
16685            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16686            if (view != null || start == this) {
16687                return view;
16688            }
16689
16690            ViewParent parent = start.getParent();
16691            if (parent == null || !(parent instanceof View)) {
16692                return null;
16693            }
16694
16695            childToSkip = start;
16696            start = (View) parent;
16697        }
16698    }
16699
16700    /**
16701     * Sets the identifier for this view. The identifier does not have to be
16702     * unique in this view's hierarchy. The identifier should be a positive
16703     * number.
16704     *
16705     * @see #NO_ID
16706     * @see #getId()
16707     * @see #findViewById(int)
16708     *
16709     * @param id a number used to identify the view
16710     *
16711     * @attr ref android.R.styleable#View_id
16712     */
16713    public void setId(int id) {
16714        mID = id;
16715        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16716            mID = generateViewId();
16717        }
16718    }
16719
16720    /**
16721     * {@hide}
16722     *
16723     * @param isRoot true if the view belongs to the root namespace, false
16724     *        otherwise
16725     */
16726    public void setIsRootNamespace(boolean isRoot) {
16727        if (isRoot) {
16728            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16729        } else {
16730            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16731        }
16732    }
16733
16734    /**
16735     * {@hide}
16736     *
16737     * @return true if the view belongs to the root namespace, false otherwise
16738     */
16739    public boolean isRootNamespace() {
16740        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16741    }
16742
16743    /**
16744     * Returns this view's identifier.
16745     *
16746     * @return a positive integer used to identify the view or {@link #NO_ID}
16747     *         if the view has no ID
16748     *
16749     * @see #setId(int)
16750     * @see #findViewById(int)
16751     * @attr ref android.R.styleable#View_id
16752     */
16753    @ViewDebug.CapturedViewProperty
16754    public int getId() {
16755        return mID;
16756    }
16757
16758    /**
16759     * Returns this view's tag.
16760     *
16761     * @return the Object stored in this view as a tag, or {@code null} if not
16762     *         set
16763     *
16764     * @see #setTag(Object)
16765     * @see #getTag(int)
16766     */
16767    @ViewDebug.ExportedProperty
16768    public Object getTag() {
16769        return mTag;
16770    }
16771
16772    /**
16773     * Sets the tag associated with this view. A tag can be used to mark
16774     * a view in its hierarchy and does not have to be unique within the
16775     * hierarchy. Tags can also be used to store data within a view without
16776     * resorting to another data structure.
16777     *
16778     * @param tag an Object to tag the view with
16779     *
16780     * @see #getTag()
16781     * @see #setTag(int, Object)
16782     */
16783    public void setTag(final Object tag) {
16784        mTag = tag;
16785    }
16786
16787    /**
16788     * Returns the tag associated with this view and the specified key.
16789     *
16790     * @param key The key identifying the tag
16791     *
16792     * @return the Object stored in this view as a tag, or {@code null} if not
16793     *         set
16794     *
16795     * @see #setTag(int, Object)
16796     * @see #getTag()
16797     */
16798    public Object getTag(int key) {
16799        if (mKeyedTags != null) return mKeyedTags.get(key);
16800        return null;
16801    }
16802
16803    /**
16804     * Sets a tag associated with this view and a key. A tag can be used
16805     * to mark a view in its hierarchy and does not have to be unique within
16806     * the hierarchy. Tags can also be used to store data within a view
16807     * without resorting to another data structure.
16808     *
16809     * The specified key should be an id declared in the resources of the
16810     * application to ensure it is unique (see the <a
16811     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16812     * Keys identified as belonging to
16813     * the Android framework or not associated with any package will cause
16814     * an {@link IllegalArgumentException} to be thrown.
16815     *
16816     * @param key The key identifying the tag
16817     * @param tag An Object to tag the view with
16818     *
16819     * @throws IllegalArgumentException If they specified key is not valid
16820     *
16821     * @see #setTag(Object)
16822     * @see #getTag(int)
16823     */
16824    public void setTag(int key, final Object tag) {
16825        // If the package id is 0x00 or 0x01, it's either an undefined package
16826        // or a framework id
16827        if ((key >>> 24) < 2) {
16828            throw new IllegalArgumentException("The key must be an application-specific "
16829                    + "resource id.");
16830        }
16831
16832        setKeyedTag(key, tag);
16833    }
16834
16835    /**
16836     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16837     * framework id.
16838     *
16839     * @hide
16840     */
16841    public void setTagInternal(int key, Object tag) {
16842        if ((key >>> 24) != 0x1) {
16843            throw new IllegalArgumentException("The key must be a framework-specific "
16844                    + "resource id.");
16845        }
16846
16847        setKeyedTag(key, tag);
16848    }
16849
16850    private void setKeyedTag(int key, Object tag) {
16851        if (mKeyedTags == null) {
16852            mKeyedTags = new SparseArray<Object>(2);
16853        }
16854
16855        mKeyedTags.put(key, tag);
16856    }
16857
16858    /**
16859     * Prints information about this view in the log output, with the tag
16860     * {@link #VIEW_LOG_TAG}.
16861     *
16862     * @hide
16863     */
16864    public void debug() {
16865        debug(0);
16866    }
16867
16868    /**
16869     * Prints information about this view in the log output, with the tag
16870     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16871     * indentation defined by the <code>depth</code>.
16872     *
16873     * @param depth the indentation level
16874     *
16875     * @hide
16876     */
16877    protected void debug(int depth) {
16878        String output = debugIndent(depth - 1);
16879
16880        output += "+ " + this;
16881        int id = getId();
16882        if (id != -1) {
16883            output += " (id=" + id + ")";
16884        }
16885        Object tag = getTag();
16886        if (tag != null) {
16887            output += " (tag=" + tag + ")";
16888        }
16889        Log.d(VIEW_LOG_TAG, output);
16890
16891        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16892            output = debugIndent(depth) + " FOCUSED";
16893            Log.d(VIEW_LOG_TAG, output);
16894        }
16895
16896        output = debugIndent(depth);
16897        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16898                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16899                + "} ";
16900        Log.d(VIEW_LOG_TAG, output);
16901
16902        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16903                || mPaddingBottom != 0) {
16904            output = debugIndent(depth);
16905            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16906                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16907            Log.d(VIEW_LOG_TAG, output);
16908        }
16909
16910        output = debugIndent(depth);
16911        output += "mMeasureWidth=" + mMeasuredWidth +
16912                " mMeasureHeight=" + mMeasuredHeight;
16913        Log.d(VIEW_LOG_TAG, output);
16914
16915        output = debugIndent(depth);
16916        if (mLayoutParams == null) {
16917            output += "BAD! no layout params";
16918        } else {
16919            output = mLayoutParams.debug(output);
16920        }
16921        Log.d(VIEW_LOG_TAG, output);
16922
16923        output = debugIndent(depth);
16924        output += "flags={";
16925        output += View.printFlags(mViewFlags);
16926        output += "}";
16927        Log.d(VIEW_LOG_TAG, output);
16928
16929        output = debugIndent(depth);
16930        output += "privateFlags={";
16931        output += View.printPrivateFlags(mPrivateFlags);
16932        output += "}";
16933        Log.d(VIEW_LOG_TAG, output);
16934    }
16935
16936    /**
16937     * Creates a string of whitespaces used for indentation.
16938     *
16939     * @param depth the indentation level
16940     * @return a String containing (depth * 2 + 3) * 2 white spaces
16941     *
16942     * @hide
16943     */
16944    protected static String debugIndent(int depth) {
16945        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16946        for (int i = 0; i < (depth * 2) + 3; i++) {
16947            spaces.append(' ').append(' ');
16948        }
16949        return spaces.toString();
16950    }
16951
16952    /**
16953     * <p>Return the offset of the widget's text baseline from the widget's top
16954     * boundary. If this widget does not support baseline alignment, this
16955     * method returns -1. </p>
16956     *
16957     * @return the offset of the baseline within the widget's bounds or -1
16958     *         if baseline alignment is not supported
16959     */
16960    @ViewDebug.ExportedProperty(category = "layout")
16961    public int getBaseline() {
16962        return -1;
16963    }
16964
16965    /**
16966     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16967     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16968     * a layout pass.
16969     *
16970     * @return whether the view hierarchy is currently undergoing a layout pass
16971     */
16972    public boolean isInLayout() {
16973        ViewRootImpl viewRoot = getViewRootImpl();
16974        return (viewRoot != null && viewRoot.isInLayout());
16975    }
16976
16977    /**
16978     * Call this when something has changed which has invalidated the
16979     * layout of this view. This will schedule a layout pass of the view
16980     * tree. This should not be called while the view hierarchy is currently in a layout
16981     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16982     * end of the current layout pass (and then layout will run again) or after the current
16983     * frame is drawn and the next layout occurs.
16984     *
16985     * <p>Subclasses which override this method should call the superclass method to
16986     * handle possible request-during-layout errors correctly.</p>
16987     */
16988    public void requestLayout() {
16989        if (mMeasureCache != null) mMeasureCache.clear();
16990
16991        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16992            // Only trigger request-during-layout logic if this is the view requesting it,
16993            // not the views in its parent hierarchy
16994            ViewRootImpl viewRoot = getViewRootImpl();
16995            if (viewRoot != null && viewRoot.isInLayout()) {
16996                if (!viewRoot.requestLayoutDuringLayout(this)) {
16997                    return;
16998                }
16999            }
17000            mAttachInfo.mViewRequestingLayout = this;
17001        }
17002
17003        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17004        mPrivateFlags |= PFLAG_INVALIDATED;
17005
17006        if (mParent != null && !mParent.isLayoutRequested()) {
17007            mParent.requestLayout();
17008        }
17009        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17010            mAttachInfo.mViewRequestingLayout = null;
17011        }
17012    }
17013
17014    /**
17015     * Forces this view to be laid out during the next layout pass.
17016     * This method does not call requestLayout() or forceLayout()
17017     * on the parent.
17018     */
17019    public void forceLayout() {
17020        if (mMeasureCache != null) mMeasureCache.clear();
17021
17022        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17023        mPrivateFlags |= PFLAG_INVALIDATED;
17024    }
17025
17026    /**
17027     * <p>
17028     * This is called to find out how big a view should be. The parent
17029     * supplies constraint information in the width and height parameters.
17030     * </p>
17031     *
17032     * <p>
17033     * The actual measurement work of a view is performed in
17034     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17035     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17036     * </p>
17037     *
17038     *
17039     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17040     *        parent
17041     * @param heightMeasureSpec Vertical space requirements as imposed by the
17042     *        parent
17043     *
17044     * @see #onMeasure(int, int)
17045     */
17046    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17047        boolean optical = isLayoutModeOptical(this);
17048        if (optical != isLayoutModeOptical(mParent)) {
17049            Insets insets = getOpticalInsets();
17050            int oWidth  = insets.left + insets.right;
17051            int oHeight = insets.top  + insets.bottom;
17052            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17053            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17054        }
17055
17056        // Suppress sign extension for the low bytes
17057        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17058        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17059
17060        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17061                widthMeasureSpec != mOldWidthMeasureSpec ||
17062                heightMeasureSpec != mOldHeightMeasureSpec) {
17063
17064            // first clears the measured dimension flag
17065            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17066
17067            resolveRtlPropertiesIfNeeded();
17068
17069            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17070                    mMeasureCache.indexOfKey(key);
17071            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17072                // measure ourselves, this should set the measured dimension flag back
17073                onMeasure(widthMeasureSpec, heightMeasureSpec);
17074                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17075            } else {
17076                long value = mMeasureCache.valueAt(cacheIndex);
17077                // Casting a long to int drops the high 32 bits, no mask needed
17078                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17079                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17080            }
17081
17082            // flag not set, setMeasuredDimension() was not invoked, we raise
17083            // an exception to warn the developer
17084            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17085                throw new IllegalStateException("onMeasure() did not set the"
17086                        + " measured dimension by calling"
17087                        + " setMeasuredDimension()");
17088            }
17089
17090            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17091        }
17092
17093        mOldWidthMeasureSpec = widthMeasureSpec;
17094        mOldHeightMeasureSpec = heightMeasureSpec;
17095
17096        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17097                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17098    }
17099
17100    /**
17101     * <p>
17102     * Measure the view and its content to determine the measured width and the
17103     * measured height. This method is invoked by {@link #measure(int, int)} and
17104     * should be overriden by subclasses to provide accurate and efficient
17105     * measurement of their contents.
17106     * </p>
17107     *
17108     * <p>
17109     * <strong>CONTRACT:</strong> When overriding this method, you
17110     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17111     * measured width and height of this view. Failure to do so will trigger an
17112     * <code>IllegalStateException</code>, thrown by
17113     * {@link #measure(int, int)}. Calling the superclass'
17114     * {@link #onMeasure(int, int)} is a valid use.
17115     * </p>
17116     *
17117     * <p>
17118     * The base class implementation of measure defaults to the background size,
17119     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17120     * override {@link #onMeasure(int, int)} to provide better measurements of
17121     * their content.
17122     * </p>
17123     *
17124     * <p>
17125     * If this method is overridden, it is the subclass's responsibility to make
17126     * sure the measured height and width are at least the view's minimum height
17127     * and width ({@link #getSuggestedMinimumHeight()} and
17128     * {@link #getSuggestedMinimumWidth()}).
17129     * </p>
17130     *
17131     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17132     *                         The requirements are encoded with
17133     *                         {@link android.view.View.MeasureSpec}.
17134     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17135     *                         The requirements are encoded with
17136     *                         {@link android.view.View.MeasureSpec}.
17137     *
17138     * @see #getMeasuredWidth()
17139     * @see #getMeasuredHeight()
17140     * @see #setMeasuredDimension(int, int)
17141     * @see #getSuggestedMinimumHeight()
17142     * @see #getSuggestedMinimumWidth()
17143     * @see android.view.View.MeasureSpec#getMode(int)
17144     * @see android.view.View.MeasureSpec#getSize(int)
17145     */
17146    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17147        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17148                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17149    }
17150
17151    /**
17152     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17153     * measured width and measured height. Failing to do so will trigger an
17154     * exception at measurement time.</p>
17155     *
17156     * @param measuredWidth The measured width of this view.  May be a complex
17157     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17158     * {@link #MEASURED_STATE_TOO_SMALL}.
17159     * @param measuredHeight The measured height of this view.  May be a complex
17160     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17161     * {@link #MEASURED_STATE_TOO_SMALL}.
17162     */
17163    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17164        boolean optical = isLayoutModeOptical(this);
17165        if (optical != isLayoutModeOptical(mParent)) {
17166            Insets insets = getOpticalInsets();
17167            int opticalWidth  = insets.left + insets.right;
17168            int opticalHeight = insets.top  + insets.bottom;
17169
17170            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17171            measuredHeight += optical ? opticalHeight : -opticalHeight;
17172        }
17173        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17174    }
17175
17176    /**
17177     * Sets the measured dimension without extra processing for things like optical bounds.
17178     * Useful for reapplying consistent values that have already been cooked with adjustments
17179     * for optical bounds, etc. such as those from the measurement cache.
17180     *
17181     * @param measuredWidth The measured width of this view.  May be a complex
17182     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17183     * {@link #MEASURED_STATE_TOO_SMALL}.
17184     * @param measuredHeight The measured height of this view.  May be a complex
17185     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17186     * {@link #MEASURED_STATE_TOO_SMALL}.
17187     */
17188    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17189        mMeasuredWidth = measuredWidth;
17190        mMeasuredHeight = measuredHeight;
17191
17192        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17193    }
17194
17195    /**
17196     * Merge two states as returned by {@link #getMeasuredState()}.
17197     * @param curState The current state as returned from a view or the result
17198     * of combining multiple views.
17199     * @param newState The new view state to combine.
17200     * @return Returns a new integer reflecting the combination of the two
17201     * states.
17202     */
17203    public static int combineMeasuredStates(int curState, int newState) {
17204        return curState | newState;
17205    }
17206
17207    /**
17208     * Version of {@link #resolveSizeAndState(int, int, int)}
17209     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17210     */
17211    public static int resolveSize(int size, int measureSpec) {
17212        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17213    }
17214
17215    /**
17216     * Utility to reconcile a desired size and state, with constraints imposed
17217     * by a MeasureSpec.  Will take the desired size, unless a different size
17218     * is imposed by the constraints.  The returned value is a compound integer,
17219     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17220     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17221     * size is smaller than the size the view wants to be.
17222     *
17223     * @param size How big the view wants to be
17224     * @param measureSpec Constraints imposed by the parent
17225     * @return Size information bit mask as defined by
17226     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17227     */
17228    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17229        int result = size;
17230        int specMode = MeasureSpec.getMode(measureSpec);
17231        int specSize =  MeasureSpec.getSize(measureSpec);
17232        switch (specMode) {
17233        case MeasureSpec.UNSPECIFIED:
17234            result = size;
17235            break;
17236        case MeasureSpec.AT_MOST:
17237            if (specSize < size) {
17238                result = specSize | MEASURED_STATE_TOO_SMALL;
17239            } else {
17240                result = size;
17241            }
17242            break;
17243        case MeasureSpec.EXACTLY:
17244            result = specSize;
17245            break;
17246        }
17247        return result | (childMeasuredState&MEASURED_STATE_MASK);
17248    }
17249
17250    /**
17251     * Utility to return a default size. Uses the supplied size if the
17252     * MeasureSpec imposed no constraints. Will get larger if allowed
17253     * by the MeasureSpec.
17254     *
17255     * @param size Default size for this view
17256     * @param measureSpec Constraints imposed by the parent
17257     * @return The size this view should be.
17258     */
17259    public static int getDefaultSize(int size, int measureSpec) {
17260        int result = size;
17261        int specMode = MeasureSpec.getMode(measureSpec);
17262        int specSize = MeasureSpec.getSize(measureSpec);
17263
17264        switch (specMode) {
17265        case MeasureSpec.UNSPECIFIED:
17266            result = size;
17267            break;
17268        case MeasureSpec.AT_MOST:
17269        case MeasureSpec.EXACTLY:
17270            result = specSize;
17271            break;
17272        }
17273        return result;
17274    }
17275
17276    /**
17277     * Returns the suggested minimum height that the view should use. This
17278     * returns the maximum of the view's minimum height
17279     * and the background's minimum height
17280     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17281     * <p>
17282     * When being used in {@link #onMeasure(int, int)}, the caller should still
17283     * ensure the returned height is within the requirements of the parent.
17284     *
17285     * @return The suggested minimum height of the view.
17286     */
17287    protected int getSuggestedMinimumHeight() {
17288        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17289
17290    }
17291
17292    /**
17293     * Returns the suggested minimum width that the view should use. This
17294     * returns the maximum of the view's minimum width)
17295     * and the background's minimum width
17296     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17297     * <p>
17298     * When being used in {@link #onMeasure(int, int)}, the caller should still
17299     * ensure the returned width is within the requirements of the parent.
17300     *
17301     * @return The suggested minimum width of the view.
17302     */
17303    protected int getSuggestedMinimumWidth() {
17304        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17305    }
17306
17307    /**
17308     * Returns the minimum height of the view.
17309     *
17310     * @return the minimum height the view will try to be.
17311     *
17312     * @see #setMinimumHeight(int)
17313     *
17314     * @attr ref android.R.styleable#View_minHeight
17315     */
17316    public int getMinimumHeight() {
17317        return mMinHeight;
17318    }
17319
17320    /**
17321     * Sets the minimum height of the view. It is not guaranteed the view will
17322     * be able to achieve this minimum height (for example, if its parent layout
17323     * constrains it with less available height).
17324     *
17325     * @param minHeight The minimum height the view will try to be.
17326     *
17327     * @see #getMinimumHeight()
17328     *
17329     * @attr ref android.R.styleable#View_minHeight
17330     */
17331    public void setMinimumHeight(int minHeight) {
17332        mMinHeight = minHeight;
17333        requestLayout();
17334    }
17335
17336    /**
17337     * Returns the minimum width of the view.
17338     *
17339     * @return the minimum width the view will try to be.
17340     *
17341     * @see #setMinimumWidth(int)
17342     *
17343     * @attr ref android.R.styleable#View_minWidth
17344     */
17345    public int getMinimumWidth() {
17346        return mMinWidth;
17347    }
17348
17349    /**
17350     * Sets the minimum width of the view. It is not guaranteed the view will
17351     * be able to achieve this minimum width (for example, if its parent layout
17352     * constrains it with less available width).
17353     *
17354     * @param minWidth The minimum width the view will try to be.
17355     *
17356     * @see #getMinimumWidth()
17357     *
17358     * @attr ref android.R.styleable#View_minWidth
17359     */
17360    public void setMinimumWidth(int minWidth) {
17361        mMinWidth = minWidth;
17362        requestLayout();
17363
17364    }
17365
17366    /**
17367     * Get the animation currently associated with this view.
17368     *
17369     * @return The animation that is currently playing or
17370     *         scheduled to play for this view.
17371     */
17372    public Animation getAnimation() {
17373        return mCurrentAnimation;
17374    }
17375
17376    /**
17377     * Start the specified animation now.
17378     *
17379     * @param animation the animation to start now
17380     */
17381    public void startAnimation(Animation animation) {
17382        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17383        setAnimation(animation);
17384        invalidateParentCaches();
17385        invalidate(true);
17386    }
17387
17388    /**
17389     * Cancels any animations for this view.
17390     */
17391    public void clearAnimation() {
17392        if (mCurrentAnimation != null) {
17393            mCurrentAnimation.detach();
17394        }
17395        mCurrentAnimation = null;
17396        invalidateParentIfNeeded();
17397    }
17398
17399    /**
17400     * Sets the next animation to play for this view.
17401     * If you want the animation to play immediately, use
17402     * {@link #startAnimation(android.view.animation.Animation)} instead.
17403     * This method provides allows fine-grained
17404     * control over the start time and invalidation, but you
17405     * must make sure that 1) the animation has a start time set, and
17406     * 2) the view's parent (which controls animations on its children)
17407     * will be invalidated when the animation is supposed to
17408     * start.
17409     *
17410     * @param animation The next animation, or null.
17411     */
17412    public void setAnimation(Animation animation) {
17413        mCurrentAnimation = animation;
17414
17415        if (animation != null) {
17416            // If the screen is off assume the animation start time is now instead of
17417            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17418            // would cause the animation to start when the screen turns back on
17419            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17420                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17421                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17422            }
17423            animation.reset();
17424        }
17425    }
17426
17427    /**
17428     * Invoked by a parent ViewGroup to notify the start of the animation
17429     * currently associated with this view. If you override this method,
17430     * always call super.onAnimationStart();
17431     *
17432     * @see #setAnimation(android.view.animation.Animation)
17433     * @see #getAnimation()
17434     */
17435    protected void onAnimationStart() {
17436        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17437    }
17438
17439    /**
17440     * Invoked by a parent ViewGroup to notify the end of the animation
17441     * currently associated with this view. If you override this method,
17442     * always call super.onAnimationEnd();
17443     *
17444     * @see #setAnimation(android.view.animation.Animation)
17445     * @see #getAnimation()
17446     */
17447    protected void onAnimationEnd() {
17448        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17449    }
17450
17451    /**
17452     * Invoked if there is a Transform that involves alpha. Subclass that can
17453     * draw themselves with the specified alpha should return true, and then
17454     * respect that alpha when their onDraw() is called. If this returns false
17455     * then the view may be redirected to draw into an offscreen buffer to
17456     * fulfill the request, which will look fine, but may be slower than if the
17457     * subclass handles it internally. The default implementation returns false.
17458     *
17459     * @param alpha The alpha (0..255) to apply to the view's drawing
17460     * @return true if the view can draw with the specified alpha.
17461     */
17462    protected boolean onSetAlpha(int alpha) {
17463        return false;
17464    }
17465
17466    /**
17467     * This is used by the RootView to perform an optimization when
17468     * the view hierarchy contains one or several SurfaceView.
17469     * SurfaceView is always considered transparent, but its children are not,
17470     * therefore all View objects remove themselves from the global transparent
17471     * region (passed as a parameter to this function).
17472     *
17473     * @param region The transparent region for this ViewAncestor (window).
17474     *
17475     * @return Returns true if the effective visibility of the view at this
17476     * point is opaque, regardless of the transparent region; returns false
17477     * if it is possible for underlying windows to be seen behind the view.
17478     *
17479     * {@hide}
17480     */
17481    public boolean gatherTransparentRegion(Region region) {
17482        final AttachInfo attachInfo = mAttachInfo;
17483        if (region != null && attachInfo != null) {
17484            final int pflags = mPrivateFlags;
17485            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17486                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17487                // remove it from the transparent region.
17488                final int[] location = attachInfo.mTransparentLocation;
17489                getLocationInWindow(location);
17490                region.op(location[0], location[1], location[0] + mRight - mLeft,
17491                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17492            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17493                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17494                // exists, so we remove the background drawable's non-transparent
17495                // parts from this transparent region.
17496                applyDrawableToTransparentRegion(mBackground, region);
17497            }
17498        }
17499        return true;
17500    }
17501
17502    /**
17503     * Play a sound effect for this view.
17504     *
17505     * <p>The framework will play sound effects for some built in actions, such as
17506     * clicking, but you may wish to play these effects in your widget,
17507     * for instance, for internal navigation.
17508     *
17509     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17510     * {@link #isSoundEffectsEnabled()} is true.
17511     *
17512     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17513     */
17514    public void playSoundEffect(int soundConstant) {
17515        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17516            return;
17517        }
17518        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17519    }
17520
17521    /**
17522     * BZZZTT!!1!
17523     *
17524     * <p>Provide haptic feedback to the user for this view.
17525     *
17526     * <p>The framework will provide haptic feedback for some built in actions,
17527     * such as long presses, but you may wish to provide feedback for your
17528     * own widget.
17529     *
17530     * <p>The feedback will only be performed if
17531     * {@link #isHapticFeedbackEnabled()} is true.
17532     *
17533     * @param feedbackConstant One of the constants defined in
17534     * {@link HapticFeedbackConstants}
17535     */
17536    public boolean performHapticFeedback(int feedbackConstant) {
17537        return performHapticFeedback(feedbackConstant, 0);
17538    }
17539
17540    /**
17541     * BZZZTT!!1!
17542     *
17543     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17544     *
17545     * @param feedbackConstant One of the constants defined in
17546     * {@link HapticFeedbackConstants}
17547     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17548     */
17549    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17550        if (mAttachInfo == null) {
17551            return false;
17552        }
17553        //noinspection SimplifiableIfStatement
17554        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17555                && !isHapticFeedbackEnabled()) {
17556            return false;
17557        }
17558        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17559                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17560    }
17561
17562    /**
17563     * Request that the visibility of the status bar or other screen/window
17564     * decorations be changed.
17565     *
17566     * <p>This method is used to put the over device UI into temporary modes
17567     * where the user's attention is focused more on the application content,
17568     * by dimming or hiding surrounding system affordances.  This is typically
17569     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17570     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17571     * to be placed behind the action bar (and with these flags other system
17572     * affordances) so that smooth transitions between hiding and showing them
17573     * can be done.
17574     *
17575     * <p>Two representative examples of the use of system UI visibility is
17576     * implementing a content browsing application (like a magazine reader)
17577     * and a video playing application.
17578     *
17579     * <p>The first code shows a typical implementation of a View in a content
17580     * browsing application.  In this implementation, the application goes
17581     * into a content-oriented mode by hiding the status bar and action bar,
17582     * and putting the navigation elements into lights out mode.  The user can
17583     * then interact with content while in this mode.  Such an application should
17584     * provide an easy way for the user to toggle out of the mode (such as to
17585     * check information in the status bar or access notifications).  In the
17586     * implementation here, this is done simply by tapping on the content.
17587     *
17588     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17589     *      content}
17590     *
17591     * <p>This second code sample shows a typical implementation of a View
17592     * in a video playing application.  In this situation, while the video is
17593     * playing the application would like to go into a complete full-screen mode,
17594     * to use as much of the display as possible for the video.  When in this state
17595     * the user can not interact with the application; the system intercepts
17596     * touching on the screen to pop the UI out of full screen mode.  See
17597     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17598     *
17599     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17600     *      content}
17601     *
17602     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17603     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17604     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17605     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17606     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17607     */
17608    public void setSystemUiVisibility(int visibility) {
17609        if (visibility != mSystemUiVisibility) {
17610            mSystemUiVisibility = visibility;
17611            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17612                mParent.recomputeViewAttributes(this);
17613            }
17614        }
17615    }
17616
17617    /**
17618     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17619     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17620     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17621     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17622     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17623     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17624     */
17625    public int getSystemUiVisibility() {
17626        return mSystemUiVisibility;
17627    }
17628
17629    /**
17630     * Returns the current system UI visibility that is currently set for
17631     * the entire window.  This is the combination of the
17632     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17633     * views in the window.
17634     */
17635    public int getWindowSystemUiVisibility() {
17636        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17637    }
17638
17639    /**
17640     * Override to find out when the window's requested system UI visibility
17641     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17642     * This is different from the callbacks received through
17643     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17644     * in that this is only telling you about the local request of the window,
17645     * not the actual values applied by the system.
17646     */
17647    public void onWindowSystemUiVisibilityChanged(int visible) {
17648    }
17649
17650    /**
17651     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17652     * the view hierarchy.
17653     */
17654    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17655        onWindowSystemUiVisibilityChanged(visible);
17656    }
17657
17658    /**
17659     * Set a listener to receive callbacks when the visibility of the system bar changes.
17660     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17661     */
17662    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17663        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17664        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17665            mParent.recomputeViewAttributes(this);
17666        }
17667    }
17668
17669    /**
17670     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17671     * the view hierarchy.
17672     */
17673    public void dispatchSystemUiVisibilityChanged(int visibility) {
17674        ListenerInfo li = mListenerInfo;
17675        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17676            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17677                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17678        }
17679    }
17680
17681    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17682        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17683        if (val != mSystemUiVisibility) {
17684            setSystemUiVisibility(val);
17685            return true;
17686        }
17687        return false;
17688    }
17689
17690    /** @hide */
17691    public void setDisabledSystemUiVisibility(int flags) {
17692        if (mAttachInfo != null) {
17693            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17694                mAttachInfo.mDisabledSystemUiVisibility = flags;
17695                if (mParent != null) {
17696                    mParent.recomputeViewAttributes(this);
17697                }
17698            }
17699        }
17700    }
17701
17702    /**
17703     * Creates an image that the system displays during the drag and drop
17704     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17705     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17706     * appearance as the given View. The default also positions the center of the drag shadow
17707     * directly under the touch point. If no View is provided (the constructor with no parameters
17708     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17709     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17710     * default is an invisible drag shadow.
17711     * <p>
17712     * You are not required to use the View you provide to the constructor as the basis of the
17713     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17714     * anything you want as the drag shadow.
17715     * </p>
17716     * <p>
17717     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17718     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17719     *  size and position of the drag shadow. It uses this data to construct a
17720     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17721     *  so that your application can draw the shadow image in the Canvas.
17722     * </p>
17723     *
17724     * <div class="special reference">
17725     * <h3>Developer Guides</h3>
17726     * <p>For a guide to implementing drag and drop features, read the
17727     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17728     * </div>
17729     */
17730    public static class DragShadowBuilder {
17731        private final WeakReference<View> mView;
17732
17733        /**
17734         * Constructs a shadow image builder based on a View. By default, the resulting drag
17735         * shadow will have the same appearance and dimensions as the View, with the touch point
17736         * over the center of the View.
17737         * @param view A View. Any View in scope can be used.
17738         */
17739        public DragShadowBuilder(View view) {
17740            mView = new WeakReference<View>(view);
17741        }
17742
17743        /**
17744         * Construct a shadow builder object with no associated View.  This
17745         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17746         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17747         * to supply the drag shadow's dimensions and appearance without
17748         * reference to any View object. If they are not overridden, then the result is an
17749         * invisible drag shadow.
17750         */
17751        public DragShadowBuilder() {
17752            mView = new WeakReference<View>(null);
17753        }
17754
17755        /**
17756         * Returns the View object that had been passed to the
17757         * {@link #View.DragShadowBuilder(View)}
17758         * constructor.  If that View parameter was {@code null} or if the
17759         * {@link #View.DragShadowBuilder()}
17760         * constructor was used to instantiate the builder object, this method will return
17761         * null.
17762         *
17763         * @return The View object associate with this builder object.
17764         */
17765        @SuppressWarnings({"JavadocReference"})
17766        final public View getView() {
17767            return mView.get();
17768        }
17769
17770        /**
17771         * Provides the metrics for the shadow image. These include the dimensions of
17772         * the shadow image, and the point within that shadow that should
17773         * be centered under the touch location while dragging.
17774         * <p>
17775         * The default implementation sets the dimensions of the shadow to be the
17776         * same as the dimensions of the View itself and centers the shadow under
17777         * the touch point.
17778         * </p>
17779         *
17780         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17781         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17782         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17783         * image.
17784         *
17785         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17786         * shadow image that should be underneath the touch point during the drag and drop
17787         * operation. Your application must set {@link android.graphics.Point#x} to the
17788         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17789         */
17790        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17791            final View view = mView.get();
17792            if (view != null) {
17793                shadowSize.set(view.getWidth(), view.getHeight());
17794                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17795            } else {
17796                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17797            }
17798        }
17799
17800        /**
17801         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17802         * based on the dimensions it received from the
17803         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17804         *
17805         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17806         */
17807        public void onDrawShadow(Canvas canvas) {
17808            final View view = mView.get();
17809            if (view != null) {
17810                view.draw(canvas);
17811            } else {
17812                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17813            }
17814        }
17815    }
17816
17817    /**
17818     * Starts a drag and drop operation. When your application calls this method, it passes a
17819     * {@link android.view.View.DragShadowBuilder} object to the system. The
17820     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17821     * to get metrics for the drag shadow, and then calls the object's
17822     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17823     * <p>
17824     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17825     *  drag events to all the View objects in your application that are currently visible. It does
17826     *  this either by calling the View object's drag listener (an implementation of
17827     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17828     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17829     *  Both are passed a {@link android.view.DragEvent} object that has a
17830     *  {@link android.view.DragEvent#getAction()} value of
17831     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17832     * </p>
17833     * <p>
17834     * Your application can invoke startDrag() on any attached View object. The View object does not
17835     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17836     * be related to the View the user selected for dragging.
17837     * </p>
17838     * @param data A {@link android.content.ClipData} object pointing to the data to be
17839     * transferred by the drag and drop operation.
17840     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17841     * drag shadow.
17842     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17843     * drop operation. This Object is put into every DragEvent object sent by the system during the
17844     * current drag.
17845     * <p>
17846     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17847     * to the target Views. For example, it can contain flags that differentiate between a
17848     * a copy operation and a move operation.
17849     * </p>
17850     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17851     * so the parameter should be set to 0.
17852     * @return {@code true} if the method completes successfully, or
17853     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17854     * do a drag, and so no drag operation is in progress.
17855     */
17856    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17857            Object myLocalState, int flags) {
17858        if (ViewDebug.DEBUG_DRAG) {
17859            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17860        }
17861        boolean okay = false;
17862
17863        Point shadowSize = new Point();
17864        Point shadowTouchPoint = new Point();
17865        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17866
17867        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17868                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17869            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17870        }
17871
17872        if (ViewDebug.DEBUG_DRAG) {
17873            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17874                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17875        }
17876        Surface surface = new Surface();
17877        try {
17878            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17879                    flags, shadowSize.x, shadowSize.y, surface);
17880            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17881                    + " surface=" + surface);
17882            if (token != null) {
17883                Canvas canvas = surface.lockCanvas(null);
17884                try {
17885                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17886                    shadowBuilder.onDrawShadow(canvas);
17887                } finally {
17888                    surface.unlockCanvasAndPost(canvas);
17889                }
17890
17891                final ViewRootImpl root = getViewRootImpl();
17892
17893                // Cache the local state object for delivery with DragEvents
17894                root.setLocalDragState(myLocalState);
17895
17896                // repurpose 'shadowSize' for the last touch point
17897                root.getLastTouchPoint(shadowSize);
17898
17899                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17900                        shadowSize.x, shadowSize.y,
17901                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17902                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17903
17904                // Off and running!  Release our local surface instance; the drag
17905                // shadow surface is now managed by the system process.
17906                surface.release();
17907            }
17908        } catch (Exception e) {
17909            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17910            surface.destroy();
17911        }
17912
17913        return okay;
17914    }
17915
17916    /**
17917     * Handles drag events sent by the system following a call to
17918     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17919     *<p>
17920     * When the system calls this method, it passes a
17921     * {@link android.view.DragEvent} object. A call to
17922     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17923     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17924     * operation.
17925     * @param event The {@link android.view.DragEvent} sent by the system.
17926     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17927     * in DragEvent, indicating the type of drag event represented by this object.
17928     * @return {@code true} if the method was successful, otherwise {@code false}.
17929     * <p>
17930     *  The method should return {@code true} in response to an action type of
17931     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17932     *  operation.
17933     * </p>
17934     * <p>
17935     *  The method should also return {@code true} in response to an action type of
17936     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17937     *  {@code false} if it didn't.
17938     * </p>
17939     */
17940    public boolean onDragEvent(DragEvent event) {
17941        return false;
17942    }
17943
17944    /**
17945     * Detects if this View is enabled and has a drag event listener.
17946     * If both are true, then it calls the drag event listener with the
17947     * {@link android.view.DragEvent} it received. If the drag event listener returns
17948     * {@code true}, then dispatchDragEvent() returns {@code true}.
17949     * <p>
17950     * For all other cases, the method calls the
17951     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17952     * method and returns its result.
17953     * </p>
17954     * <p>
17955     * This ensures that a drag event is always consumed, even if the View does not have a drag
17956     * event listener. However, if the View has a listener and the listener returns true, then
17957     * onDragEvent() is not called.
17958     * </p>
17959     */
17960    public boolean dispatchDragEvent(DragEvent event) {
17961        ListenerInfo li = mListenerInfo;
17962        //noinspection SimplifiableIfStatement
17963        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17964                && li.mOnDragListener.onDrag(this, event)) {
17965            return true;
17966        }
17967        return onDragEvent(event);
17968    }
17969
17970    boolean canAcceptDrag() {
17971        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17972    }
17973
17974    /**
17975     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17976     * it is ever exposed at all.
17977     * @hide
17978     */
17979    public void onCloseSystemDialogs(String reason) {
17980    }
17981
17982    /**
17983     * Given a Drawable whose bounds have been set to draw into this view,
17984     * update a Region being computed for
17985     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17986     * that any non-transparent parts of the Drawable are removed from the
17987     * given transparent region.
17988     *
17989     * @param dr The Drawable whose transparency is to be applied to the region.
17990     * @param region A Region holding the current transparency information,
17991     * where any parts of the region that are set are considered to be
17992     * transparent.  On return, this region will be modified to have the
17993     * transparency information reduced by the corresponding parts of the
17994     * Drawable that are not transparent.
17995     * {@hide}
17996     */
17997    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17998        if (DBG) {
17999            Log.i("View", "Getting transparent region for: " + this);
18000        }
18001        final Region r = dr.getTransparentRegion();
18002        final Rect db = dr.getBounds();
18003        final AttachInfo attachInfo = mAttachInfo;
18004        if (r != null && attachInfo != null) {
18005            final int w = getRight()-getLeft();
18006            final int h = getBottom()-getTop();
18007            if (db.left > 0) {
18008                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18009                r.op(0, 0, db.left, h, Region.Op.UNION);
18010            }
18011            if (db.right < w) {
18012                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18013                r.op(db.right, 0, w, h, Region.Op.UNION);
18014            }
18015            if (db.top > 0) {
18016                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18017                r.op(0, 0, w, db.top, Region.Op.UNION);
18018            }
18019            if (db.bottom < h) {
18020                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18021                r.op(0, db.bottom, w, h, Region.Op.UNION);
18022            }
18023            final int[] location = attachInfo.mTransparentLocation;
18024            getLocationInWindow(location);
18025            r.translate(location[0], location[1]);
18026            region.op(r, Region.Op.INTERSECT);
18027        } else {
18028            region.op(db, Region.Op.DIFFERENCE);
18029        }
18030    }
18031
18032    private void checkForLongClick(int delayOffset) {
18033        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18034            mHasPerformedLongPress = false;
18035
18036            if (mPendingCheckForLongPress == null) {
18037                mPendingCheckForLongPress = new CheckForLongPress();
18038            }
18039            mPendingCheckForLongPress.rememberWindowAttachCount();
18040            postDelayed(mPendingCheckForLongPress,
18041                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18042        }
18043    }
18044
18045    /**
18046     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18047     * LayoutInflater} class, which provides a full range of options for view inflation.
18048     *
18049     * @param context The Context object for your activity or application.
18050     * @param resource The resource ID to inflate
18051     * @param root A view group that will be the parent.  Used to properly inflate the
18052     * layout_* parameters.
18053     * @see LayoutInflater
18054     */
18055    public static View inflate(Context context, int resource, ViewGroup root) {
18056        LayoutInflater factory = LayoutInflater.from(context);
18057        return factory.inflate(resource, root);
18058    }
18059
18060    /**
18061     * Scroll the view with standard behavior for scrolling beyond the normal
18062     * content boundaries. Views that call this method should override
18063     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18064     * results of an over-scroll operation.
18065     *
18066     * Views can use this method to handle any touch or fling-based scrolling.
18067     *
18068     * @param deltaX Change in X in pixels
18069     * @param deltaY Change in Y in pixels
18070     * @param scrollX Current X scroll value in pixels before applying deltaX
18071     * @param scrollY Current Y scroll value in pixels before applying deltaY
18072     * @param scrollRangeX Maximum content scroll range along the X axis
18073     * @param scrollRangeY Maximum content scroll range along the Y axis
18074     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18075     *          along the X axis.
18076     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18077     *          along the Y axis.
18078     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18079     * @return true if scrolling was clamped to an over-scroll boundary along either
18080     *          axis, false otherwise.
18081     */
18082    @SuppressWarnings({"UnusedParameters"})
18083    protected boolean overScrollBy(int deltaX, int deltaY,
18084            int scrollX, int scrollY,
18085            int scrollRangeX, int scrollRangeY,
18086            int maxOverScrollX, int maxOverScrollY,
18087            boolean isTouchEvent) {
18088        final int overScrollMode = mOverScrollMode;
18089        final boolean canScrollHorizontal =
18090                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18091        final boolean canScrollVertical =
18092                computeVerticalScrollRange() > computeVerticalScrollExtent();
18093        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18094                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18095        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18096                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18097
18098        int newScrollX = scrollX + deltaX;
18099        if (!overScrollHorizontal) {
18100            maxOverScrollX = 0;
18101        }
18102
18103        int newScrollY = scrollY + deltaY;
18104        if (!overScrollVertical) {
18105            maxOverScrollY = 0;
18106        }
18107
18108        // Clamp values if at the limits and record
18109        final int left = -maxOverScrollX;
18110        final int right = maxOverScrollX + scrollRangeX;
18111        final int top = -maxOverScrollY;
18112        final int bottom = maxOverScrollY + scrollRangeY;
18113
18114        boolean clampedX = false;
18115        if (newScrollX > right) {
18116            newScrollX = right;
18117            clampedX = true;
18118        } else if (newScrollX < left) {
18119            newScrollX = left;
18120            clampedX = true;
18121        }
18122
18123        boolean clampedY = false;
18124        if (newScrollY > bottom) {
18125            newScrollY = bottom;
18126            clampedY = true;
18127        } else if (newScrollY < top) {
18128            newScrollY = top;
18129            clampedY = true;
18130        }
18131
18132        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18133
18134        return clampedX || clampedY;
18135    }
18136
18137    /**
18138     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18139     * respond to the results of an over-scroll operation.
18140     *
18141     * @param scrollX New X scroll value in pixels
18142     * @param scrollY New Y scroll value in pixels
18143     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18144     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18145     */
18146    protected void onOverScrolled(int scrollX, int scrollY,
18147            boolean clampedX, boolean clampedY) {
18148        // Intentionally empty.
18149    }
18150
18151    /**
18152     * Returns the over-scroll mode for this view. The result will be
18153     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18154     * (allow over-scrolling only if the view content is larger than the container),
18155     * or {@link #OVER_SCROLL_NEVER}.
18156     *
18157     * @return This view's over-scroll mode.
18158     */
18159    public int getOverScrollMode() {
18160        return mOverScrollMode;
18161    }
18162
18163    /**
18164     * Set the over-scroll mode for this view. Valid over-scroll modes are
18165     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18166     * (allow over-scrolling only if the view content is larger than the container),
18167     * or {@link #OVER_SCROLL_NEVER}.
18168     *
18169     * Setting the over-scroll mode of a view will have an effect only if the
18170     * view is capable of scrolling.
18171     *
18172     * @param overScrollMode The new over-scroll mode for this view.
18173     */
18174    public void setOverScrollMode(int overScrollMode) {
18175        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18176                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18177                overScrollMode != OVER_SCROLL_NEVER) {
18178            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18179        }
18180        mOverScrollMode = overScrollMode;
18181    }
18182
18183    /**
18184     * Enable or disable nested scrolling for this view.
18185     *
18186     * <p>If this property is set to true the view will be permitted to initiate nested
18187     * scrolling operations with a compatible parent view in the current hierarchy. If this
18188     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18189     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18190     * the nested scroll.</p>
18191     *
18192     * @param enabled true to enable nested scrolling, false to disable
18193     *
18194     * @see #isNestedScrollingEnabled()
18195     */
18196    public void setNestedScrollingEnabled(boolean enabled) {
18197        if (enabled) {
18198            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18199        } else {
18200            stopNestedScroll();
18201            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18202        }
18203    }
18204
18205    /**
18206     * Returns true if nested scrolling is enabled for this view.
18207     *
18208     * <p>If nested scrolling is enabled and this View class implementation supports it,
18209     * this view will act as a nested scrolling child view when applicable, forwarding data
18210     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18211     * parent.</p>
18212     *
18213     * @return true if nested scrolling is enabled
18214     *
18215     * @see #setNestedScrollingEnabled(boolean)
18216     */
18217    public boolean isNestedScrollingEnabled() {
18218        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18219                PFLAG3_NESTED_SCROLLING_ENABLED;
18220    }
18221
18222    /**
18223     * Begin a nestable scroll operation along the given axes.
18224     *
18225     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18226     *
18227     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18228     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18229     * In the case of touch scrolling the nested scroll will be terminated automatically in
18230     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18231     * In the event of programmatic scrolling the caller must explicitly call
18232     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18233     *
18234     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18235     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18236     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18237     *
18238     * <p>At each incremental step of the scroll the caller should invoke
18239     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18240     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18241     * parent at least partially consumed the scroll and the caller should adjust the amount it
18242     * scrolls by.</p>
18243     *
18244     * <p>After applying the remainder of the scroll delta the caller should invoke
18245     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18246     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18247     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18248     * </p>
18249     *
18250     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18251     *             {@link #SCROLL_AXIS_VERTICAL}.
18252     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18253     *         the current gesture.
18254     *
18255     * @see #stopNestedScroll()
18256     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18257     * @see #dispatchNestedScroll(int, int, int, int, int[])
18258     */
18259    public boolean startNestedScroll(int axes) {
18260        if (hasNestedScrollingParent()) {
18261            // Already in progress
18262            return true;
18263        }
18264        if (isNestedScrollingEnabled()) {
18265            ViewParent p = getParent();
18266            View child = this;
18267            while (p != null) {
18268                try {
18269                    if (p.onStartNestedScroll(child, this, axes)) {
18270                        mNestedScrollingParent = p;
18271                        p.onNestedScrollAccepted(child, this, axes);
18272                        return true;
18273                    }
18274                } catch (AbstractMethodError e) {
18275                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18276                            "method onStartNestedScroll", e);
18277                    // Allow the search upward to continue
18278                }
18279                if (p instanceof View) {
18280                    child = (View) p;
18281                }
18282                p = p.getParent();
18283            }
18284        }
18285        return false;
18286    }
18287
18288    /**
18289     * Stop a nested scroll in progress.
18290     *
18291     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18292     *
18293     * @see #startNestedScroll(int)
18294     */
18295    public void stopNestedScroll() {
18296        if (mNestedScrollingParent != null) {
18297            mNestedScrollingParent.onStopNestedScroll(this);
18298            mNestedScrollingParent = null;
18299        }
18300    }
18301
18302    /**
18303     * Returns true if this view has a nested scrolling parent.
18304     *
18305     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18306     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18307     *
18308     * @return whether this view has a nested scrolling parent
18309     */
18310    public boolean hasNestedScrollingParent() {
18311        return mNestedScrollingParent != null;
18312    }
18313
18314    /**
18315     * Dispatch one step of a nested scroll in progress.
18316     *
18317     * <p>Implementations of views that support nested scrolling should call this to report
18318     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18319     * is not currently in progress or nested scrolling is not
18320     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18321     *
18322     * <p>Compatible View implementations should also call
18323     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18324     * consuming a component of the scroll event themselves.</p>
18325     *
18326     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18327     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18328     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18329     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18330     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18331     *                       in local view coordinates of this view from before this operation
18332     *                       to after it completes. View implementations may use this to adjust
18333     *                       expected input coordinate tracking.
18334     * @return true if the event was dispatched, false if it could not be dispatched.
18335     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18336     */
18337    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18338            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18339        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18340            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18341                int startX = 0;
18342                int startY = 0;
18343                if (offsetInWindow != null) {
18344                    getLocationInWindow(offsetInWindow);
18345                    startX = offsetInWindow[0];
18346                    startY = offsetInWindow[1];
18347                }
18348
18349                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18350                        dxUnconsumed, dyUnconsumed);
18351
18352                if (offsetInWindow != null) {
18353                    getLocationInWindow(offsetInWindow);
18354                    offsetInWindow[0] -= startX;
18355                    offsetInWindow[1] -= startY;
18356                }
18357                return true;
18358            } else if (offsetInWindow != null) {
18359                // No motion, no dispatch. Keep offsetInWindow up to date.
18360                offsetInWindow[0] = 0;
18361                offsetInWindow[1] = 0;
18362            }
18363        }
18364        return false;
18365    }
18366
18367    /**
18368     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18369     *
18370     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18371     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18372     * scrolling operation to consume some or all of the scroll operation before the child view
18373     * consumes it.</p>
18374     *
18375     * @param dx Horizontal scroll distance in pixels
18376     * @param dy Vertical scroll distance in pixels
18377     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18378     *                 and consumed[1] the consumed dy.
18379     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18380     *                       in local view coordinates of this view from before this operation
18381     *                       to after it completes. View implementations may use this to adjust
18382     *                       expected input coordinate tracking.
18383     * @return true if the parent consumed some or all of the scroll delta
18384     * @see #dispatchNestedScroll(int, int, int, int, int[])
18385     */
18386    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18387        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18388            if (dx != 0 || dy != 0) {
18389                int startX = 0;
18390                int startY = 0;
18391                if (offsetInWindow != null) {
18392                    getLocationInWindow(offsetInWindow);
18393                    startX = offsetInWindow[0];
18394                    startY = offsetInWindow[1];
18395                }
18396
18397                if (consumed == null) {
18398                    if (mTempNestedScrollConsumed == null) {
18399                        mTempNestedScrollConsumed = new int[2];
18400                    }
18401                    consumed = mTempNestedScrollConsumed;
18402                }
18403                consumed[0] = 0;
18404                consumed[1] = 0;
18405                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18406
18407                if (offsetInWindow != null) {
18408                    getLocationInWindow(offsetInWindow);
18409                    offsetInWindow[0] -= startX;
18410                    offsetInWindow[1] -= startY;
18411                }
18412                return consumed[0] != 0 || consumed[1] != 0;
18413            } else if (offsetInWindow != null) {
18414                offsetInWindow[0] = 0;
18415                offsetInWindow[1] = 0;
18416            }
18417        }
18418        return false;
18419    }
18420
18421    /**
18422     * Dispatch a fling to a nested scrolling parent.
18423     *
18424     * <p>This method should be used to indicate that a nested scrolling child has detected
18425     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18426     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18427     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18428     * along a scrollable axis.</p>
18429     *
18430     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18431     * its own content, it can use this method to delegate the fling to its nested scrolling
18432     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18433     *
18434     * @param velocityX Horizontal fling velocity in pixels per second
18435     * @param velocityY Vertical fling velocity in pixels per second
18436     * @param consumed true if the child consumed the fling, false otherwise
18437     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18438     */
18439    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18440        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18441            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18442        }
18443        return false;
18444    }
18445
18446    /**
18447     * Gets a scale factor that determines the distance the view should scroll
18448     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18449     * @return The vertical scroll scale factor.
18450     * @hide
18451     */
18452    protected float getVerticalScrollFactor() {
18453        if (mVerticalScrollFactor == 0) {
18454            TypedValue outValue = new TypedValue();
18455            if (!mContext.getTheme().resolveAttribute(
18456                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18457                throw new IllegalStateException(
18458                        "Expected theme to define listPreferredItemHeight.");
18459            }
18460            mVerticalScrollFactor = outValue.getDimension(
18461                    mContext.getResources().getDisplayMetrics());
18462        }
18463        return mVerticalScrollFactor;
18464    }
18465
18466    /**
18467     * Gets a scale factor that determines the distance the view should scroll
18468     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18469     * @return The horizontal scroll scale factor.
18470     * @hide
18471     */
18472    protected float getHorizontalScrollFactor() {
18473        // TODO: Should use something else.
18474        return getVerticalScrollFactor();
18475    }
18476
18477    /**
18478     * Return the value specifying the text direction or policy that was set with
18479     * {@link #setTextDirection(int)}.
18480     *
18481     * @return the defined text direction. It can be one of:
18482     *
18483     * {@link #TEXT_DIRECTION_INHERIT},
18484     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18485     * {@link #TEXT_DIRECTION_ANY_RTL},
18486     * {@link #TEXT_DIRECTION_LTR},
18487     * {@link #TEXT_DIRECTION_RTL},
18488     * {@link #TEXT_DIRECTION_LOCALE}
18489     *
18490     * @attr ref android.R.styleable#View_textDirection
18491     *
18492     * @hide
18493     */
18494    @ViewDebug.ExportedProperty(category = "text", mapping = {
18495            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18496            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18497            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18498            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18499            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18500            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18501    })
18502    public int getRawTextDirection() {
18503        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18504    }
18505
18506    /**
18507     * Set the text direction.
18508     *
18509     * @param textDirection the direction to set. Should be one of:
18510     *
18511     * {@link #TEXT_DIRECTION_INHERIT},
18512     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18513     * {@link #TEXT_DIRECTION_ANY_RTL},
18514     * {@link #TEXT_DIRECTION_LTR},
18515     * {@link #TEXT_DIRECTION_RTL},
18516     * {@link #TEXT_DIRECTION_LOCALE}
18517     *
18518     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18519     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18520     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18521     *
18522     * @attr ref android.R.styleable#View_textDirection
18523     */
18524    public void setTextDirection(int textDirection) {
18525        if (getRawTextDirection() != textDirection) {
18526            // Reset the current text direction and the resolved one
18527            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18528            resetResolvedTextDirection();
18529            // Set the new text direction
18530            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18531            // Do resolution
18532            resolveTextDirection();
18533            // Notify change
18534            onRtlPropertiesChanged(getLayoutDirection());
18535            // Refresh
18536            requestLayout();
18537            invalidate(true);
18538        }
18539    }
18540
18541    /**
18542     * Return the resolved text direction.
18543     *
18544     * @return the resolved text direction. Returns one of:
18545     *
18546     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18547     * {@link #TEXT_DIRECTION_ANY_RTL},
18548     * {@link #TEXT_DIRECTION_LTR},
18549     * {@link #TEXT_DIRECTION_RTL},
18550     * {@link #TEXT_DIRECTION_LOCALE}
18551     *
18552     * @attr ref android.R.styleable#View_textDirection
18553     */
18554    @ViewDebug.ExportedProperty(category = "text", mapping = {
18555            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18556            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18557            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18558            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18559            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18560            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18561    })
18562    public int getTextDirection() {
18563        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18564    }
18565
18566    /**
18567     * Resolve the text direction.
18568     *
18569     * @return true if resolution has been done, false otherwise.
18570     *
18571     * @hide
18572     */
18573    public boolean resolveTextDirection() {
18574        // Reset any previous text direction resolution
18575        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18576
18577        if (hasRtlSupport()) {
18578            // Set resolved text direction flag depending on text direction flag
18579            final int textDirection = getRawTextDirection();
18580            switch(textDirection) {
18581                case TEXT_DIRECTION_INHERIT:
18582                    if (!canResolveTextDirection()) {
18583                        // We cannot do the resolution if there is no parent, so use the default one
18584                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18585                        // Resolution will need to happen again later
18586                        return false;
18587                    }
18588
18589                    // Parent has not yet resolved, so we still return the default
18590                    try {
18591                        if (!mParent.isTextDirectionResolved()) {
18592                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18593                            // Resolution will need to happen again later
18594                            return false;
18595                        }
18596                    } catch (AbstractMethodError e) {
18597                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18598                                " does not fully implement ViewParent", e);
18599                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18600                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18601                        return true;
18602                    }
18603
18604                    // Set current resolved direction to the same value as the parent's one
18605                    int parentResolvedDirection;
18606                    try {
18607                        parentResolvedDirection = mParent.getTextDirection();
18608                    } catch (AbstractMethodError e) {
18609                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18610                                " does not fully implement ViewParent", e);
18611                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18612                    }
18613                    switch (parentResolvedDirection) {
18614                        case TEXT_DIRECTION_FIRST_STRONG:
18615                        case TEXT_DIRECTION_ANY_RTL:
18616                        case TEXT_DIRECTION_LTR:
18617                        case TEXT_DIRECTION_RTL:
18618                        case TEXT_DIRECTION_LOCALE:
18619                            mPrivateFlags2 |=
18620                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18621                            break;
18622                        default:
18623                            // Default resolved direction is "first strong" heuristic
18624                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18625                    }
18626                    break;
18627                case TEXT_DIRECTION_FIRST_STRONG:
18628                case TEXT_DIRECTION_ANY_RTL:
18629                case TEXT_DIRECTION_LTR:
18630                case TEXT_DIRECTION_RTL:
18631                case TEXT_DIRECTION_LOCALE:
18632                    // Resolved direction is the same as text direction
18633                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18634                    break;
18635                default:
18636                    // Default resolved direction is "first strong" heuristic
18637                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18638            }
18639        } else {
18640            // Default resolved direction is "first strong" heuristic
18641            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18642        }
18643
18644        // Set to resolved
18645        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18646        return true;
18647    }
18648
18649    /**
18650     * Check if text direction resolution can be done.
18651     *
18652     * @return true if text direction resolution can be done otherwise return false.
18653     */
18654    public boolean canResolveTextDirection() {
18655        switch (getRawTextDirection()) {
18656            case TEXT_DIRECTION_INHERIT:
18657                if (mParent != null) {
18658                    try {
18659                        return mParent.canResolveTextDirection();
18660                    } catch (AbstractMethodError e) {
18661                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18662                                " does not fully implement ViewParent", e);
18663                    }
18664                }
18665                return false;
18666
18667            default:
18668                return true;
18669        }
18670    }
18671
18672    /**
18673     * Reset resolved text direction. Text direction will be resolved during a call to
18674     * {@link #onMeasure(int, int)}.
18675     *
18676     * @hide
18677     */
18678    public void resetResolvedTextDirection() {
18679        // Reset any previous text direction resolution
18680        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18681        // Set to default value
18682        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18683    }
18684
18685    /**
18686     * @return true if text direction is inherited.
18687     *
18688     * @hide
18689     */
18690    public boolean isTextDirectionInherited() {
18691        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18692    }
18693
18694    /**
18695     * @return true if text direction is resolved.
18696     */
18697    public boolean isTextDirectionResolved() {
18698        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18699    }
18700
18701    /**
18702     * Return the value specifying the text alignment or policy that was set with
18703     * {@link #setTextAlignment(int)}.
18704     *
18705     * @return the defined text alignment. It can be one of:
18706     *
18707     * {@link #TEXT_ALIGNMENT_INHERIT},
18708     * {@link #TEXT_ALIGNMENT_GRAVITY},
18709     * {@link #TEXT_ALIGNMENT_CENTER},
18710     * {@link #TEXT_ALIGNMENT_TEXT_START},
18711     * {@link #TEXT_ALIGNMENT_TEXT_END},
18712     * {@link #TEXT_ALIGNMENT_VIEW_START},
18713     * {@link #TEXT_ALIGNMENT_VIEW_END}
18714     *
18715     * @attr ref android.R.styleable#View_textAlignment
18716     *
18717     * @hide
18718     */
18719    @ViewDebug.ExportedProperty(category = "text", mapping = {
18720            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18721            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18722            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18723            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18724            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18725            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18726            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18727    })
18728    @TextAlignment
18729    public int getRawTextAlignment() {
18730        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18731    }
18732
18733    /**
18734     * Set the text alignment.
18735     *
18736     * @param textAlignment The text alignment to set. Should be one of
18737     *
18738     * {@link #TEXT_ALIGNMENT_INHERIT},
18739     * {@link #TEXT_ALIGNMENT_GRAVITY},
18740     * {@link #TEXT_ALIGNMENT_CENTER},
18741     * {@link #TEXT_ALIGNMENT_TEXT_START},
18742     * {@link #TEXT_ALIGNMENT_TEXT_END},
18743     * {@link #TEXT_ALIGNMENT_VIEW_START},
18744     * {@link #TEXT_ALIGNMENT_VIEW_END}
18745     *
18746     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18747     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18748     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18749     *
18750     * @attr ref android.R.styleable#View_textAlignment
18751     */
18752    public void setTextAlignment(@TextAlignment int textAlignment) {
18753        if (textAlignment != getRawTextAlignment()) {
18754            // Reset the current and resolved text alignment
18755            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18756            resetResolvedTextAlignment();
18757            // Set the new text alignment
18758            mPrivateFlags2 |=
18759                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18760            // Do resolution
18761            resolveTextAlignment();
18762            // Notify change
18763            onRtlPropertiesChanged(getLayoutDirection());
18764            // Refresh
18765            requestLayout();
18766            invalidate(true);
18767        }
18768    }
18769
18770    /**
18771     * Return the resolved text alignment.
18772     *
18773     * @return the resolved text alignment. Returns one of:
18774     *
18775     * {@link #TEXT_ALIGNMENT_GRAVITY},
18776     * {@link #TEXT_ALIGNMENT_CENTER},
18777     * {@link #TEXT_ALIGNMENT_TEXT_START},
18778     * {@link #TEXT_ALIGNMENT_TEXT_END},
18779     * {@link #TEXT_ALIGNMENT_VIEW_START},
18780     * {@link #TEXT_ALIGNMENT_VIEW_END}
18781     *
18782     * @attr ref android.R.styleable#View_textAlignment
18783     */
18784    @ViewDebug.ExportedProperty(category = "text", mapping = {
18785            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18786            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18787            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18788            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18789            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18790            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18791            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18792    })
18793    @TextAlignment
18794    public int getTextAlignment() {
18795        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18796                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18797    }
18798
18799    /**
18800     * Resolve the text alignment.
18801     *
18802     * @return true if resolution has been done, false otherwise.
18803     *
18804     * @hide
18805     */
18806    public boolean resolveTextAlignment() {
18807        // Reset any previous text alignment resolution
18808        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18809
18810        if (hasRtlSupport()) {
18811            // Set resolved text alignment flag depending on text alignment flag
18812            final int textAlignment = getRawTextAlignment();
18813            switch (textAlignment) {
18814                case TEXT_ALIGNMENT_INHERIT:
18815                    // Check if we can resolve the text alignment
18816                    if (!canResolveTextAlignment()) {
18817                        // We cannot do the resolution if there is no parent so use the default
18818                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18819                        // Resolution will need to happen again later
18820                        return false;
18821                    }
18822
18823                    // Parent has not yet resolved, so we still return the default
18824                    try {
18825                        if (!mParent.isTextAlignmentResolved()) {
18826                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18827                            // Resolution will need to happen again later
18828                            return false;
18829                        }
18830                    } catch (AbstractMethodError e) {
18831                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18832                                " does not fully implement ViewParent", e);
18833                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18834                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18835                        return true;
18836                    }
18837
18838                    int parentResolvedTextAlignment;
18839                    try {
18840                        parentResolvedTextAlignment = mParent.getTextAlignment();
18841                    } catch (AbstractMethodError e) {
18842                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18843                                " does not fully implement ViewParent", e);
18844                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18845                    }
18846                    switch (parentResolvedTextAlignment) {
18847                        case TEXT_ALIGNMENT_GRAVITY:
18848                        case TEXT_ALIGNMENT_TEXT_START:
18849                        case TEXT_ALIGNMENT_TEXT_END:
18850                        case TEXT_ALIGNMENT_CENTER:
18851                        case TEXT_ALIGNMENT_VIEW_START:
18852                        case TEXT_ALIGNMENT_VIEW_END:
18853                            // Resolved text alignment is the same as the parent resolved
18854                            // text alignment
18855                            mPrivateFlags2 |=
18856                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18857                            break;
18858                        default:
18859                            // Use default resolved text alignment
18860                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18861                    }
18862                    break;
18863                case TEXT_ALIGNMENT_GRAVITY:
18864                case TEXT_ALIGNMENT_TEXT_START:
18865                case TEXT_ALIGNMENT_TEXT_END:
18866                case TEXT_ALIGNMENT_CENTER:
18867                case TEXT_ALIGNMENT_VIEW_START:
18868                case TEXT_ALIGNMENT_VIEW_END:
18869                    // Resolved text alignment is the same as text alignment
18870                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18871                    break;
18872                default:
18873                    // Use default resolved text alignment
18874                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18875            }
18876        } else {
18877            // Use default resolved text alignment
18878            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18879        }
18880
18881        // Set the resolved
18882        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18883        return true;
18884    }
18885
18886    /**
18887     * Check if text alignment resolution can be done.
18888     *
18889     * @return true if text alignment resolution can be done otherwise return false.
18890     */
18891    public boolean canResolveTextAlignment() {
18892        switch (getRawTextAlignment()) {
18893            case TEXT_DIRECTION_INHERIT:
18894                if (mParent != null) {
18895                    try {
18896                        return mParent.canResolveTextAlignment();
18897                    } catch (AbstractMethodError e) {
18898                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18899                                " does not fully implement ViewParent", e);
18900                    }
18901                }
18902                return false;
18903
18904            default:
18905                return true;
18906        }
18907    }
18908
18909    /**
18910     * Reset resolved text alignment. Text alignment will be resolved during a call to
18911     * {@link #onMeasure(int, int)}.
18912     *
18913     * @hide
18914     */
18915    public void resetResolvedTextAlignment() {
18916        // Reset any previous text alignment resolution
18917        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18918        // Set to default
18919        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18920    }
18921
18922    /**
18923     * @return true if text alignment is inherited.
18924     *
18925     * @hide
18926     */
18927    public boolean isTextAlignmentInherited() {
18928        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18929    }
18930
18931    /**
18932     * @return true if text alignment is resolved.
18933     */
18934    public boolean isTextAlignmentResolved() {
18935        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18936    }
18937
18938    /**
18939     * Generate a value suitable for use in {@link #setId(int)}.
18940     * This value will not collide with ID values generated at build time by aapt for R.id.
18941     *
18942     * @return a generated ID value
18943     */
18944    public static int generateViewId() {
18945        for (;;) {
18946            final int result = sNextGeneratedId.get();
18947            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18948            int newValue = result + 1;
18949            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18950            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18951                return result;
18952            }
18953        }
18954    }
18955
18956    /**
18957     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18958     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18959     *                           a normal View or a ViewGroup with
18960     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18961     * @hide
18962     */
18963    public void captureTransitioningViews(List<View> transitioningViews) {
18964        if (getVisibility() == View.VISIBLE) {
18965            transitioningViews.add(this);
18966        }
18967    }
18968
18969    /**
18970     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
18971     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
18972     * @hide
18973     */
18974    public void findNamedViews(Map<String, View> namedElements) {
18975        if (getVisibility() == VISIBLE) {
18976            String transitionName = getTransitionName();
18977            if (transitionName != null) {
18978                namedElements.put(transitionName, this);
18979            }
18980        }
18981    }
18982
18983    //
18984    // Properties
18985    //
18986    /**
18987     * A Property wrapper around the <code>alpha</code> functionality handled by the
18988     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18989     */
18990    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18991        @Override
18992        public void setValue(View object, float value) {
18993            object.setAlpha(value);
18994        }
18995
18996        @Override
18997        public Float get(View object) {
18998            return object.getAlpha();
18999        }
19000    };
19001
19002    /**
19003     * A Property wrapper around the <code>translationX</code> functionality handled by the
19004     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19005     */
19006    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19007        @Override
19008        public void setValue(View object, float value) {
19009            object.setTranslationX(value);
19010        }
19011
19012                @Override
19013        public Float get(View object) {
19014            return object.getTranslationX();
19015        }
19016    };
19017
19018    /**
19019     * A Property wrapper around the <code>translationY</code> functionality handled by the
19020     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19021     */
19022    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19023        @Override
19024        public void setValue(View object, float value) {
19025            object.setTranslationY(value);
19026        }
19027
19028        @Override
19029        public Float get(View object) {
19030            return object.getTranslationY();
19031        }
19032    };
19033
19034    /**
19035     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19036     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19037     */
19038    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19039        @Override
19040        public void setValue(View object, float value) {
19041            object.setTranslationZ(value);
19042        }
19043
19044        @Override
19045        public Float get(View object) {
19046            return object.getTranslationZ();
19047        }
19048    };
19049
19050    /**
19051     * A Property wrapper around the <code>x</code> functionality handled by the
19052     * {@link View#setX(float)} and {@link View#getX()} methods.
19053     */
19054    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19055        @Override
19056        public void setValue(View object, float value) {
19057            object.setX(value);
19058        }
19059
19060        @Override
19061        public Float get(View object) {
19062            return object.getX();
19063        }
19064    };
19065
19066    /**
19067     * A Property wrapper around the <code>y</code> functionality handled by the
19068     * {@link View#setY(float)} and {@link View#getY()} methods.
19069     */
19070    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19071        @Override
19072        public void setValue(View object, float value) {
19073            object.setY(value);
19074        }
19075
19076        @Override
19077        public Float get(View object) {
19078            return object.getY();
19079        }
19080    };
19081
19082    /**
19083     * A Property wrapper around the <code>z</code> functionality handled by the
19084     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19085     */
19086    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19087        @Override
19088        public void setValue(View object, float value) {
19089            object.setZ(value);
19090        }
19091
19092        @Override
19093        public Float get(View object) {
19094            return object.getZ();
19095        }
19096    };
19097
19098    /**
19099     * A Property wrapper around the <code>rotation</code> functionality handled by the
19100     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19101     */
19102    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19103        @Override
19104        public void setValue(View object, float value) {
19105            object.setRotation(value);
19106        }
19107
19108        @Override
19109        public Float get(View object) {
19110            return object.getRotation();
19111        }
19112    };
19113
19114    /**
19115     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19116     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19117     */
19118    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19119        @Override
19120        public void setValue(View object, float value) {
19121            object.setRotationX(value);
19122        }
19123
19124        @Override
19125        public Float get(View object) {
19126            return object.getRotationX();
19127        }
19128    };
19129
19130    /**
19131     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19132     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19133     */
19134    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19135        @Override
19136        public void setValue(View object, float value) {
19137            object.setRotationY(value);
19138        }
19139
19140        @Override
19141        public Float get(View object) {
19142            return object.getRotationY();
19143        }
19144    };
19145
19146    /**
19147     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19148     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19149     */
19150    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19151        @Override
19152        public void setValue(View object, float value) {
19153            object.setScaleX(value);
19154        }
19155
19156        @Override
19157        public Float get(View object) {
19158            return object.getScaleX();
19159        }
19160    };
19161
19162    /**
19163     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19164     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19165     */
19166    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19167        @Override
19168        public void setValue(View object, float value) {
19169            object.setScaleY(value);
19170        }
19171
19172        @Override
19173        public Float get(View object) {
19174            return object.getScaleY();
19175        }
19176    };
19177
19178    /**
19179     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19180     * Each MeasureSpec represents a requirement for either the width or the height.
19181     * A MeasureSpec is comprised of a size and a mode. There are three possible
19182     * modes:
19183     * <dl>
19184     * <dt>UNSPECIFIED</dt>
19185     * <dd>
19186     * The parent has not imposed any constraint on the child. It can be whatever size
19187     * it wants.
19188     * </dd>
19189     *
19190     * <dt>EXACTLY</dt>
19191     * <dd>
19192     * The parent has determined an exact size for the child. The child is going to be
19193     * given those bounds regardless of how big it wants to be.
19194     * </dd>
19195     *
19196     * <dt>AT_MOST</dt>
19197     * <dd>
19198     * The child can be as large as it wants up to the specified size.
19199     * </dd>
19200     * </dl>
19201     *
19202     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19203     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19204     */
19205    public static class MeasureSpec {
19206        private static final int MODE_SHIFT = 30;
19207        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19208
19209        /**
19210         * Measure specification mode: The parent has not imposed any constraint
19211         * on the child. It can be whatever size it wants.
19212         */
19213        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19214
19215        /**
19216         * Measure specification mode: The parent has determined an exact size
19217         * for the child. The child is going to be given those bounds regardless
19218         * of how big it wants to be.
19219         */
19220        public static final int EXACTLY     = 1 << MODE_SHIFT;
19221
19222        /**
19223         * Measure specification mode: The child can be as large as it wants up
19224         * to the specified size.
19225         */
19226        public static final int AT_MOST     = 2 << MODE_SHIFT;
19227
19228        /**
19229         * Creates a measure specification based on the supplied size and mode.
19230         *
19231         * The mode must always be one of the following:
19232         * <ul>
19233         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19234         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19235         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19236         * </ul>
19237         *
19238         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19239         * implementation was such that the order of arguments did not matter
19240         * and overflow in either value could impact the resulting MeasureSpec.
19241         * {@link android.widget.RelativeLayout} was affected by this bug.
19242         * Apps targeting API levels greater than 17 will get the fixed, more strict
19243         * behavior.</p>
19244         *
19245         * @param size the size of the measure specification
19246         * @param mode the mode of the measure specification
19247         * @return the measure specification based on size and mode
19248         */
19249        public static int makeMeasureSpec(int size, int mode) {
19250            if (sUseBrokenMakeMeasureSpec) {
19251                return size + mode;
19252            } else {
19253                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19254            }
19255        }
19256
19257        /**
19258         * Extracts the mode from the supplied measure specification.
19259         *
19260         * @param measureSpec the measure specification to extract the mode from
19261         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19262         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19263         *         {@link android.view.View.MeasureSpec#EXACTLY}
19264         */
19265        public static int getMode(int measureSpec) {
19266            return (measureSpec & MODE_MASK);
19267        }
19268
19269        /**
19270         * Extracts the size from the supplied measure specification.
19271         *
19272         * @param measureSpec the measure specification to extract the size from
19273         * @return the size in pixels defined in the supplied measure specification
19274         */
19275        public static int getSize(int measureSpec) {
19276            return (measureSpec & ~MODE_MASK);
19277        }
19278
19279        static int adjust(int measureSpec, int delta) {
19280            final int mode = getMode(measureSpec);
19281            if (mode == UNSPECIFIED) {
19282                // No need to adjust size for UNSPECIFIED mode.
19283                return makeMeasureSpec(0, UNSPECIFIED);
19284            }
19285            int size = getSize(measureSpec) + delta;
19286            if (size < 0) {
19287                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19288                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19289                size = 0;
19290            }
19291            return makeMeasureSpec(size, mode);
19292        }
19293
19294        /**
19295         * Returns a String representation of the specified measure
19296         * specification.
19297         *
19298         * @param measureSpec the measure specification to convert to a String
19299         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19300         */
19301        public static String toString(int measureSpec) {
19302            int mode = getMode(measureSpec);
19303            int size = getSize(measureSpec);
19304
19305            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19306
19307            if (mode == UNSPECIFIED)
19308                sb.append("UNSPECIFIED ");
19309            else if (mode == EXACTLY)
19310                sb.append("EXACTLY ");
19311            else if (mode == AT_MOST)
19312                sb.append("AT_MOST ");
19313            else
19314                sb.append(mode).append(" ");
19315
19316            sb.append(size);
19317            return sb.toString();
19318        }
19319    }
19320
19321    private final class CheckForLongPress implements Runnable {
19322        private int mOriginalWindowAttachCount;
19323
19324        @Override
19325        public void run() {
19326            if (isPressed() && (mParent != null)
19327                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19328                if (performLongClick()) {
19329                    mHasPerformedLongPress = true;
19330                }
19331            }
19332        }
19333
19334        public void rememberWindowAttachCount() {
19335            mOriginalWindowAttachCount = mWindowAttachCount;
19336        }
19337    }
19338
19339    private final class CheckForTap implements Runnable {
19340        public float x;
19341        public float y;
19342
19343        @Override
19344        public void run() {
19345            mPrivateFlags &= ~PFLAG_PREPRESSED;
19346            setPressed(true, x, y);
19347            checkForLongClick(ViewConfiguration.getTapTimeout());
19348        }
19349    }
19350
19351    private final class PerformClick implements Runnable {
19352        @Override
19353        public void run() {
19354            performClick();
19355        }
19356    }
19357
19358    /** @hide */
19359    public void hackTurnOffWindowResizeAnim(boolean off) {
19360        mAttachInfo.mTurnOffWindowResizeAnim = off;
19361    }
19362
19363    /**
19364     * This method returns a ViewPropertyAnimator object, which can be used to animate
19365     * specific properties on this View.
19366     *
19367     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19368     */
19369    public ViewPropertyAnimator animate() {
19370        if (mAnimator == null) {
19371            mAnimator = new ViewPropertyAnimator(this);
19372        }
19373        return mAnimator;
19374    }
19375
19376    /**
19377     * Sets the name of the View to be used to identify Views in Transitions.
19378     * Names should be unique in the View hierarchy.
19379     *
19380     * @param transitionName The name of the View to uniquely identify it for Transitions.
19381     */
19382    public final void setTransitionName(String transitionName) {
19383        mTransitionName = transitionName;
19384    }
19385
19386    /**
19387     * To be removed before L release.
19388     * @hide
19389     */
19390    public final void setViewName(String transitionName) {
19391        setTransitionName(transitionName);
19392    }
19393
19394    /**
19395     * Returns the name of the View to be used to identify Views in Transitions.
19396     * Names should be unique in the View hierarchy.
19397     *
19398     * <p>This returns null if the View has not been given a name.</p>
19399     *
19400     * @return The name used of the View to be used to identify Views in Transitions or null
19401     * if no name has been given.
19402     */
19403    public String getTransitionName() {
19404        return mTransitionName;
19405    }
19406
19407    /**
19408     * To be removed before L release.
19409     * @hide
19410     */
19411    public String getViewName() { return getTransitionName(); }
19412
19413    /**
19414     * Interface definition for a callback to be invoked when a hardware key event is
19415     * dispatched to this view. The callback will be invoked before the key event is
19416     * given to the view. This is only useful for hardware keyboards; a software input
19417     * method has no obligation to trigger this listener.
19418     */
19419    public interface OnKeyListener {
19420        /**
19421         * Called when a hardware key is dispatched to a view. This allows listeners to
19422         * get a chance to respond before the target view.
19423         * <p>Key presses in software keyboards will generally NOT trigger this method,
19424         * although some may elect to do so in some situations. Do not assume a
19425         * software input method has to be key-based; even if it is, it may use key presses
19426         * in a different way than you expect, so there is no way to reliably catch soft
19427         * input key presses.
19428         *
19429         * @param v The view the key has been dispatched to.
19430         * @param keyCode The code for the physical key that was pressed
19431         * @param event The KeyEvent object containing full information about
19432         *        the event.
19433         * @return True if the listener has consumed the event, false otherwise.
19434         */
19435        boolean onKey(View v, int keyCode, KeyEvent event);
19436    }
19437
19438    /**
19439     * Interface definition for a callback to be invoked when a touch event is
19440     * dispatched to this view. The callback will be invoked before the touch
19441     * event is given to the view.
19442     */
19443    public interface OnTouchListener {
19444        /**
19445         * Called when a touch event is dispatched to a view. This allows listeners to
19446         * get a chance to respond before the target view.
19447         *
19448         * @param v The view the touch event has been dispatched to.
19449         * @param event The MotionEvent object containing full information about
19450         *        the event.
19451         * @return True if the listener has consumed the event, false otherwise.
19452         */
19453        boolean onTouch(View v, MotionEvent event);
19454    }
19455
19456    /**
19457     * Interface definition for a callback to be invoked when a hover event is
19458     * dispatched to this view. The callback will be invoked before the hover
19459     * event is given to the view.
19460     */
19461    public interface OnHoverListener {
19462        /**
19463         * Called when a hover event is dispatched to a view. This allows listeners to
19464         * get a chance to respond before the target view.
19465         *
19466         * @param v The view the hover event has been dispatched to.
19467         * @param event The MotionEvent object containing full information about
19468         *        the event.
19469         * @return True if the listener has consumed the event, false otherwise.
19470         */
19471        boolean onHover(View v, MotionEvent event);
19472    }
19473
19474    /**
19475     * Interface definition for a callback to be invoked when a generic motion event is
19476     * dispatched to this view. The callback will be invoked before the generic motion
19477     * event is given to the view.
19478     */
19479    public interface OnGenericMotionListener {
19480        /**
19481         * Called when a generic motion event is dispatched to a view. This allows listeners to
19482         * get a chance to respond before the target view.
19483         *
19484         * @param v The view the generic motion event has been dispatched to.
19485         * @param event The MotionEvent object containing full information about
19486         *        the event.
19487         * @return True if the listener has consumed the event, false otherwise.
19488         */
19489        boolean onGenericMotion(View v, MotionEvent event);
19490    }
19491
19492    /**
19493     * Interface definition for a callback to be invoked when a view has been clicked and held.
19494     */
19495    public interface OnLongClickListener {
19496        /**
19497         * Called when a view has been clicked and held.
19498         *
19499         * @param v The view that was clicked and held.
19500         *
19501         * @return true if the callback consumed the long click, false otherwise.
19502         */
19503        boolean onLongClick(View v);
19504    }
19505
19506    /**
19507     * Interface definition for a callback to be invoked when a drag is being dispatched
19508     * to this view.  The callback will be invoked before the hosting view's own
19509     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19510     * onDrag(event) behavior, it should return 'false' from this callback.
19511     *
19512     * <div class="special reference">
19513     * <h3>Developer Guides</h3>
19514     * <p>For a guide to implementing drag and drop features, read the
19515     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19516     * </div>
19517     */
19518    public interface OnDragListener {
19519        /**
19520         * Called when a drag event is dispatched to a view. This allows listeners
19521         * to get a chance to override base View behavior.
19522         *
19523         * @param v The View that received the drag event.
19524         * @param event The {@link android.view.DragEvent} object for the drag event.
19525         * @return {@code true} if the drag event was handled successfully, or {@code false}
19526         * if the drag event was not handled. Note that {@code false} will trigger the View
19527         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19528         */
19529        boolean onDrag(View v, DragEvent event);
19530    }
19531
19532    /**
19533     * Interface definition for a callback to be invoked when the focus state of
19534     * a view changed.
19535     */
19536    public interface OnFocusChangeListener {
19537        /**
19538         * Called when the focus state of a view has changed.
19539         *
19540         * @param v The view whose state has changed.
19541         * @param hasFocus The new focus state of v.
19542         */
19543        void onFocusChange(View v, boolean hasFocus);
19544    }
19545
19546    /**
19547     * Interface definition for a callback to be invoked when a view is clicked.
19548     */
19549    public interface OnClickListener {
19550        /**
19551         * Called when a view has been clicked.
19552         *
19553         * @param v The view that was clicked.
19554         */
19555        void onClick(View v);
19556    }
19557
19558    /**
19559     * Interface definition for a callback to be invoked when the context menu
19560     * for this view is being built.
19561     */
19562    public interface OnCreateContextMenuListener {
19563        /**
19564         * Called when the context menu for this view is being built. It is not
19565         * safe to hold onto the menu after this method returns.
19566         *
19567         * @param menu The context menu that is being built
19568         * @param v The view for which the context menu is being built
19569         * @param menuInfo Extra information about the item for which the
19570         *            context menu should be shown. This information will vary
19571         *            depending on the class of v.
19572         */
19573        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19574    }
19575
19576    /**
19577     * Interface definition for a callback to be invoked when the status bar changes
19578     * visibility.  This reports <strong>global</strong> changes to the system UI
19579     * state, not what the application is requesting.
19580     *
19581     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19582     */
19583    public interface OnSystemUiVisibilityChangeListener {
19584        /**
19585         * Called when the status bar changes visibility because of a call to
19586         * {@link View#setSystemUiVisibility(int)}.
19587         *
19588         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19589         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19590         * This tells you the <strong>global</strong> state of these UI visibility
19591         * flags, not what your app is currently applying.
19592         */
19593        public void onSystemUiVisibilityChange(int visibility);
19594    }
19595
19596    /**
19597     * Interface definition for a callback to be invoked when this view is attached
19598     * or detached from its window.
19599     */
19600    public interface OnAttachStateChangeListener {
19601        /**
19602         * Called when the view is attached to a window.
19603         * @param v The view that was attached
19604         */
19605        public void onViewAttachedToWindow(View v);
19606        /**
19607         * Called when the view is detached from a window.
19608         * @param v The view that was detached
19609         */
19610        public void onViewDetachedFromWindow(View v);
19611    }
19612
19613    /**
19614     * Listener for applying window insets on a view in a custom way.
19615     *
19616     * <p>Apps may choose to implement this interface if they want to apply custom policy
19617     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19618     * is set, its
19619     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19620     * method will be called instead of the View's own
19621     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19622     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19623     * the View's normal behavior as part of its own.</p>
19624     */
19625    public interface OnApplyWindowInsetsListener {
19626        /**
19627         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19628         * on a View, this listener method will be called instead of the view's own
19629         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19630         *
19631         * @param v The view applying window insets
19632         * @param insets The insets to apply
19633         * @return The insets supplied, minus any insets that were consumed
19634         */
19635        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19636    }
19637
19638    private final class UnsetPressedState implements Runnable {
19639        @Override
19640        public void run() {
19641            setPressed(false);
19642        }
19643    }
19644
19645    /**
19646     * Base class for derived classes that want to save and restore their own
19647     * state in {@link android.view.View#onSaveInstanceState()}.
19648     */
19649    public static class BaseSavedState extends AbsSavedState {
19650        /**
19651         * Constructor used when reading from a parcel. Reads the state of the superclass.
19652         *
19653         * @param source
19654         */
19655        public BaseSavedState(Parcel source) {
19656            super(source);
19657        }
19658
19659        /**
19660         * Constructor called by derived classes when creating their SavedState objects
19661         *
19662         * @param superState The state of the superclass of this view
19663         */
19664        public BaseSavedState(Parcelable superState) {
19665            super(superState);
19666        }
19667
19668        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19669                new Parcelable.Creator<BaseSavedState>() {
19670            public BaseSavedState createFromParcel(Parcel in) {
19671                return new BaseSavedState(in);
19672            }
19673
19674            public BaseSavedState[] newArray(int size) {
19675                return new BaseSavedState[size];
19676            }
19677        };
19678    }
19679
19680    /**
19681     * A set of information given to a view when it is attached to its parent
19682     * window.
19683     */
19684    final static class AttachInfo {
19685        interface Callbacks {
19686            void playSoundEffect(int effectId);
19687            boolean performHapticFeedback(int effectId, boolean always);
19688        }
19689
19690        /**
19691         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19692         * to a Handler. This class contains the target (View) to invalidate and
19693         * the coordinates of the dirty rectangle.
19694         *
19695         * For performance purposes, this class also implements a pool of up to
19696         * POOL_LIMIT objects that get reused. This reduces memory allocations
19697         * whenever possible.
19698         */
19699        static class InvalidateInfo {
19700            private static final int POOL_LIMIT = 10;
19701
19702            private static final SynchronizedPool<InvalidateInfo> sPool =
19703                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19704
19705            View target;
19706
19707            int left;
19708            int top;
19709            int right;
19710            int bottom;
19711
19712            public static InvalidateInfo obtain() {
19713                InvalidateInfo instance = sPool.acquire();
19714                return (instance != null) ? instance : new InvalidateInfo();
19715            }
19716
19717            public void recycle() {
19718                target = null;
19719                sPool.release(this);
19720            }
19721        }
19722
19723        final IWindowSession mSession;
19724
19725        final IWindow mWindow;
19726
19727        final IBinder mWindowToken;
19728
19729        final Display mDisplay;
19730
19731        final Callbacks mRootCallbacks;
19732
19733        IWindowId mIWindowId;
19734        WindowId mWindowId;
19735
19736        /**
19737         * The top view of the hierarchy.
19738         */
19739        View mRootView;
19740
19741        IBinder mPanelParentWindowToken;
19742
19743        boolean mHardwareAccelerated;
19744        boolean mHardwareAccelerationRequested;
19745        HardwareRenderer mHardwareRenderer;
19746
19747        /**
19748         * The state of the display to which the window is attached, as reported
19749         * by {@link Display#getState()}.  Note that the display state constants
19750         * declared by {@link Display} do not exactly line up with the screen state
19751         * constants declared by {@link View} (there are more display states than
19752         * screen states).
19753         */
19754        int mDisplayState = Display.STATE_UNKNOWN;
19755
19756        /**
19757         * Scale factor used by the compatibility mode
19758         */
19759        float mApplicationScale;
19760
19761        /**
19762         * Indicates whether the application is in compatibility mode
19763         */
19764        boolean mScalingRequired;
19765
19766        /**
19767         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19768         */
19769        boolean mTurnOffWindowResizeAnim;
19770
19771        /**
19772         * Left position of this view's window
19773         */
19774        int mWindowLeft;
19775
19776        /**
19777         * Top position of this view's window
19778         */
19779        int mWindowTop;
19780
19781        /**
19782         * Indicates whether views need to use 32-bit drawing caches
19783         */
19784        boolean mUse32BitDrawingCache;
19785
19786        /**
19787         * For windows that are full-screen but using insets to layout inside
19788         * of the screen areas, these are the current insets to appear inside
19789         * the overscan area of the display.
19790         */
19791        final Rect mOverscanInsets = new Rect();
19792
19793        /**
19794         * For windows that are full-screen but using insets to layout inside
19795         * of the screen decorations, these are the current insets for the
19796         * content of the window.
19797         */
19798        final Rect mContentInsets = new Rect();
19799
19800        /**
19801         * For windows that are full-screen but using insets to layout inside
19802         * of the screen decorations, these are the current insets for the
19803         * actual visible parts of the window.
19804         */
19805        final Rect mVisibleInsets = new Rect();
19806
19807        /**
19808         * The internal insets given by this window.  This value is
19809         * supplied by the client (through
19810         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19811         * be given to the window manager when changed to be used in laying
19812         * out windows behind it.
19813         */
19814        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19815                = new ViewTreeObserver.InternalInsetsInfo();
19816
19817        /**
19818         * Set to true when mGivenInternalInsets is non-empty.
19819         */
19820        boolean mHasNonEmptyGivenInternalInsets;
19821
19822        /**
19823         * All views in the window's hierarchy that serve as scroll containers,
19824         * used to determine if the window can be resized or must be panned
19825         * to adjust for a soft input area.
19826         */
19827        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19828
19829        final KeyEvent.DispatcherState mKeyDispatchState
19830                = new KeyEvent.DispatcherState();
19831
19832        /**
19833         * Indicates whether the view's window currently has the focus.
19834         */
19835        boolean mHasWindowFocus;
19836
19837        /**
19838         * The current visibility of the window.
19839         */
19840        int mWindowVisibility;
19841
19842        /**
19843         * Indicates the time at which drawing started to occur.
19844         */
19845        long mDrawingTime;
19846
19847        /**
19848         * Indicates whether or not ignoring the DIRTY_MASK flags.
19849         */
19850        boolean mIgnoreDirtyState;
19851
19852        /**
19853         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19854         * to avoid clearing that flag prematurely.
19855         */
19856        boolean mSetIgnoreDirtyState = false;
19857
19858        /**
19859         * Indicates whether the view's window is currently in touch mode.
19860         */
19861        boolean mInTouchMode;
19862
19863        /**
19864         * Indicates whether the view has requested unbuffered input dispatching for the current
19865         * event stream.
19866         */
19867        boolean mUnbufferedDispatchRequested;
19868
19869        /**
19870         * Indicates that ViewAncestor should trigger a global layout change
19871         * the next time it performs a traversal
19872         */
19873        boolean mRecomputeGlobalAttributes;
19874
19875        /**
19876         * Always report new attributes at next traversal.
19877         */
19878        boolean mForceReportNewAttributes;
19879
19880        /**
19881         * Set during a traveral if any views want to keep the screen on.
19882         */
19883        boolean mKeepScreenOn;
19884
19885        /**
19886         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19887         */
19888        int mSystemUiVisibility;
19889
19890        /**
19891         * Hack to force certain system UI visibility flags to be cleared.
19892         */
19893        int mDisabledSystemUiVisibility;
19894
19895        /**
19896         * Last global system UI visibility reported by the window manager.
19897         */
19898        int mGlobalSystemUiVisibility;
19899
19900        /**
19901         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19902         * attached.
19903         */
19904        boolean mHasSystemUiListeners;
19905
19906        /**
19907         * Set if the window has requested to extend into the overscan region
19908         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19909         */
19910        boolean mOverscanRequested;
19911
19912        /**
19913         * Set if the visibility of any views has changed.
19914         */
19915        boolean mViewVisibilityChanged;
19916
19917        /**
19918         * Set to true if a view has been scrolled.
19919         */
19920        boolean mViewScrollChanged;
19921
19922        /**
19923         * Global to the view hierarchy used as a temporary for dealing with
19924         * x/y points in the transparent region computations.
19925         */
19926        final int[] mTransparentLocation = new int[2];
19927
19928        /**
19929         * Global to the view hierarchy used as a temporary for dealing with
19930         * x/y points in the ViewGroup.invalidateChild implementation.
19931         */
19932        final int[] mInvalidateChildLocation = new int[2];
19933
19934        /**
19935         * Global to the view hierarchy used as a temporary for dealng with
19936         * computing absolute on-screen location.
19937         */
19938        final int[] mTmpLocation = new int[2];
19939
19940        /**
19941         * Global to the view hierarchy used as a temporary for dealing with
19942         * x/y location when view is transformed.
19943         */
19944        final float[] mTmpTransformLocation = new float[2];
19945
19946        /**
19947         * The view tree observer used to dispatch global events like
19948         * layout, pre-draw, touch mode change, etc.
19949         */
19950        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19951
19952        /**
19953         * A Canvas used by the view hierarchy to perform bitmap caching.
19954         */
19955        Canvas mCanvas;
19956
19957        /**
19958         * The view root impl.
19959         */
19960        final ViewRootImpl mViewRootImpl;
19961
19962        /**
19963         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19964         * handler can be used to pump events in the UI events queue.
19965         */
19966        final Handler mHandler;
19967
19968        /**
19969         * Temporary for use in computing invalidate rectangles while
19970         * calling up the hierarchy.
19971         */
19972        final Rect mTmpInvalRect = new Rect();
19973
19974        /**
19975         * Temporary for use in computing hit areas with transformed views
19976         */
19977        final RectF mTmpTransformRect = new RectF();
19978
19979        /**
19980         * Temporary for use in transforming invalidation rect
19981         */
19982        final Matrix mTmpMatrix = new Matrix();
19983
19984        /**
19985         * Temporary for use in transforming invalidation rect
19986         */
19987        final Transformation mTmpTransformation = new Transformation();
19988
19989        /**
19990         * Temporary list for use in collecting focusable descendents of a view.
19991         */
19992        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19993
19994        /**
19995         * The id of the window for accessibility purposes.
19996         */
19997        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19998
19999        /**
20000         * Flags related to accessibility processing.
20001         *
20002         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20003         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20004         */
20005        int mAccessibilityFetchFlags;
20006
20007        /**
20008         * The drawable for highlighting accessibility focus.
20009         */
20010        Drawable mAccessibilityFocusDrawable;
20011
20012        /**
20013         * Show where the margins, bounds and layout bounds are for each view.
20014         */
20015        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20016
20017        /**
20018         * Point used to compute visible regions.
20019         */
20020        final Point mPoint = new Point();
20021
20022        /**
20023         * Used to track which View originated a requestLayout() call, used when
20024         * requestLayout() is called during layout.
20025         */
20026        View mViewRequestingLayout;
20027
20028        /**
20029         * Creates a new set of attachment information with the specified
20030         * events handler and thread.
20031         *
20032         * @param handler the events handler the view must use
20033         */
20034        AttachInfo(IWindowSession session, IWindow window, Display display,
20035                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20036            mSession = session;
20037            mWindow = window;
20038            mWindowToken = window.asBinder();
20039            mDisplay = display;
20040            mViewRootImpl = viewRootImpl;
20041            mHandler = handler;
20042            mRootCallbacks = effectPlayer;
20043        }
20044    }
20045
20046    /**
20047     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20048     * is supported. This avoids keeping too many unused fields in most
20049     * instances of View.</p>
20050     */
20051    private static class ScrollabilityCache implements Runnable {
20052
20053        /**
20054         * Scrollbars are not visible
20055         */
20056        public static final int OFF = 0;
20057
20058        /**
20059         * Scrollbars are visible
20060         */
20061        public static final int ON = 1;
20062
20063        /**
20064         * Scrollbars are fading away
20065         */
20066        public static final int FADING = 2;
20067
20068        public boolean fadeScrollBars;
20069
20070        public int fadingEdgeLength;
20071        public int scrollBarDefaultDelayBeforeFade;
20072        public int scrollBarFadeDuration;
20073
20074        public int scrollBarSize;
20075        public ScrollBarDrawable scrollBar;
20076        public float[] interpolatorValues;
20077        public View host;
20078
20079        public final Paint paint;
20080        public final Matrix matrix;
20081        public Shader shader;
20082
20083        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20084
20085        private static final float[] OPAQUE = { 255 };
20086        private static final float[] TRANSPARENT = { 0.0f };
20087
20088        /**
20089         * When fading should start. This time moves into the future every time
20090         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20091         */
20092        public long fadeStartTime;
20093
20094
20095        /**
20096         * The current state of the scrollbars: ON, OFF, or FADING
20097         */
20098        public int state = OFF;
20099
20100        private int mLastColor;
20101
20102        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20103            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20104            scrollBarSize = configuration.getScaledScrollBarSize();
20105            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20106            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20107
20108            paint = new Paint();
20109            matrix = new Matrix();
20110            // use use a height of 1, and then wack the matrix each time we
20111            // actually use it.
20112            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20113            paint.setShader(shader);
20114            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20115
20116            this.host = host;
20117        }
20118
20119        public void setFadeColor(int color) {
20120            if (color != mLastColor) {
20121                mLastColor = color;
20122
20123                if (color != 0) {
20124                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20125                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20126                    paint.setShader(shader);
20127                    // Restore the default transfer mode (src_over)
20128                    paint.setXfermode(null);
20129                } else {
20130                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20131                    paint.setShader(shader);
20132                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20133                }
20134            }
20135        }
20136
20137        public void run() {
20138            long now = AnimationUtils.currentAnimationTimeMillis();
20139            if (now >= fadeStartTime) {
20140
20141                // the animation fades the scrollbars out by changing
20142                // the opacity (alpha) from fully opaque to fully
20143                // transparent
20144                int nextFrame = (int) now;
20145                int framesCount = 0;
20146
20147                Interpolator interpolator = scrollBarInterpolator;
20148
20149                // Start opaque
20150                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20151
20152                // End transparent
20153                nextFrame += scrollBarFadeDuration;
20154                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20155
20156                state = FADING;
20157
20158                // Kick off the fade animation
20159                host.invalidate(true);
20160            }
20161        }
20162    }
20163
20164    /**
20165     * Resuable callback for sending
20166     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20167     */
20168    private class SendViewScrolledAccessibilityEvent implements Runnable {
20169        public volatile boolean mIsPending;
20170
20171        public void run() {
20172            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20173            mIsPending = false;
20174        }
20175    }
20176
20177    /**
20178     * <p>
20179     * This class represents a delegate that can be registered in a {@link View}
20180     * to enhance accessibility support via composition rather via inheritance.
20181     * It is specifically targeted to widget developers that extend basic View
20182     * classes i.e. classes in package android.view, that would like their
20183     * applications to be backwards compatible.
20184     * </p>
20185     * <div class="special reference">
20186     * <h3>Developer Guides</h3>
20187     * <p>For more information about making applications accessible, read the
20188     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20189     * developer guide.</p>
20190     * </div>
20191     * <p>
20192     * A scenario in which a developer would like to use an accessibility delegate
20193     * is overriding a method introduced in a later API version then the minimal API
20194     * version supported by the application. For example, the method
20195     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20196     * in API version 4 when the accessibility APIs were first introduced. If a
20197     * developer would like his application to run on API version 4 devices (assuming
20198     * all other APIs used by the application are version 4 or lower) and take advantage
20199     * of this method, instead of overriding the method which would break the application's
20200     * backwards compatibility, he can override the corresponding method in this
20201     * delegate and register the delegate in the target View if the API version of
20202     * the system is high enough i.e. the API version is same or higher to the API
20203     * version that introduced
20204     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20205     * </p>
20206     * <p>
20207     * Here is an example implementation:
20208     * </p>
20209     * <code><pre><p>
20210     * if (Build.VERSION.SDK_INT >= 14) {
20211     *     // If the API version is equal of higher than the version in
20212     *     // which onInitializeAccessibilityNodeInfo was introduced we
20213     *     // register a delegate with a customized implementation.
20214     *     View view = findViewById(R.id.view_id);
20215     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20216     *         public void onInitializeAccessibilityNodeInfo(View host,
20217     *                 AccessibilityNodeInfo info) {
20218     *             // Let the default implementation populate the info.
20219     *             super.onInitializeAccessibilityNodeInfo(host, info);
20220     *             // Set some other information.
20221     *             info.setEnabled(host.isEnabled());
20222     *         }
20223     *     });
20224     * }
20225     * </code></pre></p>
20226     * <p>
20227     * This delegate contains methods that correspond to the accessibility methods
20228     * in View. If a delegate has been specified the implementation in View hands
20229     * off handling to the corresponding method in this delegate. The default
20230     * implementation the delegate methods behaves exactly as the corresponding
20231     * method in View for the case of no accessibility delegate been set. Hence,
20232     * to customize the behavior of a View method, clients can override only the
20233     * corresponding delegate method without altering the behavior of the rest
20234     * accessibility related methods of the host view.
20235     * </p>
20236     */
20237    public static class AccessibilityDelegate {
20238
20239        /**
20240         * Sends an accessibility event of the given type. If accessibility is not
20241         * enabled this method has no effect.
20242         * <p>
20243         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20244         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20245         * been set.
20246         * </p>
20247         *
20248         * @param host The View hosting the delegate.
20249         * @param eventType The type of the event to send.
20250         *
20251         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20252         */
20253        public void sendAccessibilityEvent(View host, int eventType) {
20254            host.sendAccessibilityEventInternal(eventType);
20255        }
20256
20257        /**
20258         * Performs the specified accessibility action on the view. For
20259         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20260         * <p>
20261         * The default implementation behaves as
20262         * {@link View#performAccessibilityAction(int, Bundle)
20263         *  View#performAccessibilityAction(int, Bundle)} for the case of
20264         *  no accessibility delegate been set.
20265         * </p>
20266         *
20267         * @param action The action to perform.
20268         * @return Whether the action was performed.
20269         *
20270         * @see View#performAccessibilityAction(int, Bundle)
20271         *      View#performAccessibilityAction(int, Bundle)
20272         */
20273        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20274            return host.performAccessibilityActionInternal(action, args);
20275        }
20276
20277        /**
20278         * Sends an accessibility event. This method behaves exactly as
20279         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20280         * empty {@link AccessibilityEvent} and does not perform a check whether
20281         * accessibility is enabled.
20282         * <p>
20283         * The default implementation behaves as
20284         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20285         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20286         * the case of no accessibility delegate been set.
20287         * </p>
20288         *
20289         * @param host The View hosting the delegate.
20290         * @param event The event to send.
20291         *
20292         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20293         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20294         */
20295        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20296            host.sendAccessibilityEventUncheckedInternal(event);
20297        }
20298
20299        /**
20300         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20301         * to its children for adding their text content to the event.
20302         * <p>
20303         * The default implementation behaves as
20304         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20305         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20306         * the case of no accessibility delegate been set.
20307         * </p>
20308         *
20309         * @param host The View hosting the delegate.
20310         * @param event The event.
20311         * @return True if the event population was completed.
20312         *
20313         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20314         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20315         */
20316        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20317            return host.dispatchPopulateAccessibilityEventInternal(event);
20318        }
20319
20320        /**
20321         * Gives a chance to the host View to populate the accessibility event with its
20322         * text content.
20323         * <p>
20324         * The default implementation behaves as
20325         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20326         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20327         * the case of no accessibility delegate been set.
20328         * </p>
20329         *
20330         * @param host The View hosting the delegate.
20331         * @param event The accessibility event which to populate.
20332         *
20333         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20334         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20335         */
20336        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20337            host.onPopulateAccessibilityEventInternal(event);
20338        }
20339
20340        /**
20341         * Initializes an {@link AccessibilityEvent} with information about the
20342         * the host View which is the event source.
20343         * <p>
20344         * The default implementation behaves as
20345         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20346         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20347         * the case of no accessibility delegate been set.
20348         * </p>
20349         *
20350         * @param host The View hosting the delegate.
20351         * @param event The event to initialize.
20352         *
20353         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20354         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20355         */
20356        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20357            host.onInitializeAccessibilityEventInternal(event);
20358        }
20359
20360        /**
20361         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20362         * <p>
20363         * The default implementation behaves as
20364         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20365         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20366         * the case of no accessibility delegate been set.
20367         * </p>
20368         *
20369         * @param host The View hosting the delegate.
20370         * @param info The instance to initialize.
20371         *
20372         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20373         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20374         */
20375        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20376            host.onInitializeAccessibilityNodeInfoInternal(info);
20377        }
20378
20379        /**
20380         * Called when a child of the host View has requested sending an
20381         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20382         * to augment the event.
20383         * <p>
20384         * The default implementation behaves as
20385         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20386         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20387         * the case of no accessibility delegate been set.
20388         * </p>
20389         *
20390         * @param host The View hosting the delegate.
20391         * @param child The child which requests sending the event.
20392         * @param event The event to be sent.
20393         * @return True if the event should be sent
20394         *
20395         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20396         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20397         */
20398        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20399                AccessibilityEvent event) {
20400            return host.onRequestSendAccessibilityEventInternal(child, event);
20401        }
20402
20403        /**
20404         * Gets the provider for managing a virtual view hierarchy rooted at this View
20405         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20406         * that explore the window content.
20407         * <p>
20408         * The default implementation behaves as
20409         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20410         * the case of no accessibility delegate been set.
20411         * </p>
20412         *
20413         * @return The provider.
20414         *
20415         * @see AccessibilityNodeProvider
20416         */
20417        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20418            return null;
20419        }
20420
20421        /**
20422         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20423         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20424         * This method is responsible for obtaining an accessibility node info from a
20425         * pool of reusable instances and calling
20426         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20427         * view to initialize the former.
20428         * <p>
20429         * <strong>Note:</strong> The client is responsible for recycling the obtained
20430         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20431         * creation.
20432         * </p>
20433         * <p>
20434         * The default implementation behaves as
20435         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20436         * the case of no accessibility delegate been set.
20437         * </p>
20438         * @return A populated {@link AccessibilityNodeInfo}.
20439         *
20440         * @see AccessibilityNodeInfo
20441         *
20442         * @hide
20443         */
20444        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20445            return host.createAccessibilityNodeInfoInternal();
20446        }
20447    }
20448
20449    private class MatchIdPredicate implements Predicate<View> {
20450        public int mId;
20451
20452        @Override
20453        public boolean apply(View view) {
20454            return (view.mID == mId);
20455        }
20456    }
20457
20458    private class MatchLabelForPredicate implements Predicate<View> {
20459        private int mLabeledId;
20460
20461        @Override
20462        public boolean apply(View view) {
20463            return (view.mLabelForId == mLabeledId);
20464        }
20465    }
20466
20467    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20468        private int mChangeTypes = 0;
20469        private boolean mPosted;
20470        private boolean mPostedWithDelay;
20471        private long mLastEventTimeMillis;
20472
20473        @Override
20474        public void run() {
20475            mPosted = false;
20476            mPostedWithDelay = false;
20477            mLastEventTimeMillis = SystemClock.uptimeMillis();
20478            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20479                final AccessibilityEvent event = AccessibilityEvent.obtain();
20480                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20481                event.setContentChangeTypes(mChangeTypes);
20482                sendAccessibilityEventUnchecked(event);
20483            }
20484            mChangeTypes = 0;
20485        }
20486
20487        public void runOrPost(int changeType) {
20488            mChangeTypes |= changeType;
20489
20490            // If this is a live region or the child of a live region, collect
20491            // all events from this frame and send them on the next frame.
20492            if (inLiveRegion()) {
20493                // If we're already posted with a delay, remove that.
20494                if (mPostedWithDelay) {
20495                    removeCallbacks(this);
20496                    mPostedWithDelay = false;
20497                }
20498                // Only post if we're not already posted.
20499                if (!mPosted) {
20500                    post(this);
20501                    mPosted = true;
20502                }
20503                return;
20504            }
20505
20506            if (mPosted) {
20507                return;
20508            }
20509            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20510            final long minEventIntevalMillis =
20511                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20512            if (timeSinceLastMillis >= minEventIntevalMillis) {
20513                removeCallbacks(this);
20514                run();
20515            } else {
20516                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20517                mPosted = true;
20518                mPostedWithDelay = true;
20519            }
20520        }
20521    }
20522
20523    private boolean inLiveRegion() {
20524        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20525            return true;
20526        }
20527
20528        ViewParent parent = getParent();
20529        while (parent instanceof View) {
20530            if (((View) parent).getAccessibilityLiveRegion()
20531                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20532                return true;
20533            }
20534            parent = parent.getParent();
20535        }
20536
20537        return false;
20538    }
20539
20540    /**
20541     * Dump all private flags in readable format, useful for documentation and
20542     * sanity checking.
20543     */
20544    private static void dumpFlags() {
20545        final HashMap<String, String> found = Maps.newHashMap();
20546        try {
20547            for (Field field : View.class.getDeclaredFields()) {
20548                final int modifiers = field.getModifiers();
20549                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20550                    if (field.getType().equals(int.class)) {
20551                        final int value = field.getInt(null);
20552                        dumpFlag(found, field.getName(), value);
20553                    } else if (field.getType().equals(int[].class)) {
20554                        final int[] values = (int[]) field.get(null);
20555                        for (int i = 0; i < values.length; i++) {
20556                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20557                        }
20558                    }
20559                }
20560            }
20561        } catch (IllegalAccessException e) {
20562            throw new RuntimeException(e);
20563        }
20564
20565        final ArrayList<String> keys = Lists.newArrayList();
20566        keys.addAll(found.keySet());
20567        Collections.sort(keys);
20568        for (String key : keys) {
20569            Log.d(VIEW_LOG_TAG, found.get(key));
20570        }
20571    }
20572
20573    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20574        // Sort flags by prefix, then by bits, always keeping unique keys
20575        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20576        final int prefix = name.indexOf('_');
20577        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20578        final String output = bits + " " + name;
20579        found.put(key, output);
20580    }
20581}
20582