View.java revision bbc9cd32d70343ff0144fe706b4090e776ec5a0c
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    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13013    }
13014
13015    /**
13016     * @return The number of times this view has been attached to a window
13017     */
13018    protected int getWindowAttachCount() {
13019        return mWindowAttachCount;
13020    }
13021
13022    /**
13023     * Retrieve a unique token identifying the window this view is attached to.
13024     * @return Return the window's token for use in
13025     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13026     */
13027    public IBinder getWindowToken() {
13028        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13029    }
13030
13031    /**
13032     * Retrieve the {@link WindowId} for the window this view is
13033     * currently attached to.
13034     */
13035    public WindowId getWindowId() {
13036        if (mAttachInfo == null) {
13037            return null;
13038        }
13039        if (mAttachInfo.mWindowId == null) {
13040            try {
13041                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13042                        mAttachInfo.mWindowToken);
13043                mAttachInfo.mWindowId = new WindowId(
13044                        mAttachInfo.mIWindowId);
13045            } catch (RemoteException e) {
13046            }
13047        }
13048        return mAttachInfo.mWindowId;
13049    }
13050
13051    /**
13052     * Retrieve a unique token identifying the top-level "real" window of
13053     * the window that this view is attached to.  That is, this is like
13054     * {@link #getWindowToken}, except if the window this view in is a panel
13055     * window (attached to another containing window), then the token of
13056     * the containing window is returned instead.
13057     *
13058     * @return Returns the associated window token, either
13059     * {@link #getWindowToken()} or the containing window's token.
13060     */
13061    public IBinder getApplicationWindowToken() {
13062        AttachInfo ai = mAttachInfo;
13063        if (ai != null) {
13064            IBinder appWindowToken = ai.mPanelParentWindowToken;
13065            if (appWindowToken == null) {
13066                appWindowToken = ai.mWindowToken;
13067            }
13068            return appWindowToken;
13069        }
13070        return null;
13071    }
13072
13073    /**
13074     * Gets the logical display to which the view's window has been attached.
13075     *
13076     * @return The logical display, or null if the view is not currently attached to a window.
13077     */
13078    public Display getDisplay() {
13079        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13080    }
13081
13082    /**
13083     * Retrieve private session object this view hierarchy is using to
13084     * communicate with the window manager.
13085     * @return the session object to communicate with the window manager
13086     */
13087    /*package*/ IWindowSession getWindowSession() {
13088        return mAttachInfo != null ? mAttachInfo.mSession : null;
13089    }
13090
13091    /**
13092     * @param info the {@link android.view.View.AttachInfo} to associated with
13093     *        this view
13094     */
13095    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13096        //System.out.println("Attached! " + this);
13097        mAttachInfo = info;
13098        if (mOverlay != null) {
13099            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13100        }
13101        mWindowAttachCount++;
13102        // We will need to evaluate the drawable state at least once.
13103        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13104        if (mFloatingTreeObserver != null) {
13105            info.mTreeObserver.merge(mFloatingTreeObserver);
13106            mFloatingTreeObserver = null;
13107        }
13108        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13109            mAttachInfo.mScrollContainers.add(this);
13110            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13111        }
13112        performCollectViewAttributes(mAttachInfo, visibility);
13113        onAttachedToWindow();
13114
13115        ListenerInfo li = mListenerInfo;
13116        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13117                li != null ? li.mOnAttachStateChangeListeners : null;
13118        if (listeners != null && listeners.size() > 0) {
13119            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13120            // perform the dispatching. The iterator is a safe guard against listeners that
13121            // could mutate the list by calling the various add/remove methods. This prevents
13122            // the array from being modified while we iterate it.
13123            for (OnAttachStateChangeListener listener : listeners) {
13124                listener.onViewAttachedToWindow(this);
13125            }
13126        }
13127
13128        int vis = info.mWindowVisibility;
13129        if (vis != GONE) {
13130            onWindowVisibilityChanged(vis);
13131        }
13132        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13133            // If nobody has evaluated the drawable state yet, then do it now.
13134            refreshDrawableState();
13135        }
13136        needGlobalAttributesUpdate(false);
13137    }
13138
13139    void dispatchDetachedFromWindow() {
13140        AttachInfo info = mAttachInfo;
13141        if (info != null) {
13142            int vis = info.mWindowVisibility;
13143            if (vis != GONE) {
13144                onWindowVisibilityChanged(GONE);
13145            }
13146        }
13147
13148        onDetachedFromWindow();
13149        onDetachedFromWindowInternal();
13150
13151        ListenerInfo li = mListenerInfo;
13152        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13153                li != null ? li.mOnAttachStateChangeListeners : null;
13154        if (listeners != null && listeners.size() > 0) {
13155            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13156            // perform the dispatching. The iterator is a safe guard against listeners that
13157            // could mutate the list by calling the various add/remove methods. This prevents
13158            // the array from being modified while we iterate it.
13159            for (OnAttachStateChangeListener listener : listeners) {
13160                listener.onViewDetachedFromWindow(this);
13161            }
13162        }
13163
13164        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13165            mAttachInfo.mScrollContainers.remove(this);
13166            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13167        }
13168
13169        mAttachInfo = null;
13170        if (mOverlay != null) {
13171            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13172        }
13173    }
13174
13175    /**
13176     * Cancel any deferred high-level input events that were previously posted to the event queue.
13177     *
13178     * <p>Many views post high-level events such as click handlers to the event queue
13179     * to run deferred in order to preserve a desired user experience - clearing visible
13180     * pressed states before executing, etc. This method will abort any events of this nature
13181     * that are currently in flight.</p>
13182     *
13183     * <p>Custom views that generate their own high-level deferred input events should override
13184     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13185     *
13186     * <p>This will also cancel pending input events for any child views.</p>
13187     *
13188     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13189     * This will not impact newer events posted after this call that may occur as a result of
13190     * lower-level input events still waiting in the queue. If you are trying to prevent
13191     * double-submitted  events for the duration of some sort of asynchronous transaction
13192     * you should also take other steps to protect against unexpected double inputs e.g. calling
13193     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13194     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13195     */
13196    public final void cancelPendingInputEvents() {
13197        dispatchCancelPendingInputEvents();
13198    }
13199
13200    /**
13201     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13202     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13203     */
13204    void dispatchCancelPendingInputEvents() {
13205        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13206        onCancelPendingInputEvents();
13207        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13208            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13209                    " did not call through to super.onCancelPendingInputEvents()");
13210        }
13211    }
13212
13213    /**
13214     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13215     * a parent view.
13216     *
13217     * <p>This method is responsible for removing any pending high-level input events that were
13218     * posted to the event queue to run later. Custom view classes that post their own deferred
13219     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13220     * {@link android.os.Handler} should override this method, call
13221     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13222     * </p>
13223     */
13224    public void onCancelPendingInputEvents() {
13225        removePerformClickCallback();
13226        cancelLongPress();
13227        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13228    }
13229
13230    /**
13231     * Store this view hierarchy's frozen state into the given container.
13232     *
13233     * @param container The SparseArray in which to save the view's state.
13234     *
13235     * @see #restoreHierarchyState(android.util.SparseArray)
13236     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13237     * @see #onSaveInstanceState()
13238     */
13239    public void saveHierarchyState(SparseArray<Parcelable> container) {
13240        dispatchSaveInstanceState(container);
13241    }
13242
13243    /**
13244     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13245     * this view and its children. May be overridden to modify how freezing happens to a
13246     * view's children; for example, some views may want to not store state for their children.
13247     *
13248     * @param container The SparseArray in which to save the view's state.
13249     *
13250     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13251     * @see #saveHierarchyState(android.util.SparseArray)
13252     * @see #onSaveInstanceState()
13253     */
13254    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13255        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13256            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13257            Parcelable state = onSaveInstanceState();
13258            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13259                throw new IllegalStateException(
13260                        "Derived class did not call super.onSaveInstanceState()");
13261            }
13262            if (state != null) {
13263                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13264                // + ": " + state);
13265                container.put(mID, state);
13266            }
13267        }
13268    }
13269
13270    /**
13271     * Hook allowing a view to generate a representation of its internal state
13272     * that can later be used to create a new instance with that same state.
13273     * This state should only contain information that is not persistent or can
13274     * not be reconstructed later. For example, you will never store your
13275     * current position on screen because that will be computed again when a
13276     * new instance of the view is placed in its view hierarchy.
13277     * <p>
13278     * Some examples of things you may store here: the current cursor position
13279     * in a text view (but usually not the text itself since that is stored in a
13280     * content provider or other persistent storage), the currently selected
13281     * item in a list view.
13282     *
13283     * @return Returns a Parcelable object containing the view's current dynamic
13284     *         state, or null if there is nothing interesting to save. The
13285     *         default implementation returns null.
13286     * @see #onRestoreInstanceState(android.os.Parcelable)
13287     * @see #saveHierarchyState(android.util.SparseArray)
13288     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13289     * @see #setSaveEnabled(boolean)
13290     */
13291    protected Parcelable onSaveInstanceState() {
13292        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13293        return BaseSavedState.EMPTY_STATE;
13294    }
13295
13296    /**
13297     * Restore this view hierarchy's frozen state from the given container.
13298     *
13299     * @param container The SparseArray which holds previously frozen states.
13300     *
13301     * @see #saveHierarchyState(android.util.SparseArray)
13302     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13303     * @see #onRestoreInstanceState(android.os.Parcelable)
13304     */
13305    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13306        dispatchRestoreInstanceState(container);
13307    }
13308
13309    /**
13310     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13311     * state for this view and its children. May be overridden to modify how restoring
13312     * happens to a view's children; for example, some views may want to not store state
13313     * for their children.
13314     *
13315     * @param container The SparseArray which holds previously saved state.
13316     *
13317     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13318     * @see #restoreHierarchyState(android.util.SparseArray)
13319     * @see #onRestoreInstanceState(android.os.Parcelable)
13320     */
13321    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13322        if (mID != NO_ID) {
13323            Parcelable state = container.get(mID);
13324            if (state != null) {
13325                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13326                // + ": " + state);
13327                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13328                onRestoreInstanceState(state);
13329                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13330                    throw new IllegalStateException(
13331                            "Derived class did not call super.onRestoreInstanceState()");
13332                }
13333            }
13334        }
13335    }
13336
13337    /**
13338     * Hook allowing a view to re-apply a representation of its internal state that had previously
13339     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13340     * null state.
13341     *
13342     * @param state The frozen state that had previously been returned by
13343     *        {@link #onSaveInstanceState}.
13344     *
13345     * @see #onSaveInstanceState()
13346     * @see #restoreHierarchyState(android.util.SparseArray)
13347     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13348     */
13349    protected void onRestoreInstanceState(Parcelable state) {
13350        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13351        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13352            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13353                    + "received " + state.getClass().toString() + " instead. This usually happens "
13354                    + "when two views of different type have the same id in the same hierarchy. "
13355                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13356                    + "other views do not use the same id.");
13357        }
13358    }
13359
13360    /**
13361     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13362     *
13363     * @return the drawing start time in milliseconds
13364     */
13365    public long getDrawingTime() {
13366        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13367    }
13368
13369    /**
13370     * <p>Enables or disables the duplication of the parent's state into this view. When
13371     * duplication is enabled, this view gets its drawable state from its parent rather
13372     * than from its own internal properties.</p>
13373     *
13374     * <p>Note: in the current implementation, setting this property to true after the
13375     * view was added to a ViewGroup might have no effect at all. This property should
13376     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13377     *
13378     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13379     * property is enabled, an exception will be thrown.</p>
13380     *
13381     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13382     * parent, these states should not be affected by this method.</p>
13383     *
13384     * @param enabled True to enable duplication of the parent's drawable state, false
13385     *                to disable it.
13386     *
13387     * @see #getDrawableState()
13388     * @see #isDuplicateParentStateEnabled()
13389     */
13390    public void setDuplicateParentStateEnabled(boolean enabled) {
13391        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13392    }
13393
13394    /**
13395     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13396     *
13397     * @return True if this view's drawable state is duplicated from the parent,
13398     *         false otherwise
13399     *
13400     * @see #getDrawableState()
13401     * @see #setDuplicateParentStateEnabled(boolean)
13402     */
13403    public boolean isDuplicateParentStateEnabled() {
13404        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13405    }
13406
13407    /**
13408     * <p>Specifies the type of layer backing this view. The layer can be
13409     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13410     * {@link #LAYER_TYPE_HARDWARE}.</p>
13411     *
13412     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13413     * instance that controls how the layer is composed on screen. The following
13414     * properties of the paint are taken into account when composing the layer:</p>
13415     * <ul>
13416     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13417     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13418     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13419     * </ul>
13420     *
13421     * <p>If this view has an alpha value set to < 1.0 by calling
13422     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13423     * by this view's alpha value.</p>
13424     *
13425     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13426     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13427     * for more information on when and how to use layers.</p>
13428     *
13429     * @param layerType The type of layer to use with this view, must be one of
13430     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13431     *        {@link #LAYER_TYPE_HARDWARE}
13432     * @param paint The paint used to compose the layer. This argument is optional
13433     *        and can be null. It is ignored when the layer type is
13434     *        {@link #LAYER_TYPE_NONE}
13435     *
13436     * @see #getLayerType()
13437     * @see #LAYER_TYPE_NONE
13438     * @see #LAYER_TYPE_SOFTWARE
13439     * @see #LAYER_TYPE_HARDWARE
13440     * @see #setAlpha(float)
13441     *
13442     * @attr ref android.R.styleable#View_layerType
13443     */
13444    public void setLayerType(int layerType, Paint paint) {
13445        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13446            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13447                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13448        }
13449
13450        boolean typeChanged = mRenderNode.setLayerType(layerType);
13451
13452        if (!typeChanged) {
13453            setLayerPaint(paint);
13454            return;
13455        }
13456
13457        // Destroy any previous software drawing cache if needed
13458        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13459            destroyDrawingCache();
13460        }
13461
13462        mLayerType = layerType;
13463        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13464        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13465        mRenderNode.setLayerPaint(mLayerPaint);
13466
13467        // draw() behaves differently if we are on a layer, so we need to
13468        // invalidate() here
13469        invalidateParentCaches();
13470        invalidate(true);
13471    }
13472
13473    /**
13474     * Updates the {@link Paint} object used with the current layer (used only if the current
13475     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13476     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13477     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13478     * ensure that the view gets redrawn immediately.
13479     *
13480     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13481     * instance that controls how the layer is composed on screen. The following
13482     * properties of the paint are taken into account when composing the layer:</p>
13483     * <ul>
13484     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13485     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13486     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13487     * </ul>
13488     *
13489     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13490     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13491     *
13492     * @param paint The paint used to compose the layer. This argument is optional
13493     *        and can be null. It is ignored when the layer type is
13494     *        {@link #LAYER_TYPE_NONE}
13495     *
13496     * @see #setLayerType(int, android.graphics.Paint)
13497     */
13498    public void setLayerPaint(Paint paint) {
13499        int layerType = getLayerType();
13500        if (layerType != LAYER_TYPE_NONE) {
13501            mLayerPaint = paint == null ? new Paint() : paint;
13502            if (layerType == LAYER_TYPE_HARDWARE) {
13503                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13504                    invalidateViewProperty(false, false);
13505                }
13506            } else {
13507                invalidate();
13508            }
13509        }
13510    }
13511
13512    /**
13513     * Indicates whether this view has a static layer. A view with layer type
13514     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13515     * dynamic.
13516     */
13517    boolean hasStaticLayer() {
13518        return true;
13519    }
13520
13521    /**
13522     * Indicates what type of layer is currently associated with this view. By default
13523     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13524     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13525     * for more information on the different types of layers.
13526     *
13527     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13528     *         {@link #LAYER_TYPE_HARDWARE}
13529     *
13530     * @see #setLayerType(int, android.graphics.Paint)
13531     * @see #buildLayer()
13532     * @see #LAYER_TYPE_NONE
13533     * @see #LAYER_TYPE_SOFTWARE
13534     * @see #LAYER_TYPE_HARDWARE
13535     */
13536    public int getLayerType() {
13537        return mLayerType;
13538    }
13539
13540    /**
13541     * Forces this view's layer to be created and this view to be rendered
13542     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13543     * invoking this method will have no effect.
13544     *
13545     * This method can for instance be used to render a view into its layer before
13546     * starting an animation. If this view is complex, rendering into the layer
13547     * before starting the animation will avoid skipping frames.
13548     *
13549     * @throws IllegalStateException If this view is not attached to a window
13550     *
13551     * @see #setLayerType(int, android.graphics.Paint)
13552     */
13553    public void buildLayer() {
13554        if (mLayerType == LAYER_TYPE_NONE) return;
13555
13556        final AttachInfo attachInfo = mAttachInfo;
13557        if (attachInfo == null) {
13558            throw new IllegalStateException("This view must be attached to a window first");
13559        }
13560
13561        if (getWidth() == 0 || getHeight() == 0) {
13562            return;
13563        }
13564
13565        switch (mLayerType) {
13566            case LAYER_TYPE_HARDWARE:
13567                // The only part of a hardware layer we can build in response to
13568                // this call is to ensure the display list is up to date.
13569                // The actual rendering of the display list into the layer must
13570                // be done at playback time
13571                updateDisplayListIfDirty();
13572                break;
13573            case LAYER_TYPE_SOFTWARE:
13574                buildDrawingCache(true);
13575                break;
13576        }
13577    }
13578
13579    /**
13580     * If this View draws with a HardwareLayer, returns it.
13581     * Otherwise returns null
13582     *
13583     * TODO: Only TextureView uses this, can we eliminate it?
13584     */
13585    HardwareLayer getHardwareLayer() {
13586        return null;
13587    }
13588
13589    /**
13590     * Destroys all hardware rendering resources. This method is invoked
13591     * when the system needs to reclaim resources. Upon execution of this
13592     * method, you should free any OpenGL resources created by the view.
13593     *
13594     * Note: you <strong>must</strong> call
13595     * <code>super.destroyHardwareResources()</code> when overriding
13596     * this method.
13597     *
13598     * @hide
13599     */
13600    protected void destroyHardwareResources() {
13601        resetDisplayList();
13602    }
13603
13604    /**
13605     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13606     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13607     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13608     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13609     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13610     * null.</p>
13611     *
13612     * <p>Enabling the drawing cache is similar to
13613     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13614     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13615     * drawing cache has no effect on rendering because the system uses a different mechanism
13616     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13617     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13618     * for information on how to enable software and hardware layers.</p>
13619     *
13620     * <p>This API can be used to manually generate
13621     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13622     * {@link #getDrawingCache()}.</p>
13623     *
13624     * @param enabled true to enable the drawing cache, false otherwise
13625     *
13626     * @see #isDrawingCacheEnabled()
13627     * @see #getDrawingCache()
13628     * @see #buildDrawingCache()
13629     * @see #setLayerType(int, android.graphics.Paint)
13630     */
13631    public void setDrawingCacheEnabled(boolean enabled) {
13632        mCachingFailed = false;
13633        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13634    }
13635
13636    /**
13637     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13638     *
13639     * @return true if the drawing cache is enabled
13640     *
13641     * @see #setDrawingCacheEnabled(boolean)
13642     * @see #getDrawingCache()
13643     */
13644    @ViewDebug.ExportedProperty(category = "drawing")
13645    public boolean isDrawingCacheEnabled() {
13646        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13647    }
13648
13649    /**
13650     * Debugging utility which recursively outputs the dirty state of a view and its
13651     * descendants.
13652     *
13653     * @hide
13654     */
13655    @SuppressWarnings({"UnusedDeclaration"})
13656    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13657        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13658                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13659                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13660                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13661        if (clear) {
13662            mPrivateFlags &= clearMask;
13663        }
13664        if (this instanceof ViewGroup) {
13665            ViewGroup parent = (ViewGroup) this;
13666            final int count = parent.getChildCount();
13667            for (int i = 0; i < count; i++) {
13668                final View child = parent.getChildAt(i);
13669                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13670            }
13671        }
13672    }
13673
13674    /**
13675     * This method is used by ViewGroup to cause its children to restore or recreate their
13676     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13677     * to recreate its own display list, which would happen if it went through the normal
13678     * draw/dispatchDraw mechanisms.
13679     *
13680     * @hide
13681     */
13682    protected void dispatchGetDisplayList() {}
13683
13684    /**
13685     * A view that is not attached or hardware accelerated cannot create a display list.
13686     * This method checks these conditions and returns the appropriate result.
13687     *
13688     * @return true if view has the ability to create a display list, false otherwise.
13689     *
13690     * @hide
13691     */
13692    public boolean canHaveDisplayList() {
13693        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13694    }
13695
13696    private void updateDisplayListIfDirty() {
13697        final RenderNode renderNode = mRenderNode;
13698        if (!canHaveDisplayList()) {
13699            // can't populate RenderNode, don't try
13700            return;
13701        }
13702
13703        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13704                || !renderNode.isValid()
13705                || (mRecreateDisplayList)) {
13706            // Don't need to recreate the display list, just need to tell our
13707            // children to restore/recreate theirs
13708            if (renderNode.isValid()
13709                    && !mRecreateDisplayList) {
13710                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13711                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13712                dispatchGetDisplayList();
13713
13714                return; // no work needed
13715            }
13716
13717            // If we got here, we're recreating it. Mark it as such to ensure that
13718            // we copy in child display lists into ours in drawChild()
13719            mRecreateDisplayList = true;
13720
13721            int width = mRight - mLeft;
13722            int height = mBottom - mTop;
13723            int layerType = getLayerType();
13724
13725            final HardwareCanvas canvas = renderNode.start(width, height);
13726
13727            try {
13728                final HardwareLayer layer = getHardwareLayer();
13729                if (layer != null && layer.isValid()) {
13730                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13731                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13732                    buildDrawingCache(true);
13733                    Bitmap cache = getDrawingCache(true);
13734                    if (cache != null) {
13735                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13736                    }
13737                } else {
13738                    computeScroll();
13739
13740                    canvas.translate(-mScrollX, -mScrollY);
13741                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13742                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13743
13744                    // Fast path for layouts with no backgrounds
13745                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13746                        dispatchDraw(canvas);
13747                        if (mOverlay != null && !mOverlay.isEmpty()) {
13748                            mOverlay.getOverlayView().draw(canvas);
13749                        }
13750                    } else {
13751                        draw(canvas);
13752                    }
13753                }
13754            } finally {
13755                renderNode.end(canvas);
13756                setDisplayListProperties(renderNode);
13757            }
13758        } else {
13759            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13760            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13761        }
13762    }
13763
13764    /**
13765     * Returns a RenderNode with View draw content recorded, which can be
13766     * used to draw this view again without executing its draw method.
13767     *
13768     * @return A RenderNode ready to replay, or null if caching is not enabled.
13769     *
13770     * @hide
13771     */
13772    public RenderNode getDisplayList() {
13773        updateDisplayListIfDirty();
13774        return mRenderNode;
13775    }
13776
13777    private void resetDisplayList() {
13778        if (mRenderNode.isValid()) {
13779            mRenderNode.destroyDisplayListData();
13780        }
13781
13782        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13783            mBackgroundRenderNode.destroyDisplayListData();
13784        }
13785    }
13786
13787    /**
13788     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13789     *
13790     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13791     *
13792     * @see #getDrawingCache(boolean)
13793     */
13794    public Bitmap getDrawingCache() {
13795        return getDrawingCache(false);
13796    }
13797
13798    /**
13799     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13800     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13801     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13802     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13803     * request the drawing cache by calling this method and draw it on screen if the
13804     * returned bitmap is not null.</p>
13805     *
13806     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13807     * this method will create a bitmap of the same size as this view. Because this bitmap
13808     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13809     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13810     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13811     * size than the view. This implies that your application must be able to handle this
13812     * size.</p>
13813     *
13814     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13815     *        the current density of the screen when the application is in compatibility
13816     *        mode.
13817     *
13818     * @return A bitmap representing this view or null if cache is disabled.
13819     *
13820     * @see #setDrawingCacheEnabled(boolean)
13821     * @see #isDrawingCacheEnabled()
13822     * @see #buildDrawingCache(boolean)
13823     * @see #destroyDrawingCache()
13824     */
13825    public Bitmap getDrawingCache(boolean autoScale) {
13826        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13827            return null;
13828        }
13829        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13830            buildDrawingCache(autoScale);
13831        }
13832        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13833    }
13834
13835    /**
13836     * <p>Frees the resources used by the drawing cache. If you call
13837     * {@link #buildDrawingCache()} manually without calling
13838     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13839     * should cleanup the cache with this method afterwards.</p>
13840     *
13841     * @see #setDrawingCacheEnabled(boolean)
13842     * @see #buildDrawingCache()
13843     * @see #getDrawingCache()
13844     */
13845    public void destroyDrawingCache() {
13846        if (mDrawingCache != null) {
13847            mDrawingCache.recycle();
13848            mDrawingCache = null;
13849        }
13850        if (mUnscaledDrawingCache != null) {
13851            mUnscaledDrawingCache.recycle();
13852            mUnscaledDrawingCache = null;
13853        }
13854    }
13855
13856    /**
13857     * Setting a solid background color for the drawing cache's bitmaps will improve
13858     * performance and memory usage. Note, though that this should only be used if this
13859     * view will always be drawn on top of a solid color.
13860     *
13861     * @param color The background color to use for the drawing cache's bitmap
13862     *
13863     * @see #setDrawingCacheEnabled(boolean)
13864     * @see #buildDrawingCache()
13865     * @see #getDrawingCache()
13866     */
13867    public void setDrawingCacheBackgroundColor(int color) {
13868        if (color != mDrawingCacheBackgroundColor) {
13869            mDrawingCacheBackgroundColor = color;
13870            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13871        }
13872    }
13873
13874    /**
13875     * @see #setDrawingCacheBackgroundColor(int)
13876     *
13877     * @return The background color to used for the drawing cache's bitmap
13878     */
13879    public int getDrawingCacheBackgroundColor() {
13880        return mDrawingCacheBackgroundColor;
13881    }
13882
13883    /**
13884     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13885     *
13886     * @see #buildDrawingCache(boolean)
13887     */
13888    public void buildDrawingCache() {
13889        buildDrawingCache(false);
13890    }
13891
13892    /**
13893     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13894     *
13895     * <p>If you call {@link #buildDrawingCache()} manually without calling
13896     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13897     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13898     *
13899     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13900     * this method will create a bitmap of the same size as this view. Because this bitmap
13901     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13902     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13903     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13904     * size than the view. This implies that your application must be able to handle this
13905     * size.</p>
13906     *
13907     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13908     * you do not need the drawing cache bitmap, calling this method will increase memory
13909     * usage and cause the view to be rendered in software once, thus negatively impacting
13910     * performance.</p>
13911     *
13912     * @see #getDrawingCache()
13913     * @see #destroyDrawingCache()
13914     */
13915    public void buildDrawingCache(boolean autoScale) {
13916        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13917                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13918            mCachingFailed = false;
13919
13920            int width = mRight - mLeft;
13921            int height = mBottom - mTop;
13922
13923            final AttachInfo attachInfo = mAttachInfo;
13924            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13925
13926            if (autoScale && scalingRequired) {
13927                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13928                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13929            }
13930
13931            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13932            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13933            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13934
13935            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13936            final long drawingCacheSize =
13937                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13938            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13939                if (width > 0 && height > 0) {
13940                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13941                            + projectedBitmapSize + " bytes, only "
13942                            + drawingCacheSize + " available");
13943                }
13944                destroyDrawingCache();
13945                mCachingFailed = true;
13946                return;
13947            }
13948
13949            boolean clear = true;
13950            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13951
13952            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13953                Bitmap.Config quality;
13954                if (!opaque) {
13955                    // Never pick ARGB_4444 because it looks awful
13956                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13957                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13958                        case DRAWING_CACHE_QUALITY_AUTO:
13959                        case DRAWING_CACHE_QUALITY_LOW:
13960                        case DRAWING_CACHE_QUALITY_HIGH:
13961                        default:
13962                            quality = Bitmap.Config.ARGB_8888;
13963                            break;
13964                    }
13965                } else {
13966                    // Optimization for translucent windows
13967                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13968                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13969                }
13970
13971                // Try to cleanup memory
13972                if (bitmap != null) bitmap.recycle();
13973
13974                try {
13975                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13976                            width, height, quality);
13977                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13978                    if (autoScale) {
13979                        mDrawingCache = bitmap;
13980                    } else {
13981                        mUnscaledDrawingCache = bitmap;
13982                    }
13983                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13984                } catch (OutOfMemoryError e) {
13985                    // If there is not enough memory to create the bitmap cache, just
13986                    // ignore the issue as bitmap caches are not required to draw the
13987                    // view hierarchy
13988                    if (autoScale) {
13989                        mDrawingCache = null;
13990                    } else {
13991                        mUnscaledDrawingCache = null;
13992                    }
13993                    mCachingFailed = true;
13994                    return;
13995                }
13996
13997                clear = drawingCacheBackgroundColor != 0;
13998            }
13999
14000            Canvas canvas;
14001            if (attachInfo != null) {
14002                canvas = attachInfo.mCanvas;
14003                if (canvas == null) {
14004                    canvas = new Canvas();
14005                }
14006                canvas.setBitmap(bitmap);
14007                // Temporarily clobber the cached Canvas in case one of our children
14008                // is also using a drawing cache. Without this, the children would
14009                // steal the canvas by attaching their own bitmap to it and bad, bad
14010                // thing would happen (invisible views, corrupted drawings, etc.)
14011                attachInfo.mCanvas = null;
14012            } else {
14013                // This case should hopefully never or seldom happen
14014                canvas = new Canvas(bitmap);
14015            }
14016
14017            if (clear) {
14018                bitmap.eraseColor(drawingCacheBackgroundColor);
14019            }
14020
14021            computeScroll();
14022            final int restoreCount = canvas.save();
14023
14024            if (autoScale && scalingRequired) {
14025                final float scale = attachInfo.mApplicationScale;
14026                canvas.scale(scale, scale);
14027            }
14028
14029            canvas.translate(-mScrollX, -mScrollY);
14030
14031            mPrivateFlags |= PFLAG_DRAWN;
14032            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14033                    mLayerType != LAYER_TYPE_NONE) {
14034                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14035            }
14036
14037            // Fast path for layouts with no backgrounds
14038            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14039                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14040                dispatchDraw(canvas);
14041                if (mOverlay != null && !mOverlay.isEmpty()) {
14042                    mOverlay.getOverlayView().draw(canvas);
14043                }
14044            } else {
14045                draw(canvas);
14046            }
14047
14048            canvas.restoreToCount(restoreCount);
14049            canvas.setBitmap(null);
14050
14051            if (attachInfo != null) {
14052                // Restore the cached Canvas for our siblings
14053                attachInfo.mCanvas = canvas;
14054            }
14055        }
14056    }
14057
14058    /**
14059     * Create a snapshot of the view into a bitmap.  We should probably make
14060     * some form of this public, but should think about the API.
14061     */
14062    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14063        int width = mRight - mLeft;
14064        int height = mBottom - mTop;
14065
14066        final AttachInfo attachInfo = mAttachInfo;
14067        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14068        width = (int) ((width * scale) + 0.5f);
14069        height = (int) ((height * scale) + 0.5f);
14070
14071        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14072                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14073        if (bitmap == null) {
14074            throw new OutOfMemoryError();
14075        }
14076
14077        Resources resources = getResources();
14078        if (resources != null) {
14079            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14080        }
14081
14082        Canvas canvas;
14083        if (attachInfo != null) {
14084            canvas = attachInfo.mCanvas;
14085            if (canvas == null) {
14086                canvas = new Canvas();
14087            }
14088            canvas.setBitmap(bitmap);
14089            // Temporarily clobber the cached Canvas in case one of our children
14090            // is also using a drawing cache. Without this, the children would
14091            // steal the canvas by attaching their own bitmap to it and bad, bad
14092            // things would happen (invisible views, corrupted drawings, etc.)
14093            attachInfo.mCanvas = null;
14094        } else {
14095            // This case should hopefully never or seldom happen
14096            canvas = new Canvas(bitmap);
14097        }
14098
14099        if ((backgroundColor & 0xff000000) != 0) {
14100            bitmap.eraseColor(backgroundColor);
14101        }
14102
14103        computeScroll();
14104        final int restoreCount = canvas.save();
14105        canvas.scale(scale, scale);
14106        canvas.translate(-mScrollX, -mScrollY);
14107
14108        // Temporarily remove the dirty mask
14109        int flags = mPrivateFlags;
14110        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14111
14112        // Fast path for layouts with no backgrounds
14113        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14114            dispatchDraw(canvas);
14115            if (mOverlay != null && !mOverlay.isEmpty()) {
14116                mOverlay.getOverlayView().draw(canvas);
14117            }
14118        } else {
14119            draw(canvas);
14120        }
14121
14122        mPrivateFlags = flags;
14123
14124        canvas.restoreToCount(restoreCount);
14125        canvas.setBitmap(null);
14126
14127        if (attachInfo != null) {
14128            // Restore the cached Canvas for our siblings
14129            attachInfo.mCanvas = canvas;
14130        }
14131
14132        return bitmap;
14133    }
14134
14135    /**
14136     * Indicates whether this View is currently in edit mode. A View is usually
14137     * in edit mode when displayed within a developer tool. For instance, if
14138     * this View is being drawn by a visual user interface builder, this method
14139     * should return true.
14140     *
14141     * Subclasses should check the return value of this method to provide
14142     * different behaviors if their normal behavior might interfere with the
14143     * host environment. For instance: the class spawns a thread in its
14144     * constructor, the drawing code relies on device-specific features, etc.
14145     *
14146     * This method is usually checked in the drawing code of custom widgets.
14147     *
14148     * @return True if this View is in edit mode, false otherwise.
14149     */
14150    public boolean isInEditMode() {
14151        return false;
14152    }
14153
14154    /**
14155     * If the View draws content inside its padding and enables fading edges,
14156     * it needs to support padding offsets. Padding offsets are added to the
14157     * fading edges to extend the length of the fade so that it covers pixels
14158     * drawn inside the padding.
14159     *
14160     * Subclasses of this class should override this method if they need
14161     * to draw content inside the padding.
14162     *
14163     * @return True if padding offset must be applied, false otherwise.
14164     *
14165     * @see #getLeftPaddingOffset()
14166     * @see #getRightPaddingOffset()
14167     * @see #getTopPaddingOffset()
14168     * @see #getBottomPaddingOffset()
14169     *
14170     * @since CURRENT
14171     */
14172    protected boolean isPaddingOffsetRequired() {
14173        return false;
14174    }
14175
14176    /**
14177     * Amount by which to extend the left fading region. Called only when
14178     * {@link #isPaddingOffsetRequired()} returns true.
14179     *
14180     * @return The left padding offset in pixels.
14181     *
14182     * @see #isPaddingOffsetRequired()
14183     *
14184     * @since CURRENT
14185     */
14186    protected int getLeftPaddingOffset() {
14187        return 0;
14188    }
14189
14190    /**
14191     * Amount by which to extend the right fading region. Called only when
14192     * {@link #isPaddingOffsetRequired()} returns true.
14193     *
14194     * @return The right padding offset in pixels.
14195     *
14196     * @see #isPaddingOffsetRequired()
14197     *
14198     * @since CURRENT
14199     */
14200    protected int getRightPaddingOffset() {
14201        return 0;
14202    }
14203
14204    /**
14205     * Amount by which to extend the top fading region. Called only when
14206     * {@link #isPaddingOffsetRequired()} returns true.
14207     *
14208     * @return The top padding offset in pixels.
14209     *
14210     * @see #isPaddingOffsetRequired()
14211     *
14212     * @since CURRENT
14213     */
14214    protected int getTopPaddingOffset() {
14215        return 0;
14216    }
14217
14218    /**
14219     * Amount by which to extend the bottom fading region. Called only when
14220     * {@link #isPaddingOffsetRequired()} returns true.
14221     *
14222     * @return The bottom padding offset in pixels.
14223     *
14224     * @see #isPaddingOffsetRequired()
14225     *
14226     * @since CURRENT
14227     */
14228    protected int getBottomPaddingOffset() {
14229        return 0;
14230    }
14231
14232    /**
14233     * @hide
14234     * @param offsetRequired
14235     */
14236    protected int getFadeTop(boolean offsetRequired) {
14237        int top = mPaddingTop;
14238        if (offsetRequired) top += getTopPaddingOffset();
14239        return top;
14240    }
14241
14242    /**
14243     * @hide
14244     * @param offsetRequired
14245     */
14246    protected int getFadeHeight(boolean offsetRequired) {
14247        int padding = mPaddingTop;
14248        if (offsetRequired) padding += getTopPaddingOffset();
14249        return mBottom - mTop - mPaddingBottom - padding;
14250    }
14251
14252    /**
14253     * <p>Indicates whether this view is attached to a hardware accelerated
14254     * window or not.</p>
14255     *
14256     * <p>Even if this method returns true, it does not mean that every call
14257     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14258     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14259     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14260     * window is hardware accelerated,
14261     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14262     * return false, and this method will return true.</p>
14263     *
14264     * @return True if the view is attached to a window and the window is
14265     *         hardware accelerated; false in any other case.
14266     */
14267    @ViewDebug.ExportedProperty(category = "drawing")
14268    public boolean isHardwareAccelerated() {
14269        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14270    }
14271
14272    /**
14273     * Sets a rectangular area on this view to which the view will be clipped
14274     * when it is drawn. Setting the value to null will remove the clip bounds
14275     * and the view will draw normally, using its full bounds.
14276     *
14277     * @param clipBounds The rectangular area, in the local coordinates of
14278     * this view, to which future drawing operations will be clipped.
14279     */
14280    public void setClipBounds(Rect clipBounds) {
14281        if (clipBounds != null) {
14282            if (clipBounds.equals(mClipBounds)) {
14283                return;
14284            }
14285            if (mClipBounds == null) {
14286                invalidate();
14287                mClipBounds = new Rect(clipBounds);
14288            } else {
14289                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14290                        Math.min(mClipBounds.top, clipBounds.top),
14291                        Math.max(mClipBounds.right, clipBounds.right),
14292                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14293                mClipBounds.set(clipBounds);
14294            }
14295        } else {
14296            if (mClipBounds != null) {
14297                invalidate();
14298                mClipBounds = null;
14299            }
14300        }
14301    }
14302
14303    /**
14304     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14305     *
14306     * @return A copy of the current clip bounds if clip bounds are set,
14307     * otherwise null.
14308     */
14309    public Rect getClipBounds() {
14310        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14311    }
14312
14313    /**
14314     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14315     * case of an active Animation being run on the view.
14316     */
14317    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14318            Animation a, boolean scalingRequired) {
14319        Transformation invalidationTransform;
14320        final int flags = parent.mGroupFlags;
14321        final boolean initialized = a.isInitialized();
14322        if (!initialized) {
14323            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14324            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14325            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14326            onAnimationStart();
14327        }
14328
14329        final Transformation t = parent.getChildTransformation();
14330        boolean more = a.getTransformation(drawingTime, t, 1f);
14331        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14332            if (parent.mInvalidationTransformation == null) {
14333                parent.mInvalidationTransformation = new Transformation();
14334            }
14335            invalidationTransform = parent.mInvalidationTransformation;
14336            a.getTransformation(drawingTime, invalidationTransform, 1f);
14337        } else {
14338            invalidationTransform = t;
14339        }
14340
14341        if (more) {
14342            if (!a.willChangeBounds()) {
14343                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14344                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14345                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14346                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14347                    // The child need to draw an animation, potentially offscreen, so
14348                    // make sure we do not cancel invalidate requests
14349                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14350                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14351                }
14352            } else {
14353                if (parent.mInvalidateRegion == null) {
14354                    parent.mInvalidateRegion = new RectF();
14355                }
14356                final RectF region = parent.mInvalidateRegion;
14357                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14358                        invalidationTransform);
14359
14360                // The child need to draw an animation, potentially offscreen, so
14361                // make sure we do not cancel invalidate requests
14362                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14363
14364                final int left = mLeft + (int) region.left;
14365                final int top = mTop + (int) region.top;
14366                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14367                        top + (int) (region.height() + .5f));
14368            }
14369        }
14370        return more;
14371    }
14372
14373    /**
14374     * This method is called by getDisplayList() when a display list is recorded for a View.
14375     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14376     */
14377    void setDisplayListProperties(RenderNode renderNode) {
14378        if (renderNode != null) {
14379            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14380            if (mParent instanceof ViewGroup) {
14381                renderNode.setClipToBounds(
14382                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14383            }
14384            float alpha = 1;
14385            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14386                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14387                ViewGroup parentVG = (ViewGroup) mParent;
14388                final Transformation t = parentVG.getChildTransformation();
14389                if (parentVG.getChildStaticTransformation(this, t)) {
14390                    final int transformType = t.getTransformationType();
14391                    if (transformType != Transformation.TYPE_IDENTITY) {
14392                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14393                            alpha = t.getAlpha();
14394                        }
14395                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14396                            renderNode.setStaticMatrix(t.getMatrix());
14397                        }
14398                    }
14399                }
14400            }
14401            if (mTransformationInfo != null) {
14402                alpha *= getFinalAlpha();
14403                if (alpha < 1) {
14404                    final int multipliedAlpha = (int) (255 * alpha);
14405                    if (onSetAlpha(multipliedAlpha)) {
14406                        alpha = 1;
14407                    }
14408                }
14409                renderNode.setAlpha(alpha);
14410            } else if (alpha < 1) {
14411                renderNode.setAlpha(alpha);
14412            }
14413        }
14414    }
14415
14416    /**
14417     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14418     * This draw() method is an implementation detail and is not intended to be overridden or
14419     * to be called from anywhere else other than ViewGroup.drawChild().
14420     */
14421    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14422        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14423        boolean more = false;
14424        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14425        final int flags = parent.mGroupFlags;
14426
14427        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14428            parent.getChildTransformation().clear();
14429            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14430        }
14431
14432        Transformation transformToApply = null;
14433        boolean concatMatrix = false;
14434
14435        boolean scalingRequired = false;
14436        boolean caching;
14437        int layerType = getLayerType();
14438
14439        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14440        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14441                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14442            caching = true;
14443            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14444            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14445        } else {
14446            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14447        }
14448
14449        final Animation a = getAnimation();
14450        if (a != null) {
14451            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14452            concatMatrix = a.willChangeTransformationMatrix();
14453            if (concatMatrix) {
14454                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14455            }
14456            transformToApply = parent.getChildTransformation();
14457        } else {
14458            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14459                // No longer animating: clear out old animation matrix
14460                mRenderNode.setAnimationMatrix(null);
14461                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14462            }
14463            if (!useDisplayListProperties &&
14464                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14465                final Transformation t = parent.getChildTransformation();
14466                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14467                if (hasTransform) {
14468                    final int transformType = t.getTransformationType();
14469                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14470                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14471                }
14472            }
14473        }
14474
14475        concatMatrix |= !childHasIdentityMatrix;
14476
14477        // Sets the flag as early as possible to allow draw() implementations
14478        // to call invalidate() successfully when doing animations
14479        mPrivateFlags |= PFLAG_DRAWN;
14480
14481        if (!concatMatrix &&
14482                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14483                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14484                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14485                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14486            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14487            return more;
14488        }
14489        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14490
14491        if (hardwareAccelerated) {
14492            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14493            // retain the flag's value temporarily in the mRecreateDisplayList flag
14494            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14495            mPrivateFlags &= ~PFLAG_INVALIDATED;
14496        }
14497
14498        RenderNode renderNode = null;
14499        Bitmap cache = null;
14500        boolean hasDisplayList = false;
14501        if (caching) {
14502            if (!hardwareAccelerated) {
14503                if (layerType != LAYER_TYPE_NONE) {
14504                    layerType = LAYER_TYPE_SOFTWARE;
14505                    buildDrawingCache(true);
14506                }
14507                cache = getDrawingCache(true);
14508            } else {
14509                switch (layerType) {
14510                    case LAYER_TYPE_SOFTWARE:
14511                        if (useDisplayListProperties) {
14512                            hasDisplayList = canHaveDisplayList();
14513                        } else {
14514                            buildDrawingCache(true);
14515                            cache = getDrawingCache(true);
14516                        }
14517                        break;
14518                    case LAYER_TYPE_HARDWARE:
14519                        if (useDisplayListProperties) {
14520                            hasDisplayList = canHaveDisplayList();
14521                        }
14522                        break;
14523                    case LAYER_TYPE_NONE:
14524                        // Delay getting the display list until animation-driven alpha values are
14525                        // set up and possibly passed on to the view
14526                        hasDisplayList = canHaveDisplayList();
14527                        break;
14528                }
14529            }
14530        }
14531        useDisplayListProperties &= hasDisplayList;
14532        if (useDisplayListProperties) {
14533            renderNode = getDisplayList();
14534            if (!renderNode.isValid()) {
14535                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14536                // to getDisplayList(), the display list will be marked invalid and we should not
14537                // try to use it again.
14538                renderNode = null;
14539                hasDisplayList = false;
14540                useDisplayListProperties = false;
14541            }
14542        }
14543
14544        int sx = 0;
14545        int sy = 0;
14546        if (!hasDisplayList) {
14547            computeScroll();
14548            sx = mScrollX;
14549            sy = mScrollY;
14550        }
14551
14552        final boolean hasNoCache = cache == null || hasDisplayList;
14553        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14554                layerType != LAYER_TYPE_HARDWARE;
14555
14556        int restoreTo = -1;
14557        if (!useDisplayListProperties || transformToApply != null) {
14558            restoreTo = canvas.save();
14559        }
14560        if (offsetForScroll) {
14561            canvas.translate(mLeft - sx, mTop - sy);
14562        } else {
14563            if (!useDisplayListProperties) {
14564                canvas.translate(mLeft, mTop);
14565            }
14566            if (scalingRequired) {
14567                if (useDisplayListProperties) {
14568                    // TODO: Might not need this if we put everything inside the DL
14569                    restoreTo = canvas.save();
14570                }
14571                // mAttachInfo cannot be null, otherwise scalingRequired == false
14572                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14573                canvas.scale(scale, scale);
14574            }
14575        }
14576
14577        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14578        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14579                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14580            if (transformToApply != null || !childHasIdentityMatrix) {
14581                int transX = 0;
14582                int transY = 0;
14583
14584                if (offsetForScroll) {
14585                    transX = -sx;
14586                    transY = -sy;
14587                }
14588
14589                if (transformToApply != null) {
14590                    if (concatMatrix) {
14591                        if (useDisplayListProperties) {
14592                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14593                        } else {
14594                            // Undo the scroll translation, apply the transformation matrix,
14595                            // then redo the scroll translate to get the correct result.
14596                            canvas.translate(-transX, -transY);
14597                            canvas.concat(transformToApply.getMatrix());
14598                            canvas.translate(transX, transY);
14599                        }
14600                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14601                    }
14602
14603                    float transformAlpha = transformToApply.getAlpha();
14604                    if (transformAlpha < 1) {
14605                        alpha *= transformAlpha;
14606                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14607                    }
14608                }
14609
14610                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14611                    canvas.translate(-transX, -transY);
14612                    canvas.concat(getMatrix());
14613                    canvas.translate(transX, transY);
14614                }
14615            }
14616
14617            // Deal with alpha if it is or used to be <1
14618            if (alpha < 1 ||
14619                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14620                if (alpha < 1) {
14621                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14622                } else {
14623                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14624                }
14625                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14626                if (hasNoCache) {
14627                    final int multipliedAlpha = (int) (255 * alpha);
14628                    if (!onSetAlpha(multipliedAlpha)) {
14629                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14630                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14631                                layerType != LAYER_TYPE_NONE) {
14632                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14633                        }
14634                        if (useDisplayListProperties) {
14635                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14636                        } else  if (layerType == LAYER_TYPE_NONE) {
14637                            final int scrollX = hasDisplayList ? 0 : sx;
14638                            final int scrollY = hasDisplayList ? 0 : sy;
14639                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14640                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14641                        }
14642                    } else {
14643                        // Alpha is handled by the child directly, clobber the layer's alpha
14644                        mPrivateFlags |= PFLAG_ALPHA_SET;
14645                    }
14646                }
14647            }
14648        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14649            onSetAlpha(255);
14650            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14651        }
14652
14653        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14654                !useDisplayListProperties && cache == null) {
14655            if (offsetForScroll) {
14656                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14657            } else {
14658                if (!scalingRequired || cache == null) {
14659                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14660                } else {
14661                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14662                }
14663            }
14664        }
14665
14666        if (!useDisplayListProperties && hasDisplayList) {
14667            renderNode = getDisplayList();
14668            if (!renderNode.isValid()) {
14669                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14670                // to getDisplayList(), the display list will be marked invalid and we should not
14671                // try to use it again.
14672                renderNode = null;
14673                hasDisplayList = false;
14674            }
14675        }
14676
14677        if (hasNoCache) {
14678            boolean layerRendered = false;
14679            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14680                final HardwareLayer layer = getHardwareLayer();
14681                if (layer != null && layer.isValid()) {
14682                    mLayerPaint.setAlpha((int) (alpha * 255));
14683                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14684                    layerRendered = true;
14685                } else {
14686                    final int scrollX = hasDisplayList ? 0 : sx;
14687                    final int scrollY = hasDisplayList ? 0 : sy;
14688                    canvas.saveLayer(scrollX, scrollY,
14689                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14690                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14691                }
14692            }
14693
14694            if (!layerRendered) {
14695                if (!hasDisplayList) {
14696                    // Fast path for layouts with no backgrounds
14697                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14698                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14699                        dispatchDraw(canvas);
14700                    } else {
14701                        draw(canvas);
14702                    }
14703                } else {
14704                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14705                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14706                }
14707            }
14708        } else if (cache != null) {
14709            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14710            Paint cachePaint;
14711
14712            if (layerType == LAYER_TYPE_NONE) {
14713                cachePaint = parent.mCachePaint;
14714                if (cachePaint == null) {
14715                    cachePaint = new Paint();
14716                    cachePaint.setDither(false);
14717                    parent.mCachePaint = cachePaint;
14718                }
14719                if (alpha < 1) {
14720                    cachePaint.setAlpha((int) (alpha * 255));
14721                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14722                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14723                    cachePaint.setAlpha(255);
14724                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14725                }
14726            } else {
14727                cachePaint = mLayerPaint;
14728                cachePaint.setAlpha((int) (alpha * 255));
14729            }
14730            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14731        }
14732
14733        if (restoreTo >= 0) {
14734            canvas.restoreToCount(restoreTo);
14735        }
14736
14737        if (a != null && !more) {
14738            if (!hardwareAccelerated && !a.getFillAfter()) {
14739                onSetAlpha(255);
14740            }
14741            parent.finishAnimatingView(this, a);
14742        }
14743
14744        if (more && hardwareAccelerated) {
14745            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14746                // alpha animations should cause the child to recreate its display list
14747                invalidate(true);
14748            }
14749        }
14750
14751        mRecreateDisplayList = false;
14752
14753        return more;
14754    }
14755
14756    /**
14757     * Manually render this view (and all of its children) to the given Canvas.
14758     * The view must have already done a full layout before this function is
14759     * called.  When implementing a view, implement
14760     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14761     * If you do need to override this method, call the superclass version.
14762     *
14763     * @param canvas The Canvas to which the View is rendered.
14764     */
14765    public void draw(Canvas canvas) {
14766        if (mClipBounds != null) {
14767            canvas.clipRect(mClipBounds);
14768        }
14769        final int privateFlags = mPrivateFlags;
14770        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14771                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14772        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14773
14774        /*
14775         * Draw traversal performs several drawing steps which must be executed
14776         * in the appropriate order:
14777         *
14778         *      1. Draw the background
14779         *      2. If necessary, save the canvas' layers to prepare for fading
14780         *      3. Draw view's content
14781         *      4. Draw children
14782         *      5. If necessary, draw the fading edges and restore layers
14783         *      6. Draw decorations (scrollbars for instance)
14784         */
14785
14786        // Step 1, draw the background, if needed
14787        int saveCount;
14788
14789        if (!dirtyOpaque) {
14790            drawBackground(canvas);
14791        }
14792
14793        // skip step 2 & 5 if possible (common case)
14794        final int viewFlags = mViewFlags;
14795        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14796        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14797        if (!verticalEdges && !horizontalEdges) {
14798            // Step 3, draw the content
14799            if (!dirtyOpaque) onDraw(canvas);
14800
14801            // Step 4, draw the children
14802            dispatchDraw(canvas);
14803
14804            // Step 6, draw decorations (scrollbars)
14805            onDrawScrollBars(canvas);
14806
14807            if (mOverlay != null && !mOverlay.isEmpty()) {
14808                mOverlay.getOverlayView().dispatchDraw(canvas);
14809            }
14810
14811            // we're done...
14812            return;
14813        }
14814
14815        /*
14816         * Here we do the full fledged routine...
14817         * (this is an uncommon case where speed matters less,
14818         * this is why we repeat some of the tests that have been
14819         * done above)
14820         */
14821
14822        boolean drawTop = false;
14823        boolean drawBottom = false;
14824        boolean drawLeft = false;
14825        boolean drawRight = false;
14826
14827        float topFadeStrength = 0.0f;
14828        float bottomFadeStrength = 0.0f;
14829        float leftFadeStrength = 0.0f;
14830        float rightFadeStrength = 0.0f;
14831
14832        // Step 2, save the canvas' layers
14833        int paddingLeft = mPaddingLeft;
14834
14835        final boolean offsetRequired = isPaddingOffsetRequired();
14836        if (offsetRequired) {
14837            paddingLeft += getLeftPaddingOffset();
14838        }
14839
14840        int left = mScrollX + paddingLeft;
14841        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14842        int top = mScrollY + getFadeTop(offsetRequired);
14843        int bottom = top + getFadeHeight(offsetRequired);
14844
14845        if (offsetRequired) {
14846            right += getRightPaddingOffset();
14847            bottom += getBottomPaddingOffset();
14848        }
14849
14850        final ScrollabilityCache scrollabilityCache = mScrollCache;
14851        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14852        int length = (int) fadeHeight;
14853
14854        // clip the fade length if top and bottom fades overlap
14855        // overlapping fades produce odd-looking artifacts
14856        if (verticalEdges && (top + length > bottom - length)) {
14857            length = (bottom - top) / 2;
14858        }
14859
14860        // also clip horizontal fades if necessary
14861        if (horizontalEdges && (left + length > right - length)) {
14862            length = (right - left) / 2;
14863        }
14864
14865        if (verticalEdges) {
14866            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14867            drawTop = topFadeStrength * fadeHeight > 1.0f;
14868            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14869            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14870        }
14871
14872        if (horizontalEdges) {
14873            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14874            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14875            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14876            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14877        }
14878
14879        saveCount = canvas.getSaveCount();
14880
14881        int solidColor = getSolidColor();
14882        if (solidColor == 0) {
14883            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14884
14885            if (drawTop) {
14886                canvas.saveLayer(left, top, right, top + length, null, flags);
14887            }
14888
14889            if (drawBottom) {
14890                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14891            }
14892
14893            if (drawLeft) {
14894                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14895            }
14896
14897            if (drawRight) {
14898                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14899            }
14900        } else {
14901            scrollabilityCache.setFadeColor(solidColor);
14902        }
14903
14904        // Step 3, draw the content
14905        if (!dirtyOpaque) onDraw(canvas);
14906
14907        // Step 4, draw the children
14908        dispatchDraw(canvas);
14909
14910        // Step 5, draw the fade effect and restore layers
14911        final Paint p = scrollabilityCache.paint;
14912        final Matrix matrix = scrollabilityCache.matrix;
14913        final Shader fade = scrollabilityCache.shader;
14914
14915        if (drawTop) {
14916            matrix.setScale(1, fadeHeight * topFadeStrength);
14917            matrix.postTranslate(left, top);
14918            fade.setLocalMatrix(matrix);
14919            canvas.drawRect(left, top, right, top + length, p);
14920        }
14921
14922        if (drawBottom) {
14923            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14924            matrix.postRotate(180);
14925            matrix.postTranslate(left, bottom);
14926            fade.setLocalMatrix(matrix);
14927            canvas.drawRect(left, bottom - length, right, bottom, p);
14928        }
14929
14930        if (drawLeft) {
14931            matrix.setScale(1, fadeHeight * leftFadeStrength);
14932            matrix.postRotate(-90);
14933            matrix.postTranslate(left, top);
14934            fade.setLocalMatrix(matrix);
14935            canvas.drawRect(left, top, left + length, bottom, p);
14936        }
14937
14938        if (drawRight) {
14939            matrix.setScale(1, fadeHeight * rightFadeStrength);
14940            matrix.postRotate(90);
14941            matrix.postTranslate(right, top);
14942            fade.setLocalMatrix(matrix);
14943            canvas.drawRect(right - length, top, right, bottom, p);
14944        }
14945
14946        canvas.restoreToCount(saveCount);
14947
14948        // Step 6, draw decorations (scrollbars)
14949        onDrawScrollBars(canvas);
14950
14951        if (mOverlay != null && !mOverlay.isEmpty()) {
14952            mOverlay.getOverlayView().dispatchDraw(canvas);
14953        }
14954    }
14955
14956    /**
14957     * Draws the background onto the specified canvas.
14958     *
14959     * @param canvas Canvas on which to draw the background
14960     */
14961    private void drawBackground(Canvas canvas) {
14962        final Drawable background = mBackground;
14963        if (background == null) {
14964            return;
14965        }
14966
14967        if (mBackgroundSizeChanged) {
14968            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14969            mBackgroundSizeChanged = false;
14970            queryOutlineFromBackgroundIfUndefined();
14971        }
14972
14973        // Attempt to use a display list if requested.
14974        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14975                && mAttachInfo.mHardwareRenderer != null) {
14976            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
14977
14978            final RenderNode displayList = mBackgroundRenderNode;
14979            if (displayList != null && displayList.isValid()) {
14980                setBackgroundDisplayListProperties(displayList);
14981                ((HardwareCanvas) canvas).drawRenderNode(displayList);
14982                return;
14983            }
14984        }
14985
14986        final int scrollX = mScrollX;
14987        final int scrollY = mScrollY;
14988        if ((scrollX | scrollY) == 0) {
14989            background.draw(canvas);
14990        } else {
14991            canvas.translate(scrollX, scrollY);
14992            background.draw(canvas);
14993            canvas.translate(-scrollX, -scrollY);
14994        }
14995    }
14996
14997    /**
14998     * Set up background drawable display list properties.
14999     *
15000     * @param displayList Valid display list for the background drawable
15001     */
15002    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15003        displayList.setTranslationX(mScrollX);
15004        displayList.setTranslationY(mScrollY);
15005    }
15006
15007    /**
15008     * Creates a new display list or updates the existing display list for the
15009     * specified Drawable.
15010     *
15011     * @param drawable Drawable for which to create a display list
15012     * @param renderNode Existing RenderNode, or {@code null}
15013     * @return A valid display list for the specified drawable
15014     */
15015    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15016        if (renderNode == null) {
15017            renderNode = RenderNode.create(drawable.getClass().getName());
15018        }
15019
15020        final Rect bounds = drawable.getBounds();
15021        final int width = bounds.width();
15022        final int height = bounds.height();
15023        final HardwareCanvas canvas = renderNode.start(width, height);
15024        try {
15025            drawable.draw(canvas);
15026        } finally {
15027            renderNode.end(canvas);
15028        }
15029
15030        // Set up drawable properties that are view-independent.
15031        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15032        renderNode.setProjectBackwards(drawable.isProjected());
15033        renderNode.setProjectionReceiver(true);
15034        renderNode.setClipToBounds(false);
15035        return renderNode;
15036    }
15037
15038    /**
15039     * Returns the overlay for this view, creating it if it does not yet exist.
15040     * Adding drawables to the overlay will cause them to be displayed whenever
15041     * the view itself is redrawn. Objects in the overlay should be actively
15042     * managed: remove them when they should not be displayed anymore. The
15043     * overlay will always have the same size as its host view.
15044     *
15045     * <p>Note: Overlays do not currently work correctly with {@link
15046     * SurfaceView} or {@link TextureView}; contents in overlays for these
15047     * types of views may not display correctly.</p>
15048     *
15049     * @return The ViewOverlay object for this view.
15050     * @see ViewOverlay
15051     */
15052    public ViewOverlay getOverlay() {
15053        if (mOverlay == null) {
15054            mOverlay = new ViewOverlay(mContext, this);
15055        }
15056        return mOverlay;
15057    }
15058
15059    /**
15060     * Override this if your view is known to always be drawn on top of a solid color background,
15061     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15062     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15063     * should be set to 0xFF.
15064     *
15065     * @see #setVerticalFadingEdgeEnabled(boolean)
15066     * @see #setHorizontalFadingEdgeEnabled(boolean)
15067     *
15068     * @return The known solid color background for this view, or 0 if the color may vary
15069     */
15070    @ViewDebug.ExportedProperty(category = "drawing")
15071    public int getSolidColor() {
15072        return 0;
15073    }
15074
15075    /**
15076     * Build a human readable string representation of the specified view flags.
15077     *
15078     * @param flags the view flags to convert to a string
15079     * @return a String representing the supplied flags
15080     */
15081    private static String printFlags(int flags) {
15082        String output = "";
15083        int numFlags = 0;
15084        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15085            output += "TAKES_FOCUS";
15086            numFlags++;
15087        }
15088
15089        switch (flags & VISIBILITY_MASK) {
15090        case INVISIBLE:
15091            if (numFlags > 0) {
15092                output += " ";
15093            }
15094            output += "INVISIBLE";
15095            // USELESS HERE numFlags++;
15096            break;
15097        case GONE:
15098            if (numFlags > 0) {
15099                output += " ";
15100            }
15101            output += "GONE";
15102            // USELESS HERE numFlags++;
15103            break;
15104        default:
15105            break;
15106        }
15107        return output;
15108    }
15109
15110    /**
15111     * Build a human readable string representation of the specified private
15112     * view flags.
15113     *
15114     * @param privateFlags the private view flags to convert to a string
15115     * @return a String representing the supplied flags
15116     */
15117    private static String printPrivateFlags(int privateFlags) {
15118        String output = "";
15119        int numFlags = 0;
15120
15121        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15122            output += "WANTS_FOCUS";
15123            numFlags++;
15124        }
15125
15126        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15127            if (numFlags > 0) {
15128                output += " ";
15129            }
15130            output += "FOCUSED";
15131            numFlags++;
15132        }
15133
15134        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15135            if (numFlags > 0) {
15136                output += " ";
15137            }
15138            output += "SELECTED";
15139            numFlags++;
15140        }
15141
15142        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15143            if (numFlags > 0) {
15144                output += " ";
15145            }
15146            output += "IS_ROOT_NAMESPACE";
15147            numFlags++;
15148        }
15149
15150        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15151            if (numFlags > 0) {
15152                output += " ";
15153            }
15154            output += "HAS_BOUNDS";
15155            numFlags++;
15156        }
15157
15158        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15159            if (numFlags > 0) {
15160                output += " ";
15161            }
15162            output += "DRAWN";
15163            // USELESS HERE numFlags++;
15164        }
15165        return output;
15166    }
15167
15168    /**
15169     * <p>Indicates whether or not this view's layout will be requested during
15170     * the next hierarchy layout pass.</p>
15171     *
15172     * @return true if the layout will be forced during next layout pass
15173     */
15174    public boolean isLayoutRequested() {
15175        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15176    }
15177
15178    /**
15179     * Return true if o is a ViewGroup that is laying out using optical bounds.
15180     * @hide
15181     */
15182    public static boolean isLayoutModeOptical(Object o) {
15183        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15184    }
15185
15186    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15187        Insets parentInsets = mParent instanceof View ?
15188                ((View) mParent).getOpticalInsets() : Insets.NONE;
15189        Insets childInsets = getOpticalInsets();
15190        return setFrame(
15191                left   + parentInsets.left - childInsets.left,
15192                top    + parentInsets.top  - childInsets.top,
15193                right  + parentInsets.left + childInsets.right,
15194                bottom + parentInsets.top  + childInsets.bottom);
15195    }
15196
15197    /**
15198     * Assign a size and position to a view and all of its
15199     * descendants
15200     *
15201     * <p>This is the second phase of the layout mechanism.
15202     * (The first is measuring). In this phase, each parent calls
15203     * layout on all of its children to position them.
15204     * This is typically done using the child measurements
15205     * that were stored in the measure pass().</p>
15206     *
15207     * <p>Derived classes should not override this method.
15208     * Derived classes with children should override
15209     * onLayout. In that method, they should
15210     * call layout on each of their children.</p>
15211     *
15212     * @param l Left position, relative to parent
15213     * @param t Top position, relative to parent
15214     * @param r Right position, relative to parent
15215     * @param b Bottom position, relative to parent
15216     */
15217    @SuppressWarnings({"unchecked"})
15218    public void layout(int l, int t, int r, int b) {
15219        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15220            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15221            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15222        }
15223
15224        int oldL = mLeft;
15225        int oldT = mTop;
15226        int oldB = mBottom;
15227        int oldR = mRight;
15228
15229        boolean changed = isLayoutModeOptical(mParent) ?
15230                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15231
15232        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15233            onLayout(changed, l, t, r, b);
15234            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15235
15236            ListenerInfo li = mListenerInfo;
15237            if (li != null && li.mOnLayoutChangeListeners != null) {
15238                ArrayList<OnLayoutChangeListener> listenersCopy =
15239                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15240                int numListeners = listenersCopy.size();
15241                for (int i = 0; i < numListeners; ++i) {
15242                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15243                }
15244            }
15245        }
15246
15247        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15248        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15249    }
15250
15251    /**
15252     * Called from layout when this view should
15253     * assign a size and position to each of its children.
15254     *
15255     * Derived classes with children should override
15256     * this method and call layout on each of
15257     * their children.
15258     * @param changed This is a new size or position for this view
15259     * @param left Left position, relative to parent
15260     * @param top Top position, relative to parent
15261     * @param right Right position, relative to parent
15262     * @param bottom Bottom position, relative to parent
15263     */
15264    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15265    }
15266
15267    /**
15268     * Assign a size and position to this view.
15269     *
15270     * This is called from layout.
15271     *
15272     * @param left Left position, relative to parent
15273     * @param top Top position, relative to parent
15274     * @param right Right position, relative to parent
15275     * @param bottom Bottom position, relative to parent
15276     * @return true if the new size and position are different than the
15277     *         previous ones
15278     * {@hide}
15279     */
15280    protected boolean setFrame(int left, int top, int right, int bottom) {
15281        boolean changed = false;
15282
15283        if (DBG) {
15284            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15285                    + right + "," + bottom + ")");
15286        }
15287
15288        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15289            changed = true;
15290
15291            // Remember our drawn bit
15292            int drawn = mPrivateFlags & PFLAG_DRAWN;
15293
15294            int oldWidth = mRight - mLeft;
15295            int oldHeight = mBottom - mTop;
15296            int newWidth = right - left;
15297            int newHeight = bottom - top;
15298            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15299
15300            // Invalidate our old position
15301            invalidate(sizeChanged);
15302
15303            mLeft = left;
15304            mTop = top;
15305            mRight = right;
15306            mBottom = bottom;
15307            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15308
15309            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15310
15311
15312            if (sizeChanged) {
15313                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15314            }
15315
15316            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15317                // If we are visible, force the DRAWN bit to on so that
15318                // this invalidate will go through (at least to our parent).
15319                // This is because someone may have invalidated this view
15320                // before this call to setFrame came in, thereby clearing
15321                // the DRAWN bit.
15322                mPrivateFlags |= PFLAG_DRAWN;
15323                invalidate(sizeChanged);
15324                // parent display list may need to be recreated based on a change in the bounds
15325                // of any child
15326                invalidateParentCaches();
15327            }
15328
15329            // Reset drawn bit to original value (invalidate turns it off)
15330            mPrivateFlags |= drawn;
15331
15332            mBackgroundSizeChanged = true;
15333
15334            notifySubtreeAccessibilityStateChangedIfNeeded();
15335        }
15336        return changed;
15337    }
15338
15339    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15340        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15341        if (mOverlay != null) {
15342            mOverlay.getOverlayView().setRight(newWidth);
15343            mOverlay.getOverlayView().setBottom(newHeight);
15344        }
15345    }
15346
15347    /**
15348     * Finalize inflating a view from XML.  This is called as the last phase
15349     * of inflation, after all child views have been added.
15350     *
15351     * <p>Even if the subclass overrides onFinishInflate, they should always be
15352     * sure to call the super method, so that we get called.
15353     */
15354    protected void onFinishInflate() {
15355    }
15356
15357    /**
15358     * Returns the resources associated with this view.
15359     *
15360     * @return Resources object.
15361     */
15362    public Resources getResources() {
15363        return mResources;
15364    }
15365
15366    /**
15367     * Invalidates the specified Drawable.
15368     *
15369     * @param drawable the drawable to invalidate
15370     */
15371    @Override
15372    public void invalidateDrawable(@NonNull Drawable drawable) {
15373        if (verifyDrawable(drawable)) {
15374            final Rect dirty = drawable.getDirtyBounds();
15375            final int scrollX = mScrollX;
15376            final int scrollY = mScrollY;
15377
15378            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15379                    dirty.right + scrollX, dirty.bottom + scrollY);
15380
15381            if (drawable == mBackground) {
15382                queryOutlineFromBackgroundIfUndefined();
15383            }
15384        }
15385    }
15386
15387    /**
15388     * Schedules an action on a drawable to occur at a specified time.
15389     *
15390     * @param who the recipient of the action
15391     * @param what the action to run on the drawable
15392     * @param when the time at which the action must occur. Uses the
15393     *        {@link SystemClock#uptimeMillis} timebase.
15394     */
15395    @Override
15396    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15397        if (verifyDrawable(who) && what != null) {
15398            final long delay = when - SystemClock.uptimeMillis();
15399            if (mAttachInfo != null) {
15400                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15401                        Choreographer.CALLBACK_ANIMATION, what, who,
15402                        Choreographer.subtractFrameDelay(delay));
15403            } else {
15404                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15405            }
15406        }
15407    }
15408
15409    /**
15410     * Cancels a scheduled action on a drawable.
15411     *
15412     * @param who the recipient of the action
15413     * @param what the action to cancel
15414     */
15415    @Override
15416    public void unscheduleDrawable(Drawable who, Runnable what) {
15417        if (verifyDrawable(who) && what != null) {
15418            if (mAttachInfo != null) {
15419                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15420                        Choreographer.CALLBACK_ANIMATION, what, who);
15421            }
15422            ViewRootImpl.getRunQueue().removeCallbacks(what);
15423        }
15424    }
15425
15426    /**
15427     * Unschedule any events associated with the given Drawable.  This can be
15428     * used when selecting a new Drawable into a view, so that the previous
15429     * one is completely unscheduled.
15430     *
15431     * @param who The Drawable to unschedule.
15432     *
15433     * @see #drawableStateChanged
15434     */
15435    public void unscheduleDrawable(Drawable who) {
15436        if (mAttachInfo != null && who != null) {
15437            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15438                    Choreographer.CALLBACK_ANIMATION, null, who);
15439        }
15440    }
15441
15442    /**
15443     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15444     * that the View directionality can and will be resolved before its Drawables.
15445     *
15446     * Will call {@link View#onResolveDrawables} when resolution is done.
15447     *
15448     * @hide
15449     */
15450    protected void resolveDrawables() {
15451        // Drawables resolution may need to happen before resolving the layout direction (which is
15452        // done only during the measure() call).
15453        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15454        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15455        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15456        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15457        // direction to be resolved as its resolved value will be the same as its raw value.
15458        if (!isLayoutDirectionResolved() &&
15459                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15460            return;
15461        }
15462
15463        final int layoutDirection = isLayoutDirectionResolved() ?
15464                getLayoutDirection() : getRawLayoutDirection();
15465
15466        if (mBackground != null) {
15467            mBackground.setLayoutDirection(layoutDirection);
15468        }
15469        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15470        onResolveDrawables(layoutDirection);
15471    }
15472
15473    /**
15474     * Called when layout direction has been resolved.
15475     *
15476     * The default implementation does nothing.
15477     *
15478     * @param layoutDirection The resolved layout direction.
15479     *
15480     * @see #LAYOUT_DIRECTION_LTR
15481     * @see #LAYOUT_DIRECTION_RTL
15482     *
15483     * @hide
15484     */
15485    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15486    }
15487
15488    /**
15489     * @hide
15490     */
15491    protected void resetResolvedDrawables() {
15492        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15493    }
15494
15495    private boolean isDrawablesResolved() {
15496        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15497    }
15498
15499    /**
15500     * If your view subclass is displaying its own Drawable objects, it should
15501     * override this function and return true for any Drawable it is
15502     * displaying.  This allows animations for those drawables to be
15503     * scheduled.
15504     *
15505     * <p>Be sure to call through to the super class when overriding this
15506     * function.
15507     *
15508     * @param who The Drawable to verify.  Return true if it is one you are
15509     *            displaying, else return the result of calling through to the
15510     *            super class.
15511     *
15512     * @return boolean If true than the Drawable is being displayed in the
15513     *         view; else false and it is not allowed to animate.
15514     *
15515     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15516     * @see #drawableStateChanged()
15517     */
15518    protected boolean verifyDrawable(Drawable who) {
15519        return who == mBackground;
15520    }
15521
15522    /**
15523     * This function is called whenever the state of the view changes in such
15524     * a way that it impacts the state of drawables being shown.
15525     * <p>
15526     * If the View has a StateListAnimator, it will also be called to run necessary state
15527     * change animations.
15528     * <p>
15529     * Be sure to call through to the superclass when overriding this function.
15530     *
15531     * @see Drawable#setState(int[])
15532     */
15533    protected void drawableStateChanged() {
15534        final Drawable d = mBackground;
15535        if (d != null && d.isStateful()) {
15536            d.setState(getDrawableState());
15537        }
15538
15539        if (mStateListAnimator != null) {
15540            mStateListAnimator.setState(getDrawableState());
15541        }
15542    }
15543
15544    /**
15545     * This function is called whenever the drawable hotspot changes.
15546     * <p>
15547     * Be sure to call through to the superclass when overriding this function.
15548     *
15549     * @param x hotspot x coordinate
15550     * @param y hotspot y coordinate
15551     */
15552    public void drawableHotspotChanged(float x, float y) {
15553        if (mBackground != null) {
15554            mBackground.setHotspot(x, y);
15555        }
15556    }
15557
15558    /**
15559     * Call this to force a view to update its drawable state. This will cause
15560     * drawableStateChanged to be called on this view. Views that are interested
15561     * in the new state should call getDrawableState.
15562     *
15563     * @see #drawableStateChanged
15564     * @see #getDrawableState
15565     */
15566    public void refreshDrawableState() {
15567        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15568        drawableStateChanged();
15569
15570        ViewParent parent = mParent;
15571        if (parent != null) {
15572            parent.childDrawableStateChanged(this);
15573        }
15574    }
15575
15576    /**
15577     * Return an array of resource IDs of the drawable states representing the
15578     * current state of the view.
15579     *
15580     * @return The current drawable state
15581     *
15582     * @see Drawable#setState(int[])
15583     * @see #drawableStateChanged()
15584     * @see #onCreateDrawableState(int)
15585     */
15586    public final int[] getDrawableState() {
15587        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15588            return mDrawableState;
15589        } else {
15590            mDrawableState = onCreateDrawableState(0);
15591            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15592            return mDrawableState;
15593        }
15594    }
15595
15596    /**
15597     * Generate the new {@link android.graphics.drawable.Drawable} state for
15598     * this view. This is called by the view
15599     * system when the cached Drawable state is determined to be invalid.  To
15600     * retrieve the current state, you should use {@link #getDrawableState}.
15601     *
15602     * @param extraSpace if non-zero, this is the number of extra entries you
15603     * would like in the returned array in which you can place your own
15604     * states.
15605     *
15606     * @return Returns an array holding the current {@link Drawable} state of
15607     * the view.
15608     *
15609     * @see #mergeDrawableStates(int[], int[])
15610     */
15611    protected int[] onCreateDrawableState(int extraSpace) {
15612        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15613                mParent instanceof View) {
15614            return ((View) mParent).onCreateDrawableState(extraSpace);
15615        }
15616
15617        int[] drawableState;
15618
15619        int privateFlags = mPrivateFlags;
15620
15621        int viewStateIndex = 0;
15622        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15623        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15624        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15625        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15626        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15627        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15628        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15629                HardwareRenderer.isAvailable()) {
15630            // This is set if HW acceleration is requested, even if the current
15631            // process doesn't allow it.  This is just to allow app preview
15632            // windows to better match their app.
15633            viewStateIndex |= VIEW_STATE_ACCELERATED;
15634        }
15635        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15636
15637        final int privateFlags2 = mPrivateFlags2;
15638        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15639        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15640
15641        drawableState = VIEW_STATE_SETS[viewStateIndex];
15642
15643        //noinspection ConstantIfStatement
15644        if (false) {
15645            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15646            Log.i("View", toString()
15647                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15648                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15649                    + " fo=" + hasFocus()
15650                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15651                    + " wf=" + hasWindowFocus()
15652                    + ": " + Arrays.toString(drawableState));
15653        }
15654
15655        if (extraSpace == 0) {
15656            return drawableState;
15657        }
15658
15659        final int[] fullState;
15660        if (drawableState != null) {
15661            fullState = new int[drawableState.length + extraSpace];
15662            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15663        } else {
15664            fullState = new int[extraSpace];
15665        }
15666
15667        return fullState;
15668    }
15669
15670    /**
15671     * Merge your own state values in <var>additionalState</var> into the base
15672     * state values <var>baseState</var> that were returned by
15673     * {@link #onCreateDrawableState(int)}.
15674     *
15675     * @param baseState The base state values returned by
15676     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15677     * own additional state values.
15678     *
15679     * @param additionalState The additional state values you would like
15680     * added to <var>baseState</var>; this array is not modified.
15681     *
15682     * @return As a convenience, the <var>baseState</var> array you originally
15683     * passed into the function is returned.
15684     *
15685     * @see #onCreateDrawableState(int)
15686     */
15687    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15688        final int N = baseState.length;
15689        int i = N - 1;
15690        while (i >= 0 && baseState[i] == 0) {
15691            i--;
15692        }
15693        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15694        return baseState;
15695    }
15696
15697    /**
15698     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15699     * on all Drawable objects associated with this view.
15700     * <p>
15701     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15702     * attached to this view.
15703     */
15704    public void jumpDrawablesToCurrentState() {
15705        if (mBackground != null) {
15706            mBackground.jumpToCurrentState();
15707        }
15708        if (mStateListAnimator != null) {
15709            mStateListAnimator.jumpToCurrentState();
15710        }
15711    }
15712
15713    /**
15714     * Sets the background color for this view.
15715     * @param color the color of the background
15716     */
15717    @RemotableViewMethod
15718    public void setBackgroundColor(int color) {
15719        if (mBackground instanceof ColorDrawable) {
15720            ((ColorDrawable) mBackground.mutate()).setColor(color);
15721            computeOpaqueFlags();
15722            mBackgroundResource = 0;
15723        } else {
15724            setBackground(new ColorDrawable(color));
15725        }
15726    }
15727
15728    /**
15729     * Set the background to a given resource. The resource should refer to
15730     * a Drawable object or 0 to remove the background.
15731     * @param resid The identifier of the resource.
15732     *
15733     * @attr ref android.R.styleable#View_background
15734     */
15735    @RemotableViewMethod
15736    public void setBackgroundResource(int resid) {
15737        if (resid != 0 && resid == mBackgroundResource) {
15738            return;
15739        }
15740
15741        Drawable d = null;
15742        if (resid != 0) {
15743            d = mContext.getDrawable(resid);
15744        }
15745        setBackground(d);
15746
15747        mBackgroundResource = resid;
15748    }
15749
15750    /**
15751     * Set the background to a given Drawable, or remove the background. If the
15752     * background has padding, this View's padding is set to the background's
15753     * padding. However, when a background is removed, this View's padding isn't
15754     * touched. If setting the padding is desired, please use
15755     * {@link #setPadding(int, int, int, int)}.
15756     *
15757     * @param background The Drawable to use as the background, or null to remove the
15758     *        background
15759     */
15760    public void setBackground(Drawable background) {
15761        //noinspection deprecation
15762        setBackgroundDrawable(background);
15763    }
15764
15765    /**
15766     * @deprecated use {@link #setBackground(Drawable)} instead
15767     */
15768    @Deprecated
15769    public void setBackgroundDrawable(Drawable background) {
15770        computeOpaqueFlags();
15771
15772        if (background == mBackground) {
15773            return;
15774        }
15775
15776        boolean requestLayout = false;
15777
15778        mBackgroundResource = 0;
15779
15780        /*
15781         * Regardless of whether we're setting a new background or not, we want
15782         * to clear the previous drawable.
15783         */
15784        if (mBackground != null) {
15785            mBackground.setCallback(null);
15786            unscheduleDrawable(mBackground);
15787        }
15788
15789        if (background != null) {
15790            Rect padding = sThreadLocal.get();
15791            if (padding == null) {
15792                padding = new Rect();
15793                sThreadLocal.set(padding);
15794            }
15795            resetResolvedDrawables();
15796            background.setLayoutDirection(getLayoutDirection());
15797            if (background.getPadding(padding)) {
15798                resetResolvedPadding();
15799                switch (background.getLayoutDirection()) {
15800                    case LAYOUT_DIRECTION_RTL:
15801                        mUserPaddingLeftInitial = padding.right;
15802                        mUserPaddingRightInitial = padding.left;
15803                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15804                        break;
15805                    case LAYOUT_DIRECTION_LTR:
15806                    default:
15807                        mUserPaddingLeftInitial = padding.left;
15808                        mUserPaddingRightInitial = padding.right;
15809                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15810                }
15811                mLeftPaddingDefined = false;
15812                mRightPaddingDefined = false;
15813            }
15814
15815            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15816            // if it has a different minimum size, we should layout again
15817            if (mBackground == null
15818                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15819                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15820                requestLayout = true;
15821            }
15822
15823            background.setCallback(this);
15824            if (background.isStateful()) {
15825                background.setState(getDrawableState());
15826            }
15827            background.setVisible(getVisibility() == VISIBLE, false);
15828            mBackground = background;
15829
15830            applyBackgroundTint();
15831
15832            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15833                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15834                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15835                requestLayout = true;
15836            }
15837        } else {
15838            /* Remove the background */
15839            mBackground = null;
15840
15841            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15842                /*
15843                 * This view ONLY drew the background before and we're removing
15844                 * the background, so now it won't draw anything
15845                 * (hence we SKIP_DRAW)
15846                 */
15847                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15848                mPrivateFlags |= PFLAG_SKIP_DRAW;
15849            }
15850
15851            /*
15852             * When the background is set, we try to apply its padding to this
15853             * View. When the background is removed, we don't touch this View's
15854             * padding. This is noted in the Javadocs. Hence, we don't need to
15855             * requestLayout(), the invalidate() below is sufficient.
15856             */
15857
15858            // The old background's minimum size could have affected this
15859            // View's layout, so let's requestLayout
15860            requestLayout = true;
15861        }
15862
15863        computeOpaqueFlags();
15864
15865        if (requestLayout) {
15866            requestLayout();
15867        }
15868
15869        mBackgroundSizeChanged = true;
15870        invalidate(true);
15871    }
15872
15873    /**
15874     * Gets the background drawable
15875     *
15876     * @return The drawable used as the background for this view, if any.
15877     *
15878     * @see #setBackground(Drawable)
15879     *
15880     * @attr ref android.R.styleable#View_background
15881     */
15882    public Drawable getBackground() {
15883        return mBackground;
15884    }
15885
15886    /**
15887     * Applies a tint to the background drawable.
15888     * <p>
15889     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15890     * mutate the drawable and apply the specified tint and tint mode using
15891     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15892     *
15893     * @param tint the tint to apply, may be {@code null} to clear tint
15894     * @param tintMode the blending mode used to apply the tint, may be
15895     *                 {@code null} to clear tint
15896     *
15897     * @attr ref android.R.styleable#View_backgroundTint
15898     * @attr ref android.R.styleable#View_backgroundTintMode
15899     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15900     */
15901    private void setBackgroundTint(@Nullable ColorStateList tint,
15902            @Nullable PorterDuff.Mode tintMode) {
15903        mBackgroundTint = tint;
15904        mBackgroundTintMode = tintMode;
15905        mHasBackgroundTint = true;
15906
15907        applyBackgroundTint();
15908    }
15909
15910    /**
15911     * Applies a tint to the background drawable. Does not modify the current tint
15912     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15913     * <p>
15914     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15915     * mutate the drawable and apply the specified tint and tint mode using
15916     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15917     *
15918     * @param tint the tint to apply, may be {@code null} to clear tint
15919     *
15920     * @attr ref android.R.styleable#View_backgroundTint
15921     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15922     */
15923    public void setBackgroundTint(@Nullable ColorStateList tint) {
15924        setBackgroundTint(tint, mBackgroundTintMode);
15925    }
15926
15927    /**
15928     * @return the tint applied to the background drawable
15929     * @attr ref android.R.styleable#View_backgroundTint
15930     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15931     */
15932    @Nullable
15933    public ColorStateList getBackgroundTint() {
15934        return mBackgroundTint;
15935    }
15936
15937    /**
15938     * Specifies the blending mode used to apply the tint specified by
15939     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15940     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15941     *
15942     * @param tintMode the blending mode used to apply the tint, may be
15943     *                 {@code null} to clear tint
15944     * @attr ref android.R.styleable#View_backgroundTintMode
15945     * @see #setBackgroundTint(ColorStateList)
15946     */
15947    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15948        setBackgroundTint(mBackgroundTint, tintMode);
15949    }
15950
15951    /**
15952     * @return the blending mode used to apply the tint to the background drawable
15953     * @attr ref android.R.styleable#View_backgroundTintMode
15954     * @see #setBackgroundTint(ColorStateList, PorterDuff.Mode)
15955     */
15956    @Nullable
15957    public PorterDuff.Mode getBackgroundTintMode() {
15958        return mBackgroundTintMode;
15959    }
15960
15961    private void applyBackgroundTint() {
15962        if (mBackground != null && mHasBackgroundTint) {
15963            mBackground = mBackground.mutate();
15964            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15965        }
15966    }
15967
15968    /**
15969     * Sets the padding. The view may add on the space required to display
15970     * the scrollbars, depending on the style and visibility of the scrollbars.
15971     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15972     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15973     * from the values set in this call.
15974     *
15975     * @attr ref android.R.styleable#View_padding
15976     * @attr ref android.R.styleable#View_paddingBottom
15977     * @attr ref android.R.styleable#View_paddingLeft
15978     * @attr ref android.R.styleable#View_paddingRight
15979     * @attr ref android.R.styleable#View_paddingTop
15980     * @param left the left padding in pixels
15981     * @param top the top padding in pixels
15982     * @param right the right padding in pixels
15983     * @param bottom the bottom padding in pixels
15984     */
15985    public void setPadding(int left, int top, int right, int bottom) {
15986        resetResolvedPadding();
15987
15988        mUserPaddingStart = UNDEFINED_PADDING;
15989        mUserPaddingEnd = UNDEFINED_PADDING;
15990
15991        mUserPaddingLeftInitial = left;
15992        mUserPaddingRightInitial = right;
15993
15994        mLeftPaddingDefined = true;
15995        mRightPaddingDefined = true;
15996
15997        internalSetPadding(left, top, right, bottom);
15998    }
15999
16000    /**
16001     * @hide
16002     */
16003    protected void internalSetPadding(int left, int top, int right, int bottom) {
16004        mUserPaddingLeft = left;
16005        mUserPaddingRight = right;
16006        mUserPaddingBottom = bottom;
16007
16008        final int viewFlags = mViewFlags;
16009        boolean changed = false;
16010
16011        // Common case is there are no scroll bars.
16012        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16013            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16014                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16015                        ? 0 : getVerticalScrollbarWidth();
16016                switch (mVerticalScrollbarPosition) {
16017                    case SCROLLBAR_POSITION_DEFAULT:
16018                        if (isLayoutRtl()) {
16019                            left += offset;
16020                        } else {
16021                            right += offset;
16022                        }
16023                        break;
16024                    case SCROLLBAR_POSITION_RIGHT:
16025                        right += offset;
16026                        break;
16027                    case SCROLLBAR_POSITION_LEFT:
16028                        left += offset;
16029                        break;
16030                }
16031            }
16032            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16033                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16034                        ? 0 : getHorizontalScrollbarHeight();
16035            }
16036        }
16037
16038        if (mPaddingLeft != left) {
16039            changed = true;
16040            mPaddingLeft = left;
16041        }
16042        if (mPaddingTop != top) {
16043            changed = true;
16044            mPaddingTop = top;
16045        }
16046        if (mPaddingRight != right) {
16047            changed = true;
16048            mPaddingRight = right;
16049        }
16050        if (mPaddingBottom != bottom) {
16051            changed = true;
16052            mPaddingBottom = bottom;
16053        }
16054
16055        if (changed) {
16056            requestLayout();
16057        }
16058    }
16059
16060    /**
16061     * Sets the relative padding. The view may add on the space required to display
16062     * the scrollbars, depending on the style and visibility of the scrollbars.
16063     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16064     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16065     * from the values set in this call.
16066     *
16067     * @attr ref android.R.styleable#View_padding
16068     * @attr ref android.R.styleable#View_paddingBottom
16069     * @attr ref android.R.styleable#View_paddingStart
16070     * @attr ref android.R.styleable#View_paddingEnd
16071     * @attr ref android.R.styleable#View_paddingTop
16072     * @param start the start padding in pixels
16073     * @param top the top padding in pixels
16074     * @param end the end padding in pixels
16075     * @param bottom the bottom padding in pixels
16076     */
16077    public void setPaddingRelative(int start, int top, int end, int bottom) {
16078        resetResolvedPadding();
16079
16080        mUserPaddingStart = start;
16081        mUserPaddingEnd = end;
16082        mLeftPaddingDefined = true;
16083        mRightPaddingDefined = true;
16084
16085        switch(getLayoutDirection()) {
16086            case LAYOUT_DIRECTION_RTL:
16087                mUserPaddingLeftInitial = end;
16088                mUserPaddingRightInitial = start;
16089                internalSetPadding(end, top, start, bottom);
16090                break;
16091            case LAYOUT_DIRECTION_LTR:
16092            default:
16093                mUserPaddingLeftInitial = start;
16094                mUserPaddingRightInitial = end;
16095                internalSetPadding(start, top, end, bottom);
16096        }
16097    }
16098
16099    /**
16100     * Returns the top padding of this view.
16101     *
16102     * @return the top padding in pixels
16103     */
16104    public int getPaddingTop() {
16105        return mPaddingTop;
16106    }
16107
16108    /**
16109     * Returns the bottom padding of this view. If there are inset and enabled
16110     * scrollbars, this value may include the space required to display the
16111     * scrollbars as well.
16112     *
16113     * @return the bottom padding in pixels
16114     */
16115    public int getPaddingBottom() {
16116        return mPaddingBottom;
16117    }
16118
16119    /**
16120     * Returns the left padding of this view. If there are inset and enabled
16121     * scrollbars, this value may include the space required to display the
16122     * scrollbars as well.
16123     *
16124     * @return the left padding in pixels
16125     */
16126    public int getPaddingLeft() {
16127        if (!isPaddingResolved()) {
16128            resolvePadding();
16129        }
16130        return mPaddingLeft;
16131    }
16132
16133    /**
16134     * Returns the start padding of this view depending on its resolved layout direction.
16135     * If there are inset and enabled scrollbars, this value may include the space
16136     * required to display the scrollbars as well.
16137     *
16138     * @return the start padding in pixels
16139     */
16140    public int getPaddingStart() {
16141        if (!isPaddingResolved()) {
16142            resolvePadding();
16143        }
16144        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16145                mPaddingRight : mPaddingLeft;
16146    }
16147
16148    /**
16149     * Returns the right padding of this view. If there are inset and enabled
16150     * scrollbars, this value may include the space required to display the
16151     * scrollbars as well.
16152     *
16153     * @return the right padding in pixels
16154     */
16155    public int getPaddingRight() {
16156        if (!isPaddingResolved()) {
16157            resolvePadding();
16158        }
16159        return mPaddingRight;
16160    }
16161
16162    /**
16163     * Returns the end padding of this view depending on its resolved layout direction.
16164     * If there are inset and enabled scrollbars, this value may include the space
16165     * required to display the scrollbars as well.
16166     *
16167     * @return the end padding in pixels
16168     */
16169    public int getPaddingEnd() {
16170        if (!isPaddingResolved()) {
16171            resolvePadding();
16172        }
16173        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16174                mPaddingLeft : mPaddingRight;
16175    }
16176
16177    /**
16178     * Return if the padding as been set thru relative values
16179     * {@link #setPaddingRelative(int, int, int, int)} or thru
16180     * @attr ref android.R.styleable#View_paddingStart or
16181     * @attr ref android.R.styleable#View_paddingEnd
16182     *
16183     * @return true if the padding is relative or false if it is not.
16184     */
16185    public boolean isPaddingRelative() {
16186        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16187    }
16188
16189    Insets computeOpticalInsets() {
16190        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16191    }
16192
16193    /**
16194     * @hide
16195     */
16196    public void resetPaddingToInitialValues() {
16197        if (isRtlCompatibilityMode()) {
16198            mPaddingLeft = mUserPaddingLeftInitial;
16199            mPaddingRight = mUserPaddingRightInitial;
16200            return;
16201        }
16202        if (isLayoutRtl()) {
16203            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16204            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16205        } else {
16206            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16207            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16208        }
16209    }
16210
16211    /**
16212     * @hide
16213     */
16214    public Insets getOpticalInsets() {
16215        if (mLayoutInsets == null) {
16216            mLayoutInsets = computeOpticalInsets();
16217        }
16218        return mLayoutInsets;
16219    }
16220
16221    /**
16222     * Set this view's optical insets.
16223     *
16224     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16225     * property. Views that compute their own optical insets should call it as part of measurement.
16226     * This method does not request layout. If you are setting optical insets outside of
16227     * measure/layout itself you will want to call requestLayout() yourself.
16228     * </p>
16229     * @hide
16230     */
16231    public void setOpticalInsets(Insets insets) {
16232        mLayoutInsets = insets;
16233    }
16234
16235    /**
16236     * Changes the selection state of this view. A view can be selected or not.
16237     * Note that selection is not the same as focus. Views are typically
16238     * selected in the context of an AdapterView like ListView or GridView;
16239     * the selected view is the view that is highlighted.
16240     *
16241     * @param selected true if the view must be selected, false otherwise
16242     */
16243    public void setSelected(boolean selected) {
16244        //noinspection DoubleNegation
16245        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16246            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16247            if (!selected) resetPressedState();
16248            invalidate(true);
16249            refreshDrawableState();
16250            dispatchSetSelected(selected);
16251            notifyViewAccessibilityStateChangedIfNeeded(
16252                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16253        }
16254    }
16255
16256    /**
16257     * Dispatch setSelected to all of this View's children.
16258     *
16259     * @see #setSelected(boolean)
16260     *
16261     * @param selected The new selected state
16262     */
16263    protected void dispatchSetSelected(boolean selected) {
16264    }
16265
16266    /**
16267     * Indicates the selection state of this view.
16268     *
16269     * @return true if the view is selected, false otherwise
16270     */
16271    @ViewDebug.ExportedProperty
16272    public boolean isSelected() {
16273        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16274    }
16275
16276    /**
16277     * Changes the activated state of this view. A view can be activated or not.
16278     * Note that activation is not the same as selection.  Selection is
16279     * a transient property, representing the view (hierarchy) the user is
16280     * currently interacting with.  Activation is a longer-term state that the
16281     * user can move views in and out of.  For example, in a list view with
16282     * single or multiple selection enabled, the views in the current selection
16283     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16284     * here.)  The activated state is propagated down to children of the view it
16285     * is set on.
16286     *
16287     * @param activated true if the view must be activated, false otherwise
16288     */
16289    public void setActivated(boolean activated) {
16290        //noinspection DoubleNegation
16291        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16292            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16293            invalidate(true);
16294            refreshDrawableState();
16295            dispatchSetActivated(activated);
16296        }
16297    }
16298
16299    /**
16300     * Dispatch setActivated to all of this View's children.
16301     *
16302     * @see #setActivated(boolean)
16303     *
16304     * @param activated The new activated state
16305     */
16306    protected void dispatchSetActivated(boolean activated) {
16307    }
16308
16309    /**
16310     * Indicates the activation state of this view.
16311     *
16312     * @return true if the view is activated, false otherwise
16313     */
16314    @ViewDebug.ExportedProperty
16315    public boolean isActivated() {
16316        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16317    }
16318
16319    /**
16320     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16321     * observer can be used to get notifications when global events, like
16322     * layout, happen.
16323     *
16324     * The returned ViewTreeObserver observer is not guaranteed to remain
16325     * valid for the lifetime of this View. If the caller of this method keeps
16326     * a long-lived reference to ViewTreeObserver, it should always check for
16327     * the return value of {@link ViewTreeObserver#isAlive()}.
16328     *
16329     * @return The ViewTreeObserver for this view's hierarchy.
16330     */
16331    public ViewTreeObserver getViewTreeObserver() {
16332        if (mAttachInfo != null) {
16333            return mAttachInfo.mTreeObserver;
16334        }
16335        if (mFloatingTreeObserver == null) {
16336            mFloatingTreeObserver = new ViewTreeObserver();
16337        }
16338        return mFloatingTreeObserver;
16339    }
16340
16341    /**
16342     * <p>Finds the topmost view in the current view hierarchy.</p>
16343     *
16344     * @return the topmost view containing this view
16345     */
16346    public View getRootView() {
16347        if (mAttachInfo != null) {
16348            final View v = mAttachInfo.mRootView;
16349            if (v != null) {
16350                return v;
16351            }
16352        }
16353
16354        View parent = this;
16355
16356        while (parent.mParent != null && parent.mParent instanceof View) {
16357            parent = (View) parent.mParent;
16358        }
16359
16360        return parent;
16361    }
16362
16363    /**
16364     * Transforms a motion event from view-local coordinates to on-screen
16365     * coordinates.
16366     *
16367     * @param ev the view-local motion event
16368     * @return false if the transformation could not be applied
16369     * @hide
16370     */
16371    public boolean toGlobalMotionEvent(MotionEvent ev) {
16372        final AttachInfo info = mAttachInfo;
16373        if (info == null) {
16374            return false;
16375        }
16376
16377        final Matrix m = info.mTmpMatrix;
16378        m.set(Matrix.IDENTITY_MATRIX);
16379        transformMatrixToGlobal(m);
16380        ev.transform(m);
16381        return true;
16382    }
16383
16384    /**
16385     * Transforms a motion event from on-screen coordinates to view-local
16386     * coordinates.
16387     *
16388     * @param ev the on-screen motion event
16389     * @return false if the transformation could not be applied
16390     * @hide
16391     */
16392    public boolean toLocalMotionEvent(MotionEvent ev) {
16393        final AttachInfo info = mAttachInfo;
16394        if (info == null) {
16395            return false;
16396        }
16397
16398        final Matrix m = info.mTmpMatrix;
16399        m.set(Matrix.IDENTITY_MATRIX);
16400        transformMatrixToLocal(m);
16401        ev.transform(m);
16402        return true;
16403    }
16404
16405    /**
16406     * Modifies the input matrix such that it maps view-local coordinates to
16407     * on-screen coordinates.
16408     *
16409     * @param m input matrix to modify
16410     */
16411    void transformMatrixToGlobal(Matrix m) {
16412        final ViewParent parent = mParent;
16413        if (parent instanceof View) {
16414            final View vp = (View) parent;
16415            vp.transformMatrixToGlobal(m);
16416            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16417        } else if (parent instanceof ViewRootImpl) {
16418            final ViewRootImpl vr = (ViewRootImpl) parent;
16419            vr.transformMatrixToGlobal(m);
16420            m.postTranslate(0, -vr.mCurScrollY);
16421        }
16422
16423        m.postTranslate(mLeft, mTop);
16424
16425        if (!hasIdentityMatrix()) {
16426            m.postConcat(getMatrix());
16427        }
16428    }
16429
16430    /**
16431     * Modifies the input matrix such that it maps on-screen coordinates to
16432     * view-local coordinates.
16433     *
16434     * @param m input matrix to modify
16435     */
16436    void transformMatrixToLocal(Matrix m) {
16437        final ViewParent parent = mParent;
16438        if (parent instanceof View) {
16439            final View vp = (View) parent;
16440            vp.transformMatrixToLocal(m);
16441            m.preTranslate(vp.mScrollX, vp.mScrollY);
16442        } else if (parent instanceof ViewRootImpl) {
16443            final ViewRootImpl vr = (ViewRootImpl) parent;
16444            vr.transformMatrixToLocal(m);
16445            m.preTranslate(0, vr.mCurScrollY);
16446        }
16447
16448        m.preTranslate(-mLeft, -mTop);
16449
16450        if (!hasIdentityMatrix()) {
16451            m.preConcat(getInverseMatrix());
16452        }
16453    }
16454
16455    /**
16456     * <p>Computes the coordinates of this view on the screen. The argument
16457     * must be an array of two integers. After the method returns, the array
16458     * contains the x and y location in that order.</p>
16459     *
16460     * @param location an array of two integers in which to hold the coordinates
16461     */
16462    public void getLocationOnScreen(int[] location) {
16463        getLocationInWindow(location);
16464
16465        final AttachInfo info = mAttachInfo;
16466        if (info != null) {
16467            location[0] += info.mWindowLeft;
16468            location[1] += info.mWindowTop;
16469        }
16470    }
16471
16472    /**
16473     * <p>Computes the coordinates of this view in its window. The argument
16474     * must be an array of two integers. After the method returns, the array
16475     * contains the x and y location in that order.</p>
16476     *
16477     * @param location an array of two integers in which to hold the coordinates
16478     */
16479    public void getLocationInWindow(int[] location) {
16480        if (location == null || location.length < 2) {
16481            throw new IllegalArgumentException("location must be an array of two integers");
16482        }
16483
16484        if (mAttachInfo == null) {
16485            // When the view is not attached to a window, this method does not make sense
16486            location[0] = location[1] = 0;
16487            return;
16488        }
16489
16490        float[] position = mAttachInfo.mTmpTransformLocation;
16491        position[0] = position[1] = 0.0f;
16492
16493        if (!hasIdentityMatrix()) {
16494            getMatrix().mapPoints(position);
16495        }
16496
16497        position[0] += mLeft;
16498        position[1] += mTop;
16499
16500        ViewParent viewParent = mParent;
16501        while (viewParent instanceof View) {
16502            final View view = (View) viewParent;
16503
16504            position[0] -= view.mScrollX;
16505            position[1] -= view.mScrollY;
16506
16507            if (!view.hasIdentityMatrix()) {
16508                view.getMatrix().mapPoints(position);
16509            }
16510
16511            position[0] += view.mLeft;
16512            position[1] += view.mTop;
16513
16514            viewParent = view.mParent;
16515         }
16516
16517        if (viewParent instanceof ViewRootImpl) {
16518            // *cough*
16519            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16520            position[1] -= vr.mCurScrollY;
16521        }
16522
16523        location[0] = (int) (position[0] + 0.5f);
16524        location[1] = (int) (position[1] + 0.5f);
16525    }
16526
16527    /**
16528     * {@hide}
16529     * @param id the id of the view to be found
16530     * @return the view of the specified id, null if cannot be found
16531     */
16532    protected View findViewTraversal(int id) {
16533        if (id == mID) {
16534            return this;
16535        }
16536        return null;
16537    }
16538
16539    /**
16540     * {@hide}
16541     * @param tag the tag of the view to be found
16542     * @return the view of specified tag, null if cannot be found
16543     */
16544    protected View findViewWithTagTraversal(Object tag) {
16545        if (tag != null && tag.equals(mTag)) {
16546            return this;
16547        }
16548        return null;
16549    }
16550
16551    /**
16552     * {@hide}
16553     * @param predicate The predicate to evaluate.
16554     * @param childToSkip If not null, ignores this child during the recursive traversal.
16555     * @return The first view that matches the predicate or null.
16556     */
16557    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16558        if (predicate.apply(this)) {
16559            return this;
16560        }
16561        return null;
16562    }
16563
16564    /**
16565     * Look for a child view with the given id.  If this view has the given
16566     * id, return this view.
16567     *
16568     * @param id The id to search for.
16569     * @return The view that has the given id in the hierarchy or null
16570     */
16571    public final View findViewById(int id) {
16572        if (id < 0) {
16573            return null;
16574        }
16575        return findViewTraversal(id);
16576    }
16577
16578    /**
16579     * Finds a view by its unuque and stable accessibility id.
16580     *
16581     * @param accessibilityId The searched accessibility id.
16582     * @return The found view.
16583     */
16584    final View findViewByAccessibilityId(int accessibilityId) {
16585        if (accessibilityId < 0) {
16586            return null;
16587        }
16588        return findViewByAccessibilityIdTraversal(accessibilityId);
16589    }
16590
16591    /**
16592     * Performs the traversal to find a view by its unuque and stable accessibility id.
16593     *
16594     * <strong>Note:</strong>This method does not stop at the root namespace
16595     * boundary since the user can touch the screen at an arbitrary location
16596     * potentially crossing the root namespace bounday which will send an
16597     * accessibility event to accessibility services and they should be able
16598     * to obtain the event source. Also accessibility ids are guaranteed to be
16599     * unique in the window.
16600     *
16601     * @param accessibilityId The accessibility id.
16602     * @return The found view.
16603     *
16604     * @hide
16605     */
16606    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16607        if (getAccessibilityViewId() == accessibilityId) {
16608            return this;
16609        }
16610        return null;
16611    }
16612
16613    /**
16614     * Look for a child view with the given tag.  If this view has the given
16615     * tag, return this view.
16616     *
16617     * @param tag The tag to search for, using "tag.equals(getTag())".
16618     * @return The View that has the given tag in the hierarchy or null
16619     */
16620    public final View findViewWithTag(Object tag) {
16621        if (tag == null) {
16622            return null;
16623        }
16624        return findViewWithTagTraversal(tag);
16625    }
16626
16627    /**
16628     * {@hide}
16629     * Look for a child view that matches the specified predicate.
16630     * If this view matches the predicate, return this view.
16631     *
16632     * @param predicate The predicate to evaluate.
16633     * @return The first view that matches the predicate or null.
16634     */
16635    public final View findViewByPredicate(Predicate<View> predicate) {
16636        return findViewByPredicateTraversal(predicate, null);
16637    }
16638
16639    /**
16640     * {@hide}
16641     * Look for a child view that matches the specified predicate,
16642     * starting with the specified view and its descendents and then
16643     * recusively searching the ancestors and siblings of that view
16644     * until this view is reached.
16645     *
16646     * This method is useful in cases where the predicate does not match
16647     * a single unique view (perhaps multiple views use the same id)
16648     * and we are trying to find the view that is "closest" in scope to the
16649     * starting view.
16650     *
16651     * @param start The view to start from.
16652     * @param predicate The predicate to evaluate.
16653     * @return The first view that matches the predicate or null.
16654     */
16655    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16656        View childToSkip = null;
16657        for (;;) {
16658            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16659            if (view != null || start == this) {
16660                return view;
16661            }
16662
16663            ViewParent parent = start.getParent();
16664            if (parent == null || !(parent instanceof View)) {
16665                return null;
16666            }
16667
16668            childToSkip = start;
16669            start = (View) parent;
16670        }
16671    }
16672
16673    /**
16674     * Sets the identifier for this view. The identifier does not have to be
16675     * unique in this view's hierarchy. The identifier should be a positive
16676     * number.
16677     *
16678     * @see #NO_ID
16679     * @see #getId()
16680     * @see #findViewById(int)
16681     *
16682     * @param id a number used to identify the view
16683     *
16684     * @attr ref android.R.styleable#View_id
16685     */
16686    public void setId(int id) {
16687        mID = id;
16688        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16689            mID = generateViewId();
16690        }
16691    }
16692
16693    /**
16694     * {@hide}
16695     *
16696     * @param isRoot true if the view belongs to the root namespace, false
16697     *        otherwise
16698     */
16699    public void setIsRootNamespace(boolean isRoot) {
16700        if (isRoot) {
16701            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16702        } else {
16703            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16704        }
16705    }
16706
16707    /**
16708     * {@hide}
16709     *
16710     * @return true if the view belongs to the root namespace, false otherwise
16711     */
16712    public boolean isRootNamespace() {
16713        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16714    }
16715
16716    /**
16717     * Returns this view's identifier.
16718     *
16719     * @return a positive integer used to identify the view or {@link #NO_ID}
16720     *         if the view has no ID
16721     *
16722     * @see #setId(int)
16723     * @see #findViewById(int)
16724     * @attr ref android.R.styleable#View_id
16725     */
16726    @ViewDebug.CapturedViewProperty
16727    public int getId() {
16728        return mID;
16729    }
16730
16731    /**
16732     * Returns this view's tag.
16733     *
16734     * @return the Object stored in this view as a tag, or {@code null} if not
16735     *         set
16736     *
16737     * @see #setTag(Object)
16738     * @see #getTag(int)
16739     */
16740    @ViewDebug.ExportedProperty
16741    public Object getTag() {
16742        return mTag;
16743    }
16744
16745    /**
16746     * Sets the tag associated with this view. A tag can be used to mark
16747     * a view in its hierarchy and does not have to be unique within the
16748     * hierarchy. Tags can also be used to store data within a view without
16749     * resorting to another data structure.
16750     *
16751     * @param tag an Object to tag the view with
16752     *
16753     * @see #getTag()
16754     * @see #setTag(int, Object)
16755     */
16756    public void setTag(final Object tag) {
16757        mTag = tag;
16758    }
16759
16760    /**
16761     * Returns the tag associated with this view and the specified key.
16762     *
16763     * @param key The key identifying the tag
16764     *
16765     * @return the Object stored in this view as a tag, or {@code null} if not
16766     *         set
16767     *
16768     * @see #setTag(int, Object)
16769     * @see #getTag()
16770     */
16771    public Object getTag(int key) {
16772        if (mKeyedTags != null) return mKeyedTags.get(key);
16773        return null;
16774    }
16775
16776    /**
16777     * Sets a tag associated with this view and a key. A tag can be used
16778     * to mark a view in its hierarchy and does not have to be unique within
16779     * the hierarchy. Tags can also be used to store data within a view
16780     * without resorting to another data structure.
16781     *
16782     * The specified key should be an id declared in the resources of the
16783     * application to ensure it is unique (see the <a
16784     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16785     * Keys identified as belonging to
16786     * the Android framework or not associated with any package will cause
16787     * an {@link IllegalArgumentException} to be thrown.
16788     *
16789     * @param key The key identifying the tag
16790     * @param tag An Object to tag the view with
16791     *
16792     * @throws IllegalArgumentException If they specified key is not valid
16793     *
16794     * @see #setTag(Object)
16795     * @see #getTag(int)
16796     */
16797    public void setTag(int key, final Object tag) {
16798        // If the package id is 0x00 or 0x01, it's either an undefined package
16799        // or a framework id
16800        if ((key >>> 24) < 2) {
16801            throw new IllegalArgumentException("The key must be an application-specific "
16802                    + "resource id.");
16803        }
16804
16805        setKeyedTag(key, tag);
16806    }
16807
16808    /**
16809     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16810     * framework id.
16811     *
16812     * @hide
16813     */
16814    public void setTagInternal(int key, Object tag) {
16815        if ((key >>> 24) != 0x1) {
16816            throw new IllegalArgumentException("The key must be a framework-specific "
16817                    + "resource id.");
16818        }
16819
16820        setKeyedTag(key, tag);
16821    }
16822
16823    private void setKeyedTag(int key, Object tag) {
16824        if (mKeyedTags == null) {
16825            mKeyedTags = new SparseArray<Object>(2);
16826        }
16827
16828        mKeyedTags.put(key, tag);
16829    }
16830
16831    /**
16832     * Prints information about this view in the log output, with the tag
16833     * {@link #VIEW_LOG_TAG}.
16834     *
16835     * @hide
16836     */
16837    public void debug() {
16838        debug(0);
16839    }
16840
16841    /**
16842     * Prints information about this view in the log output, with the tag
16843     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16844     * indentation defined by the <code>depth</code>.
16845     *
16846     * @param depth the indentation level
16847     *
16848     * @hide
16849     */
16850    protected void debug(int depth) {
16851        String output = debugIndent(depth - 1);
16852
16853        output += "+ " + this;
16854        int id = getId();
16855        if (id != -1) {
16856            output += " (id=" + id + ")";
16857        }
16858        Object tag = getTag();
16859        if (tag != null) {
16860            output += " (tag=" + tag + ")";
16861        }
16862        Log.d(VIEW_LOG_TAG, output);
16863
16864        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16865            output = debugIndent(depth) + " FOCUSED";
16866            Log.d(VIEW_LOG_TAG, output);
16867        }
16868
16869        output = debugIndent(depth);
16870        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16871                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16872                + "} ";
16873        Log.d(VIEW_LOG_TAG, output);
16874
16875        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16876                || mPaddingBottom != 0) {
16877            output = debugIndent(depth);
16878            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16879                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16880            Log.d(VIEW_LOG_TAG, output);
16881        }
16882
16883        output = debugIndent(depth);
16884        output += "mMeasureWidth=" + mMeasuredWidth +
16885                " mMeasureHeight=" + mMeasuredHeight;
16886        Log.d(VIEW_LOG_TAG, output);
16887
16888        output = debugIndent(depth);
16889        if (mLayoutParams == null) {
16890            output += "BAD! no layout params";
16891        } else {
16892            output = mLayoutParams.debug(output);
16893        }
16894        Log.d(VIEW_LOG_TAG, output);
16895
16896        output = debugIndent(depth);
16897        output += "flags={";
16898        output += View.printFlags(mViewFlags);
16899        output += "}";
16900        Log.d(VIEW_LOG_TAG, output);
16901
16902        output = debugIndent(depth);
16903        output += "privateFlags={";
16904        output += View.printPrivateFlags(mPrivateFlags);
16905        output += "}";
16906        Log.d(VIEW_LOG_TAG, output);
16907    }
16908
16909    /**
16910     * Creates a string of whitespaces used for indentation.
16911     *
16912     * @param depth the indentation level
16913     * @return a String containing (depth * 2 + 3) * 2 white spaces
16914     *
16915     * @hide
16916     */
16917    protected static String debugIndent(int depth) {
16918        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16919        for (int i = 0; i < (depth * 2) + 3; i++) {
16920            spaces.append(' ').append(' ');
16921        }
16922        return spaces.toString();
16923    }
16924
16925    /**
16926     * <p>Return the offset of the widget's text baseline from the widget's top
16927     * boundary. If this widget does not support baseline alignment, this
16928     * method returns -1. </p>
16929     *
16930     * @return the offset of the baseline within the widget's bounds or -1
16931     *         if baseline alignment is not supported
16932     */
16933    @ViewDebug.ExportedProperty(category = "layout")
16934    public int getBaseline() {
16935        return -1;
16936    }
16937
16938    /**
16939     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16940     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16941     * a layout pass.
16942     *
16943     * @return whether the view hierarchy is currently undergoing a layout pass
16944     */
16945    public boolean isInLayout() {
16946        ViewRootImpl viewRoot = getViewRootImpl();
16947        return (viewRoot != null && viewRoot.isInLayout());
16948    }
16949
16950    /**
16951     * Call this when something has changed which has invalidated the
16952     * layout of this view. This will schedule a layout pass of the view
16953     * tree. This should not be called while the view hierarchy is currently in a layout
16954     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16955     * end of the current layout pass (and then layout will run again) or after the current
16956     * frame is drawn and the next layout occurs.
16957     *
16958     * <p>Subclasses which override this method should call the superclass method to
16959     * handle possible request-during-layout errors correctly.</p>
16960     */
16961    public void requestLayout() {
16962        if (mMeasureCache != null) mMeasureCache.clear();
16963
16964        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16965            // Only trigger request-during-layout logic if this is the view requesting it,
16966            // not the views in its parent hierarchy
16967            ViewRootImpl viewRoot = getViewRootImpl();
16968            if (viewRoot != null && viewRoot.isInLayout()) {
16969                if (!viewRoot.requestLayoutDuringLayout(this)) {
16970                    return;
16971                }
16972            }
16973            mAttachInfo.mViewRequestingLayout = this;
16974        }
16975
16976        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16977        mPrivateFlags |= PFLAG_INVALIDATED;
16978
16979        if (mParent != null && !mParent.isLayoutRequested()) {
16980            mParent.requestLayout();
16981        }
16982        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16983            mAttachInfo.mViewRequestingLayout = null;
16984        }
16985    }
16986
16987    /**
16988     * Forces this view to be laid out during the next layout pass.
16989     * This method does not call requestLayout() or forceLayout()
16990     * on the parent.
16991     */
16992    public void forceLayout() {
16993        if (mMeasureCache != null) mMeasureCache.clear();
16994
16995        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16996        mPrivateFlags |= PFLAG_INVALIDATED;
16997    }
16998
16999    /**
17000     * <p>
17001     * This is called to find out how big a view should be. The parent
17002     * supplies constraint information in the width and height parameters.
17003     * </p>
17004     *
17005     * <p>
17006     * The actual measurement work of a view is performed in
17007     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17008     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17009     * </p>
17010     *
17011     *
17012     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17013     *        parent
17014     * @param heightMeasureSpec Vertical space requirements as imposed by the
17015     *        parent
17016     *
17017     * @see #onMeasure(int, int)
17018     */
17019    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17020        boolean optical = isLayoutModeOptical(this);
17021        if (optical != isLayoutModeOptical(mParent)) {
17022            Insets insets = getOpticalInsets();
17023            int oWidth  = insets.left + insets.right;
17024            int oHeight = insets.top  + insets.bottom;
17025            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17026            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17027        }
17028
17029        // Suppress sign extension for the low bytes
17030        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17031        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17032
17033        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17034                widthMeasureSpec != mOldWidthMeasureSpec ||
17035                heightMeasureSpec != mOldHeightMeasureSpec) {
17036
17037            // first clears the measured dimension flag
17038            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17039
17040            resolveRtlPropertiesIfNeeded();
17041
17042            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17043                    mMeasureCache.indexOfKey(key);
17044            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17045                // measure ourselves, this should set the measured dimension flag back
17046                onMeasure(widthMeasureSpec, heightMeasureSpec);
17047                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17048            } else {
17049                long value = mMeasureCache.valueAt(cacheIndex);
17050                // Casting a long to int drops the high 32 bits, no mask needed
17051                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17052                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17053            }
17054
17055            // flag not set, setMeasuredDimension() was not invoked, we raise
17056            // an exception to warn the developer
17057            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17058                throw new IllegalStateException("onMeasure() did not set the"
17059                        + " measured dimension by calling"
17060                        + " setMeasuredDimension()");
17061            }
17062
17063            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17064        }
17065
17066        mOldWidthMeasureSpec = widthMeasureSpec;
17067        mOldHeightMeasureSpec = heightMeasureSpec;
17068
17069        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17070                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17071    }
17072
17073    /**
17074     * <p>
17075     * Measure the view and its content to determine the measured width and the
17076     * measured height. This method is invoked by {@link #measure(int, int)} and
17077     * should be overriden by subclasses to provide accurate and efficient
17078     * measurement of their contents.
17079     * </p>
17080     *
17081     * <p>
17082     * <strong>CONTRACT:</strong> When overriding this method, you
17083     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17084     * measured width and height of this view. Failure to do so will trigger an
17085     * <code>IllegalStateException</code>, thrown by
17086     * {@link #measure(int, int)}. Calling the superclass'
17087     * {@link #onMeasure(int, int)} is a valid use.
17088     * </p>
17089     *
17090     * <p>
17091     * The base class implementation of measure defaults to the background size,
17092     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17093     * override {@link #onMeasure(int, int)} to provide better measurements of
17094     * their content.
17095     * </p>
17096     *
17097     * <p>
17098     * If this method is overridden, it is the subclass's responsibility to make
17099     * sure the measured height and width are at least the view's minimum height
17100     * and width ({@link #getSuggestedMinimumHeight()} and
17101     * {@link #getSuggestedMinimumWidth()}).
17102     * </p>
17103     *
17104     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17105     *                         The requirements are encoded with
17106     *                         {@link android.view.View.MeasureSpec}.
17107     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17108     *                         The requirements are encoded with
17109     *                         {@link android.view.View.MeasureSpec}.
17110     *
17111     * @see #getMeasuredWidth()
17112     * @see #getMeasuredHeight()
17113     * @see #setMeasuredDimension(int, int)
17114     * @see #getSuggestedMinimumHeight()
17115     * @see #getSuggestedMinimumWidth()
17116     * @see android.view.View.MeasureSpec#getMode(int)
17117     * @see android.view.View.MeasureSpec#getSize(int)
17118     */
17119    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17120        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17121                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17122    }
17123
17124    /**
17125     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17126     * measured width and measured height. Failing to do so will trigger an
17127     * exception at measurement time.</p>
17128     *
17129     * @param measuredWidth The measured width of this view.  May be a complex
17130     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17131     * {@link #MEASURED_STATE_TOO_SMALL}.
17132     * @param measuredHeight The measured height of this view.  May be a complex
17133     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17134     * {@link #MEASURED_STATE_TOO_SMALL}.
17135     */
17136    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17137        boolean optical = isLayoutModeOptical(this);
17138        if (optical != isLayoutModeOptical(mParent)) {
17139            Insets insets = getOpticalInsets();
17140            int opticalWidth  = insets.left + insets.right;
17141            int opticalHeight = insets.top  + insets.bottom;
17142
17143            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17144            measuredHeight += optical ? opticalHeight : -opticalHeight;
17145        }
17146        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17147    }
17148
17149    /**
17150     * Sets the measured dimension without extra processing for things like optical bounds.
17151     * Useful for reapplying consistent values that have already been cooked with adjustments
17152     * for optical bounds, etc. such as those from the measurement cache.
17153     *
17154     * @param measuredWidth The measured width of this view.  May be a complex
17155     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17156     * {@link #MEASURED_STATE_TOO_SMALL}.
17157     * @param measuredHeight The measured height of this view.  May be a complex
17158     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17159     * {@link #MEASURED_STATE_TOO_SMALL}.
17160     */
17161    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17162        mMeasuredWidth = measuredWidth;
17163        mMeasuredHeight = measuredHeight;
17164
17165        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17166    }
17167
17168    /**
17169     * Merge two states as returned by {@link #getMeasuredState()}.
17170     * @param curState The current state as returned from a view or the result
17171     * of combining multiple views.
17172     * @param newState The new view state to combine.
17173     * @return Returns a new integer reflecting the combination of the two
17174     * states.
17175     */
17176    public static int combineMeasuredStates(int curState, int newState) {
17177        return curState | newState;
17178    }
17179
17180    /**
17181     * Version of {@link #resolveSizeAndState(int, int, int)}
17182     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17183     */
17184    public static int resolveSize(int size, int measureSpec) {
17185        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17186    }
17187
17188    /**
17189     * Utility to reconcile a desired size and state, with constraints imposed
17190     * by a MeasureSpec.  Will take the desired size, unless a different size
17191     * is imposed by the constraints.  The returned value is a compound integer,
17192     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17193     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17194     * size is smaller than the size the view wants to be.
17195     *
17196     * @param size How big the view wants to be
17197     * @param measureSpec Constraints imposed by the parent
17198     * @return Size information bit mask as defined by
17199     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17200     */
17201    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17202        int result = size;
17203        int specMode = MeasureSpec.getMode(measureSpec);
17204        int specSize =  MeasureSpec.getSize(measureSpec);
17205        switch (specMode) {
17206        case MeasureSpec.UNSPECIFIED:
17207            result = size;
17208            break;
17209        case MeasureSpec.AT_MOST:
17210            if (specSize < size) {
17211                result = specSize | MEASURED_STATE_TOO_SMALL;
17212            } else {
17213                result = size;
17214            }
17215            break;
17216        case MeasureSpec.EXACTLY:
17217            result = specSize;
17218            break;
17219        }
17220        return result | (childMeasuredState&MEASURED_STATE_MASK);
17221    }
17222
17223    /**
17224     * Utility to return a default size. Uses the supplied size if the
17225     * MeasureSpec imposed no constraints. Will get larger if allowed
17226     * by the MeasureSpec.
17227     *
17228     * @param size Default size for this view
17229     * @param measureSpec Constraints imposed by the parent
17230     * @return The size this view should be.
17231     */
17232    public static int getDefaultSize(int size, int measureSpec) {
17233        int result = size;
17234        int specMode = MeasureSpec.getMode(measureSpec);
17235        int specSize = MeasureSpec.getSize(measureSpec);
17236
17237        switch (specMode) {
17238        case MeasureSpec.UNSPECIFIED:
17239            result = size;
17240            break;
17241        case MeasureSpec.AT_MOST:
17242        case MeasureSpec.EXACTLY:
17243            result = specSize;
17244            break;
17245        }
17246        return result;
17247    }
17248
17249    /**
17250     * Returns the suggested minimum height that the view should use. This
17251     * returns the maximum of the view's minimum height
17252     * and the background's minimum height
17253     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17254     * <p>
17255     * When being used in {@link #onMeasure(int, int)}, the caller should still
17256     * ensure the returned height is within the requirements of the parent.
17257     *
17258     * @return The suggested minimum height of the view.
17259     */
17260    protected int getSuggestedMinimumHeight() {
17261        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17262
17263    }
17264
17265    /**
17266     * Returns the suggested minimum width that the view should use. This
17267     * returns the maximum of the view's minimum width)
17268     * and the background's minimum width
17269     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17270     * <p>
17271     * When being used in {@link #onMeasure(int, int)}, the caller should still
17272     * ensure the returned width is within the requirements of the parent.
17273     *
17274     * @return The suggested minimum width of the view.
17275     */
17276    protected int getSuggestedMinimumWidth() {
17277        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17278    }
17279
17280    /**
17281     * Returns the minimum height of the view.
17282     *
17283     * @return the minimum height the view will try to be.
17284     *
17285     * @see #setMinimumHeight(int)
17286     *
17287     * @attr ref android.R.styleable#View_minHeight
17288     */
17289    public int getMinimumHeight() {
17290        return mMinHeight;
17291    }
17292
17293    /**
17294     * Sets the minimum height of the view. It is not guaranteed the view will
17295     * be able to achieve this minimum height (for example, if its parent layout
17296     * constrains it with less available height).
17297     *
17298     * @param minHeight The minimum height the view will try to be.
17299     *
17300     * @see #getMinimumHeight()
17301     *
17302     * @attr ref android.R.styleable#View_minHeight
17303     */
17304    public void setMinimumHeight(int minHeight) {
17305        mMinHeight = minHeight;
17306        requestLayout();
17307    }
17308
17309    /**
17310     * Returns the minimum width of the view.
17311     *
17312     * @return the minimum width the view will try to be.
17313     *
17314     * @see #setMinimumWidth(int)
17315     *
17316     * @attr ref android.R.styleable#View_minWidth
17317     */
17318    public int getMinimumWidth() {
17319        return mMinWidth;
17320    }
17321
17322    /**
17323     * Sets the minimum width of the view. It is not guaranteed the view will
17324     * be able to achieve this minimum width (for example, if its parent layout
17325     * constrains it with less available width).
17326     *
17327     * @param minWidth The minimum width the view will try to be.
17328     *
17329     * @see #getMinimumWidth()
17330     *
17331     * @attr ref android.R.styleable#View_minWidth
17332     */
17333    public void setMinimumWidth(int minWidth) {
17334        mMinWidth = minWidth;
17335        requestLayout();
17336
17337    }
17338
17339    /**
17340     * Get the animation currently associated with this view.
17341     *
17342     * @return The animation that is currently playing or
17343     *         scheduled to play for this view.
17344     */
17345    public Animation getAnimation() {
17346        return mCurrentAnimation;
17347    }
17348
17349    /**
17350     * Start the specified animation now.
17351     *
17352     * @param animation the animation to start now
17353     */
17354    public void startAnimation(Animation animation) {
17355        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17356        setAnimation(animation);
17357        invalidateParentCaches();
17358        invalidate(true);
17359    }
17360
17361    /**
17362     * Cancels any animations for this view.
17363     */
17364    public void clearAnimation() {
17365        if (mCurrentAnimation != null) {
17366            mCurrentAnimation.detach();
17367        }
17368        mCurrentAnimation = null;
17369        invalidateParentIfNeeded();
17370    }
17371
17372    /**
17373     * Sets the next animation to play for this view.
17374     * If you want the animation to play immediately, use
17375     * {@link #startAnimation(android.view.animation.Animation)} instead.
17376     * This method provides allows fine-grained
17377     * control over the start time and invalidation, but you
17378     * must make sure that 1) the animation has a start time set, and
17379     * 2) the view's parent (which controls animations on its children)
17380     * will be invalidated when the animation is supposed to
17381     * start.
17382     *
17383     * @param animation The next animation, or null.
17384     */
17385    public void setAnimation(Animation animation) {
17386        mCurrentAnimation = animation;
17387
17388        if (animation != null) {
17389            // If the screen is off assume the animation start time is now instead of
17390            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17391            // would cause the animation to start when the screen turns back on
17392            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17393                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17394                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17395            }
17396            animation.reset();
17397        }
17398    }
17399
17400    /**
17401     * Invoked by a parent ViewGroup to notify the start of the animation
17402     * currently associated with this view. If you override this method,
17403     * always call super.onAnimationStart();
17404     *
17405     * @see #setAnimation(android.view.animation.Animation)
17406     * @see #getAnimation()
17407     */
17408    protected void onAnimationStart() {
17409        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17410    }
17411
17412    /**
17413     * Invoked by a parent ViewGroup to notify the end of the animation
17414     * currently associated with this view. If you override this method,
17415     * always call super.onAnimationEnd();
17416     *
17417     * @see #setAnimation(android.view.animation.Animation)
17418     * @see #getAnimation()
17419     */
17420    protected void onAnimationEnd() {
17421        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17422    }
17423
17424    /**
17425     * Invoked if there is a Transform that involves alpha. Subclass that can
17426     * draw themselves with the specified alpha should return true, and then
17427     * respect that alpha when their onDraw() is called. If this returns false
17428     * then the view may be redirected to draw into an offscreen buffer to
17429     * fulfill the request, which will look fine, but may be slower than if the
17430     * subclass handles it internally. The default implementation returns false.
17431     *
17432     * @param alpha The alpha (0..255) to apply to the view's drawing
17433     * @return true if the view can draw with the specified alpha.
17434     */
17435    protected boolean onSetAlpha(int alpha) {
17436        return false;
17437    }
17438
17439    /**
17440     * This is used by the RootView to perform an optimization when
17441     * the view hierarchy contains one or several SurfaceView.
17442     * SurfaceView is always considered transparent, but its children are not,
17443     * therefore all View objects remove themselves from the global transparent
17444     * region (passed as a parameter to this function).
17445     *
17446     * @param region The transparent region for this ViewAncestor (window).
17447     *
17448     * @return Returns true if the effective visibility of the view at this
17449     * point is opaque, regardless of the transparent region; returns false
17450     * if it is possible for underlying windows to be seen behind the view.
17451     *
17452     * {@hide}
17453     */
17454    public boolean gatherTransparentRegion(Region region) {
17455        final AttachInfo attachInfo = mAttachInfo;
17456        if (region != null && attachInfo != null) {
17457            final int pflags = mPrivateFlags;
17458            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17459                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17460                // remove it from the transparent region.
17461                final int[] location = attachInfo.mTransparentLocation;
17462                getLocationInWindow(location);
17463                region.op(location[0], location[1], location[0] + mRight - mLeft,
17464                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17465            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17466                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17467                // exists, so we remove the background drawable's non-transparent
17468                // parts from this transparent region.
17469                applyDrawableToTransparentRegion(mBackground, region);
17470            }
17471        }
17472        return true;
17473    }
17474
17475    /**
17476     * Play a sound effect for this view.
17477     *
17478     * <p>The framework will play sound effects for some built in actions, such as
17479     * clicking, but you may wish to play these effects in your widget,
17480     * for instance, for internal navigation.
17481     *
17482     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17483     * {@link #isSoundEffectsEnabled()} is true.
17484     *
17485     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17486     */
17487    public void playSoundEffect(int soundConstant) {
17488        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17489            return;
17490        }
17491        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17492    }
17493
17494    /**
17495     * BZZZTT!!1!
17496     *
17497     * <p>Provide haptic feedback to the user for this view.
17498     *
17499     * <p>The framework will provide haptic feedback for some built in actions,
17500     * such as long presses, but you may wish to provide feedback for your
17501     * own widget.
17502     *
17503     * <p>The feedback will only be performed if
17504     * {@link #isHapticFeedbackEnabled()} is true.
17505     *
17506     * @param feedbackConstant One of the constants defined in
17507     * {@link HapticFeedbackConstants}
17508     */
17509    public boolean performHapticFeedback(int feedbackConstant) {
17510        return performHapticFeedback(feedbackConstant, 0);
17511    }
17512
17513    /**
17514     * BZZZTT!!1!
17515     *
17516     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17517     *
17518     * @param feedbackConstant One of the constants defined in
17519     * {@link HapticFeedbackConstants}
17520     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17521     */
17522    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17523        if (mAttachInfo == null) {
17524            return false;
17525        }
17526        //noinspection SimplifiableIfStatement
17527        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17528                && !isHapticFeedbackEnabled()) {
17529            return false;
17530        }
17531        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17532                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17533    }
17534
17535    /**
17536     * Request that the visibility of the status bar or other screen/window
17537     * decorations be changed.
17538     *
17539     * <p>This method is used to put the over device UI into temporary modes
17540     * where the user's attention is focused more on the application content,
17541     * by dimming or hiding surrounding system affordances.  This is typically
17542     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17543     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17544     * to be placed behind the action bar (and with these flags other system
17545     * affordances) so that smooth transitions between hiding and showing them
17546     * can be done.
17547     *
17548     * <p>Two representative examples of the use of system UI visibility is
17549     * implementing a content browsing application (like a magazine reader)
17550     * and a video playing application.
17551     *
17552     * <p>The first code shows a typical implementation of a View in a content
17553     * browsing application.  In this implementation, the application goes
17554     * into a content-oriented mode by hiding the status bar and action bar,
17555     * and putting the navigation elements into lights out mode.  The user can
17556     * then interact with content while in this mode.  Such an application should
17557     * provide an easy way for the user to toggle out of the mode (such as to
17558     * check information in the status bar or access notifications).  In the
17559     * implementation here, this is done simply by tapping on the content.
17560     *
17561     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17562     *      content}
17563     *
17564     * <p>This second code sample shows a typical implementation of a View
17565     * in a video playing application.  In this situation, while the video is
17566     * playing the application would like to go into a complete full-screen mode,
17567     * to use as much of the display as possible for the video.  When in this state
17568     * the user can not interact with the application; the system intercepts
17569     * touching on the screen to pop the UI out of full screen mode.  See
17570     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17571     *
17572     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17573     *      content}
17574     *
17575     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17576     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17577     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17578     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17579     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17580     */
17581    public void setSystemUiVisibility(int visibility) {
17582        if (visibility != mSystemUiVisibility) {
17583            mSystemUiVisibility = visibility;
17584            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17585                mParent.recomputeViewAttributes(this);
17586            }
17587        }
17588    }
17589
17590    /**
17591     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17592     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17593     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17594     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17595     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17596     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17597     */
17598    public int getSystemUiVisibility() {
17599        return mSystemUiVisibility;
17600    }
17601
17602    /**
17603     * Returns the current system UI visibility that is currently set for
17604     * the entire window.  This is the combination of the
17605     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17606     * views in the window.
17607     */
17608    public int getWindowSystemUiVisibility() {
17609        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17610    }
17611
17612    /**
17613     * Override to find out when the window's requested system UI visibility
17614     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17615     * This is different from the callbacks received through
17616     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17617     * in that this is only telling you about the local request of the window,
17618     * not the actual values applied by the system.
17619     */
17620    public void onWindowSystemUiVisibilityChanged(int visible) {
17621    }
17622
17623    /**
17624     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17625     * the view hierarchy.
17626     */
17627    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17628        onWindowSystemUiVisibilityChanged(visible);
17629    }
17630
17631    /**
17632     * Set a listener to receive callbacks when the visibility of the system bar changes.
17633     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17634     */
17635    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17636        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17637        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17638            mParent.recomputeViewAttributes(this);
17639        }
17640    }
17641
17642    /**
17643     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17644     * the view hierarchy.
17645     */
17646    public void dispatchSystemUiVisibilityChanged(int visibility) {
17647        ListenerInfo li = mListenerInfo;
17648        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17649            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17650                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17651        }
17652    }
17653
17654    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17655        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17656        if (val != mSystemUiVisibility) {
17657            setSystemUiVisibility(val);
17658            return true;
17659        }
17660        return false;
17661    }
17662
17663    /** @hide */
17664    public void setDisabledSystemUiVisibility(int flags) {
17665        if (mAttachInfo != null) {
17666            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17667                mAttachInfo.mDisabledSystemUiVisibility = flags;
17668                if (mParent != null) {
17669                    mParent.recomputeViewAttributes(this);
17670                }
17671            }
17672        }
17673    }
17674
17675    /**
17676     * Creates an image that the system displays during the drag and drop
17677     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17678     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17679     * appearance as the given View. The default also positions the center of the drag shadow
17680     * directly under the touch point. If no View is provided (the constructor with no parameters
17681     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17682     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17683     * default is an invisible drag shadow.
17684     * <p>
17685     * You are not required to use the View you provide to the constructor as the basis of the
17686     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17687     * anything you want as the drag shadow.
17688     * </p>
17689     * <p>
17690     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17691     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17692     *  size and position of the drag shadow. It uses this data to construct a
17693     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17694     *  so that your application can draw the shadow image in the Canvas.
17695     * </p>
17696     *
17697     * <div class="special reference">
17698     * <h3>Developer Guides</h3>
17699     * <p>For a guide to implementing drag and drop features, read the
17700     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17701     * </div>
17702     */
17703    public static class DragShadowBuilder {
17704        private final WeakReference<View> mView;
17705
17706        /**
17707         * Constructs a shadow image builder based on a View. By default, the resulting drag
17708         * shadow will have the same appearance and dimensions as the View, with the touch point
17709         * over the center of the View.
17710         * @param view A View. Any View in scope can be used.
17711         */
17712        public DragShadowBuilder(View view) {
17713            mView = new WeakReference<View>(view);
17714        }
17715
17716        /**
17717         * Construct a shadow builder object with no associated View.  This
17718         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17719         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17720         * to supply the drag shadow's dimensions and appearance without
17721         * reference to any View object. If they are not overridden, then the result is an
17722         * invisible drag shadow.
17723         */
17724        public DragShadowBuilder() {
17725            mView = new WeakReference<View>(null);
17726        }
17727
17728        /**
17729         * Returns the View object that had been passed to the
17730         * {@link #View.DragShadowBuilder(View)}
17731         * constructor.  If that View parameter was {@code null} or if the
17732         * {@link #View.DragShadowBuilder()}
17733         * constructor was used to instantiate the builder object, this method will return
17734         * null.
17735         *
17736         * @return The View object associate with this builder object.
17737         */
17738        @SuppressWarnings({"JavadocReference"})
17739        final public View getView() {
17740            return mView.get();
17741        }
17742
17743        /**
17744         * Provides the metrics for the shadow image. These include the dimensions of
17745         * the shadow image, and the point within that shadow that should
17746         * be centered under the touch location while dragging.
17747         * <p>
17748         * The default implementation sets the dimensions of the shadow to be the
17749         * same as the dimensions of the View itself and centers the shadow under
17750         * the touch point.
17751         * </p>
17752         *
17753         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17754         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17755         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17756         * image.
17757         *
17758         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17759         * shadow image that should be underneath the touch point during the drag and drop
17760         * operation. Your application must set {@link android.graphics.Point#x} to the
17761         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17762         */
17763        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17764            final View view = mView.get();
17765            if (view != null) {
17766                shadowSize.set(view.getWidth(), view.getHeight());
17767                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17768            } else {
17769                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17770            }
17771        }
17772
17773        /**
17774         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17775         * based on the dimensions it received from the
17776         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17777         *
17778         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17779         */
17780        public void onDrawShadow(Canvas canvas) {
17781            final View view = mView.get();
17782            if (view != null) {
17783                view.draw(canvas);
17784            } else {
17785                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17786            }
17787        }
17788    }
17789
17790    /**
17791     * Starts a drag and drop operation. When your application calls this method, it passes a
17792     * {@link android.view.View.DragShadowBuilder} object to the system. The
17793     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17794     * to get metrics for the drag shadow, and then calls the object's
17795     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17796     * <p>
17797     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17798     *  drag events to all the View objects in your application that are currently visible. It does
17799     *  this either by calling the View object's drag listener (an implementation of
17800     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17801     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17802     *  Both are passed a {@link android.view.DragEvent} object that has a
17803     *  {@link android.view.DragEvent#getAction()} value of
17804     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17805     * </p>
17806     * <p>
17807     * Your application can invoke startDrag() on any attached View object. The View object does not
17808     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17809     * be related to the View the user selected for dragging.
17810     * </p>
17811     * @param data A {@link android.content.ClipData} object pointing to the data to be
17812     * transferred by the drag and drop operation.
17813     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17814     * drag shadow.
17815     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17816     * drop operation. This Object is put into every DragEvent object sent by the system during the
17817     * current drag.
17818     * <p>
17819     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17820     * to the target Views. For example, it can contain flags that differentiate between a
17821     * a copy operation and a move operation.
17822     * </p>
17823     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17824     * so the parameter should be set to 0.
17825     * @return {@code true} if the method completes successfully, or
17826     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17827     * do a drag, and so no drag operation is in progress.
17828     */
17829    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17830            Object myLocalState, int flags) {
17831        if (ViewDebug.DEBUG_DRAG) {
17832            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17833        }
17834        boolean okay = false;
17835
17836        Point shadowSize = new Point();
17837        Point shadowTouchPoint = new Point();
17838        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17839
17840        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17841                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17842            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17843        }
17844
17845        if (ViewDebug.DEBUG_DRAG) {
17846            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17847                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17848        }
17849        Surface surface = new Surface();
17850        try {
17851            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17852                    flags, shadowSize.x, shadowSize.y, surface);
17853            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17854                    + " surface=" + surface);
17855            if (token != null) {
17856                Canvas canvas = surface.lockCanvas(null);
17857                try {
17858                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17859                    shadowBuilder.onDrawShadow(canvas);
17860                } finally {
17861                    surface.unlockCanvasAndPost(canvas);
17862                }
17863
17864                final ViewRootImpl root = getViewRootImpl();
17865
17866                // Cache the local state object for delivery with DragEvents
17867                root.setLocalDragState(myLocalState);
17868
17869                // repurpose 'shadowSize' for the last touch point
17870                root.getLastTouchPoint(shadowSize);
17871
17872                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17873                        shadowSize.x, shadowSize.y,
17874                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17875                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17876
17877                // Off and running!  Release our local surface instance; the drag
17878                // shadow surface is now managed by the system process.
17879                surface.release();
17880            }
17881        } catch (Exception e) {
17882            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17883            surface.destroy();
17884        }
17885
17886        return okay;
17887    }
17888
17889    /**
17890     * Handles drag events sent by the system following a call to
17891     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17892     *<p>
17893     * When the system calls this method, it passes a
17894     * {@link android.view.DragEvent} object. A call to
17895     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17896     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17897     * operation.
17898     * @param event The {@link android.view.DragEvent} sent by the system.
17899     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17900     * in DragEvent, indicating the type of drag event represented by this object.
17901     * @return {@code true} if the method was successful, otherwise {@code false}.
17902     * <p>
17903     *  The method should return {@code true} in response to an action type of
17904     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17905     *  operation.
17906     * </p>
17907     * <p>
17908     *  The method should also return {@code true} in response to an action type of
17909     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17910     *  {@code false} if it didn't.
17911     * </p>
17912     */
17913    public boolean onDragEvent(DragEvent event) {
17914        return false;
17915    }
17916
17917    /**
17918     * Detects if this View is enabled and has a drag event listener.
17919     * If both are true, then it calls the drag event listener with the
17920     * {@link android.view.DragEvent} it received. If the drag event listener returns
17921     * {@code true}, then dispatchDragEvent() returns {@code true}.
17922     * <p>
17923     * For all other cases, the method calls the
17924     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17925     * method and returns its result.
17926     * </p>
17927     * <p>
17928     * This ensures that a drag event is always consumed, even if the View does not have a drag
17929     * event listener. However, if the View has a listener and the listener returns true, then
17930     * onDragEvent() is not called.
17931     * </p>
17932     */
17933    public boolean dispatchDragEvent(DragEvent event) {
17934        ListenerInfo li = mListenerInfo;
17935        //noinspection SimplifiableIfStatement
17936        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17937                && li.mOnDragListener.onDrag(this, event)) {
17938            return true;
17939        }
17940        return onDragEvent(event);
17941    }
17942
17943    boolean canAcceptDrag() {
17944        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17945    }
17946
17947    /**
17948     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17949     * it is ever exposed at all.
17950     * @hide
17951     */
17952    public void onCloseSystemDialogs(String reason) {
17953    }
17954
17955    /**
17956     * Given a Drawable whose bounds have been set to draw into this view,
17957     * update a Region being computed for
17958     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17959     * that any non-transparent parts of the Drawable are removed from the
17960     * given transparent region.
17961     *
17962     * @param dr The Drawable whose transparency is to be applied to the region.
17963     * @param region A Region holding the current transparency information,
17964     * where any parts of the region that are set are considered to be
17965     * transparent.  On return, this region will be modified to have the
17966     * transparency information reduced by the corresponding parts of the
17967     * Drawable that are not transparent.
17968     * {@hide}
17969     */
17970    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17971        if (DBG) {
17972            Log.i("View", "Getting transparent region for: " + this);
17973        }
17974        final Region r = dr.getTransparentRegion();
17975        final Rect db = dr.getBounds();
17976        final AttachInfo attachInfo = mAttachInfo;
17977        if (r != null && attachInfo != null) {
17978            final int w = getRight()-getLeft();
17979            final int h = getBottom()-getTop();
17980            if (db.left > 0) {
17981                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17982                r.op(0, 0, db.left, h, Region.Op.UNION);
17983            }
17984            if (db.right < w) {
17985                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17986                r.op(db.right, 0, w, h, Region.Op.UNION);
17987            }
17988            if (db.top > 0) {
17989                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17990                r.op(0, 0, w, db.top, Region.Op.UNION);
17991            }
17992            if (db.bottom < h) {
17993                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17994                r.op(0, db.bottom, w, h, Region.Op.UNION);
17995            }
17996            final int[] location = attachInfo.mTransparentLocation;
17997            getLocationInWindow(location);
17998            r.translate(location[0], location[1]);
17999            region.op(r, Region.Op.INTERSECT);
18000        } else {
18001            region.op(db, Region.Op.DIFFERENCE);
18002        }
18003    }
18004
18005    private void checkForLongClick(int delayOffset) {
18006        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18007            mHasPerformedLongPress = false;
18008
18009            if (mPendingCheckForLongPress == null) {
18010                mPendingCheckForLongPress = new CheckForLongPress();
18011            }
18012            mPendingCheckForLongPress.rememberWindowAttachCount();
18013            postDelayed(mPendingCheckForLongPress,
18014                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18015        }
18016    }
18017
18018    /**
18019     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18020     * LayoutInflater} class, which provides a full range of options for view inflation.
18021     *
18022     * @param context The Context object for your activity or application.
18023     * @param resource The resource ID to inflate
18024     * @param root A view group that will be the parent.  Used to properly inflate the
18025     * layout_* parameters.
18026     * @see LayoutInflater
18027     */
18028    public static View inflate(Context context, int resource, ViewGroup root) {
18029        LayoutInflater factory = LayoutInflater.from(context);
18030        return factory.inflate(resource, root);
18031    }
18032
18033    /**
18034     * Scroll the view with standard behavior for scrolling beyond the normal
18035     * content boundaries. Views that call this method should override
18036     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18037     * results of an over-scroll operation.
18038     *
18039     * Views can use this method to handle any touch or fling-based scrolling.
18040     *
18041     * @param deltaX Change in X in pixels
18042     * @param deltaY Change in Y in pixels
18043     * @param scrollX Current X scroll value in pixels before applying deltaX
18044     * @param scrollY Current Y scroll value in pixels before applying deltaY
18045     * @param scrollRangeX Maximum content scroll range along the X axis
18046     * @param scrollRangeY Maximum content scroll range along the Y axis
18047     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18048     *          along the X axis.
18049     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18050     *          along the Y axis.
18051     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18052     * @return true if scrolling was clamped to an over-scroll boundary along either
18053     *          axis, false otherwise.
18054     */
18055    @SuppressWarnings({"UnusedParameters"})
18056    protected boolean overScrollBy(int deltaX, int deltaY,
18057            int scrollX, int scrollY,
18058            int scrollRangeX, int scrollRangeY,
18059            int maxOverScrollX, int maxOverScrollY,
18060            boolean isTouchEvent) {
18061        final int overScrollMode = mOverScrollMode;
18062        final boolean canScrollHorizontal =
18063                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18064        final boolean canScrollVertical =
18065                computeVerticalScrollRange() > computeVerticalScrollExtent();
18066        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18067                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18068        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18069                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18070
18071        int newScrollX = scrollX + deltaX;
18072        if (!overScrollHorizontal) {
18073            maxOverScrollX = 0;
18074        }
18075
18076        int newScrollY = scrollY + deltaY;
18077        if (!overScrollVertical) {
18078            maxOverScrollY = 0;
18079        }
18080
18081        // Clamp values if at the limits and record
18082        final int left = -maxOverScrollX;
18083        final int right = maxOverScrollX + scrollRangeX;
18084        final int top = -maxOverScrollY;
18085        final int bottom = maxOverScrollY + scrollRangeY;
18086
18087        boolean clampedX = false;
18088        if (newScrollX > right) {
18089            newScrollX = right;
18090            clampedX = true;
18091        } else if (newScrollX < left) {
18092            newScrollX = left;
18093            clampedX = true;
18094        }
18095
18096        boolean clampedY = false;
18097        if (newScrollY > bottom) {
18098            newScrollY = bottom;
18099            clampedY = true;
18100        } else if (newScrollY < top) {
18101            newScrollY = top;
18102            clampedY = true;
18103        }
18104
18105        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18106
18107        return clampedX || clampedY;
18108    }
18109
18110    /**
18111     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18112     * respond to the results of an over-scroll operation.
18113     *
18114     * @param scrollX New X scroll value in pixels
18115     * @param scrollY New Y scroll value in pixels
18116     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18117     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18118     */
18119    protected void onOverScrolled(int scrollX, int scrollY,
18120            boolean clampedX, boolean clampedY) {
18121        // Intentionally empty.
18122    }
18123
18124    /**
18125     * Returns the over-scroll mode for this view. The result will be
18126     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18127     * (allow over-scrolling only if the view content is larger than the container),
18128     * or {@link #OVER_SCROLL_NEVER}.
18129     *
18130     * @return This view's over-scroll mode.
18131     */
18132    public int getOverScrollMode() {
18133        return mOverScrollMode;
18134    }
18135
18136    /**
18137     * Set the over-scroll mode for this view. Valid over-scroll modes are
18138     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18139     * (allow over-scrolling only if the view content is larger than the container),
18140     * or {@link #OVER_SCROLL_NEVER}.
18141     *
18142     * Setting the over-scroll mode of a view will have an effect only if the
18143     * view is capable of scrolling.
18144     *
18145     * @param overScrollMode The new over-scroll mode for this view.
18146     */
18147    public void setOverScrollMode(int overScrollMode) {
18148        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18149                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18150                overScrollMode != OVER_SCROLL_NEVER) {
18151            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18152        }
18153        mOverScrollMode = overScrollMode;
18154    }
18155
18156    /**
18157     * Enable or disable nested scrolling for this view.
18158     *
18159     * <p>If this property is set to true the view will be permitted to initiate nested
18160     * scrolling operations with a compatible parent view in the current hierarchy. If this
18161     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18162     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18163     * the nested scroll.</p>
18164     *
18165     * @param enabled true to enable nested scrolling, false to disable
18166     *
18167     * @see #isNestedScrollingEnabled()
18168     */
18169    public void setNestedScrollingEnabled(boolean enabled) {
18170        if (enabled) {
18171            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18172        } else {
18173            stopNestedScroll();
18174            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18175        }
18176    }
18177
18178    /**
18179     * Returns true if nested scrolling is enabled for this view.
18180     *
18181     * <p>If nested scrolling is enabled and this View class implementation supports it,
18182     * this view will act as a nested scrolling child view when applicable, forwarding data
18183     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18184     * parent.</p>
18185     *
18186     * @return true if nested scrolling is enabled
18187     *
18188     * @see #setNestedScrollingEnabled(boolean)
18189     */
18190    public boolean isNestedScrollingEnabled() {
18191        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18192                PFLAG3_NESTED_SCROLLING_ENABLED;
18193    }
18194
18195    /**
18196     * Begin a nestable scroll operation along the given axes.
18197     *
18198     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18199     *
18200     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18201     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18202     * In the case of touch scrolling the nested scroll will be terminated automatically in
18203     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18204     * In the event of programmatic scrolling the caller must explicitly call
18205     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18206     *
18207     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18208     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18209     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18210     *
18211     * <p>At each incremental step of the scroll the caller should invoke
18212     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18213     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18214     * parent at least partially consumed the scroll and the caller should adjust the amount it
18215     * scrolls by.</p>
18216     *
18217     * <p>After applying the remainder of the scroll delta the caller should invoke
18218     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18219     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18220     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18221     * </p>
18222     *
18223     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18224     *             {@link #SCROLL_AXIS_VERTICAL}.
18225     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18226     *         the current gesture.
18227     *
18228     * @see #stopNestedScroll()
18229     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18230     * @see #dispatchNestedScroll(int, int, int, int, int[])
18231     */
18232    public boolean startNestedScroll(int axes) {
18233        if (hasNestedScrollingParent()) {
18234            // Already in progress
18235            return true;
18236        }
18237        if (isNestedScrollingEnabled()) {
18238            ViewParent p = getParent();
18239            View child = this;
18240            while (p != null) {
18241                try {
18242                    if (p.onStartNestedScroll(child, this, axes)) {
18243                        mNestedScrollingParent = p;
18244                        p.onNestedScrollAccepted(child, this, axes);
18245                        return true;
18246                    }
18247                } catch (AbstractMethodError e) {
18248                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18249                            "method onStartNestedScroll", e);
18250                    // Allow the search upward to continue
18251                }
18252                if (p instanceof View) {
18253                    child = (View) p;
18254                }
18255                p = p.getParent();
18256            }
18257        }
18258        return false;
18259    }
18260
18261    /**
18262     * Stop a nested scroll in progress.
18263     *
18264     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18265     *
18266     * @see #startNestedScroll(int)
18267     */
18268    public void stopNestedScroll() {
18269        if (mNestedScrollingParent != null) {
18270            mNestedScrollingParent.onStopNestedScroll(this);
18271            mNestedScrollingParent = null;
18272        }
18273    }
18274
18275    /**
18276     * Returns true if this view has a nested scrolling parent.
18277     *
18278     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18279     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18280     *
18281     * @return whether this view has a nested scrolling parent
18282     */
18283    public boolean hasNestedScrollingParent() {
18284        return mNestedScrollingParent != null;
18285    }
18286
18287    /**
18288     * Dispatch one step of a nested scroll in progress.
18289     *
18290     * <p>Implementations of views that support nested scrolling should call this to report
18291     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18292     * is not currently in progress or nested scrolling is not
18293     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18294     *
18295     * <p>Compatible View implementations should also call
18296     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18297     * consuming a component of the scroll event themselves.</p>
18298     *
18299     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18300     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18301     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18302     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18303     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18304     *                       in local view coordinates of this view from before this operation
18305     *                       to after it completes. View implementations may use this to adjust
18306     *                       expected input coordinate tracking.
18307     * @return true if the event was dispatched, false if it could not be dispatched.
18308     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18309     */
18310    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18311            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18312        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18313            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18314                int startX = 0;
18315                int startY = 0;
18316                if (offsetInWindow != null) {
18317                    getLocationInWindow(offsetInWindow);
18318                    startX = offsetInWindow[0];
18319                    startY = offsetInWindow[1];
18320                }
18321
18322                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18323                        dxUnconsumed, dyUnconsumed);
18324
18325                if (offsetInWindow != null) {
18326                    getLocationInWindow(offsetInWindow);
18327                    offsetInWindow[0] -= startX;
18328                    offsetInWindow[1] -= startY;
18329                }
18330                return true;
18331            } else if (offsetInWindow != null) {
18332                // No motion, no dispatch. Keep offsetInWindow up to date.
18333                offsetInWindow[0] = 0;
18334                offsetInWindow[1] = 0;
18335            }
18336        }
18337        return false;
18338    }
18339
18340    /**
18341     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18342     *
18343     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18344     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18345     * scrolling operation to consume some or all of the scroll operation before the child view
18346     * consumes it.</p>
18347     *
18348     * @param dx Horizontal scroll distance in pixels
18349     * @param dy Vertical scroll distance in pixels
18350     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18351     *                 and consumed[1] the consumed dy.
18352     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18353     *                       in local view coordinates of this view from before this operation
18354     *                       to after it completes. View implementations may use this to adjust
18355     *                       expected input coordinate tracking.
18356     * @return true if the parent consumed some or all of the scroll delta
18357     * @see #dispatchNestedScroll(int, int, int, int, int[])
18358     */
18359    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18360        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18361            if (dx != 0 || dy != 0) {
18362                int startX = 0;
18363                int startY = 0;
18364                if (offsetInWindow != null) {
18365                    getLocationInWindow(offsetInWindow);
18366                    startX = offsetInWindow[0];
18367                    startY = offsetInWindow[1];
18368                }
18369
18370                if (consumed == null) {
18371                    if (mTempNestedScrollConsumed == null) {
18372                        mTempNestedScrollConsumed = new int[2];
18373                    }
18374                    consumed = mTempNestedScrollConsumed;
18375                }
18376                consumed[0] = 0;
18377                consumed[1] = 0;
18378                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18379
18380                if (offsetInWindow != null) {
18381                    getLocationInWindow(offsetInWindow);
18382                    offsetInWindow[0] -= startX;
18383                    offsetInWindow[1] -= startY;
18384                }
18385                return consumed[0] != 0 || consumed[1] != 0;
18386            } else if (offsetInWindow != null) {
18387                offsetInWindow[0] = 0;
18388                offsetInWindow[1] = 0;
18389            }
18390        }
18391        return false;
18392    }
18393
18394    /**
18395     * Dispatch a fling to a nested scrolling parent.
18396     *
18397     * <p>This method should be used to indicate that a nested scrolling child has detected
18398     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18399     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18400     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18401     * along a scrollable axis.</p>
18402     *
18403     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18404     * its own content, it can use this method to delegate the fling to its nested scrolling
18405     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18406     *
18407     * @param velocityX Horizontal fling velocity in pixels per second
18408     * @param velocityY Vertical fling velocity in pixels per second
18409     * @param consumed true if the child consumed the fling, false otherwise
18410     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18411     */
18412    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18413        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18414            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18415        }
18416        return false;
18417    }
18418
18419    /**
18420     * Gets a scale factor that determines the distance the view should scroll
18421     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18422     * @return The vertical scroll scale factor.
18423     * @hide
18424     */
18425    protected float getVerticalScrollFactor() {
18426        if (mVerticalScrollFactor == 0) {
18427            TypedValue outValue = new TypedValue();
18428            if (!mContext.getTheme().resolveAttribute(
18429                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18430                throw new IllegalStateException(
18431                        "Expected theme to define listPreferredItemHeight.");
18432            }
18433            mVerticalScrollFactor = outValue.getDimension(
18434                    mContext.getResources().getDisplayMetrics());
18435        }
18436        return mVerticalScrollFactor;
18437    }
18438
18439    /**
18440     * Gets a scale factor that determines the distance the view should scroll
18441     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18442     * @return The horizontal scroll scale factor.
18443     * @hide
18444     */
18445    protected float getHorizontalScrollFactor() {
18446        // TODO: Should use something else.
18447        return getVerticalScrollFactor();
18448    }
18449
18450    /**
18451     * Return the value specifying the text direction or policy that was set with
18452     * {@link #setTextDirection(int)}.
18453     *
18454     * @return the defined text direction. It can be one of:
18455     *
18456     * {@link #TEXT_DIRECTION_INHERIT},
18457     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18458     * {@link #TEXT_DIRECTION_ANY_RTL},
18459     * {@link #TEXT_DIRECTION_LTR},
18460     * {@link #TEXT_DIRECTION_RTL},
18461     * {@link #TEXT_DIRECTION_LOCALE}
18462     *
18463     * @attr ref android.R.styleable#View_textDirection
18464     *
18465     * @hide
18466     */
18467    @ViewDebug.ExportedProperty(category = "text", mapping = {
18468            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18469            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18470            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18471            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18472            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18473            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18474    })
18475    public int getRawTextDirection() {
18476        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18477    }
18478
18479    /**
18480     * Set the text direction.
18481     *
18482     * @param textDirection the direction to set. Should be one of:
18483     *
18484     * {@link #TEXT_DIRECTION_INHERIT},
18485     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18486     * {@link #TEXT_DIRECTION_ANY_RTL},
18487     * {@link #TEXT_DIRECTION_LTR},
18488     * {@link #TEXT_DIRECTION_RTL},
18489     * {@link #TEXT_DIRECTION_LOCALE}
18490     *
18491     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18492     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18493     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18494     *
18495     * @attr ref android.R.styleable#View_textDirection
18496     */
18497    public void setTextDirection(int textDirection) {
18498        if (getRawTextDirection() != textDirection) {
18499            // Reset the current text direction and the resolved one
18500            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18501            resetResolvedTextDirection();
18502            // Set the new text direction
18503            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18504            // Do resolution
18505            resolveTextDirection();
18506            // Notify change
18507            onRtlPropertiesChanged(getLayoutDirection());
18508            // Refresh
18509            requestLayout();
18510            invalidate(true);
18511        }
18512    }
18513
18514    /**
18515     * Return the resolved text direction.
18516     *
18517     * @return the resolved text direction. Returns one of:
18518     *
18519     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18520     * {@link #TEXT_DIRECTION_ANY_RTL},
18521     * {@link #TEXT_DIRECTION_LTR},
18522     * {@link #TEXT_DIRECTION_RTL},
18523     * {@link #TEXT_DIRECTION_LOCALE}
18524     *
18525     * @attr ref android.R.styleable#View_textDirection
18526     */
18527    @ViewDebug.ExportedProperty(category = "text", mapping = {
18528            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18529            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18530            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18531            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18532            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18533            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18534    })
18535    public int getTextDirection() {
18536        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18537    }
18538
18539    /**
18540     * Resolve the text direction.
18541     *
18542     * @return true if resolution has been done, false otherwise.
18543     *
18544     * @hide
18545     */
18546    public boolean resolveTextDirection() {
18547        // Reset any previous text direction resolution
18548        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18549
18550        if (hasRtlSupport()) {
18551            // Set resolved text direction flag depending on text direction flag
18552            final int textDirection = getRawTextDirection();
18553            switch(textDirection) {
18554                case TEXT_DIRECTION_INHERIT:
18555                    if (!canResolveTextDirection()) {
18556                        // We cannot do the resolution if there is no parent, so use the default one
18557                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18558                        // Resolution will need to happen again later
18559                        return false;
18560                    }
18561
18562                    // Parent has not yet resolved, so we still return the default
18563                    try {
18564                        if (!mParent.isTextDirectionResolved()) {
18565                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18566                            // Resolution will need to happen again later
18567                            return false;
18568                        }
18569                    } catch (AbstractMethodError e) {
18570                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18571                                " does not fully implement ViewParent", e);
18572                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18573                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18574                        return true;
18575                    }
18576
18577                    // Set current resolved direction to the same value as the parent's one
18578                    int parentResolvedDirection;
18579                    try {
18580                        parentResolvedDirection = mParent.getTextDirection();
18581                    } catch (AbstractMethodError e) {
18582                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18583                                " does not fully implement ViewParent", e);
18584                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18585                    }
18586                    switch (parentResolvedDirection) {
18587                        case TEXT_DIRECTION_FIRST_STRONG:
18588                        case TEXT_DIRECTION_ANY_RTL:
18589                        case TEXT_DIRECTION_LTR:
18590                        case TEXT_DIRECTION_RTL:
18591                        case TEXT_DIRECTION_LOCALE:
18592                            mPrivateFlags2 |=
18593                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18594                            break;
18595                        default:
18596                            // Default resolved direction is "first strong" heuristic
18597                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18598                    }
18599                    break;
18600                case TEXT_DIRECTION_FIRST_STRONG:
18601                case TEXT_DIRECTION_ANY_RTL:
18602                case TEXT_DIRECTION_LTR:
18603                case TEXT_DIRECTION_RTL:
18604                case TEXT_DIRECTION_LOCALE:
18605                    // Resolved direction is the same as text direction
18606                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18607                    break;
18608                default:
18609                    // Default resolved direction is "first strong" heuristic
18610                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18611            }
18612        } else {
18613            // Default resolved direction is "first strong" heuristic
18614            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18615        }
18616
18617        // Set to resolved
18618        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18619        return true;
18620    }
18621
18622    /**
18623     * Check if text direction resolution can be done.
18624     *
18625     * @return true if text direction resolution can be done otherwise return false.
18626     */
18627    public boolean canResolveTextDirection() {
18628        switch (getRawTextDirection()) {
18629            case TEXT_DIRECTION_INHERIT:
18630                if (mParent != null) {
18631                    try {
18632                        return mParent.canResolveTextDirection();
18633                    } catch (AbstractMethodError e) {
18634                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18635                                " does not fully implement ViewParent", e);
18636                    }
18637                }
18638                return false;
18639
18640            default:
18641                return true;
18642        }
18643    }
18644
18645    /**
18646     * Reset resolved text direction. Text direction will be resolved during a call to
18647     * {@link #onMeasure(int, int)}.
18648     *
18649     * @hide
18650     */
18651    public void resetResolvedTextDirection() {
18652        // Reset any previous text direction resolution
18653        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18654        // Set to default value
18655        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18656    }
18657
18658    /**
18659     * @return true if text direction is inherited.
18660     *
18661     * @hide
18662     */
18663    public boolean isTextDirectionInherited() {
18664        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18665    }
18666
18667    /**
18668     * @return true if text direction is resolved.
18669     */
18670    public boolean isTextDirectionResolved() {
18671        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18672    }
18673
18674    /**
18675     * Return the value specifying the text alignment or policy that was set with
18676     * {@link #setTextAlignment(int)}.
18677     *
18678     * @return the defined text alignment. It can be one of:
18679     *
18680     * {@link #TEXT_ALIGNMENT_INHERIT},
18681     * {@link #TEXT_ALIGNMENT_GRAVITY},
18682     * {@link #TEXT_ALIGNMENT_CENTER},
18683     * {@link #TEXT_ALIGNMENT_TEXT_START},
18684     * {@link #TEXT_ALIGNMENT_TEXT_END},
18685     * {@link #TEXT_ALIGNMENT_VIEW_START},
18686     * {@link #TEXT_ALIGNMENT_VIEW_END}
18687     *
18688     * @attr ref android.R.styleable#View_textAlignment
18689     *
18690     * @hide
18691     */
18692    @ViewDebug.ExportedProperty(category = "text", mapping = {
18693            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18694            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18695            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18696            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18697            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18698            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18699            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18700    })
18701    @TextAlignment
18702    public int getRawTextAlignment() {
18703        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18704    }
18705
18706    /**
18707     * Set the text alignment.
18708     *
18709     * @param textAlignment The text alignment to set. Should be one of
18710     *
18711     * {@link #TEXT_ALIGNMENT_INHERIT},
18712     * {@link #TEXT_ALIGNMENT_GRAVITY},
18713     * {@link #TEXT_ALIGNMENT_CENTER},
18714     * {@link #TEXT_ALIGNMENT_TEXT_START},
18715     * {@link #TEXT_ALIGNMENT_TEXT_END},
18716     * {@link #TEXT_ALIGNMENT_VIEW_START},
18717     * {@link #TEXT_ALIGNMENT_VIEW_END}
18718     *
18719     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18720     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18721     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18722     *
18723     * @attr ref android.R.styleable#View_textAlignment
18724     */
18725    public void setTextAlignment(@TextAlignment int textAlignment) {
18726        if (textAlignment != getRawTextAlignment()) {
18727            // Reset the current and resolved text alignment
18728            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18729            resetResolvedTextAlignment();
18730            // Set the new text alignment
18731            mPrivateFlags2 |=
18732                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18733            // Do resolution
18734            resolveTextAlignment();
18735            // Notify change
18736            onRtlPropertiesChanged(getLayoutDirection());
18737            // Refresh
18738            requestLayout();
18739            invalidate(true);
18740        }
18741    }
18742
18743    /**
18744     * Return the resolved text alignment.
18745     *
18746     * @return the resolved text alignment. Returns one of:
18747     *
18748     * {@link #TEXT_ALIGNMENT_GRAVITY},
18749     * {@link #TEXT_ALIGNMENT_CENTER},
18750     * {@link #TEXT_ALIGNMENT_TEXT_START},
18751     * {@link #TEXT_ALIGNMENT_TEXT_END},
18752     * {@link #TEXT_ALIGNMENT_VIEW_START},
18753     * {@link #TEXT_ALIGNMENT_VIEW_END}
18754     *
18755     * @attr ref android.R.styleable#View_textAlignment
18756     */
18757    @ViewDebug.ExportedProperty(category = "text", mapping = {
18758            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18759            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18760            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18761            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18762            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18763            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18764            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18765    })
18766    @TextAlignment
18767    public int getTextAlignment() {
18768        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18769                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18770    }
18771
18772    /**
18773     * Resolve the text alignment.
18774     *
18775     * @return true if resolution has been done, false otherwise.
18776     *
18777     * @hide
18778     */
18779    public boolean resolveTextAlignment() {
18780        // Reset any previous text alignment resolution
18781        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18782
18783        if (hasRtlSupport()) {
18784            // Set resolved text alignment flag depending on text alignment flag
18785            final int textAlignment = getRawTextAlignment();
18786            switch (textAlignment) {
18787                case TEXT_ALIGNMENT_INHERIT:
18788                    // Check if we can resolve the text alignment
18789                    if (!canResolveTextAlignment()) {
18790                        // We cannot do the resolution if there is no parent so use the default
18791                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18792                        // Resolution will need to happen again later
18793                        return false;
18794                    }
18795
18796                    // Parent has not yet resolved, so we still return the default
18797                    try {
18798                        if (!mParent.isTextAlignmentResolved()) {
18799                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18800                            // Resolution will need to happen again later
18801                            return false;
18802                        }
18803                    } catch (AbstractMethodError e) {
18804                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18805                                " does not fully implement ViewParent", e);
18806                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18807                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18808                        return true;
18809                    }
18810
18811                    int parentResolvedTextAlignment;
18812                    try {
18813                        parentResolvedTextAlignment = mParent.getTextAlignment();
18814                    } catch (AbstractMethodError e) {
18815                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18816                                " does not fully implement ViewParent", e);
18817                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18818                    }
18819                    switch (parentResolvedTextAlignment) {
18820                        case TEXT_ALIGNMENT_GRAVITY:
18821                        case TEXT_ALIGNMENT_TEXT_START:
18822                        case TEXT_ALIGNMENT_TEXT_END:
18823                        case TEXT_ALIGNMENT_CENTER:
18824                        case TEXT_ALIGNMENT_VIEW_START:
18825                        case TEXT_ALIGNMENT_VIEW_END:
18826                            // Resolved text alignment is the same as the parent resolved
18827                            // text alignment
18828                            mPrivateFlags2 |=
18829                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18830                            break;
18831                        default:
18832                            // Use default resolved text alignment
18833                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18834                    }
18835                    break;
18836                case TEXT_ALIGNMENT_GRAVITY:
18837                case TEXT_ALIGNMENT_TEXT_START:
18838                case TEXT_ALIGNMENT_TEXT_END:
18839                case TEXT_ALIGNMENT_CENTER:
18840                case TEXT_ALIGNMENT_VIEW_START:
18841                case TEXT_ALIGNMENT_VIEW_END:
18842                    // Resolved text alignment is the same as text alignment
18843                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18844                    break;
18845                default:
18846                    // Use default resolved text alignment
18847                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18848            }
18849        } else {
18850            // Use default resolved text alignment
18851            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18852        }
18853
18854        // Set the resolved
18855        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18856        return true;
18857    }
18858
18859    /**
18860     * Check if text alignment resolution can be done.
18861     *
18862     * @return true if text alignment resolution can be done otherwise return false.
18863     */
18864    public boolean canResolveTextAlignment() {
18865        switch (getRawTextAlignment()) {
18866            case TEXT_DIRECTION_INHERIT:
18867                if (mParent != null) {
18868                    try {
18869                        return mParent.canResolveTextAlignment();
18870                    } catch (AbstractMethodError e) {
18871                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18872                                " does not fully implement ViewParent", e);
18873                    }
18874                }
18875                return false;
18876
18877            default:
18878                return true;
18879        }
18880    }
18881
18882    /**
18883     * Reset resolved text alignment. Text alignment will be resolved during a call to
18884     * {@link #onMeasure(int, int)}.
18885     *
18886     * @hide
18887     */
18888    public void resetResolvedTextAlignment() {
18889        // Reset any previous text alignment resolution
18890        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18891        // Set to default
18892        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18893    }
18894
18895    /**
18896     * @return true if text alignment is inherited.
18897     *
18898     * @hide
18899     */
18900    public boolean isTextAlignmentInherited() {
18901        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18902    }
18903
18904    /**
18905     * @return true if text alignment is resolved.
18906     */
18907    public boolean isTextAlignmentResolved() {
18908        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18909    }
18910
18911    /**
18912     * Generate a value suitable for use in {@link #setId(int)}.
18913     * This value will not collide with ID values generated at build time by aapt for R.id.
18914     *
18915     * @return a generated ID value
18916     */
18917    public static int generateViewId() {
18918        for (;;) {
18919            final int result = sNextGeneratedId.get();
18920            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18921            int newValue = result + 1;
18922            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18923            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18924                return result;
18925            }
18926        }
18927    }
18928
18929    /**
18930     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18931     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18932     *                           a normal View or a ViewGroup with
18933     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18934     * @hide
18935     */
18936    public void captureTransitioningViews(List<View> transitioningViews) {
18937        if (getVisibility() == View.VISIBLE) {
18938            transitioningViews.add(this);
18939        }
18940    }
18941
18942    /**
18943     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
18944     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
18945     * @hide
18946     */
18947    public void findNamedViews(Map<String, View> namedElements) {
18948        if (getVisibility() == VISIBLE) {
18949            String transitionName = getTransitionName();
18950            if (transitionName != null) {
18951                namedElements.put(transitionName, this);
18952            }
18953        }
18954    }
18955
18956    //
18957    // Properties
18958    //
18959    /**
18960     * A Property wrapper around the <code>alpha</code> functionality handled by the
18961     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18962     */
18963    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18964        @Override
18965        public void setValue(View object, float value) {
18966            object.setAlpha(value);
18967        }
18968
18969        @Override
18970        public Float get(View object) {
18971            return object.getAlpha();
18972        }
18973    };
18974
18975    /**
18976     * A Property wrapper around the <code>translationX</code> functionality handled by the
18977     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18978     */
18979    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18980        @Override
18981        public void setValue(View object, float value) {
18982            object.setTranslationX(value);
18983        }
18984
18985                @Override
18986        public Float get(View object) {
18987            return object.getTranslationX();
18988        }
18989    };
18990
18991    /**
18992     * A Property wrapper around the <code>translationY</code> functionality handled by the
18993     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18994     */
18995    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18996        @Override
18997        public void setValue(View object, float value) {
18998            object.setTranslationY(value);
18999        }
19000
19001        @Override
19002        public Float get(View object) {
19003            return object.getTranslationY();
19004        }
19005    };
19006
19007    /**
19008     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19009     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19010     */
19011    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19012        @Override
19013        public void setValue(View object, float value) {
19014            object.setTranslationZ(value);
19015        }
19016
19017        @Override
19018        public Float get(View object) {
19019            return object.getTranslationZ();
19020        }
19021    };
19022
19023    /**
19024     * A Property wrapper around the <code>x</code> functionality handled by the
19025     * {@link View#setX(float)} and {@link View#getX()} methods.
19026     */
19027    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19028        @Override
19029        public void setValue(View object, float value) {
19030            object.setX(value);
19031        }
19032
19033        @Override
19034        public Float get(View object) {
19035            return object.getX();
19036        }
19037    };
19038
19039    /**
19040     * A Property wrapper around the <code>y</code> functionality handled by the
19041     * {@link View#setY(float)} and {@link View#getY()} methods.
19042     */
19043    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19044        @Override
19045        public void setValue(View object, float value) {
19046            object.setY(value);
19047        }
19048
19049        @Override
19050        public Float get(View object) {
19051            return object.getY();
19052        }
19053    };
19054
19055    /**
19056     * A Property wrapper around the <code>z</code> functionality handled by the
19057     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19058     */
19059    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19060        @Override
19061        public void setValue(View object, float value) {
19062            object.setZ(value);
19063        }
19064
19065        @Override
19066        public Float get(View object) {
19067            return object.getZ();
19068        }
19069    };
19070
19071    /**
19072     * A Property wrapper around the <code>rotation</code> functionality handled by the
19073     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19074     */
19075    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19076        @Override
19077        public void setValue(View object, float value) {
19078            object.setRotation(value);
19079        }
19080
19081        @Override
19082        public Float get(View object) {
19083            return object.getRotation();
19084        }
19085    };
19086
19087    /**
19088     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19089     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19090     */
19091    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19092        @Override
19093        public void setValue(View object, float value) {
19094            object.setRotationX(value);
19095        }
19096
19097        @Override
19098        public Float get(View object) {
19099            return object.getRotationX();
19100        }
19101    };
19102
19103    /**
19104     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19105     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19106     */
19107    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19108        @Override
19109        public void setValue(View object, float value) {
19110            object.setRotationY(value);
19111        }
19112
19113        @Override
19114        public Float get(View object) {
19115            return object.getRotationY();
19116        }
19117    };
19118
19119    /**
19120     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19121     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19122     */
19123    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19124        @Override
19125        public void setValue(View object, float value) {
19126            object.setScaleX(value);
19127        }
19128
19129        @Override
19130        public Float get(View object) {
19131            return object.getScaleX();
19132        }
19133    };
19134
19135    /**
19136     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19137     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19138     */
19139    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19140        @Override
19141        public void setValue(View object, float value) {
19142            object.setScaleY(value);
19143        }
19144
19145        @Override
19146        public Float get(View object) {
19147            return object.getScaleY();
19148        }
19149    };
19150
19151    /**
19152     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19153     * Each MeasureSpec represents a requirement for either the width or the height.
19154     * A MeasureSpec is comprised of a size and a mode. There are three possible
19155     * modes:
19156     * <dl>
19157     * <dt>UNSPECIFIED</dt>
19158     * <dd>
19159     * The parent has not imposed any constraint on the child. It can be whatever size
19160     * it wants.
19161     * </dd>
19162     *
19163     * <dt>EXACTLY</dt>
19164     * <dd>
19165     * The parent has determined an exact size for the child. The child is going to be
19166     * given those bounds regardless of how big it wants to be.
19167     * </dd>
19168     *
19169     * <dt>AT_MOST</dt>
19170     * <dd>
19171     * The child can be as large as it wants up to the specified size.
19172     * </dd>
19173     * </dl>
19174     *
19175     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19176     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19177     */
19178    public static class MeasureSpec {
19179        private static final int MODE_SHIFT = 30;
19180        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19181
19182        /**
19183         * Measure specification mode: The parent has not imposed any constraint
19184         * on the child. It can be whatever size it wants.
19185         */
19186        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19187
19188        /**
19189         * Measure specification mode: The parent has determined an exact size
19190         * for the child. The child is going to be given those bounds regardless
19191         * of how big it wants to be.
19192         */
19193        public static final int EXACTLY     = 1 << MODE_SHIFT;
19194
19195        /**
19196         * Measure specification mode: The child can be as large as it wants up
19197         * to the specified size.
19198         */
19199        public static final int AT_MOST     = 2 << MODE_SHIFT;
19200
19201        /**
19202         * Creates a measure specification based on the supplied size and mode.
19203         *
19204         * The mode must always be one of the following:
19205         * <ul>
19206         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19207         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19208         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19209         * </ul>
19210         *
19211         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19212         * implementation was such that the order of arguments did not matter
19213         * and overflow in either value could impact the resulting MeasureSpec.
19214         * {@link android.widget.RelativeLayout} was affected by this bug.
19215         * Apps targeting API levels greater than 17 will get the fixed, more strict
19216         * behavior.</p>
19217         *
19218         * @param size the size of the measure specification
19219         * @param mode the mode of the measure specification
19220         * @return the measure specification based on size and mode
19221         */
19222        public static int makeMeasureSpec(int size, int mode) {
19223            if (sUseBrokenMakeMeasureSpec) {
19224                return size + mode;
19225            } else {
19226                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19227            }
19228        }
19229
19230        /**
19231         * Extracts the mode from the supplied measure specification.
19232         *
19233         * @param measureSpec the measure specification to extract the mode from
19234         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19235         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19236         *         {@link android.view.View.MeasureSpec#EXACTLY}
19237         */
19238        public static int getMode(int measureSpec) {
19239            return (measureSpec & MODE_MASK);
19240        }
19241
19242        /**
19243         * Extracts the size from the supplied measure specification.
19244         *
19245         * @param measureSpec the measure specification to extract the size from
19246         * @return the size in pixels defined in the supplied measure specification
19247         */
19248        public static int getSize(int measureSpec) {
19249            return (measureSpec & ~MODE_MASK);
19250        }
19251
19252        static int adjust(int measureSpec, int delta) {
19253            final int mode = getMode(measureSpec);
19254            if (mode == UNSPECIFIED) {
19255                // No need to adjust size for UNSPECIFIED mode.
19256                return makeMeasureSpec(0, UNSPECIFIED);
19257            }
19258            int size = getSize(measureSpec) + delta;
19259            if (size < 0) {
19260                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19261                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19262                size = 0;
19263            }
19264            return makeMeasureSpec(size, mode);
19265        }
19266
19267        /**
19268         * Returns a String representation of the specified measure
19269         * specification.
19270         *
19271         * @param measureSpec the measure specification to convert to a String
19272         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19273         */
19274        public static String toString(int measureSpec) {
19275            int mode = getMode(measureSpec);
19276            int size = getSize(measureSpec);
19277
19278            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19279
19280            if (mode == UNSPECIFIED)
19281                sb.append("UNSPECIFIED ");
19282            else if (mode == EXACTLY)
19283                sb.append("EXACTLY ");
19284            else if (mode == AT_MOST)
19285                sb.append("AT_MOST ");
19286            else
19287                sb.append(mode).append(" ");
19288
19289            sb.append(size);
19290            return sb.toString();
19291        }
19292    }
19293
19294    private final class CheckForLongPress implements Runnable {
19295        private int mOriginalWindowAttachCount;
19296
19297        @Override
19298        public void run() {
19299            if (isPressed() && (mParent != null)
19300                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19301                if (performLongClick()) {
19302                    mHasPerformedLongPress = true;
19303                }
19304            }
19305        }
19306
19307        public void rememberWindowAttachCount() {
19308            mOriginalWindowAttachCount = mWindowAttachCount;
19309        }
19310    }
19311
19312    private final class CheckForTap implements Runnable {
19313        public float x;
19314        public float y;
19315
19316        @Override
19317        public void run() {
19318            mPrivateFlags &= ~PFLAG_PREPRESSED;
19319            setPressed(true, x, y);
19320            checkForLongClick(ViewConfiguration.getTapTimeout());
19321        }
19322    }
19323
19324    private final class PerformClick implements Runnable {
19325        @Override
19326        public void run() {
19327            performClick();
19328        }
19329    }
19330
19331    /** @hide */
19332    public void hackTurnOffWindowResizeAnim(boolean off) {
19333        mAttachInfo.mTurnOffWindowResizeAnim = off;
19334    }
19335
19336    /**
19337     * This method returns a ViewPropertyAnimator object, which can be used to animate
19338     * specific properties on this View.
19339     *
19340     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19341     */
19342    public ViewPropertyAnimator animate() {
19343        if (mAnimator == null) {
19344            mAnimator = new ViewPropertyAnimator(this);
19345        }
19346        return mAnimator;
19347    }
19348
19349    /**
19350     * Sets the name of the View to be used to identify Views in Transitions.
19351     * Names should be unique in the View hierarchy.
19352     *
19353     * @param transitionName The name of the View to uniquely identify it for Transitions.
19354     */
19355    public final void setTransitionName(String transitionName) {
19356        mTransitionName = transitionName;
19357    }
19358
19359    /**
19360     * To be removed before L release.
19361     * @hide
19362     */
19363    public final void setViewName(String transitionName) {
19364        setTransitionName(transitionName);
19365    }
19366
19367    /**
19368     * Returns the name of the View to be used to identify Views in Transitions.
19369     * Names should be unique in the View hierarchy.
19370     *
19371     * <p>This returns null if the View has not been given a name.</p>
19372     *
19373     * @return The name used of the View to be used to identify Views in Transitions or null
19374     * if no name has been given.
19375     */
19376    public String getTransitionName() {
19377        return mTransitionName;
19378    }
19379
19380    /**
19381     * To be removed before L release.
19382     * @hide
19383     */
19384    public String getViewName() { return getTransitionName(); }
19385
19386    /**
19387     * Interface definition for a callback to be invoked when a hardware key event is
19388     * dispatched to this view. The callback will be invoked before the key event is
19389     * given to the view. This is only useful for hardware keyboards; a software input
19390     * method has no obligation to trigger this listener.
19391     */
19392    public interface OnKeyListener {
19393        /**
19394         * Called when a hardware key is dispatched to a view. This allows listeners to
19395         * get a chance to respond before the target view.
19396         * <p>Key presses in software keyboards will generally NOT trigger this method,
19397         * although some may elect to do so in some situations. Do not assume a
19398         * software input method has to be key-based; even if it is, it may use key presses
19399         * in a different way than you expect, so there is no way to reliably catch soft
19400         * input key presses.
19401         *
19402         * @param v The view the key has been dispatched to.
19403         * @param keyCode The code for the physical key that was pressed
19404         * @param event The KeyEvent object containing full information about
19405         *        the event.
19406         * @return True if the listener has consumed the event, false otherwise.
19407         */
19408        boolean onKey(View v, int keyCode, KeyEvent event);
19409    }
19410
19411    /**
19412     * Interface definition for a callback to be invoked when a touch event is
19413     * dispatched to this view. The callback will be invoked before the touch
19414     * event is given to the view.
19415     */
19416    public interface OnTouchListener {
19417        /**
19418         * Called when a touch event is dispatched to a view. This allows listeners to
19419         * get a chance to respond before the target view.
19420         *
19421         * @param v The view the touch event has been dispatched to.
19422         * @param event The MotionEvent object containing full information about
19423         *        the event.
19424         * @return True if the listener has consumed the event, false otherwise.
19425         */
19426        boolean onTouch(View v, MotionEvent event);
19427    }
19428
19429    /**
19430     * Interface definition for a callback to be invoked when a hover event is
19431     * dispatched to this view. The callback will be invoked before the hover
19432     * event is given to the view.
19433     */
19434    public interface OnHoverListener {
19435        /**
19436         * Called when a hover event is dispatched to a view. This allows listeners to
19437         * get a chance to respond before the target view.
19438         *
19439         * @param v The view the hover event has been dispatched to.
19440         * @param event The MotionEvent object containing full information about
19441         *        the event.
19442         * @return True if the listener has consumed the event, false otherwise.
19443         */
19444        boolean onHover(View v, MotionEvent event);
19445    }
19446
19447    /**
19448     * Interface definition for a callback to be invoked when a generic motion event is
19449     * dispatched to this view. The callback will be invoked before the generic motion
19450     * event is given to the view.
19451     */
19452    public interface OnGenericMotionListener {
19453        /**
19454         * Called when a generic motion event is dispatched to a view. This allows listeners to
19455         * get a chance to respond before the target view.
19456         *
19457         * @param v The view the generic motion event has been dispatched to.
19458         * @param event The MotionEvent object containing full information about
19459         *        the event.
19460         * @return True if the listener has consumed the event, false otherwise.
19461         */
19462        boolean onGenericMotion(View v, MotionEvent event);
19463    }
19464
19465    /**
19466     * Interface definition for a callback to be invoked when a view has been clicked and held.
19467     */
19468    public interface OnLongClickListener {
19469        /**
19470         * Called when a view has been clicked and held.
19471         *
19472         * @param v The view that was clicked and held.
19473         *
19474         * @return true if the callback consumed the long click, false otherwise.
19475         */
19476        boolean onLongClick(View v);
19477    }
19478
19479    /**
19480     * Interface definition for a callback to be invoked when a drag is being dispatched
19481     * to this view.  The callback will be invoked before the hosting view's own
19482     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19483     * onDrag(event) behavior, it should return 'false' from this callback.
19484     *
19485     * <div class="special reference">
19486     * <h3>Developer Guides</h3>
19487     * <p>For a guide to implementing drag and drop features, read the
19488     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19489     * </div>
19490     */
19491    public interface OnDragListener {
19492        /**
19493         * Called when a drag event is dispatched to a view. This allows listeners
19494         * to get a chance to override base View behavior.
19495         *
19496         * @param v The View that received the drag event.
19497         * @param event The {@link android.view.DragEvent} object for the drag event.
19498         * @return {@code true} if the drag event was handled successfully, or {@code false}
19499         * if the drag event was not handled. Note that {@code false} will trigger the View
19500         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19501         */
19502        boolean onDrag(View v, DragEvent event);
19503    }
19504
19505    /**
19506     * Interface definition for a callback to be invoked when the focus state of
19507     * a view changed.
19508     */
19509    public interface OnFocusChangeListener {
19510        /**
19511         * Called when the focus state of a view has changed.
19512         *
19513         * @param v The view whose state has changed.
19514         * @param hasFocus The new focus state of v.
19515         */
19516        void onFocusChange(View v, boolean hasFocus);
19517    }
19518
19519    /**
19520     * Interface definition for a callback to be invoked when a view is clicked.
19521     */
19522    public interface OnClickListener {
19523        /**
19524         * Called when a view has been clicked.
19525         *
19526         * @param v The view that was clicked.
19527         */
19528        void onClick(View v);
19529    }
19530
19531    /**
19532     * Interface definition for a callback to be invoked when the context menu
19533     * for this view is being built.
19534     */
19535    public interface OnCreateContextMenuListener {
19536        /**
19537         * Called when the context menu for this view is being built. It is not
19538         * safe to hold onto the menu after this method returns.
19539         *
19540         * @param menu The context menu that is being built
19541         * @param v The view for which the context menu is being built
19542         * @param menuInfo Extra information about the item for which the
19543         *            context menu should be shown. This information will vary
19544         *            depending on the class of v.
19545         */
19546        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19547    }
19548
19549    /**
19550     * Interface definition for a callback to be invoked when the status bar changes
19551     * visibility.  This reports <strong>global</strong> changes to the system UI
19552     * state, not what the application is requesting.
19553     *
19554     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19555     */
19556    public interface OnSystemUiVisibilityChangeListener {
19557        /**
19558         * Called when the status bar changes visibility because of a call to
19559         * {@link View#setSystemUiVisibility(int)}.
19560         *
19561         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19562         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19563         * This tells you the <strong>global</strong> state of these UI visibility
19564         * flags, not what your app is currently applying.
19565         */
19566        public void onSystemUiVisibilityChange(int visibility);
19567    }
19568
19569    /**
19570     * Interface definition for a callback to be invoked when this view is attached
19571     * or detached from its window.
19572     */
19573    public interface OnAttachStateChangeListener {
19574        /**
19575         * Called when the view is attached to a window.
19576         * @param v The view that was attached
19577         */
19578        public void onViewAttachedToWindow(View v);
19579        /**
19580         * Called when the view is detached from a window.
19581         * @param v The view that was detached
19582         */
19583        public void onViewDetachedFromWindow(View v);
19584    }
19585
19586    /**
19587     * Listener for applying window insets on a view in a custom way.
19588     *
19589     * <p>Apps may choose to implement this interface if they want to apply custom policy
19590     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19591     * is set, its
19592     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19593     * method will be called instead of the View's own
19594     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19595     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19596     * the View's normal behavior as part of its own.</p>
19597     */
19598    public interface OnApplyWindowInsetsListener {
19599        /**
19600         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19601         * on a View, this listener method will be called instead of the view's own
19602         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19603         *
19604         * @param v The view applying window insets
19605         * @param insets The insets to apply
19606         * @return The insets supplied, minus any insets that were consumed
19607         */
19608        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19609    }
19610
19611    private final class UnsetPressedState implements Runnable {
19612        @Override
19613        public void run() {
19614            setPressed(false);
19615        }
19616    }
19617
19618    /**
19619     * Base class for derived classes that want to save and restore their own
19620     * state in {@link android.view.View#onSaveInstanceState()}.
19621     */
19622    public static class BaseSavedState extends AbsSavedState {
19623        /**
19624         * Constructor used when reading from a parcel. Reads the state of the superclass.
19625         *
19626         * @param source
19627         */
19628        public BaseSavedState(Parcel source) {
19629            super(source);
19630        }
19631
19632        /**
19633         * Constructor called by derived classes when creating their SavedState objects
19634         *
19635         * @param superState The state of the superclass of this view
19636         */
19637        public BaseSavedState(Parcelable superState) {
19638            super(superState);
19639        }
19640
19641        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19642                new Parcelable.Creator<BaseSavedState>() {
19643            public BaseSavedState createFromParcel(Parcel in) {
19644                return new BaseSavedState(in);
19645            }
19646
19647            public BaseSavedState[] newArray(int size) {
19648                return new BaseSavedState[size];
19649            }
19650        };
19651    }
19652
19653    /**
19654     * A set of information given to a view when it is attached to its parent
19655     * window.
19656     */
19657    final static class AttachInfo {
19658        interface Callbacks {
19659            void playSoundEffect(int effectId);
19660            boolean performHapticFeedback(int effectId, boolean always);
19661        }
19662
19663        /**
19664         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19665         * to a Handler. This class contains the target (View) to invalidate and
19666         * the coordinates of the dirty rectangle.
19667         *
19668         * For performance purposes, this class also implements a pool of up to
19669         * POOL_LIMIT objects that get reused. This reduces memory allocations
19670         * whenever possible.
19671         */
19672        static class InvalidateInfo {
19673            private static final int POOL_LIMIT = 10;
19674
19675            private static final SynchronizedPool<InvalidateInfo> sPool =
19676                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19677
19678            View target;
19679
19680            int left;
19681            int top;
19682            int right;
19683            int bottom;
19684
19685            public static InvalidateInfo obtain() {
19686                InvalidateInfo instance = sPool.acquire();
19687                return (instance != null) ? instance : new InvalidateInfo();
19688            }
19689
19690            public void recycle() {
19691                target = null;
19692                sPool.release(this);
19693            }
19694        }
19695
19696        final IWindowSession mSession;
19697
19698        final IWindow mWindow;
19699
19700        final IBinder mWindowToken;
19701
19702        final Display mDisplay;
19703
19704        final Callbacks mRootCallbacks;
19705
19706        IWindowId mIWindowId;
19707        WindowId mWindowId;
19708
19709        /**
19710         * The top view of the hierarchy.
19711         */
19712        View mRootView;
19713
19714        IBinder mPanelParentWindowToken;
19715
19716        boolean mHardwareAccelerated;
19717        boolean mHardwareAccelerationRequested;
19718        HardwareRenderer mHardwareRenderer;
19719
19720        /**
19721         * The state of the display to which the window is attached, as reported
19722         * by {@link Display#getState()}.  Note that the display state constants
19723         * declared by {@link Display} do not exactly line up with the screen state
19724         * constants declared by {@link View} (there are more display states than
19725         * screen states).
19726         */
19727        int mDisplayState = Display.STATE_UNKNOWN;
19728
19729        /**
19730         * Scale factor used by the compatibility mode
19731         */
19732        float mApplicationScale;
19733
19734        /**
19735         * Indicates whether the application is in compatibility mode
19736         */
19737        boolean mScalingRequired;
19738
19739        /**
19740         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19741         */
19742        boolean mTurnOffWindowResizeAnim;
19743
19744        /**
19745         * Left position of this view's window
19746         */
19747        int mWindowLeft;
19748
19749        /**
19750         * Top position of this view's window
19751         */
19752        int mWindowTop;
19753
19754        /**
19755         * Indicates whether views need to use 32-bit drawing caches
19756         */
19757        boolean mUse32BitDrawingCache;
19758
19759        /**
19760         * For windows that are full-screen but using insets to layout inside
19761         * of the screen areas, these are the current insets to appear inside
19762         * the overscan area of the display.
19763         */
19764        final Rect mOverscanInsets = new Rect();
19765
19766        /**
19767         * For windows that are full-screen but using insets to layout inside
19768         * of the screen decorations, these are the current insets for the
19769         * content of the window.
19770         */
19771        final Rect mContentInsets = new Rect();
19772
19773        /**
19774         * For windows that are full-screen but using insets to layout inside
19775         * of the screen decorations, these are the current insets for the
19776         * actual visible parts of the window.
19777         */
19778        final Rect mVisibleInsets = new Rect();
19779
19780        /**
19781         * The internal insets given by this window.  This value is
19782         * supplied by the client (through
19783         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19784         * be given to the window manager when changed to be used in laying
19785         * out windows behind it.
19786         */
19787        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19788                = new ViewTreeObserver.InternalInsetsInfo();
19789
19790        /**
19791         * Set to true when mGivenInternalInsets is non-empty.
19792         */
19793        boolean mHasNonEmptyGivenInternalInsets;
19794
19795        /**
19796         * All views in the window's hierarchy that serve as scroll containers,
19797         * used to determine if the window can be resized or must be panned
19798         * to adjust for a soft input area.
19799         */
19800        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19801
19802        final KeyEvent.DispatcherState mKeyDispatchState
19803                = new KeyEvent.DispatcherState();
19804
19805        /**
19806         * Indicates whether the view's window currently has the focus.
19807         */
19808        boolean mHasWindowFocus;
19809
19810        /**
19811         * The current visibility of the window.
19812         */
19813        int mWindowVisibility;
19814
19815        /**
19816         * Indicates the time at which drawing started to occur.
19817         */
19818        long mDrawingTime;
19819
19820        /**
19821         * Indicates whether or not ignoring the DIRTY_MASK flags.
19822         */
19823        boolean mIgnoreDirtyState;
19824
19825        /**
19826         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19827         * to avoid clearing that flag prematurely.
19828         */
19829        boolean mSetIgnoreDirtyState = false;
19830
19831        /**
19832         * Indicates whether the view's window is currently in touch mode.
19833         */
19834        boolean mInTouchMode;
19835
19836        /**
19837         * Indicates whether the view has requested unbuffered input dispatching for the current
19838         * event stream.
19839         */
19840        boolean mUnbufferedDispatchRequested;
19841
19842        /**
19843         * Indicates that ViewAncestor should trigger a global layout change
19844         * the next time it performs a traversal
19845         */
19846        boolean mRecomputeGlobalAttributes;
19847
19848        /**
19849         * Always report new attributes at next traversal.
19850         */
19851        boolean mForceReportNewAttributes;
19852
19853        /**
19854         * Set during a traveral if any views want to keep the screen on.
19855         */
19856        boolean mKeepScreenOn;
19857
19858        /**
19859         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19860         */
19861        int mSystemUiVisibility;
19862
19863        /**
19864         * Hack to force certain system UI visibility flags to be cleared.
19865         */
19866        int mDisabledSystemUiVisibility;
19867
19868        /**
19869         * Last global system UI visibility reported by the window manager.
19870         */
19871        int mGlobalSystemUiVisibility;
19872
19873        /**
19874         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19875         * attached.
19876         */
19877        boolean mHasSystemUiListeners;
19878
19879        /**
19880         * Set if the window has requested to extend into the overscan region
19881         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19882         */
19883        boolean mOverscanRequested;
19884
19885        /**
19886         * Set if the visibility of any views has changed.
19887         */
19888        boolean mViewVisibilityChanged;
19889
19890        /**
19891         * Set to true if a view has been scrolled.
19892         */
19893        boolean mViewScrollChanged;
19894
19895        /**
19896         * Global to the view hierarchy used as a temporary for dealing with
19897         * x/y points in the transparent region computations.
19898         */
19899        final int[] mTransparentLocation = new int[2];
19900
19901        /**
19902         * Global to the view hierarchy used as a temporary for dealing with
19903         * x/y points in the ViewGroup.invalidateChild implementation.
19904         */
19905        final int[] mInvalidateChildLocation = new int[2];
19906
19907        /**
19908         * Global to the view hierarchy used as a temporary for dealng with
19909         * computing absolute on-screen location.
19910         */
19911        final int[] mTmpLocation = new int[2];
19912
19913        /**
19914         * Global to the view hierarchy used as a temporary for dealing with
19915         * x/y location when view is transformed.
19916         */
19917        final float[] mTmpTransformLocation = new float[2];
19918
19919        /**
19920         * The view tree observer used to dispatch global events like
19921         * layout, pre-draw, touch mode change, etc.
19922         */
19923        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19924
19925        /**
19926         * A Canvas used by the view hierarchy to perform bitmap caching.
19927         */
19928        Canvas mCanvas;
19929
19930        /**
19931         * The view root impl.
19932         */
19933        final ViewRootImpl mViewRootImpl;
19934
19935        /**
19936         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19937         * handler can be used to pump events in the UI events queue.
19938         */
19939        final Handler mHandler;
19940
19941        /**
19942         * Temporary for use in computing invalidate rectangles while
19943         * calling up the hierarchy.
19944         */
19945        final Rect mTmpInvalRect = new Rect();
19946
19947        /**
19948         * Temporary for use in computing hit areas with transformed views
19949         */
19950        final RectF mTmpTransformRect = new RectF();
19951
19952        /**
19953         * Temporary for use in transforming invalidation rect
19954         */
19955        final Matrix mTmpMatrix = new Matrix();
19956
19957        /**
19958         * Temporary for use in transforming invalidation rect
19959         */
19960        final Transformation mTmpTransformation = new Transformation();
19961
19962        /**
19963         * Temporary list for use in collecting focusable descendents of a view.
19964         */
19965        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19966
19967        /**
19968         * The id of the window for accessibility purposes.
19969         */
19970        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19971
19972        /**
19973         * Flags related to accessibility processing.
19974         *
19975         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19976         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19977         */
19978        int mAccessibilityFetchFlags;
19979
19980        /**
19981         * The drawable for highlighting accessibility focus.
19982         */
19983        Drawable mAccessibilityFocusDrawable;
19984
19985        /**
19986         * Show where the margins, bounds and layout bounds are for each view.
19987         */
19988        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19989
19990        /**
19991         * Point used to compute visible regions.
19992         */
19993        final Point mPoint = new Point();
19994
19995        /**
19996         * Used to track which View originated a requestLayout() call, used when
19997         * requestLayout() is called during layout.
19998         */
19999        View mViewRequestingLayout;
20000
20001        /**
20002         * Creates a new set of attachment information with the specified
20003         * events handler and thread.
20004         *
20005         * @param handler the events handler the view must use
20006         */
20007        AttachInfo(IWindowSession session, IWindow window, Display display,
20008                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20009            mSession = session;
20010            mWindow = window;
20011            mWindowToken = window.asBinder();
20012            mDisplay = display;
20013            mViewRootImpl = viewRootImpl;
20014            mHandler = handler;
20015            mRootCallbacks = effectPlayer;
20016        }
20017    }
20018
20019    /**
20020     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20021     * is supported. This avoids keeping too many unused fields in most
20022     * instances of View.</p>
20023     */
20024    private static class ScrollabilityCache implements Runnable {
20025
20026        /**
20027         * Scrollbars are not visible
20028         */
20029        public static final int OFF = 0;
20030
20031        /**
20032         * Scrollbars are visible
20033         */
20034        public static final int ON = 1;
20035
20036        /**
20037         * Scrollbars are fading away
20038         */
20039        public static final int FADING = 2;
20040
20041        public boolean fadeScrollBars;
20042
20043        public int fadingEdgeLength;
20044        public int scrollBarDefaultDelayBeforeFade;
20045        public int scrollBarFadeDuration;
20046
20047        public int scrollBarSize;
20048        public ScrollBarDrawable scrollBar;
20049        public float[] interpolatorValues;
20050        public View host;
20051
20052        public final Paint paint;
20053        public final Matrix matrix;
20054        public Shader shader;
20055
20056        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20057
20058        private static final float[] OPAQUE = { 255 };
20059        private static final float[] TRANSPARENT = { 0.0f };
20060
20061        /**
20062         * When fading should start. This time moves into the future every time
20063         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20064         */
20065        public long fadeStartTime;
20066
20067
20068        /**
20069         * The current state of the scrollbars: ON, OFF, or FADING
20070         */
20071        public int state = OFF;
20072
20073        private int mLastColor;
20074
20075        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20076            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20077            scrollBarSize = configuration.getScaledScrollBarSize();
20078            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20079            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20080
20081            paint = new Paint();
20082            matrix = new Matrix();
20083            // use use a height of 1, and then wack the matrix each time we
20084            // actually use it.
20085            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20086            paint.setShader(shader);
20087            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20088
20089            this.host = host;
20090        }
20091
20092        public void setFadeColor(int color) {
20093            if (color != mLastColor) {
20094                mLastColor = color;
20095
20096                if (color != 0) {
20097                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20098                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20099                    paint.setShader(shader);
20100                    // Restore the default transfer mode (src_over)
20101                    paint.setXfermode(null);
20102                } else {
20103                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20104                    paint.setShader(shader);
20105                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20106                }
20107            }
20108        }
20109
20110        public void run() {
20111            long now = AnimationUtils.currentAnimationTimeMillis();
20112            if (now >= fadeStartTime) {
20113
20114                // the animation fades the scrollbars out by changing
20115                // the opacity (alpha) from fully opaque to fully
20116                // transparent
20117                int nextFrame = (int) now;
20118                int framesCount = 0;
20119
20120                Interpolator interpolator = scrollBarInterpolator;
20121
20122                // Start opaque
20123                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20124
20125                // End transparent
20126                nextFrame += scrollBarFadeDuration;
20127                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20128
20129                state = FADING;
20130
20131                // Kick off the fade animation
20132                host.invalidate(true);
20133            }
20134        }
20135    }
20136
20137    /**
20138     * Resuable callback for sending
20139     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20140     */
20141    private class SendViewScrolledAccessibilityEvent implements Runnable {
20142        public volatile boolean mIsPending;
20143
20144        public void run() {
20145            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20146            mIsPending = false;
20147        }
20148    }
20149
20150    /**
20151     * <p>
20152     * This class represents a delegate that can be registered in a {@link View}
20153     * to enhance accessibility support via composition rather via inheritance.
20154     * It is specifically targeted to widget developers that extend basic View
20155     * classes i.e. classes in package android.view, that would like their
20156     * applications to be backwards compatible.
20157     * </p>
20158     * <div class="special reference">
20159     * <h3>Developer Guides</h3>
20160     * <p>For more information about making applications accessible, read the
20161     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20162     * developer guide.</p>
20163     * </div>
20164     * <p>
20165     * A scenario in which a developer would like to use an accessibility delegate
20166     * is overriding a method introduced in a later API version then the minimal API
20167     * version supported by the application. For example, the method
20168     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20169     * in API version 4 when the accessibility APIs were first introduced. If a
20170     * developer would like his application to run on API version 4 devices (assuming
20171     * all other APIs used by the application are version 4 or lower) and take advantage
20172     * of this method, instead of overriding the method which would break the application's
20173     * backwards compatibility, he can override the corresponding method in this
20174     * delegate and register the delegate in the target View if the API version of
20175     * the system is high enough i.e. the API version is same or higher to the API
20176     * version that introduced
20177     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20178     * </p>
20179     * <p>
20180     * Here is an example implementation:
20181     * </p>
20182     * <code><pre><p>
20183     * if (Build.VERSION.SDK_INT >= 14) {
20184     *     // If the API version is equal of higher than the version in
20185     *     // which onInitializeAccessibilityNodeInfo was introduced we
20186     *     // register a delegate with a customized implementation.
20187     *     View view = findViewById(R.id.view_id);
20188     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20189     *         public void onInitializeAccessibilityNodeInfo(View host,
20190     *                 AccessibilityNodeInfo info) {
20191     *             // Let the default implementation populate the info.
20192     *             super.onInitializeAccessibilityNodeInfo(host, info);
20193     *             // Set some other information.
20194     *             info.setEnabled(host.isEnabled());
20195     *         }
20196     *     });
20197     * }
20198     * </code></pre></p>
20199     * <p>
20200     * This delegate contains methods that correspond to the accessibility methods
20201     * in View. If a delegate has been specified the implementation in View hands
20202     * off handling to the corresponding method in this delegate. The default
20203     * implementation the delegate methods behaves exactly as the corresponding
20204     * method in View for the case of no accessibility delegate been set. Hence,
20205     * to customize the behavior of a View method, clients can override only the
20206     * corresponding delegate method without altering the behavior of the rest
20207     * accessibility related methods of the host view.
20208     * </p>
20209     */
20210    public static class AccessibilityDelegate {
20211
20212        /**
20213         * Sends an accessibility event of the given type. If accessibility is not
20214         * enabled this method has no effect.
20215         * <p>
20216         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20217         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20218         * been set.
20219         * </p>
20220         *
20221         * @param host The View hosting the delegate.
20222         * @param eventType The type of the event to send.
20223         *
20224         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20225         */
20226        public void sendAccessibilityEvent(View host, int eventType) {
20227            host.sendAccessibilityEventInternal(eventType);
20228        }
20229
20230        /**
20231         * Performs the specified accessibility action on the view. For
20232         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20233         * <p>
20234         * The default implementation behaves as
20235         * {@link View#performAccessibilityAction(int, Bundle)
20236         *  View#performAccessibilityAction(int, Bundle)} for the case of
20237         *  no accessibility delegate been set.
20238         * </p>
20239         *
20240         * @param action The action to perform.
20241         * @return Whether the action was performed.
20242         *
20243         * @see View#performAccessibilityAction(int, Bundle)
20244         *      View#performAccessibilityAction(int, Bundle)
20245         */
20246        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20247            return host.performAccessibilityActionInternal(action, args);
20248        }
20249
20250        /**
20251         * Sends an accessibility event. This method behaves exactly as
20252         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20253         * empty {@link AccessibilityEvent} and does not perform a check whether
20254         * accessibility is enabled.
20255         * <p>
20256         * The default implementation behaves as
20257         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20258         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20259         * the case of no accessibility delegate been set.
20260         * </p>
20261         *
20262         * @param host The View hosting the delegate.
20263         * @param event The event to send.
20264         *
20265         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20266         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20267         */
20268        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20269            host.sendAccessibilityEventUncheckedInternal(event);
20270        }
20271
20272        /**
20273         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20274         * to its children for adding their text content to the event.
20275         * <p>
20276         * The default implementation behaves as
20277         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20278         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20279         * the case of no accessibility delegate been set.
20280         * </p>
20281         *
20282         * @param host The View hosting the delegate.
20283         * @param event The event.
20284         * @return True if the event population was completed.
20285         *
20286         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20287         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20288         */
20289        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20290            return host.dispatchPopulateAccessibilityEventInternal(event);
20291        }
20292
20293        /**
20294         * Gives a chance to the host View to populate the accessibility event with its
20295         * text content.
20296         * <p>
20297         * The default implementation behaves as
20298         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20299         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20300         * the case of no accessibility delegate been set.
20301         * </p>
20302         *
20303         * @param host The View hosting the delegate.
20304         * @param event The accessibility event which to populate.
20305         *
20306         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20307         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20308         */
20309        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20310            host.onPopulateAccessibilityEventInternal(event);
20311        }
20312
20313        /**
20314         * Initializes an {@link AccessibilityEvent} with information about the
20315         * the host View which is the event source.
20316         * <p>
20317         * The default implementation behaves as
20318         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20319         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20320         * the case of no accessibility delegate been set.
20321         * </p>
20322         *
20323         * @param host The View hosting the delegate.
20324         * @param event The event to initialize.
20325         *
20326         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20327         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20328         */
20329        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20330            host.onInitializeAccessibilityEventInternal(event);
20331        }
20332
20333        /**
20334         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20335         * <p>
20336         * The default implementation behaves as
20337         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20338         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20339         * the case of no accessibility delegate been set.
20340         * </p>
20341         *
20342         * @param host The View hosting the delegate.
20343         * @param info The instance to initialize.
20344         *
20345         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20346         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20347         */
20348        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20349            host.onInitializeAccessibilityNodeInfoInternal(info);
20350        }
20351
20352        /**
20353         * Called when a child of the host View has requested sending an
20354         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20355         * to augment the event.
20356         * <p>
20357         * The default implementation behaves as
20358         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20359         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20360         * the case of no accessibility delegate been set.
20361         * </p>
20362         *
20363         * @param host The View hosting the delegate.
20364         * @param child The child which requests sending the event.
20365         * @param event The event to be sent.
20366         * @return True if the event should be sent
20367         *
20368         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20369         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20370         */
20371        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20372                AccessibilityEvent event) {
20373            return host.onRequestSendAccessibilityEventInternal(child, event);
20374        }
20375
20376        /**
20377         * Gets the provider for managing a virtual view hierarchy rooted at this View
20378         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20379         * that explore the window content.
20380         * <p>
20381         * The default implementation behaves as
20382         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20383         * the case of no accessibility delegate been set.
20384         * </p>
20385         *
20386         * @return The provider.
20387         *
20388         * @see AccessibilityNodeProvider
20389         */
20390        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20391            return null;
20392        }
20393
20394        /**
20395         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20396         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20397         * This method is responsible for obtaining an accessibility node info from a
20398         * pool of reusable instances and calling
20399         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20400         * view to initialize the former.
20401         * <p>
20402         * <strong>Note:</strong> The client is responsible for recycling the obtained
20403         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20404         * creation.
20405         * </p>
20406         * <p>
20407         * The default implementation behaves as
20408         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20409         * the case of no accessibility delegate been set.
20410         * </p>
20411         * @return A populated {@link AccessibilityNodeInfo}.
20412         *
20413         * @see AccessibilityNodeInfo
20414         *
20415         * @hide
20416         */
20417        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20418            return host.createAccessibilityNodeInfoInternal();
20419        }
20420    }
20421
20422    private class MatchIdPredicate implements Predicate<View> {
20423        public int mId;
20424
20425        @Override
20426        public boolean apply(View view) {
20427            return (view.mID == mId);
20428        }
20429    }
20430
20431    private class MatchLabelForPredicate implements Predicate<View> {
20432        private int mLabeledId;
20433
20434        @Override
20435        public boolean apply(View view) {
20436            return (view.mLabelForId == mLabeledId);
20437        }
20438    }
20439
20440    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20441        private int mChangeTypes = 0;
20442        private boolean mPosted;
20443        private boolean mPostedWithDelay;
20444        private long mLastEventTimeMillis;
20445
20446        @Override
20447        public void run() {
20448            mPosted = false;
20449            mPostedWithDelay = false;
20450            mLastEventTimeMillis = SystemClock.uptimeMillis();
20451            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20452                final AccessibilityEvent event = AccessibilityEvent.obtain();
20453                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20454                event.setContentChangeTypes(mChangeTypes);
20455                sendAccessibilityEventUnchecked(event);
20456            }
20457            mChangeTypes = 0;
20458        }
20459
20460        public void runOrPost(int changeType) {
20461            mChangeTypes |= changeType;
20462
20463            // If this is a live region or the child of a live region, collect
20464            // all events from this frame and send them on the next frame.
20465            if (inLiveRegion()) {
20466                // If we're already posted with a delay, remove that.
20467                if (mPostedWithDelay) {
20468                    removeCallbacks(this);
20469                    mPostedWithDelay = false;
20470                }
20471                // Only post if we're not already posted.
20472                if (!mPosted) {
20473                    post(this);
20474                    mPosted = true;
20475                }
20476                return;
20477            }
20478
20479            if (mPosted) {
20480                return;
20481            }
20482            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20483            final long minEventIntevalMillis =
20484                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20485            if (timeSinceLastMillis >= minEventIntevalMillis) {
20486                removeCallbacks(this);
20487                run();
20488            } else {
20489                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20490                mPosted = true;
20491                mPostedWithDelay = true;
20492            }
20493        }
20494    }
20495
20496    private boolean inLiveRegion() {
20497        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20498            return true;
20499        }
20500
20501        ViewParent parent = getParent();
20502        while (parent instanceof View) {
20503            if (((View) parent).getAccessibilityLiveRegion()
20504                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20505                return true;
20506            }
20507            parent = parent.getParent();
20508        }
20509
20510        return false;
20511    }
20512
20513    /**
20514     * Dump all private flags in readable format, useful for documentation and
20515     * sanity checking.
20516     */
20517    private static void dumpFlags() {
20518        final HashMap<String, String> found = Maps.newHashMap();
20519        try {
20520            for (Field field : View.class.getDeclaredFields()) {
20521                final int modifiers = field.getModifiers();
20522                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20523                    if (field.getType().equals(int.class)) {
20524                        final int value = field.getInt(null);
20525                        dumpFlag(found, field.getName(), value);
20526                    } else if (field.getType().equals(int[].class)) {
20527                        final int[] values = (int[]) field.get(null);
20528                        for (int i = 0; i < values.length; i++) {
20529                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20530                        }
20531                    }
20532                }
20533            }
20534        } catch (IllegalAccessException e) {
20535            throw new RuntimeException(e);
20536        }
20537
20538        final ArrayList<String> keys = Lists.newArrayList();
20539        keys.addAll(found.keySet());
20540        Collections.sort(keys);
20541        for (String key : keys) {
20542            Log.d(VIEW_LOG_TAG, found.get(key));
20543        }
20544    }
20545
20546    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20547        // Sort flags by prefix, then by bits, always keeping unique keys
20548        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20549        final int prefix = name.indexOf('_');
20550        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20551        final String output = bits + " " + name;
20552        found.put(key, output);
20553    }
20554}
20555