View.java revision 9985aaf2688a84181f4c0efec47f51d453f76379
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.PixelFormat;
39import android.graphics.Point;
40import android.graphics.PorterDuff;
41import android.graphics.PorterDuffXfermode;
42import android.graphics.Rect;
43import android.graphics.RectF;
44import android.graphics.Region;
45import android.graphics.Shader;
46import android.graphics.drawable.ColorDrawable;
47import android.graphics.drawable.Drawable;
48import android.hardware.display.DisplayManagerGlobal;
49import android.os.Bundle;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.Parcel;
53import android.os.Parcelable;
54import android.os.RemoteException;
55import android.os.SystemClock;
56import android.os.SystemProperties;
57import android.text.TextUtils;
58import android.util.AttributeSet;
59import android.util.FloatProperty;
60import android.util.LayoutDirection;
61import android.util.Log;
62import android.util.LongSparseLongArray;
63import android.util.Pools.SynchronizedPool;
64import android.util.Property;
65import android.util.SparseArray;
66import android.util.SuperNotCalledException;
67import android.util.TypedValue;
68import android.view.ContextMenu.ContextMenuInfo;
69import android.view.AccessibilityIterators.TextSegmentIterator;
70import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
71import android.view.AccessibilityIterators.WordTextSegmentIterator;
72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
73import android.view.accessibility.AccessibilityEvent;
74import android.view.accessibility.AccessibilityEventSource;
75import android.view.accessibility.AccessibilityManager;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeProvider;
78import android.view.animation.Animation;
79import android.view.animation.AnimationUtils;
80import android.view.animation.Transformation;
81import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.ScrollBarDrawable;
85
86import static android.os.Build.VERSION_CODES.*;
87import static java.lang.Math.max;
88
89import com.android.internal.R;
90import com.android.internal.util.Predicate;
91import com.android.internal.view.menu.MenuBuilder;
92
93import com.google.android.collect.Lists;
94import com.google.android.collect.Maps;
95
96import java.lang.annotation.Retention;
97import java.lang.annotation.RetentionPolicy;
98import java.lang.ref.WeakReference;
99import java.lang.reflect.Field;
100import java.lang.reflect.InvocationTargetException;
101import java.lang.reflect.Method;
102import java.lang.reflect.Modifier;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.HashMap;
107import java.util.List;
108import java.util.Locale;
109import java.util.Map;
110import java.util.concurrent.CopyOnWriteArrayList;
111import java.util.concurrent.atomic.AtomicInteger;
112
113/**
114 * <p>
115 * This class represents the basic building block for user interface components. A View
116 * occupies a rectangular area on the screen and is responsible for drawing and
117 * event handling. View is the base class for <em>widgets</em>, which are
118 * used to create interactive UI components (buttons, text fields, etc.). The
119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
120 * are invisible containers that hold other Views (or other ViewGroups) and define
121 * their layout properties.
122 * </p>
123 *
124 * <div class="special reference">
125 * <h3>Developer Guides</h3>
126 * <p>For information about using this class to develop your application's user interface,
127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
128 * </div>
129 *
130 * <a name="Using"></a>
131 * <h3>Using Views</h3>
132 * <p>
133 * All of the views in a window are arranged in a single tree. You can add views
134 * either from code or by specifying a tree of views in one or more XML layout
135 * files. There are many specialized subclasses of views that act as controls or
136 * are capable of displaying text, images, or other content.
137 * </p>
138 * <p>
139 * Once you have created a tree of views, there are typically a few types of
140 * common operations you may wish to perform:
141 * <ul>
142 * <li><strong>Set properties:</strong> for example setting the text of a
143 * {@link android.widget.TextView}. The available properties and the methods
144 * that set them will vary among the different subclasses of views. Note that
145 * properties that are known at build time can be set in the XML layout
146 * files.</li>
147 * <li><strong>Set focus:</strong> The framework will handled moving focus in
148 * response to user input. To force focus to a specific view, call
149 * {@link #requestFocus}.</li>
150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
151 * that will be notified when something interesting happens to the view. For
152 * example, all views will let you set a listener to be notified when the view
153 * gains or loses focus. You can register such a listener using
154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
155 * Other view subclasses offer more specialized listeners. For example, a Button
156 * exposes a listener to notify clients when the button is clicked.</li>
157 * <li><strong>Set visibility:</strong> You can hide or show views using
158 * {@link #setVisibility(int)}.</li>
159 * </ul>
160 * </p>
161 * <p><em>
162 * Note: The Android framework is responsible for measuring, laying out and
163 * drawing views. You should not call methods that perform these actions on
164 * views yourself unless you are actually implementing a
165 * {@link android.view.ViewGroup}.
166 * </em></p>
167 *
168 * <a name="Lifecycle"></a>
169 * <h3>Implementing a Custom View</h3>
170 *
171 * <p>
172 * To implement a custom view, you will usually begin by providing overrides for
173 * some of the standard methods that the framework calls on all views. You do
174 * not need to override all of these methods. In fact, you can start by just
175 * overriding {@link #onDraw(android.graphics.Canvas)}.
176 * <table border="2" width="85%" align="center" cellpadding="5">
177 *     <thead>
178 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
179 *     </thead>
180 *
181 *     <tbody>
182 *     <tr>
183 *         <td rowspan="2">Creation</td>
184 *         <td>Constructors</td>
185 *         <td>There is a form of the constructor that are called when the view
186 *         is created from code and a form that is called when the view is
187 *         inflated from a layout file. The second form should parse and apply
188 *         any attributes defined in the layout file.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onFinishInflate()}</code></td>
193 *         <td>Called after a view and all of its children has been inflated
194 *         from XML.</td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="3">Layout</td>
199 *         <td><code>{@link #onMeasure(int, int)}</code></td>
200 *         <td>Called to determine the size requirements for this view and all
201 *         of its children.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
206 *         <td>Called when this view should assign a size and position to all
207 *         of its children.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
212 *         <td>Called when the size of this view has changed.
213 *         </td>
214 *     </tr>
215 *
216 *     <tr>
217 *         <td>Drawing</td>
218 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
219 *         <td>Called when the view should render its content.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="4">Event processing</td>
225 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
226 *         <td>Called when a new hardware key event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
231 *         <td>Called when a hardware key up event occurs.
232 *         </td>
233 *     </tr>
234 *     <tr>
235 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
236 *         <td>Called when a trackball motion event occurs.
237 *         </td>
238 *     </tr>
239 *     <tr>
240 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
241 *         <td>Called when a touch screen motion event occurs.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="2">Focus</td>
247 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
248 *         <td>Called when the view gains or loses focus.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
254 *         <td>Called when the window containing the view gains or loses focus.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="3">Attaching</td>
260 *         <td><code>{@link #onAttachedToWindow()}</code></td>
261 *         <td>Called when the view is attached to a window.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onDetachedFromWindow}</code></td>
267 *         <td>Called when the view is detached from its window.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
273 *         <td>Called when the visibility of the window containing the view
274 *         has changed.
275 *         </td>
276 *     </tr>
277 *     </tbody>
278 *
279 * </table>
280 * </p>
281 *
282 * <a name="IDs"></a>
283 * <h3>IDs</h3>
284 * Views may have an integer id associated with them. These ids are typically
285 * assigned in the layout XML files, and are used to find specific views within
286 * the view tree. A common pattern is to:
287 * <ul>
288 * <li>Define a Button in the layout file and assign it a unique ID.
289 * <pre>
290 * &lt;Button
291 *     android:id="@+id/my_button"
292 *     android:layout_width="wrap_content"
293 *     android:layout_height="wrap_content"
294 *     android:text="@string/my_button_text"/&gt;
295 * </pre></li>
296 * <li>From the onCreate method of an Activity, find the Button
297 * <pre class="prettyprint">
298 *      Button myButton = (Button) findViewById(R.id.my_button);
299 * </pre></li>
300 * </ul>
301 * <p>
302 * View IDs need not be unique throughout the tree, but it is good practice to
303 * ensure that they are at least unique within the part of the tree you are
304 * searching.
305 * </p>
306 *
307 * <a name="Position"></a>
308 * <h3>Position</h3>
309 * <p>
310 * The geometry of a view is that of a rectangle. A view has a location,
311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
312 * two dimensions, expressed as a width and a height. The unit for location
313 * and dimensions is the pixel.
314 * </p>
315 *
316 * <p>
317 * It is possible to retrieve the location of a view by invoking the methods
318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
319 * coordinate of the rectangle representing the view. The latter returns the
320 * top, or Y, coordinate of the rectangle representing the view. These methods
321 * both return the location of the view relative to its parent. For instance,
322 * when getLeft() returns 20, that means the view is located 20 pixels to the
323 * right of the left edge of its direct parent.
324 * </p>
325 *
326 * <p>
327 * In addition, several convenience methods are offered to avoid unnecessary
328 * computations, namely {@link #getRight()} and {@link #getBottom()}.
329 * These methods return the coordinates of the right and bottom edges of the
330 * rectangle representing the view. For instance, calling {@link #getRight()}
331 * is similar to the following computation: <code>getLeft() + getWidth()</code>
332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
333 * </p>
334 *
335 * <a name="SizePaddingMargins"></a>
336 * <h3>Size, padding and margins</h3>
337 * <p>
338 * The size of a view is expressed with a width and a height. A view actually
339 * possess two pairs of width and height values.
340 * </p>
341 *
342 * <p>
343 * The first pair is known as <em>measured width</em> and
344 * <em>measured height</em>. These dimensions define how big a view wants to be
345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
347 * and {@link #getMeasuredHeight()}.
348 * </p>
349 *
350 * <p>
351 * The second pair is simply known as <em>width</em> and <em>height</em>, or
352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
353 * dimensions define the actual size of the view on screen, at drawing time and
354 * after layout. These values may, but do not have to, be different from the
355 * measured width and height. The width and height can be obtained by calling
356 * {@link #getWidth()} and {@link #getHeight()}.
357 * </p>
358 *
359 * <p>
360 * To measure its dimensions, a view takes into account its padding. The padding
361 * is expressed in pixels for the left, top, right and bottom parts of the view.
362 * Padding can be used to offset the content of the view by a specific amount of
363 * pixels. For instance, a left padding of 2 will push the view's content by
364 * 2 pixels to the right of the left edge. Padding can be set using the
365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
368 * {@link #getPaddingEnd()}.
369 * </p>
370 *
371 * <p>
372 * Even though a view can define a padding, it does not provide any support for
373 * margins. However, view groups provide such a support. Refer to
374 * {@link android.view.ViewGroup} and
375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
376 * </p>
377 *
378 * <a name="Layout"></a>
379 * <h3>Layout</h3>
380 * <p>
381 * Layout is a two pass process: a measure pass and a layout pass. The measuring
382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
383 * of the view tree. Each view pushes dimension specifications down the tree
384 * during the recursion. At the end of the measure pass, every view has stored
385 * its measurements. The second pass happens in
386 * {@link #layout(int,int,int,int)} and is also top-down. During
387 * this pass each parent is responsible for positioning all of its children
388 * using the sizes computed in the measure pass.
389 * </p>
390 *
391 * <p>
392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
393 * {@link #getMeasuredHeight()} values must be set, along with those for all of
394 * that view's descendants. A view's measured width and measured height values
395 * must respect the constraints imposed by the view's parents. This guarantees
396 * that at the end of the measure pass, all parents accept all of their
397 * children's measurements. A parent view may call measure() more than once on
398 * its children. For example, the parent may measure each child once with
399 * unspecified dimensions to find out how big they want to be, then call
400 * measure() on them again with actual numbers if the sum of all the children's
401 * unconstrained sizes is too big or too small.
402 * </p>
403 *
404 * <p>
405 * The measure pass uses two classes to communicate dimensions. The
406 * {@link MeasureSpec} class is used by views to tell their parents how they
407 * want to be measured and positioned. The base LayoutParams class just
408 * describes how big the view wants to be for both width and height. For each
409 * dimension, it can specify one of:
410 * <ul>
411 * <li> an exact number
412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
413 * (minus padding)
414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
415 * enclose its content (plus padding).
416 * </ul>
417 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
419 * an X and Y value.
420 * </p>
421 *
422 * <p>
423 * MeasureSpecs are used to push requirements down the tree from parent to
424 * child. A MeasureSpec can be in one of three modes:
425 * <ul>
426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
427 * of a child view. For example, a LinearLayout may call measure() on its child
428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
429 * tall the child view wants to be given a width of 240 pixels.
430 * <li>EXACTLY: This is used by the parent to impose an exact size on the
431 * child. The child must use this size, and guarantee that all of its
432 * descendants will fit within this size.
433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
434 * child. The child must guarantee that it and all of its descendants will fit
435 * within this size.
436 * </ul>
437 * </p>
438 *
439 * <p>
440 * To intiate a layout, call {@link #requestLayout}. This method is typically
441 * called by a view on itself when it believes that is can no longer fit within
442 * its current bounds.
443 * </p>
444 *
445 * <a name="Drawing"></a>
446 * <h3>Drawing</h3>
447 * <p>
448 * Drawing is handled by walking the tree and rendering each view that
449 * intersects the invalid region. Because the tree is traversed in-order,
450 * this means that parents will draw before (i.e., behind) their children, with
451 * siblings drawn in the order they appear in the tree.
452 * If you set a background drawable for a View, then the View will draw it for you
453 * before calling back to its <code>onDraw()</code> method.
454 * </p>
455 *
456 * <p>
457 * Note that the framework will not draw views that are not in the invalid region.
458 * </p>
459 *
460 * <p>
461 * To force a view to draw, call {@link #invalidate()}.
462 * </p>
463 *
464 * <a name="EventHandlingThreading"></a>
465 * <h3>Event Handling and Threading</h3>
466 * <p>
467 * The basic cycle of a view is as follows:
468 * <ol>
469 * <li>An event comes in and is dispatched to the appropriate view. The view
470 * handles the event and notifies any listeners.</li>
471 * <li>If in the course of processing the event, the view's bounds may need
472 * to be changed, the view will call {@link #requestLayout()}.</li>
473 * <li>Similarly, if in the course of processing the event the view's appearance
474 * may need to be changed, the view will call {@link #invalidate()}.</li>
475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
476 * the framework will take care of measuring, laying out, and drawing the tree
477 * as appropriate.</li>
478 * </ol>
479 * </p>
480 *
481 * <p><em>Note: The entire view tree is single threaded. You must always be on
482 * the UI thread when calling any method on any view.</em>
483 * If you are doing work on other threads and want to update the state of a view
484 * from that thread, you should use a {@link Handler}.
485 * </p>
486 *
487 * <a name="FocusHandling"></a>
488 * <h3>Focus Handling</h3>
489 * <p>
490 * The framework will handle routine focus movement in response to user input.
491 * This includes changing the focus as views are removed or hidden, or as new
492 * views become available. Views indicate their willingness to take focus
493 * through the {@link #isFocusable} method. To change whether a view can take
494 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
496 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
497 * </p>
498 * <p>
499 * Focus movement is based on an algorithm which finds the nearest neighbor in a
500 * given direction. In rare cases, the default algorithm may not match the
501 * intended behavior of the developer. In these situations, you can provide
502 * explicit overrides by using these XML attributes in the layout file:
503 * <pre>
504 * nextFocusDown
505 * nextFocusLeft
506 * nextFocusRight
507 * nextFocusUp
508 * </pre>
509 * </p>
510 *
511 *
512 * <p>
513 * To get a particular view to take focus, call {@link #requestFocus()}.
514 * </p>
515 *
516 * <a name="TouchMode"></a>
517 * <h3>Touch Mode</h3>
518 * <p>
519 * When a user is navigating a user interface via directional keys such as a D-pad, it is
520 * necessary to give focus to actionable items such as buttons so the user can see
521 * what will take input.  If the device has touch capabilities, however, and the user
522 * begins interacting with the interface by touching it, it is no longer necessary to
523 * always highlight, or give focus to, a particular view.  This motivates a mode
524 * for interaction named 'touch mode'.
525 * </p>
526 * <p>
527 * For a touch capable device, once the user touches the screen, the device
528 * will enter touch mode.  From this point onward, only views for which
529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
530 * Other views that are touchable, like buttons, will not take focus when touched; they will
531 * only fire the on click listeners.
532 * </p>
533 * <p>
534 * Any time a user hits a directional key, such as a D-pad direction, the view device will
535 * exit touch mode, and find a view to take focus, so that the user may resume interacting
536 * with the user interface without touching the screen again.
537 * </p>
538 * <p>
539 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
540 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
541 * </p>
542 *
543 * <a name="Scrolling"></a>
544 * <h3>Scrolling</h3>
545 * <p>
546 * The framework provides basic support for views that wish to internally
547 * scroll their content. This includes keeping track of the X and Y scroll
548 * offset as well as mechanisms for drawing scrollbars. See
549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
550 * {@link #awakenScrollBars()} for more details.
551 * </p>
552 *
553 * <a name="Tags"></a>
554 * <h3>Tags</h3>
555 * <p>
556 * Unlike IDs, tags are not used to identify views. Tags are essentially an
557 * extra piece of information that can be associated with a view. They are most
558 * often used as a convenience to store data related to views in the views
559 * themselves rather than by putting them in a separate structure.
560 * </p>
561 *
562 * <a name="Properties"></a>
563 * <h3>Properties</h3>
564 * <p>
565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
567 * available both in the {@link Property} form as well as in similarly-named setter/getter
568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
569 * be used to set persistent state associated with these rendering-related properties on the view.
570 * The properties and methods can also be used in conjunction with
571 * {@link android.animation.Animator Animator}-based animations, described more in the
572 * <a href="#Animation">Animation</a> section.
573 * </p>
574 *
575 * <a name="Animation"></a>
576 * <h3>Animation</h3>
577 * <p>
578 * Starting with Android 3.0, the preferred way of animating views is to use the
579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
584 * makes animating these View properties particularly easy and efficient.
585 * </p>
586 * <p>
587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
588 * You can attach an {@link Animation} object to a view using
589 * {@link #setAnimation(Animation)} or
590 * {@link #startAnimation(Animation)}. The animation can alter the scale,
591 * rotation, translation and alpha of a view over time. If the animation is
592 * attached to a view that has children, the animation will affect the entire
593 * subtree rooted by that node. When an animation is started, the framework will
594 * take care of redrawing the appropriate views until the animation completes.
595 * </p>
596 *
597 * <a name="Security"></a>
598 * <h3>Security</h3>
599 * <p>
600 * Sometimes it is essential that an application be able to verify that an action
601 * is being performed with the full knowledge and consent of the user, such as
602 * granting a permission request, making a purchase or clicking on an advertisement.
603 * Unfortunately, a malicious application could try to spoof the user into
604 * performing these actions, unaware, by concealing the intended purpose of the view.
605 * As a remedy, the framework offers a touch filtering mechanism that can be used to
606 * improve the security of views that provide access to sensitive functionality.
607 * </p><p>
608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
609 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
610 * will discard touches that are received whenever the view's window is obscured by
611 * another visible window.  As a result, the view will not receive touches whenever a
612 * toast, dialog or other window appears above the view's window.
613 * </p><p>
614 * For more fine-grained control over security, consider overriding the
615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
617 * </p>
618 *
619 * @attr ref android.R.styleable#View_alpha
620 * @attr ref android.R.styleable#View_background
621 * @attr ref android.R.styleable#View_clickable
622 * @attr ref android.R.styleable#View_contentDescription
623 * @attr ref android.R.styleable#View_drawingCacheQuality
624 * @attr ref android.R.styleable#View_duplicateParentState
625 * @attr ref android.R.styleable#View_id
626 * @attr ref android.R.styleable#View_requiresFadingEdge
627 * @attr ref android.R.styleable#View_fadeScrollbars
628 * @attr ref android.R.styleable#View_fadingEdgeLength
629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
630 * @attr ref android.R.styleable#View_fitsSystemWindows
631 * @attr ref android.R.styleable#View_isScrollContainer
632 * @attr ref android.R.styleable#View_focusable
633 * @attr ref android.R.styleable#View_focusableInTouchMode
634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
635 * @attr ref android.R.styleable#View_keepScreenOn
636 * @attr ref android.R.styleable#View_layerType
637 * @attr ref android.R.styleable#View_layoutDirection
638 * @attr ref android.R.styleable#View_longClickable
639 * @attr ref android.R.styleable#View_minHeight
640 * @attr ref android.R.styleable#View_minWidth
641 * @attr ref android.R.styleable#View_nextFocusDown
642 * @attr ref android.R.styleable#View_nextFocusLeft
643 * @attr ref android.R.styleable#View_nextFocusRight
644 * @attr ref android.R.styleable#View_nextFocusUp
645 * @attr ref android.R.styleable#View_onClick
646 * @attr ref android.R.styleable#View_padding
647 * @attr ref android.R.styleable#View_paddingBottom
648 * @attr ref android.R.styleable#View_paddingLeft
649 * @attr ref android.R.styleable#View_paddingRight
650 * @attr ref android.R.styleable#View_paddingTop
651 * @attr ref android.R.styleable#View_paddingStart
652 * @attr ref android.R.styleable#View_paddingEnd
653 * @attr ref android.R.styleable#View_saveEnabled
654 * @attr ref android.R.styleable#View_rotation
655 * @attr ref android.R.styleable#View_rotationX
656 * @attr ref android.R.styleable#View_rotationY
657 * @attr ref android.R.styleable#View_scaleX
658 * @attr ref android.R.styleable#View_scaleY
659 * @attr ref android.R.styleable#View_scrollX
660 * @attr ref android.R.styleable#View_scrollY
661 * @attr ref android.R.styleable#View_scrollbarSize
662 * @attr ref android.R.styleable#View_scrollbarStyle
663 * @attr ref android.R.styleable#View_scrollbars
664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
665 * @attr ref android.R.styleable#View_scrollbarFadeDuration
666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
668 * @attr ref android.R.styleable#View_scrollbarThumbVertical
669 * @attr ref android.R.styleable#View_scrollbarTrackVertical
670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
672 * @attr ref android.R.styleable#View_stateListAnimator
673 * @attr ref android.R.styleable#View_transitionName
674 * @attr ref android.R.styleable#View_soundEffectsEnabled
675 * @attr ref android.R.styleable#View_tag
676 * @attr ref android.R.styleable#View_textAlignment
677 * @attr ref android.R.styleable#View_textDirection
678 * @attr ref android.R.styleable#View_transformPivotX
679 * @attr ref android.R.styleable#View_transformPivotY
680 * @attr ref android.R.styleable#View_translationX
681 * @attr ref android.R.styleable#View_translationY
682 * @attr ref android.R.styleable#View_translationZ
683 * @attr ref android.R.styleable#View_visibility
684 *
685 * @see android.view.ViewGroup
686 */
687public class View implements Drawable.Callback, KeyEvent.Callback,
688        AccessibilityEventSource {
689    private static final boolean DBG = false;
690
691    /**
692     * The logging tag used by this class with android.util.Log.
693     */
694    protected static final String VIEW_LOG_TAG = "View";
695
696    /**
697     * When set to true, apps will draw debugging information about their layouts.
698     *
699     * @hide
700     */
701    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
702
703    /**
704     * Used to mark a View that has no ID.
705     */
706    public static final int NO_ID = -1;
707
708    /**
709     * Signals that compatibility booleans have been initialized according to
710     * target SDK versions.
711     */
712    private static boolean sCompatibilityDone = false;
713
714    /**
715     * Use the old (broken) way of building MeasureSpecs.
716     */
717    private static boolean sUseBrokenMakeMeasureSpec = false;
718
719    /**
720     * Ignore any optimizations using the measure cache.
721     */
722    private static boolean sIgnoreMeasureCache = false;
723
724    /**
725     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
726     * calling setFlags.
727     */
728    private static final int NOT_FOCUSABLE = 0x00000000;
729
730    /**
731     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
732     * setFlags.
733     */
734    private static final int FOCUSABLE = 0x00000001;
735
736    /**
737     * Mask for use with setFlags indicating bits used for focus.
738     */
739    private static final int FOCUSABLE_MASK = 0x00000001;
740
741    /**
742     * This view will adjust its padding to fit sytem windows (e.g. status bar)
743     */
744    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
745
746    /** @hide */
747    @IntDef({VISIBLE, INVISIBLE, GONE})
748    @Retention(RetentionPolicy.SOURCE)
749    public @interface Visibility {}
750
751    /**
752     * This view is visible.
753     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
754     * android:visibility}.
755     */
756    public static final int VISIBLE = 0x00000000;
757
758    /**
759     * This view is invisible, but it still takes up space for layout purposes.
760     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
761     * android:visibility}.
762     */
763    public static final int INVISIBLE = 0x00000004;
764
765    /**
766     * This view is invisible, and it doesn't take any space for layout
767     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
768     * android:visibility}.
769     */
770    public static final int GONE = 0x00000008;
771
772    /**
773     * Mask for use with setFlags indicating bits used for visibility.
774     * {@hide}
775     */
776    static final int VISIBILITY_MASK = 0x0000000C;
777
778    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
779
780    /**
781     * This view is enabled. Interpretation varies by subclass.
782     * Use with ENABLED_MASK when calling setFlags.
783     * {@hide}
784     */
785    static final int ENABLED = 0x00000000;
786
787    /**
788     * This view is disabled. Interpretation varies by subclass.
789     * Use with ENABLED_MASK when calling setFlags.
790     * {@hide}
791     */
792    static final int DISABLED = 0x00000020;
793
794   /**
795    * Mask for use with setFlags indicating bits used for indicating whether
796    * this view is enabled
797    * {@hide}
798    */
799    static final int ENABLED_MASK = 0x00000020;
800
801    /**
802     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
803     * called and further optimizations will be performed. It is okay to have
804     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
805     * {@hide}
806     */
807    static final int WILL_NOT_DRAW = 0x00000080;
808
809    /**
810     * Mask for use with setFlags indicating bits used for indicating whether
811     * this view is will draw
812     * {@hide}
813     */
814    static final int DRAW_MASK = 0x00000080;
815
816    /**
817     * <p>This view doesn't show scrollbars.</p>
818     * {@hide}
819     */
820    static final int SCROLLBARS_NONE = 0x00000000;
821
822    /**
823     * <p>This view shows horizontal scrollbars.</p>
824     * {@hide}
825     */
826    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
827
828    /**
829     * <p>This view shows vertical scrollbars.</p>
830     * {@hide}
831     */
832    static final int SCROLLBARS_VERTICAL = 0x00000200;
833
834    /**
835     * <p>Mask for use with setFlags indicating bits used for indicating which
836     * scrollbars are enabled.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_MASK = 0x00000300;
840
841    /**
842     * Indicates that the view should filter touches when its window is obscured.
843     * Refer to the class comments for more information about this security feature.
844     * {@hide}
845     */
846    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
847
848    /**
849     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
850     * that they are optional and should be skipped if the window has
851     * requested system UI flags that ignore those insets for layout.
852     */
853    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
854
855    /**
856     * <p>This view doesn't show fading edges.</p>
857     * {@hide}
858     */
859    static final int FADING_EDGE_NONE = 0x00000000;
860
861    /**
862     * <p>This view shows horizontal fading edges.</p>
863     * {@hide}
864     */
865    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
866
867    /**
868     * <p>This view shows vertical fading edges.</p>
869     * {@hide}
870     */
871    static final int FADING_EDGE_VERTICAL = 0x00002000;
872
873    /**
874     * <p>Mask for use with setFlags indicating bits used for indicating which
875     * fading edges are enabled.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_MASK = 0x00003000;
879
880    /**
881     * <p>Indicates this view can be clicked. When clickable, a View reacts
882     * to clicks by notifying the OnClickListener.<p>
883     * {@hide}
884     */
885    static final int CLICKABLE = 0x00004000;
886
887    /**
888     * <p>Indicates this view is caching its drawing into a bitmap.</p>
889     * {@hide}
890     */
891    static final int DRAWING_CACHE_ENABLED = 0x00008000;
892
893    /**
894     * <p>Indicates that no icicle should be saved for this view.<p>
895     * {@hide}
896     */
897    static final int SAVE_DISABLED = 0x000010000;
898
899    /**
900     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
901     * property.</p>
902     * {@hide}
903     */
904    static final int SAVE_DISABLED_MASK = 0x000010000;
905
906    /**
907     * <p>Indicates that no drawing cache should ever be created for this view.<p>
908     * {@hide}
909     */
910    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
911
912    /**
913     * <p>Indicates this view can take / keep focus when int touch mode.</p>
914     * {@hide}
915     */
916    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
917
918    /** @hide */
919    @Retention(RetentionPolicy.SOURCE)
920    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
921    public @interface DrawingCacheQuality {}
922
923    /**
924     * <p>Enables low quality mode for the drawing cache.</p>
925     */
926    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
927
928    /**
929     * <p>Enables high quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
932
933    /**
934     * <p>Enables automatic quality mode for the drawing cache.</p>
935     */
936    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
937
938    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
939            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
940    };
941
942    /**
943     * <p>Mask for use with setFlags indicating bits used for the cache
944     * quality property.</p>
945     * {@hide}
946     */
947    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
948
949    /**
950     * <p>
951     * Indicates this view can be long clicked. When long clickable, a View
952     * reacts to long clicks by notifying the OnLongClickListener or showing a
953     * context menu.
954     * </p>
955     * {@hide}
956     */
957    static final int LONG_CLICKABLE = 0x00200000;
958
959    /**
960     * <p>Indicates that this view gets its drawable states from its direct parent
961     * and ignores its original internal states.</p>
962     *
963     * @hide
964     */
965    static final int DUPLICATE_PARENT_STATE = 0x00400000;
966
967    /** @hide */
968    @IntDef({
969        SCROLLBARS_INSIDE_OVERLAY,
970        SCROLLBARS_INSIDE_INSET,
971        SCROLLBARS_OUTSIDE_OVERLAY,
972        SCROLLBARS_OUTSIDE_INSET
973    })
974    @Retention(RetentionPolicy.SOURCE)
975    public @interface ScrollBarStyle {}
976
977    /**
978     * The scrollbar style to display the scrollbars inside the content area,
979     * without increasing the padding. The scrollbars will be overlaid with
980     * translucency on the view's content.
981     */
982    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
983
984    /**
985     * The scrollbar style to display the scrollbars inside the padded area,
986     * increasing the padding of the view. The scrollbars will not overlap the
987     * content area of the view.
988     */
989    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
990
991    /**
992     * The scrollbar style to display the scrollbars at the edge of the view,
993     * without increasing the padding. The scrollbars will be overlaid with
994     * translucency.
995     */
996    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
997
998    /**
999     * The scrollbar style to display the scrollbars at the edge of the view,
1000     * increasing the padding of the view. The scrollbars will only overlap the
1001     * background, if any.
1002     */
1003    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1004
1005    /**
1006     * Mask to check if the scrollbar style is overlay or inset.
1007     * {@hide}
1008     */
1009    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1010
1011    /**
1012     * Mask to check if the scrollbar style is inside or outside.
1013     * {@hide}
1014     */
1015    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1016
1017    /**
1018     * Mask for scrollbar style.
1019     * {@hide}
1020     */
1021    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1022
1023    /**
1024     * View flag indicating that the screen should remain on while the
1025     * window containing this view is visible to the user.  This effectively
1026     * takes care of automatically setting the WindowManager's
1027     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1028     */
1029    public static final int KEEP_SCREEN_ON = 0x04000000;
1030
1031    /**
1032     * View flag indicating whether this view should have sound effects enabled
1033     * for events such as clicking and touching.
1034     */
1035    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1036
1037    /**
1038     * View flag indicating whether this view should have haptic feedback
1039     * enabled for events such as long presses.
1040     */
1041    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1042
1043    /**
1044     * <p>Indicates that the view hierarchy should stop saving state when
1045     * it reaches this view.  If state saving is initiated immediately at
1046     * the view, it will be allowed.
1047     * {@hide}
1048     */
1049    static final int PARENT_SAVE_DISABLED = 0x20000000;
1050
1051    /**
1052     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1053     * {@hide}
1054     */
1055    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1056
1057    /** @hide */
1058    @IntDef(flag = true,
1059            value = {
1060                FOCUSABLES_ALL,
1061                FOCUSABLES_TOUCH_MODE
1062            })
1063    @Retention(RetentionPolicy.SOURCE)
1064    public @interface FocusableMode {}
1065
1066    /**
1067     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1068     * should add all focusable Views regardless if they are focusable in touch mode.
1069     */
1070    public static final int FOCUSABLES_ALL = 0x00000000;
1071
1072    /**
1073     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1074     * should add only Views focusable in touch mode.
1075     */
1076    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1077
1078    /** @hide */
1079    @IntDef({
1080            FOCUS_BACKWARD,
1081            FOCUS_FORWARD,
1082            FOCUS_LEFT,
1083            FOCUS_UP,
1084            FOCUS_RIGHT,
1085            FOCUS_DOWN
1086    })
1087    @Retention(RetentionPolicy.SOURCE)
1088    public @interface FocusDirection {}
1089
1090    /** @hide */
1091    @IntDef({
1092            FOCUS_LEFT,
1093            FOCUS_UP,
1094            FOCUS_RIGHT,
1095            FOCUS_DOWN
1096    })
1097    @Retention(RetentionPolicy.SOURCE)
1098    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1099
1100    /**
1101     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1102     * item.
1103     */
1104    public static final int FOCUS_BACKWARD = 0x00000001;
1105
1106    /**
1107     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1108     * item.
1109     */
1110    public static final int FOCUS_FORWARD = 0x00000002;
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus to the left.
1114     */
1115    public static final int FOCUS_LEFT = 0x00000011;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus up.
1119     */
1120    public static final int FOCUS_UP = 0x00000021;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus to the right.
1124     */
1125    public static final int FOCUS_RIGHT = 0x00000042;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus down.
1129     */
1130    public static final int FOCUS_DOWN = 0x00000082;
1131
1132    /**
1133     * Bits of {@link #getMeasuredWidthAndState()} and
1134     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1135     */
1136    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1137
1138    /**
1139     * Bits of {@link #getMeasuredWidthAndState()} and
1140     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1141     */
1142    public static final int MEASURED_STATE_MASK = 0xff000000;
1143
1144    /**
1145     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1146     * for functions that combine both width and height into a single int,
1147     * such as {@link #getMeasuredState()} and the childState argument of
1148     * {@link #resolveSizeAndState(int, int, int)}.
1149     */
1150    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1151
1152    /**
1153     * Bit of {@link #getMeasuredWidthAndState()} and
1154     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1155     * is smaller that the space the view would like to have.
1156     */
1157    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1158
1159    /**
1160     * Base View state sets
1161     */
1162    // Singles
1163    /**
1164     * Indicates the view has no states set. States are used with
1165     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1166     * view depending on its state.
1167     *
1168     * @see android.graphics.drawable.Drawable
1169     * @see #getDrawableState()
1170     */
1171    protected static final int[] EMPTY_STATE_SET;
1172    /**
1173     * Indicates the view is enabled. States are used with
1174     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1175     * view depending on its state.
1176     *
1177     * @see android.graphics.drawable.Drawable
1178     * @see #getDrawableState()
1179     */
1180    protected static final int[] ENABLED_STATE_SET;
1181    /**
1182     * Indicates the view is focused. States are used with
1183     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1184     * view depending on its state.
1185     *
1186     * @see android.graphics.drawable.Drawable
1187     * @see #getDrawableState()
1188     */
1189    protected static final int[] FOCUSED_STATE_SET;
1190    /**
1191     * Indicates the view is selected. States are used with
1192     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1193     * view depending on its state.
1194     *
1195     * @see android.graphics.drawable.Drawable
1196     * @see #getDrawableState()
1197     */
1198    protected static final int[] SELECTED_STATE_SET;
1199    /**
1200     * Indicates the view is pressed. States are used with
1201     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1202     * view depending on its state.
1203     *
1204     * @see android.graphics.drawable.Drawable
1205     * @see #getDrawableState()
1206     */
1207    protected static final int[] PRESSED_STATE_SET;
1208    /**
1209     * Indicates the view's window has focus. States are used with
1210     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1211     * view depending on its state.
1212     *
1213     * @see android.graphics.drawable.Drawable
1214     * @see #getDrawableState()
1215     */
1216    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1217    // Doubles
1218    /**
1219     * Indicates the view is enabled and has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled and selected.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #SELECTED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_SELECTED_STATE_SET;
1232    /**
1233     * Indicates the view is enabled and that its window has focus.
1234     *
1235     * @see #ENABLED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is focused and selected.
1241     *
1242     * @see #FOCUSED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     */
1245    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1246    /**
1247     * Indicates the view has the focus and that its window has the focus.
1248     *
1249     * @see #FOCUSED_STATE_SET
1250     * @see #WINDOW_FOCUSED_STATE_SET
1251     */
1252    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is selected and that its window has the focus.
1255     *
1256     * @see #SELECTED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1260    // Triples
1261    /**
1262     * Indicates the view is enabled, focused and selected.
1263     *
1264     * @see #ENABLED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is enabled, focused and its window has the focus.
1271     *
1272     * @see #ENABLED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is enabled, selected and its window has the focus.
1279     *
1280     * @see #ENABLED_STATE_SET
1281     * @see #SELECTED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is focused, selected and its window has the focus.
1287     *
1288     * @see #FOCUSED_STATE_SET
1289     * @see #SELECTED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is enabled, focused, selected and its window
1295     * has the focus.
1296     *
1297     * @see #ENABLED_STATE_SET
1298     * @see #FOCUSED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    /**
1304     * Indicates the view is pressed and its window has the focus.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and selected.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #SELECTED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_SELECTED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed, selected and its window has the focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed and focused.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, focused and its window has the focus.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     * @see #WINDOW_FOCUSED_STATE_SET
1338     */
1339    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1340    /**
1341     * Indicates the view is pressed, focused and selected.
1342     *
1343     * @see #PRESSED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1348    /**
1349     * Indicates the view is pressed, focused, selected and its window has the focus.
1350     *
1351     * @see #PRESSED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     * @see #SELECTED_STATE_SET
1354     * @see #WINDOW_FOCUSED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed and enabled.
1359     *
1360     * @see #PRESSED_STATE_SET
1361     * @see #ENABLED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled and its window has the focus.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #WINDOW_FOCUSED_STATE_SET
1370     */
1371    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1372    /**
1373     * Indicates the view is pressed, enabled and selected.
1374     *
1375     * @see #PRESSED_STATE_SET
1376     * @see #ENABLED_STATE_SET
1377     * @see #SELECTED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1380    /**
1381     * Indicates the view is pressed, enabled, selected and its window has the
1382     * focus.
1383     *
1384     * @see #PRESSED_STATE_SET
1385     * @see #ENABLED_STATE_SET
1386     * @see #SELECTED_STATE_SET
1387     * @see #WINDOW_FOCUSED_STATE_SET
1388     */
1389    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1390    /**
1391     * Indicates the view is pressed, enabled and focused.
1392     *
1393     * @see #PRESSED_STATE_SET
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     */
1397    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is pressed, enabled, focused and its window has the
1400     * focus.
1401     *
1402     * @see #PRESSED_STATE_SET
1403     * @see #ENABLED_STATE_SET
1404     * @see #FOCUSED_STATE_SET
1405     * @see #WINDOW_FOCUSED_STATE_SET
1406     */
1407    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1408    /**
1409     * Indicates the view is pressed, enabled, focused and selected.
1410     *
1411     * @see #PRESSED_STATE_SET
1412     * @see #ENABLED_STATE_SET
1413     * @see #SELECTED_STATE_SET
1414     * @see #FOCUSED_STATE_SET
1415     */
1416    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1417    /**
1418     * Indicates the view is pressed, enabled, focused, selected and its window
1419     * has the focus.
1420     *
1421     * @see #PRESSED_STATE_SET
1422     * @see #ENABLED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     * @see #FOCUSED_STATE_SET
1425     * @see #WINDOW_FOCUSED_STATE_SET
1426     */
1427    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1428
1429    /**
1430     * The order here is very important to {@link #getDrawableState()}
1431     */
1432    private static final int[][] VIEW_STATE_SETS;
1433
1434    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1435    static final int VIEW_STATE_SELECTED = 1 << 1;
1436    static final int VIEW_STATE_FOCUSED = 1 << 2;
1437    static final int VIEW_STATE_ENABLED = 1 << 3;
1438    static final int VIEW_STATE_PRESSED = 1 << 4;
1439    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1440    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1441    static final int VIEW_STATE_HOVERED = 1 << 7;
1442    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1443    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1444
1445    static final int[] VIEW_STATE_IDS = new int[] {
1446        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1447        R.attr.state_selected,          VIEW_STATE_SELECTED,
1448        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1449        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1450        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1451        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1452        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1453        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1454        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1455        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1456    };
1457
1458    static {
1459        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1460            throw new IllegalStateException(
1461                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1462        }
1463        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1464        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1465            int viewState = R.styleable.ViewDrawableStates[i];
1466            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1467                if (VIEW_STATE_IDS[j] == viewState) {
1468                    orderedIds[i * 2] = viewState;
1469                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1470                }
1471            }
1472        }
1473        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1474        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1475        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1476            int numBits = Integer.bitCount(i);
1477            int[] set = new int[numBits];
1478            int pos = 0;
1479            for (int j = 0; j < orderedIds.length; j += 2) {
1480                if ((i & orderedIds[j+1]) != 0) {
1481                    set[pos++] = orderedIds[j];
1482                }
1483            }
1484            VIEW_STATE_SETS[i] = set;
1485        }
1486
1487        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1488        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1489        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1490        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1492        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1493        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1495        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1497        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1499                | VIEW_STATE_FOCUSED];
1500        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1501        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1503        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1505        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1507                | VIEW_STATE_ENABLED];
1508        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1510        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1515                | VIEW_STATE_ENABLED];
1516        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1519
1520        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1521        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1523        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1525        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1527                | VIEW_STATE_PRESSED];
1528        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1535                | VIEW_STATE_PRESSED];
1536        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1539        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1549                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1552                | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1555                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1558                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1559        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1560                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1561                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1562                | VIEW_STATE_PRESSED];
1563    }
1564
1565    /**
1566     * Accessibility event types that are dispatched for text population.
1567     */
1568    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1569            AccessibilityEvent.TYPE_VIEW_CLICKED
1570            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1571            | AccessibilityEvent.TYPE_VIEW_SELECTED
1572            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1573            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1574            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1575            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1576            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1577            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1578            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1579            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1580
1581    /**
1582     * Temporary Rect currently for use in setBackground().  This will probably
1583     * be extended in the future to hold our own class with more than just
1584     * a Rect. :)
1585     */
1586    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1587
1588    /**
1589     * Map used to store views' tags.
1590     */
1591    private SparseArray<Object> mKeyedTags;
1592
1593    /**
1594     * The next available accessibility id.
1595     */
1596    private static int sNextAccessibilityViewId;
1597
1598    /**
1599     * The animation currently associated with this view.
1600     * @hide
1601     */
1602    protected Animation mCurrentAnimation = null;
1603
1604    /**
1605     * Width as measured during measure pass.
1606     * {@hide}
1607     */
1608    @ViewDebug.ExportedProperty(category = "measurement")
1609    int mMeasuredWidth;
1610
1611    /**
1612     * Height as measured during measure pass.
1613     * {@hide}
1614     */
1615    @ViewDebug.ExportedProperty(category = "measurement")
1616    int mMeasuredHeight;
1617
1618    /**
1619     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1620     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1621     * its display list. This flag, used only when hw accelerated, allows us to clear the
1622     * flag while retaining this information until it's needed (at getDisplayList() time and
1623     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1624     *
1625     * {@hide}
1626     */
1627    boolean mRecreateDisplayList = false;
1628
1629    /**
1630     * The view's identifier.
1631     * {@hide}
1632     *
1633     * @see #setId(int)
1634     * @see #getId()
1635     */
1636    @ViewDebug.ExportedProperty(resolveId = true)
1637    int mID = NO_ID;
1638
1639    /**
1640     * The stable ID of this view for accessibility purposes.
1641     */
1642    int mAccessibilityViewId = NO_ID;
1643
1644    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1645
1646    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1647
1648    /**
1649     * The view's tag.
1650     * {@hide}
1651     *
1652     * @see #setTag(Object)
1653     * @see #getTag()
1654     */
1655    protected Object mTag = null;
1656
1657    // for mPrivateFlags:
1658    /** {@hide} */
1659    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1660    /** {@hide} */
1661    static final int PFLAG_FOCUSED                     = 0x00000002;
1662    /** {@hide} */
1663    static final int PFLAG_SELECTED                    = 0x00000004;
1664    /** {@hide} */
1665    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1666    /** {@hide} */
1667    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1668    /** {@hide} */
1669    static final int PFLAG_DRAWN                       = 0x00000020;
1670    /**
1671     * When this flag is set, this view is running an animation on behalf of its
1672     * children and should therefore not cancel invalidate requests, even if they
1673     * lie outside of this view's bounds.
1674     *
1675     * {@hide}
1676     */
1677    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1678    /** {@hide} */
1679    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1680    /** {@hide} */
1681    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1682    /** {@hide} */
1683    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1684    /** {@hide} */
1685    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1686    /** {@hide} */
1687    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1688    /** {@hide} */
1689    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1690    /** {@hide} */
1691    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1692
1693    private static final int PFLAG_PRESSED             = 0x00004000;
1694
1695    /** {@hide} */
1696    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1697    /**
1698     * Flag used to indicate that this view should be drawn once more (and only once
1699     * more) after its animation has completed.
1700     * {@hide}
1701     */
1702    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1703
1704    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1705
1706    /**
1707     * Indicates that the View returned true when onSetAlpha() was called and that
1708     * the alpha must be restored.
1709     * {@hide}
1710     */
1711    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1712
1713    /**
1714     * Set by {@link #setScrollContainer(boolean)}.
1715     */
1716    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1717
1718    /**
1719     * Set by {@link #setScrollContainer(boolean)}.
1720     */
1721    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1722
1723    /**
1724     * View flag indicating whether this view was invalidated (fully or partially.)
1725     *
1726     * @hide
1727     */
1728    static final int PFLAG_DIRTY                       = 0x00200000;
1729
1730    /**
1731     * View flag indicating whether this view was invalidated by an opaque
1732     * invalidate request.
1733     *
1734     * @hide
1735     */
1736    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1737
1738    /**
1739     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1740     *
1741     * @hide
1742     */
1743    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1744
1745    /**
1746     * Indicates whether the background is opaque.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1751
1752    /**
1753     * Indicates whether the scrollbars are opaque.
1754     *
1755     * @hide
1756     */
1757    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1758
1759    /**
1760     * Indicates whether the view is opaque.
1761     *
1762     * @hide
1763     */
1764    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1765
1766    /**
1767     * Indicates a prepressed state;
1768     * the short time between ACTION_DOWN and recognizing
1769     * a 'real' press. Prepressed is used to recognize quick taps
1770     * even when they are shorter than ViewConfiguration.getTapTimeout().
1771     *
1772     * @hide
1773     */
1774    private static final int PFLAG_PREPRESSED          = 0x02000000;
1775
1776    /**
1777     * Indicates whether the view is temporarily detached.
1778     *
1779     * @hide
1780     */
1781    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1782
1783    /**
1784     * Indicates that we should awaken scroll bars once attached
1785     *
1786     * @hide
1787     */
1788    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1789
1790    /**
1791     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1792     * @hide
1793     */
1794    private static final int PFLAG_HOVERED             = 0x10000000;
1795
1796    /**
1797     * no longer needed, should be reused
1798     */
1799    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1800
1801    /** {@hide} */
1802    static final int PFLAG_ACTIVATED                   = 0x40000000;
1803
1804    /**
1805     * Indicates that this view was specifically invalidated, not just dirtied because some
1806     * child view was invalidated. The flag is used to determine when we need to recreate
1807     * a view's display list (as opposed to just returning a reference to its existing
1808     * display list).
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_INVALIDATED                 = 0x80000000;
1813
1814    /**
1815     * Masks for mPrivateFlags2, as generated by dumpFlags():
1816     *
1817     * |-------|-------|-------|-------|
1818     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1819     *                                1  PFLAG2_DRAG_HOVERED
1820     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1821     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1822     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1823     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1824     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1825     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1826     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1827     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1828     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1829     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1830     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1831     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1832     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1833     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1834     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1835     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1836     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1837     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1838     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1839     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1840     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1841     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1842     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1843     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1844     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1845     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1846     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1847     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1848     *    1                              PFLAG2_PADDING_RESOLVED
1849     *   1                               PFLAG2_DRAWABLE_RESOLVED
1850     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1851     * |-------|-------|-------|-------|
1852     */
1853
1854    /**
1855     * Indicates that this view has reported that it can accept the current drag's content.
1856     * Cleared when the drag operation concludes.
1857     * @hide
1858     */
1859    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1860
1861    /**
1862     * Indicates that this view is currently directly under the drag location in a
1863     * drag-and-drop operation involving content that it can accept.  Cleared when
1864     * the drag exits the view, or when the drag operation concludes.
1865     * @hide
1866     */
1867    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1868
1869    /** @hide */
1870    @IntDef({
1871        LAYOUT_DIRECTION_LTR,
1872        LAYOUT_DIRECTION_RTL,
1873        LAYOUT_DIRECTION_INHERIT,
1874        LAYOUT_DIRECTION_LOCALE
1875    })
1876    @Retention(RetentionPolicy.SOURCE)
1877    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1878    public @interface LayoutDir {}
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL
1884    })
1885    @Retention(RetentionPolicy.SOURCE)
1886    public @interface ResolvedLayoutDir {}
1887
1888    /**
1889     * Horizontal layout direction of this view is from Left to Right.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1893
1894    /**
1895     * Horizontal layout direction of this view is from Right to Left.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1899
1900    /**
1901     * Horizontal layout direction of this view is inherited from its parent.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1905
1906    /**
1907     * Horizontal layout direction of this view is from deduced from the default language
1908     * script for the locale. Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1911
1912    /**
1913     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1917
1918    /**
1919     * Mask for use with private flags indicating bits used for horizontal layout direction.
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1923
1924    /**
1925     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1926     * right-to-left direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1942            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /*
1945     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1946     * flag value.
1947     * @hide
1948     */
1949    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1950            LAYOUT_DIRECTION_LTR,
1951            LAYOUT_DIRECTION_RTL,
1952            LAYOUT_DIRECTION_INHERIT,
1953            LAYOUT_DIRECTION_LOCALE
1954    };
1955
1956    /**
1957     * Default horizontal layout direction.
1958     */
1959    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1960
1961    /**
1962     * Default horizontal layout direction.
1963     * @hide
1964     */
1965    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1966
1967    /**
1968     * Text direction is inherited thru {@link ViewGroup}
1969     */
1970    public static final int TEXT_DIRECTION_INHERIT = 0;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is the view's resolved layout direction.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1978
1979    /**
1980     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1981     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1982     * If there are neither, the paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1985
1986    /**
1987     * Text direction is forced to LTR.
1988     */
1989    public static final int TEXT_DIRECTION_LTR = 3;
1990
1991    /**
1992     * Text direction is forced to RTL.
1993     */
1994    public static final int TEXT_DIRECTION_RTL = 4;
1995
1996    /**
1997     * Text direction is coming from the system Locale.
1998     */
1999    public static final int TEXT_DIRECTION_LOCALE = 5;
2000
2001    /**
2002     * Default text direction is inherited
2003     */
2004    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2005
2006    /**
2007     * Default resolved text direction
2008     * @hide
2009     */
2010    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2011
2012    /**
2013     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2017
2018    /**
2019     * Mask for use with private flags indicating bits used for text direction.
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2023            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2024
2025    /**
2026     * Array of text direction flags for mapping attribute "textDirection" to correct
2027     * flag value.
2028     * @hide
2029     */
2030    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2031            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2036            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2037    };
2038
2039    /**
2040     * Indicates whether the view text direction has been resolved.
2041     * @hide
2042     */
2043    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2044            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for resolved text direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2057            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2058
2059    /**
2060     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2064            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /** @hide */
2067    @IntDef({
2068        TEXT_ALIGNMENT_INHERIT,
2069        TEXT_ALIGNMENT_GRAVITY,
2070        TEXT_ALIGNMENT_CENTER,
2071        TEXT_ALIGNMENT_TEXT_START,
2072        TEXT_ALIGNMENT_TEXT_END,
2073        TEXT_ALIGNMENT_VIEW_START,
2074        TEXT_ALIGNMENT_VIEW_END
2075    })
2076    @Retention(RetentionPolicy.SOURCE)
2077    public @interface TextAlignment {}
2078
2079    /**
2080     * Default text alignment. The text alignment of this View is inherited from its parent.
2081     * Use with {@link #setTextAlignment(int)}
2082     */
2083    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2084
2085    /**
2086     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2087     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2088     *
2089     * Use with {@link #setTextAlignment(int)}
2090     */
2091    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2092
2093    /**
2094     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2099
2100    /**
2101     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2106
2107    /**
2108     * Center the paragraph, e.g. ALIGN_CENTER.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_CENTER = 4;
2113
2114    /**
2115     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2116     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2117     *
2118     * Use with {@link #setTextAlignment(int)}
2119     */
2120    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2121
2122    /**
2123     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2124     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2125     *
2126     * Use with {@link #setTextAlignment(int)}
2127     */
2128    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2129
2130    /**
2131     * Default text alignment is inherited
2132     */
2133    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2134
2135    /**
2136     * Default resolved text alignment
2137     * @hide
2138     */
2139    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2140
2141    /**
2142      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2143      * @hide
2144      */
2145    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2146
2147    /**
2148      * Mask for use with private flags indicating bits used for text alignment.
2149      * @hide
2150      */
2151    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2152
2153    /**
2154     * Array of text direction flags for mapping attribute "textAlignment" to correct
2155     * flag value.
2156     * @hide
2157     */
2158    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2159            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2166    };
2167
2168    /**
2169     * Indicates whether the view text alignment has been resolved.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2173
2174    /**
2175     * Bit shift to get the resolved text alignment.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2179
2180    /**
2181     * Mask for use with private flags indicating bits used for text alignment.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2185            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2186
2187    /**
2188     * Indicates whether if the view text alignment has been resolved to gravity
2189     */
2190    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2191            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2192
2193    // Accessiblity constants for mPrivateFlags2
2194
2195    /**
2196     * Shift for the bits in {@link #mPrivateFlags2} related to the
2197     * "importantForAccessibility" attribute.
2198     */
2199    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2200
2201    /**
2202     * Automatically determine whether a view is important for accessibility.
2203     */
2204    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2205
2206    /**
2207     * The view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2210
2211    /**
2212     * The view is not important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2215
2216    /**
2217     * The view is not important for accessibility, nor are any of its
2218     * descendant views.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2221
2222    /**
2223     * The default whether the view is important for accessibility.
2224     */
2225    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2226
2227    /**
2228     * Mask for obtainig the bits which specify how to determine
2229     * whether a view is important for accessibility.
2230     */
2231    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2232        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2233        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2234        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2235
2236    /**
2237     * Shift for the bits in {@link #mPrivateFlags2} related to the
2238     * "accessibilityLiveRegion" attribute.
2239     */
2240    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2241
2242    /**
2243     * Live region mode specifying that accessibility services should not
2244     * automatically announce changes to this view. This is the default live
2245     * region mode for most views.
2246     * <p>
2247     * Use with {@link #setAccessibilityLiveRegion(int)}.
2248     */
2249    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2250
2251    /**
2252     * Live region mode specifying that accessibility services should announce
2253     * changes to this view.
2254     * <p>
2255     * Use with {@link #setAccessibilityLiveRegion(int)}.
2256     */
2257    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2258
2259    /**
2260     * Live region mode specifying that accessibility services should interrupt
2261     * ongoing speech to immediately announce changes to this view.
2262     * <p>
2263     * Use with {@link #setAccessibilityLiveRegion(int)}.
2264     */
2265    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2266
2267    /**
2268     * The default whether the view is important for accessibility.
2269     */
2270    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2271
2272    /**
2273     * Mask for obtaining the bits which specify a view's accessibility live
2274     * region mode.
2275     */
2276    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2277            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2278            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2279
2280    /**
2281     * Flag indicating whether a view has accessibility focus.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2284
2285    /**
2286     * Flag whether the accessibility state of the subtree rooted at this view changed.
2287     */
2288    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2289
2290    /**
2291     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2292     * is used to check whether later changes to the view's transform should invalidate the
2293     * view to force the quickReject test to run again.
2294     */
2295    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2296
2297    /**
2298     * Flag indicating that start/end padding has been resolved into left/right padding
2299     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2300     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2301     * during measurement. In some special cases this is required such as when an adapter-based
2302     * view measures prospective children without attaching them to a window.
2303     */
2304    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2305
2306    /**
2307     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2308     */
2309    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2310
2311    /**
2312     * Indicates that the view is tracking some sort of transient state
2313     * that the app should not need to be aware of, but that the framework
2314     * should take special care to preserve.
2315     */
2316    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2317
2318    /**
2319     * Group of bits indicating that RTL properties resolution is done.
2320     */
2321    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2322            PFLAG2_TEXT_DIRECTION_RESOLVED |
2323            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2324            PFLAG2_PADDING_RESOLVED |
2325            PFLAG2_DRAWABLE_RESOLVED;
2326
2327    // There are a couple of flags left in mPrivateFlags2
2328
2329    /* End of masks for mPrivateFlags2 */
2330
2331    /**
2332     * Masks for mPrivateFlags3, as generated by dumpFlags():
2333     *
2334     * |-------|-------|-------|-------|
2335     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2336     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2337     *                               1   PFLAG3_IS_LAID_OUT
2338     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2339     *                             1     PFLAG3_CALLED_SUPER
2340     * |-------|-------|-------|-------|
2341     */
2342
2343    /**
2344     * Flag indicating that view has a transform animation set on it. This is used to track whether
2345     * an animation is cleared between successive frames, in order to tell the associated
2346     * DisplayList to clear its animation matrix.
2347     */
2348    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2349
2350    /**
2351     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2352     * animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to restore its alpha value.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2356
2357    /**
2358     * Flag indicating that the view has been through at least one layout since it
2359     * was last attached to a window.
2360     */
2361    static final int PFLAG3_IS_LAID_OUT = 0x4;
2362
2363    /**
2364     * Flag indicating that a call to measure() was skipped and should be done
2365     * instead when layout() is invoked.
2366     */
2367    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2368
2369    /**
2370     * Flag indicating that an overridden method correctly called down to
2371     * the superclass implementation as required by the API spec.
2372     */
2373    static final int PFLAG3_CALLED_SUPER = 0x10;
2374
2375    /**
2376     * Flag indicating that we're in the process of applying window insets.
2377     */
2378    static final int PFLAG3_APPLYING_INSETS = 0x20;
2379
2380    /**
2381     * Flag indicating that we're in the process of fitting system windows using the old method.
2382     */
2383    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2384
2385    /**
2386     * Flag indicating that nested scrolling is enabled for this view.
2387     * The view will optionally cooperate with views up its parent chain to allow for
2388     * integrated nested scrolling along the same axis.
2389     */
2390    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2391
2392    /* End of masks for mPrivateFlags3 */
2393
2394    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2395
2396    /**
2397     * Always allow a user to over-scroll this view, provided it is a
2398     * view that can scroll.
2399     *
2400     * @see #getOverScrollMode()
2401     * @see #setOverScrollMode(int)
2402     */
2403    public static final int OVER_SCROLL_ALWAYS = 0;
2404
2405    /**
2406     * Allow a user to over-scroll this view only if the content is large
2407     * enough to meaningfully scroll, provided it is a view that can scroll.
2408     *
2409     * @see #getOverScrollMode()
2410     * @see #setOverScrollMode(int)
2411     */
2412    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2413
2414    /**
2415     * Never allow a user to over-scroll this view.
2416     *
2417     * @see #getOverScrollMode()
2418     * @see #setOverScrollMode(int)
2419     */
2420    public static final int OVER_SCROLL_NEVER = 2;
2421
2422    /**
2423     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2424     * requested the system UI (status bar) to be visible (the default).
2425     *
2426     * @see #setSystemUiVisibility(int)
2427     */
2428    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2429
2430    /**
2431     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2432     * system UI to enter an unobtrusive "low profile" mode.
2433     *
2434     * <p>This is for use in games, book readers, video players, or any other
2435     * "immersive" application where the usual system chrome is deemed too distracting.
2436     *
2437     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2438     *
2439     * @see #setSystemUiVisibility(int)
2440     */
2441    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2442
2443    /**
2444     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2445     * system navigation be temporarily hidden.
2446     *
2447     * <p>This is an even less obtrusive state than that called for by
2448     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2449     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2450     * those to disappear. This is useful (in conjunction with the
2451     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2452     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2453     * window flags) for displaying content using every last pixel on the display.
2454     *
2455     * <p>There is a limitation: because navigation controls are so important, the least user
2456     * interaction will cause them to reappear immediately.  When this happens, both
2457     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2458     * so that both elements reappear at the same time.
2459     *
2460     * @see #setSystemUiVisibility(int)
2461     */
2462    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2463
2464    /**
2465     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2466     * into the normal fullscreen mode so that its content can take over the screen
2467     * while still allowing the user to interact with the application.
2468     *
2469     * <p>This has the same visual effect as
2470     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2471     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2472     * meaning that non-critical screen decorations (such as the status bar) will be
2473     * hidden while the user is in the View's window, focusing the experience on
2474     * that content.  Unlike the window flag, if you are using ActionBar in
2475     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2476     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2477     * hide the action bar.
2478     *
2479     * <p>This approach to going fullscreen is best used over the window flag when
2480     * it is a transient state -- that is, the application does this at certain
2481     * points in its user interaction where it wants to allow the user to focus
2482     * on content, but not as a continuous state.  For situations where the application
2483     * would like to simply stay full screen the entire time (such as a game that
2484     * wants to take over the screen), the
2485     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2486     * is usually a better approach.  The state set here will be removed by the system
2487     * in various situations (such as the user moving to another application) like
2488     * the other system UI states.
2489     *
2490     * <p>When using this flag, the application should provide some easy facility
2491     * for the user to go out of it.  A common example would be in an e-book
2492     * reader, where tapping on the screen brings back whatever screen and UI
2493     * decorations that had been hidden while the user was immersed in reading
2494     * the book.
2495     *
2496     * @see #setSystemUiVisibility(int)
2497     */
2498    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2499
2500    /**
2501     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2502     * flags, we would like a stable view of the content insets given to
2503     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2504     * will always represent the worst case that the application can expect
2505     * as a continuous state.  In the stock Android UI this is the space for
2506     * the system bar, nav bar, and status bar, but not more transient elements
2507     * such as an input method.
2508     *
2509     * The stable layout your UI sees is based on the system UI modes you can
2510     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2511     * then you will get a stable layout for changes of the
2512     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2513     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2514     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2515     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2516     * with a stable layout.  (Note that you should avoid using
2517     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2518     *
2519     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2520     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2521     * then a hidden status bar will be considered a "stable" state for purposes
2522     * here.  This allows your UI to continually hide the status bar, while still
2523     * using the system UI flags to hide the action bar while still retaining
2524     * a stable layout.  Note that changing the window fullscreen flag will never
2525     * provide a stable layout for a clean transition.
2526     *
2527     * <p>If you are using ActionBar in
2528     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2529     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2530     * insets it adds to those given to the application.
2531     */
2532    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2533
2534    /**
2535     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2536     * to be layed out as if it has requested
2537     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2538     * allows it to avoid artifacts when switching in and out of that mode, at
2539     * the expense that some of its user interface may be covered by screen
2540     * decorations when they are shown.  You can perform layout of your inner
2541     * UI elements to account for the navigation system UI through the
2542     * {@link #fitSystemWindows(Rect)} method.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
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_FULLSCREEN}, 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 non-fullscreen system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2560     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2561     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2562     * user interaction.
2563     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2564     * has an effect when used in combination with that flag.</p>
2565     */
2566    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2571     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2572     * experience while also hiding the system bars.  If this flag is not set,
2573     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2574     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2575     * if the user swipes from the top of the screen.
2576     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2577     * system gestures, such as swiping from the top of the screen.  These transient system bars
2578     * will overlay app’s content, may have some degree of transparency, and will automatically
2579     * hide after a short timeout.
2580     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2581     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2582     * with one or both of those flags.</p>
2583     */
2584    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2585
2586    /**
2587     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2588     */
2589    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2590
2591    /**
2592     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2593     */
2594    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2595
2596    /**
2597     * @hide
2598     *
2599     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2600     * out of the public fields to keep the undefined bits out of the developer's way.
2601     *
2602     * Flag to make the status bar not expandable.  Unless you also
2603     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2604     */
2605    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2606
2607    /**
2608     * @hide
2609     *
2610     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2611     * out of the public fields to keep the undefined bits out of the developer's way.
2612     *
2613     * Flag to hide notification icons and scrolling ticker text.
2614     */
2615    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2616
2617    /**
2618     * @hide
2619     *
2620     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2621     * out of the public fields to keep the undefined bits out of the developer's way.
2622     *
2623     * Flag to disable incoming notification alerts.  This will not block
2624     * icons, but it will block sound, vibrating and other visual or aural notifications.
2625     */
2626    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2627
2628    /**
2629     * @hide
2630     *
2631     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2632     * out of the public fields to keep the undefined bits out of the developer's way.
2633     *
2634     * Flag to hide only the scrolling ticker.  Note that
2635     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2636     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
2647     */
2648    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2649
2650    /**
2651     * @hide
2652     *
2653     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2654     * out of the public fields to keep the undefined bits out of the developer's way.
2655     *
2656     * Flag to hide only the home button.  Don't use this
2657     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2658     */
2659    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2660
2661    /**
2662     * @hide
2663     *
2664     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2665     * out of the public fields to keep the undefined bits out of the developer's way.
2666     *
2667     * Flag to hide only the back button. Don't use this
2668     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2669     */
2670    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2671
2672    /**
2673     * @hide
2674     *
2675     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2676     * out of the public fields to keep the undefined bits out of the developer's way.
2677     *
2678     * Flag to hide only the clock.  You might use this if your activity has
2679     * its own clock making the status bar's clock redundant.
2680     */
2681    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to hide only the recent apps button. Don't use this
2690     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2691     */
2692    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2693
2694    /**
2695     * @hide
2696     *
2697     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2698     * out of the public fields to keep the undefined bits out of the developer's way.
2699     *
2700     * Flag to disable the global search gesture. Don't use this
2701     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2702     */
2703    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2704
2705    /**
2706     * @hide
2707     *
2708     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2709     * out of the public fields to keep the undefined bits out of the developer's way.
2710     *
2711     * Flag to specify that the status bar is displayed in transient mode.
2712     */
2713    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2714
2715    /**
2716     * @hide
2717     *
2718     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2719     * out of the public fields to keep the undefined bits out of the developer's way.
2720     *
2721     * Flag to specify that the navigation bar is displayed in transient mode.
2722     */
2723    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2724
2725    /**
2726     * @hide
2727     *
2728     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2729     * out of the public fields to keep the undefined bits out of the developer's way.
2730     *
2731     * Flag to specify that the hidden status bar would like to be shown.
2732     */
2733    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2734
2735    /**
2736     * @hide
2737     *
2738     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2739     * out of the public fields to keep the undefined bits out of the developer's way.
2740     *
2741     * Flag to specify that the hidden navigation bar would like to be shown.
2742     */
2743    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2744
2745    /**
2746     * @hide
2747     *
2748     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2749     * out of the public fields to keep the undefined bits out of the developer's way.
2750     *
2751     * Flag to specify that the status bar is displayed in translucent mode.
2752     */
2753    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2754
2755    /**
2756     * @hide
2757     *
2758     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2759     * out of the public fields to keep the undefined bits out of the developer's way.
2760     *
2761     * Flag to specify that the navigation bar is displayed in translucent mode.
2762     */
2763    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * Whether Recents is visible or not.
2769     */
2770    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2771
2772    /**
2773     * @hide
2774     *
2775     * Makes system ui transparent.
2776     */
2777    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2778
2779    /**
2780     * @hide
2781     */
2782    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2783
2784    /**
2785     * These are the system UI flags that can be cleared by events outside
2786     * of an application.  Currently this is just the ability to tap on the
2787     * screen while hiding the navigation bar to have it return.
2788     * @hide
2789     */
2790    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2791            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2792            | SYSTEM_UI_FLAG_FULLSCREEN;
2793
2794    /**
2795     * Flags that can impact the layout in relation to system UI.
2796     */
2797    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2798            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2799            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2800
2801    /** @hide */
2802    @IntDef(flag = true,
2803            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2804    @Retention(RetentionPolicy.SOURCE)
2805    public @interface FindViewFlags {}
2806
2807    /**
2808     * Find views that render the specified text.
2809     *
2810     * @see #findViewsWithText(ArrayList, CharSequence, int)
2811     */
2812    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2813
2814    /**
2815     * Find find views that contain the specified content description.
2816     *
2817     * @see #findViewsWithText(ArrayList, CharSequence, int)
2818     */
2819    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2820
2821    /**
2822     * Find views that contain {@link AccessibilityNodeProvider}. Such
2823     * a View is a root of virtual view hierarchy and may contain the searched
2824     * text. If this flag is set Views with providers are automatically
2825     * added and it is a responsibility of the client to call the APIs of
2826     * the provider to determine whether the virtual tree rooted at this View
2827     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2828     * representing the virtual views with this text.
2829     *
2830     * @see #findViewsWithText(ArrayList, CharSequence, int)
2831     *
2832     * @hide
2833     */
2834    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2835
2836    /**
2837     * The undefined cursor position.
2838     *
2839     * @hide
2840     */
2841    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2842
2843    /**
2844     * Indicates that the screen has changed state and is now off.
2845     *
2846     * @see #onScreenStateChanged(int)
2847     */
2848    public static final int SCREEN_STATE_OFF = 0x0;
2849
2850    /**
2851     * Indicates that the screen has changed state and is now on.
2852     *
2853     * @see #onScreenStateChanged(int)
2854     */
2855    public static final int SCREEN_STATE_ON = 0x1;
2856
2857    /**
2858     * Indicates no axis of view scrolling.
2859     */
2860    public static final int SCROLL_AXIS_NONE = 0;
2861
2862    /**
2863     * Indicates scrolling along the horizontal axis.
2864     */
2865    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2866
2867    /**
2868     * Indicates scrolling along the vertical axis.
2869     */
2870    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2871
2872    /**
2873     * Controls the over-scroll mode for this view.
2874     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2875     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2876     * and {@link #OVER_SCROLL_NEVER}.
2877     */
2878    private int mOverScrollMode;
2879
2880    /**
2881     * The parent this view is attached to.
2882     * {@hide}
2883     *
2884     * @see #getParent()
2885     */
2886    protected ViewParent mParent;
2887
2888    /**
2889     * {@hide}
2890     */
2891    AttachInfo mAttachInfo;
2892
2893    /**
2894     * {@hide}
2895     */
2896    @ViewDebug.ExportedProperty(flagMapping = {
2897        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2898                name = "FORCE_LAYOUT"),
2899        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2900                name = "LAYOUT_REQUIRED"),
2901        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2902            name = "DRAWING_CACHE_INVALID", outputIf = false),
2903        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2904        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2905        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2906        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2907    }, formatToHexString = true)
2908    int mPrivateFlags;
2909    int mPrivateFlags2;
2910    int mPrivateFlags3;
2911
2912    /**
2913     * This view's request for the visibility of the status bar.
2914     * @hide
2915     */
2916    @ViewDebug.ExportedProperty(flagMapping = {
2917        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2918                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2919                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2920        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2921                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2922                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2923        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2924                                equals = SYSTEM_UI_FLAG_VISIBLE,
2925                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2926    }, formatToHexString = true)
2927    int mSystemUiVisibility;
2928
2929    /**
2930     * Reference count for transient state.
2931     * @see #setHasTransientState(boolean)
2932     */
2933    int mTransientStateCount = 0;
2934
2935    /**
2936     * Count of how many windows this view has been attached to.
2937     */
2938    int mWindowAttachCount;
2939
2940    /**
2941     * The layout parameters associated with this view and used by the parent
2942     * {@link android.view.ViewGroup} to determine how this view should be
2943     * laid out.
2944     * {@hide}
2945     */
2946    protected ViewGroup.LayoutParams mLayoutParams;
2947
2948    /**
2949     * The view flags hold various views states.
2950     * {@hide}
2951     */
2952    @ViewDebug.ExportedProperty(formatToHexString = true)
2953    int mViewFlags;
2954
2955    static class TransformationInfo {
2956        /**
2957         * The transform matrix for the View. This transform is calculated internally
2958         * based on the translation, rotation, and scale properties.
2959         *
2960         * Do *not* use this variable directly; instead call getMatrix(), which will
2961         * load the value from the View's RenderNode.
2962         */
2963        private final Matrix mMatrix = new Matrix();
2964
2965        /**
2966         * The inverse transform matrix for the View. This transform is calculated
2967         * internally based on the translation, rotation, and scale properties.
2968         *
2969         * Do *not* use this variable directly; instead call getInverseMatrix(),
2970         * which will load the value from the View's RenderNode.
2971         */
2972        private Matrix mInverseMatrix;
2973
2974        /**
2975         * The opacity of the View. This is a value from 0 to 1, where 0 means
2976         * completely transparent and 1 means completely opaque.
2977         */
2978        @ViewDebug.ExportedProperty
2979        float mAlpha = 1f;
2980
2981        /**
2982         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2983         * property only used by transitions, which is composited with the other alpha
2984         * values to calculate the final visual alpha value.
2985         */
2986        float mTransitionAlpha = 1f;
2987    }
2988
2989    TransformationInfo mTransformationInfo;
2990
2991    /**
2992     * Current clip bounds. to which all drawing of this view are constrained.
2993     */
2994    Rect mClipBounds = null;
2995
2996    private boolean mLastIsOpaque;
2997
2998    /**
2999     * The distance in pixels from the left edge of this view's parent
3000     * to the left edge of this view.
3001     * {@hide}
3002     */
3003    @ViewDebug.ExportedProperty(category = "layout")
3004    protected int mLeft;
3005    /**
3006     * The distance in pixels from the left edge of this view's parent
3007     * to the right edge of this view.
3008     * {@hide}
3009     */
3010    @ViewDebug.ExportedProperty(category = "layout")
3011    protected int mRight;
3012    /**
3013     * The distance in pixels from the top edge of this view's parent
3014     * to the top edge of this view.
3015     * {@hide}
3016     */
3017    @ViewDebug.ExportedProperty(category = "layout")
3018    protected int mTop;
3019    /**
3020     * The distance in pixels from the top edge of this view's parent
3021     * to the bottom edge of this view.
3022     * {@hide}
3023     */
3024    @ViewDebug.ExportedProperty(category = "layout")
3025    protected int mBottom;
3026
3027    /**
3028     * The offset, in pixels, by which the content of this view is scrolled
3029     * horizontally.
3030     * {@hide}
3031     */
3032    @ViewDebug.ExportedProperty(category = "scrolling")
3033    protected int mScrollX;
3034    /**
3035     * The offset, in pixels, by which the content of this view is scrolled
3036     * vertically.
3037     * {@hide}
3038     */
3039    @ViewDebug.ExportedProperty(category = "scrolling")
3040    protected int mScrollY;
3041
3042    /**
3043     * The left padding in pixels, that is the distance in pixels between the
3044     * left edge of this view and the left edge of its content.
3045     * {@hide}
3046     */
3047    @ViewDebug.ExportedProperty(category = "padding")
3048    protected int mPaddingLeft = 0;
3049    /**
3050     * The right padding in pixels, that is the distance in pixels between the
3051     * right edge of this view and the right edge of its content.
3052     * {@hide}
3053     */
3054    @ViewDebug.ExportedProperty(category = "padding")
3055    protected int mPaddingRight = 0;
3056    /**
3057     * The top padding in pixels, that is the distance in pixels between the
3058     * top edge of this view and the top edge of its content.
3059     * {@hide}
3060     */
3061    @ViewDebug.ExportedProperty(category = "padding")
3062    protected int mPaddingTop;
3063    /**
3064     * The bottom padding in pixels, that is the distance in pixels between the
3065     * bottom edge of this view and the bottom edge of its content.
3066     * {@hide}
3067     */
3068    @ViewDebug.ExportedProperty(category = "padding")
3069    protected int mPaddingBottom;
3070
3071    /**
3072     * The layout insets in pixels, that is the distance in pixels between the
3073     * visible edges of this view its bounds.
3074     */
3075    private Insets mLayoutInsets;
3076
3077    /**
3078     * Briefly describes the view and is primarily used for accessibility support.
3079     */
3080    private CharSequence mContentDescription;
3081
3082    /**
3083     * Specifies the id of a view for which this view serves as a label for
3084     * accessibility purposes.
3085     */
3086    private int mLabelForId = View.NO_ID;
3087
3088    /**
3089     * Predicate for matching labeled view id with its label for
3090     * accessibility purposes.
3091     */
3092    private MatchLabelForPredicate mMatchLabelForPredicate;
3093
3094    /**
3095     * Predicate for matching a view by its id.
3096     */
3097    private MatchIdPredicate mMatchIdPredicate;
3098
3099    /**
3100     * Cache the paddingRight set by the user to append to the scrollbar's size.
3101     *
3102     * @hide
3103     */
3104    @ViewDebug.ExportedProperty(category = "padding")
3105    protected int mUserPaddingRight;
3106
3107    /**
3108     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3109     *
3110     * @hide
3111     */
3112    @ViewDebug.ExportedProperty(category = "padding")
3113    protected int mUserPaddingBottom;
3114
3115    /**
3116     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3117     *
3118     * @hide
3119     */
3120    @ViewDebug.ExportedProperty(category = "padding")
3121    protected int mUserPaddingLeft;
3122
3123    /**
3124     * Cache the paddingStart set by the user to append to the scrollbar's size.
3125     *
3126     */
3127    @ViewDebug.ExportedProperty(category = "padding")
3128    int mUserPaddingStart;
3129
3130    /**
3131     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3132     *
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    int mUserPaddingEnd;
3136
3137    /**
3138     * Cache initial left padding.
3139     *
3140     * @hide
3141     */
3142    int mUserPaddingLeftInitial;
3143
3144    /**
3145     * Cache initial right padding.
3146     *
3147     * @hide
3148     */
3149    int mUserPaddingRightInitial;
3150
3151    /**
3152     * Default undefined padding
3153     */
3154    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3155
3156    /**
3157     * Cache if a left padding has been defined
3158     */
3159    private boolean mLeftPaddingDefined = false;
3160
3161    /**
3162     * Cache if a right padding has been defined
3163     */
3164    private boolean mRightPaddingDefined = false;
3165
3166    /**
3167     * @hide
3168     */
3169    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3170    /**
3171     * @hide
3172     */
3173    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3174
3175    private LongSparseLongArray mMeasureCache;
3176
3177    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3178    private Drawable mBackground;
3179    private ColorStateList mBackgroundTintList = null;
3180    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3181    private boolean mHasBackgroundTint = false;
3182
3183    /**
3184     * RenderNode used for backgrounds.
3185     * <p>
3186     * When non-null and valid, this is expected to contain an up-to-date copy
3187     * of the background drawable. It is cleared on temporary detach, and reset
3188     * on cleanup.
3189     */
3190    private RenderNode mBackgroundRenderNode;
3191
3192    private int mBackgroundResource;
3193    private boolean mBackgroundSizeChanged;
3194
3195    private String mTransitionName;
3196
3197    static class ListenerInfo {
3198        /**
3199         * Listener used to dispatch focus change events.
3200         * This field should be made private, so it is hidden from the SDK.
3201         * {@hide}
3202         */
3203        protected OnFocusChangeListener mOnFocusChangeListener;
3204
3205        /**
3206         * Listeners for layout change events.
3207         */
3208        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3209
3210        /**
3211         * Listeners for attach events.
3212         */
3213        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3214
3215        /**
3216         * Listener used to dispatch click events.
3217         * This field should be made private, so it is hidden from the SDK.
3218         * {@hide}
3219         */
3220        public OnClickListener mOnClickListener;
3221
3222        /**
3223         * Listener used to dispatch long click events.
3224         * This field should be made private, so it is hidden from the SDK.
3225         * {@hide}
3226         */
3227        protected OnLongClickListener mOnLongClickListener;
3228
3229        /**
3230         * Listener used to build the context menu.
3231         * This field should be made private, so it is hidden from the SDK.
3232         * {@hide}
3233         */
3234        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3235
3236        private OnKeyListener mOnKeyListener;
3237
3238        private OnTouchListener mOnTouchListener;
3239
3240        private OnHoverListener mOnHoverListener;
3241
3242        private OnGenericMotionListener mOnGenericMotionListener;
3243
3244        private OnDragListener mOnDragListener;
3245
3246        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3247
3248        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3249    }
3250
3251    ListenerInfo mListenerInfo;
3252
3253    /**
3254     * The application environment this view lives in.
3255     * This field should be made private, so it is hidden from the SDK.
3256     * {@hide}
3257     */
3258    protected Context mContext;
3259
3260    private final Resources mResources;
3261
3262    private ScrollabilityCache mScrollCache;
3263
3264    private int[] mDrawableState = null;
3265
3266    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3267
3268    /**
3269     * Animator that automatically runs based on state changes.
3270     */
3271    private StateListAnimator mStateListAnimator;
3272
3273    /**
3274     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3275     * the user may specify which view to go to next.
3276     */
3277    private int mNextFocusLeftId = View.NO_ID;
3278
3279    /**
3280     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3281     * the user may specify which view to go to next.
3282     */
3283    private int mNextFocusRightId = View.NO_ID;
3284
3285    /**
3286     * When this view has focus and the next focus is {@link #FOCUS_UP},
3287     * the user may specify which view to go to next.
3288     */
3289    private int mNextFocusUpId = View.NO_ID;
3290
3291    /**
3292     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3293     * the user may specify which view to go to next.
3294     */
3295    private int mNextFocusDownId = View.NO_ID;
3296
3297    /**
3298     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3299     * the user may specify which view to go to next.
3300     */
3301    int mNextFocusForwardId = View.NO_ID;
3302
3303    private CheckForLongPress mPendingCheckForLongPress;
3304    private CheckForTap mPendingCheckForTap = null;
3305    private PerformClick mPerformClick;
3306    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3307
3308    private UnsetPressedState mUnsetPressedState;
3309
3310    /**
3311     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3312     * up event while a long press is invoked as soon as the long press duration is reached, so
3313     * a long press could be performed before the tap is checked, in which case the tap's action
3314     * should not be invoked.
3315     */
3316    private boolean mHasPerformedLongPress;
3317
3318    /**
3319     * The minimum height of the view. We'll try our best to have the height
3320     * of this view to at least this amount.
3321     */
3322    @ViewDebug.ExportedProperty(category = "measurement")
3323    private int mMinHeight;
3324
3325    /**
3326     * The minimum width of the view. We'll try our best to have the width
3327     * of this view to at least this amount.
3328     */
3329    @ViewDebug.ExportedProperty(category = "measurement")
3330    private int mMinWidth;
3331
3332    /**
3333     * The delegate to handle touch events that are physically in this view
3334     * but should be handled by another view.
3335     */
3336    private TouchDelegate mTouchDelegate = null;
3337
3338    /**
3339     * Solid color to use as a background when creating the drawing cache. Enables
3340     * the cache to use 16 bit bitmaps instead of 32 bit.
3341     */
3342    private int mDrawingCacheBackgroundColor = 0;
3343
3344    /**
3345     * Special tree observer used when mAttachInfo is null.
3346     */
3347    private ViewTreeObserver mFloatingTreeObserver;
3348
3349    /**
3350     * Cache the touch slop from the context that created the view.
3351     */
3352    private int mTouchSlop;
3353
3354    /**
3355     * Object that handles automatic animation of view properties.
3356     */
3357    private ViewPropertyAnimator mAnimator = null;
3358
3359    /**
3360     * Flag indicating that a drag can cross window boundaries.  When
3361     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3362     * with this flag set, all visible applications will be able to participate
3363     * in the drag operation and receive the dragged content.
3364     *
3365     * @hide
3366     */
3367    public static final int DRAG_FLAG_GLOBAL = 1;
3368
3369    /**
3370     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3371     */
3372    private float mVerticalScrollFactor;
3373
3374    /**
3375     * Position of the vertical scroll bar.
3376     */
3377    private int mVerticalScrollbarPosition;
3378
3379    /**
3380     * Position the scroll bar at the default position as determined by the system.
3381     */
3382    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3383
3384    /**
3385     * Position the scroll bar along the left edge.
3386     */
3387    public static final int SCROLLBAR_POSITION_LEFT = 1;
3388
3389    /**
3390     * Position the scroll bar along the right edge.
3391     */
3392    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3393
3394    /**
3395     * Indicates that the view does not have a layer.
3396     *
3397     * @see #getLayerType()
3398     * @see #setLayerType(int, android.graphics.Paint)
3399     * @see #LAYER_TYPE_SOFTWARE
3400     * @see #LAYER_TYPE_HARDWARE
3401     */
3402    public static final int LAYER_TYPE_NONE = 0;
3403
3404    /**
3405     * <p>Indicates that the view has a software layer. A software layer is backed
3406     * by a bitmap and causes the view to be rendered using Android's software
3407     * rendering pipeline, even if hardware acceleration is enabled.</p>
3408     *
3409     * <p>Software layers have various usages:</p>
3410     * <p>When the application is not using hardware acceleration, a software layer
3411     * is useful to apply a specific color filter and/or blending mode and/or
3412     * translucency to a view and all its children.</p>
3413     * <p>When the application is using hardware acceleration, a software layer
3414     * is useful to render drawing primitives not supported by the hardware
3415     * accelerated pipeline. It can also be used to cache a complex view tree
3416     * into a texture and reduce the complexity of drawing operations. For instance,
3417     * when animating a complex view tree with a translation, a software layer can
3418     * be used to render the view tree only once.</p>
3419     * <p>Software layers should be avoided when the affected view tree updates
3420     * often. Every update will require to re-render the software layer, which can
3421     * potentially be slow (particularly when hardware acceleration is turned on
3422     * since the layer will have to be uploaded into a hardware texture after every
3423     * update.)</p>
3424     *
3425     * @see #getLayerType()
3426     * @see #setLayerType(int, android.graphics.Paint)
3427     * @see #LAYER_TYPE_NONE
3428     * @see #LAYER_TYPE_HARDWARE
3429     */
3430    public static final int LAYER_TYPE_SOFTWARE = 1;
3431
3432    /**
3433     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3434     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3435     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3436     * rendering pipeline, but only if hardware acceleration is turned on for the
3437     * view hierarchy. When hardware acceleration is turned off, hardware layers
3438     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3439     *
3440     * <p>A hardware layer is useful to apply a specific color filter and/or
3441     * blending mode and/or translucency to a view and all its children.</p>
3442     * <p>A hardware layer can be used to cache a complex view tree into a
3443     * texture and reduce the complexity of drawing operations. For instance,
3444     * when animating a complex view tree with a translation, a hardware layer can
3445     * be used to render the view tree only once.</p>
3446     * <p>A hardware layer can also be used to increase the rendering quality when
3447     * rotation transformations are applied on a view. It can also be used to
3448     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3449     *
3450     * @see #getLayerType()
3451     * @see #setLayerType(int, android.graphics.Paint)
3452     * @see #LAYER_TYPE_NONE
3453     * @see #LAYER_TYPE_SOFTWARE
3454     */
3455    public static final int LAYER_TYPE_HARDWARE = 2;
3456
3457    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3458            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3459            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3460            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3461    })
3462    int mLayerType = LAYER_TYPE_NONE;
3463    Paint mLayerPaint;
3464
3465    /**
3466     * Set to true when drawing cache is enabled and cannot be created.
3467     *
3468     * @hide
3469     */
3470    public boolean mCachingFailed;
3471    private Bitmap mDrawingCache;
3472    private Bitmap mUnscaledDrawingCache;
3473
3474    /**
3475     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3476     * <p>
3477     * When non-null and valid, this is expected to contain an up-to-date copy
3478     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3479     * cleanup.
3480     */
3481    final RenderNode mRenderNode;
3482
3483    /**
3484     * Set to true when the view is sending hover accessibility events because it
3485     * is the innermost hovered view.
3486     */
3487    private boolean mSendingHoverAccessibilityEvents;
3488
3489    /**
3490     * Delegate for injecting accessibility functionality.
3491     */
3492    AccessibilityDelegate mAccessibilityDelegate;
3493
3494    /**
3495     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3496     * and add/remove objects to/from the overlay directly through the Overlay methods.
3497     */
3498    ViewOverlay mOverlay;
3499
3500    /**
3501     * The currently active parent view for receiving delegated nested scrolling events.
3502     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3503     * by {@link #stopNestedScroll()} at the same point where we clear
3504     * requestDisallowInterceptTouchEvent.
3505     */
3506    private ViewParent mNestedScrollingParent;
3507
3508    /**
3509     * Consistency verifier for debugging purposes.
3510     * @hide
3511     */
3512    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3513            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3514                    new InputEventConsistencyVerifier(this, 0) : null;
3515
3516    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3517
3518    private int[] mTempNestedScrollConsumed;
3519
3520    /**
3521     * An overlay is going to draw this View instead of being drawn as part of this
3522     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3523     * when this view is invalidated.
3524     */
3525    GhostView mGhostView;
3526
3527    /**
3528     * Simple constructor to use when creating a view from code.
3529     *
3530     * @param context The Context the view is running in, through which it can
3531     *        access the current theme, resources, etc.
3532     */
3533    public View(Context context) {
3534        mContext = context;
3535        mResources = context != null ? context.getResources() : null;
3536        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3537        // Set some flags defaults
3538        mPrivateFlags2 =
3539                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3540                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3541                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3542                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3543                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3544                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3545        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3546        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3547        mUserPaddingStart = UNDEFINED_PADDING;
3548        mUserPaddingEnd = UNDEFINED_PADDING;
3549        mRenderNode = RenderNode.create(getClass().getName());
3550
3551        if (!sCompatibilityDone && context != null) {
3552            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3553
3554            // Older apps may need this compatibility hack for measurement.
3555            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3556
3557            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3558            // of whether a layout was requested on that View.
3559            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3560
3561            sCompatibilityDone = true;
3562        }
3563    }
3564
3565    /**
3566     * Constructor that is called when inflating a view from XML. This is called
3567     * when a view is being constructed from an XML file, supplying attributes
3568     * that were specified in the XML file. This version uses a default style of
3569     * 0, so the only attribute values applied are those in the Context's Theme
3570     * and the given AttributeSet.
3571     *
3572     * <p>
3573     * The method onFinishInflate() will be called after all children have been
3574     * added.
3575     *
3576     * @param context The Context the view is running in, through which it can
3577     *        access the current theme, resources, etc.
3578     * @param attrs The attributes of the XML tag that is inflating the view.
3579     * @see #View(Context, AttributeSet, int)
3580     */
3581    public View(Context context, AttributeSet attrs) {
3582        this(context, attrs, 0);
3583    }
3584
3585    /**
3586     * Perform inflation from XML and apply a class-specific base style from a
3587     * theme attribute. This constructor of View allows subclasses to use their
3588     * own base style when they are inflating. For example, a Button class's
3589     * constructor would call this version of the super class constructor and
3590     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3591     * allows the theme's button style to modify all of the base view attributes
3592     * (in particular its background) as well as the Button class's attributes.
3593     *
3594     * @param context The Context the view is running in, through which it can
3595     *        access the current theme, resources, etc.
3596     * @param attrs The attributes of the XML tag that is inflating the view.
3597     * @param defStyleAttr An attribute in the current theme that contains a
3598     *        reference to a style resource that supplies default values for
3599     *        the view. Can be 0 to not look for defaults.
3600     * @see #View(Context, AttributeSet)
3601     */
3602    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3603        this(context, attrs, defStyleAttr, 0);
3604    }
3605
3606    /**
3607     * Perform inflation from XML and apply a class-specific base style from a
3608     * theme attribute or style resource. This constructor of View allows
3609     * subclasses to use their own base style when they are inflating.
3610     * <p>
3611     * When determining the final value of a particular attribute, there are
3612     * four inputs that come into play:
3613     * <ol>
3614     * <li>Any attribute values in the given AttributeSet.
3615     * <li>The style resource specified in the AttributeSet (named "style").
3616     * <li>The default style specified by <var>defStyleAttr</var>.
3617     * <li>The default style specified by <var>defStyleRes</var>.
3618     * <li>The base values in this theme.
3619     * </ol>
3620     * <p>
3621     * Each of these inputs is considered in-order, with the first listed taking
3622     * precedence over the following ones. In other words, if in the
3623     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3624     * , then the button's text will <em>always</em> be black, regardless of
3625     * what is specified in any of the styles.
3626     *
3627     * @param context The Context the view is running in, through which it can
3628     *        access the current theme, resources, etc.
3629     * @param attrs The attributes of the XML tag that is inflating the view.
3630     * @param defStyleAttr An attribute in the current theme that contains a
3631     *        reference to a style resource that supplies default values for
3632     *        the view. Can be 0 to not look for defaults.
3633     * @param defStyleRes A resource identifier of a style resource that
3634     *        supplies default values for the view, used only if
3635     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3636     *        to not look for defaults.
3637     * @see #View(Context, AttributeSet, int)
3638     */
3639    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3640        this(context);
3641
3642        final TypedArray a = context.obtainStyledAttributes(
3643                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3644
3645        Drawable background = null;
3646
3647        int leftPadding = -1;
3648        int topPadding = -1;
3649        int rightPadding = -1;
3650        int bottomPadding = -1;
3651        int startPadding = UNDEFINED_PADDING;
3652        int endPadding = UNDEFINED_PADDING;
3653
3654        int padding = -1;
3655
3656        int viewFlagValues = 0;
3657        int viewFlagMasks = 0;
3658
3659        boolean setScrollContainer = false;
3660
3661        int x = 0;
3662        int y = 0;
3663
3664        float tx = 0;
3665        float ty = 0;
3666        float tz = 0;
3667        float elevation = 0;
3668        float rotation = 0;
3669        float rotationX = 0;
3670        float rotationY = 0;
3671        float sx = 1f;
3672        float sy = 1f;
3673        boolean transformSet = false;
3674
3675        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3676        int overScrollMode = mOverScrollMode;
3677        boolean initializeScrollbars = false;
3678
3679        boolean startPaddingDefined = false;
3680        boolean endPaddingDefined = false;
3681        boolean leftPaddingDefined = false;
3682        boolean rightPaddingDefined = false;
3683
3684        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3685
3686        final int N = a.getIndexCount();
3687        for (int i = 0; i < N; i++) {
3688            int attr = a.getIndex(i);
3689            switch (attr) {
3690                case com.android.internal.R.styleable.View_background:
3691                    background = a.getDrawable(attr);
3692                    break;
3693                case com.android.internal.R.styleable.View_padding:
3694                    padding = a.getDimensionPixelSize(attr, -1);
3695                    mUserPaddingLeftInitial = padding;
3696                    mUserPaddingRightInitial = padding;
3697                    leftPaddingDefined = true;
3698                    rightPaddingDefined = true;
3699                    break;
3700                 case com.android.internal.R.styleable.View_paddingLeft:
3701                    leftPadding = a.getDimensionPixelSize(attr, -1);
3702                    mUserPaddingLeftInitial = leftPadding;
3703                    leftPaddingDefined = true;
3704                    break;
3705                case com.android.internal.R.styleable.View_paddingTop:
3706                    topPadding = a.getDimensionPixelSize(attr, -1);
3707                    break;
3708                case com.android.internal.R.styleable.View_paddingRight:
3709                    rightPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingRightInitial = rightPadding;
3711                    rightPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingBottom:
3714                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingStart:
3717                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3718                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3719                    break;
3720                case com.android.internal.R.styleable.View_paddingEnd:
3721                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3722                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3723                    break;
3724                case com.android.internal.R.styleable.View_scrollX:
3725                    x = a.getDimensionPixelOffset(attr, 0);
3726                    break;
3727                case com.android.internal.R.styleable.View_scrollY:
3728                    y = a.getDimensionPixelOffset(attr, 0);
3729                    break;
3730                case com.android.internal.R.styleable.View_alpha:
3731                    setAlpha(a.getFloat(attr, 1f));
3732                    break;
3733                case com.android.internal.R.styleable.View_transformPivotX:
3734                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3735                    break;
3736                case com.android.internal.R.styleable.View_transformPivotY:
3737                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3738                    break;
3739                case com.android.internal.R.styleable.View_translationX:
3740                    tx = a.getDimensionPixelOffset(attr, 0);
3741                    transformSet = true;
3742                    break;
3743                case com.android.internal.R.styleable.View_translationY:
3744                    ty = a.getDimensionPixelOffset(attr, 0);
3745                    transformSet = true;
3746                    break;
3747                case com.android.internal.R.styleable.View_translationZ:
3748                    tz = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_elevation:
3752                    elevation = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_rotation:
3756                    rotation = a.getFloat(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_rotationX:
3760                    rotationX = a.getFloat(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotationY:
3764                    rotationY = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_scaleX:
3768                    sx = a.getFloat(attr, 1f);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_scaleY:
3772                    sy = a.getFloat(attr, 1f);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_id:
3776                    mID = a.getResourceId(attr, NO_ID);
3777                    break;
3778                case com.android.internal.R.styleable.View_tag:
3779                    mTag = a.getText(attr);
3780                    break;
3781                case com.android.internal.R.styleable.View_fitsSystemWindows:
3782                    if (a.getBoolean(attr, false)) {
3783                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3784                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3785                    }
3786                    break;
3787                case com.android.internal.R.styleable.View_focusable:
3788                    if (a.getBoolean(attr, false)) {
3789                        viewFlagValues |= FOCUSABLE;
3790                        viewFlagMasks |= FOCUSABLE_MASK;
3791                    }
3792                    break;
3793                case com.android.internal.R.styleable.View_focusableInTouchMode:
3794                    if (a.getBoolean(attr, false)) {
3795                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3796                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3797                    }
3798                    break;
3799                case com.android.internal.R.styleable.View_clickable:
3800                    if (a.getBoolean(attr, false)) {
3801                        viewFlagValues |= CLICKABLE;
3802                        viewFlagMasks |= CLICKABLE;
3803                    }
3804                    break;
3805                case com.android.internal.R.styleable.View_longClickable:
3806                    if (a.getBoolean(attr, false)) {
3807                        viewFlagValues |= LONG_CLICKABLE;
3808                        viewFlagMasks |= LONG_CLICKABLE;
3809                    }
3810                    break;
3811                case com.android.internal.R.styleable.View_saveEnabled:
3812                    if (!a.getBoolean(attr, true)) {
3813                        viewFlagValues |= SAVE_DISABLED;
3814                        viewFlagMasks |= SAVE_DISABLED_MASK;
3815                    }
3816                    break;
3817                case com.android.internal.R.styleable.View_duplicateParentState:
3818                    if (a.getBoolean(attr, false)) {
3819                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3820                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3821                    }
3822                    break;
3823                case com.android.internal.R.styleable.View_visibility:
3824                    final int visibility = a.getInt(attr, 0);
3825                    if (visibility != 0) {
3826                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3827                        viewFlagMasks |= VISIBILITY_MASK;
3828                    }
3829                    break;
3830                case com.android.internal.R.styleable.View_layoutDirection:
3831                    // Clear any layout direction flags (included resolved bits) already set
3832                    mPrivateFlags2 &=
3833                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3834                    // Set the layout direction flags depending on the value of the attribute
3835                    final int layoutDirection = a.getInt(attr, -1);
3836                    final int value = (layoutDirection != -1) ?
3837                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3838                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3839                    break;
3840                case com.android.internal.R.styleable.View_drawingCacheQuality:
3841                    final int cacheQuality = a.getInt(attr, 0);
3842                    if (cacheQuality != 0) {
3843                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3844                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3845                    }
3846                    break;
3847                case com.android.internal.R.styleable.View_contentDescription:
3848                    setContentDescription(a.getString(attr));
3849                    break;
3850                case com.android.internal.R.styleable.View_labelFor:
3851                    setLabelFor(a.getResourceId(attr, NO_ID));
3852                    break;
3853                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3854                    if (!a.getBoolean(attr, true)) {
3855                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3856                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3860                    if (!a.getBoolean(attr, true)) {
3861                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3862                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3863                    }
3864                    break;
3865                case R.styleable.View_scrollbars:
3866                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3867                    if (scrollbars != SCROLLBARS_NONE) {
3868                        viewFlagValues |= scrollbars;
3869                        viewFlagMasks |= SCROLLBARS_MASK;
3870                        initializeScrollbars = true;
3871                    }
3872                    break;
3873                //noinspection deprecation
3874                case R.styleable.View_fadingEdge:
3875                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3876                        // Ignore the attribute starting with ICS
3877                        break;
3878                    }
3879                    // With builds < ICS, fall through and apply fading edges
3880                case R.styleable.View_requiresFadingEdge:
3881                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3882                    if (fadingEdge != FADING_EDGE_NONE) {
3883                        viewFlagValues |= fadingEdge;
3884                        viewFlagMasks |= FADING_EDGE_MASK;
3885                        initializeFadingEdgeInternal(a);
3886                    }
3887                    break;
3888                case R.styleable.View_scrollbarStyle:
3889                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3890                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3891                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3892                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3893                    }
3894                    break;
3895                case R.styleable.View_isScrollContainer:
3896                    setScrollContainer = true;
3897                    if (a.getBoolean(attr, false)) {
3898                        setScrollContainer(true);
3899                    }
3900                    break;
3901                case com.android.internal.R.styleable.View_keepScreenOn:
3902                    if (a.getBoolean(attr, false)) {
3903                        viewFlagValues |= KEEP_SCREEN_ON;
3904                        viewFlagMasks |= KEEP_SCREEN_ON;
3905                    }
3906                    break;
3907                case R.styleable.View_filterTouchesWhenObscured:
3908                    if (a.getBoolean(attr, false)) {
3909                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3910                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3911                    }
3912                    break;
3913                case R.styleable.View_nextFocusLeft:
3914                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3915                    break;
3916                case R.styleable.View_nextFocusRight:
3917                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3918                    break;
3919                case R.styleable.View_nextFocusUp:
3920                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3921                    break;
3922                case R.styleable.View_nextFocusDown:
3923                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3924                    break;
3925                case R.styleable.View_nextFocusForward:
3926                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3927                    break;
3928                case R.styleable.View_minWidth:
3929                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3930                    break;
3931                case R.styleable.View_minHeight:
3932                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3933                    break;
3934                case R.styleable.View_onClick:
3935                    if (context.isRestricted()) {
3936                        throw new IllegalStateException("The android:onClick attribute cannot "
3937                                + "be used within a restricted context");
3938                    }
3939
3940                    final String handlerName = a.getString(attr);
3941                    if (handlerName != null) {
3942                        setOnClickListener(new OnClickListener() {
3943                            private Method mHandler;
3944
3945                            public void onClick(View v) {
3946                                if (mHandler == null) {
3947                                    try {
3948                                        mHandler = getContext().getClass().getMethod(handlerName,
3949                                                View.class);
3950                                    } catch (NoSuchMethodException e) {
3951                                        int id = getId();
3952                                        String idText = id == NO_ID ? "" : " with id '"
3953                                                + getContext().getResources().getResourceEntryName(
3954                                                    id) + "'";
3955                                        throw new IllegalStateException("Could not find a method " +
3956                                                handlerName + "(View) in the activity "
3957                                                + getContext().getClass() + " for onClick handler"
3958                                                + " on view " + View.this.getClass() + idText, e);
3959                                    }
3960                                }
3961
3962                                try {
3963                                    mHandler.invoke(getContext(), View.this);
3964                                } catch (IllegalAccessException e) {
3965                                    throw new IllegalStateException("Could not execute non "
3966                                            + "public method of the activity", e);
3967                                } catch (InvocationTargetException e) {
3968                                    throw new IllegalStateException("Could not execute "
3969                                            + "method of the activity", e);
3970                                }
3971                            }
3972                        });
3973                    }
3974                    break;
3975                case R.styleable.View_overScrollMode:
3976                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3977                    break;
3978                case R.styleable.View_verticalScrollbarPosition:
3979                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3980                    break;
3981                case R.styleable.View_layerType:
3982                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3983                    break;
3984                case R.styleable.View_textDirection:
3985                    // Clear any text direction flag already set
3986                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3987                    // Set the text direction flags depending on the value of the attribute
3988                    final int textDirection = a.getInt(attr, -1);
3989                    if (textDirection != -1) {
3990                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3991                    }
3992                    break;
3993                case R.styleable.View_textAlignment:
3994                    // Clear any text alignment flag already set
3995                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3996                    // Set the text alignment flag depending on the value of the attribute
3997                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3998                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3999                    break;
4000                case R.styleable.View_importantForAccessibility:
4001                    setImportantForAccessibility(a.getInt(attr,
4002                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4003                    break;
4004                case R.styleable.View_accessibilityLiveRegion:
4005                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4006                    break;
4007                case R.styleable.View_transitionName:
4008                    setTransitionName(a.getString(attr));
4009                    break;
4010                case R.styleable.View_nestedScrollingEnabled:
4011                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4012                    break;
4013                case R.styleable.View_stateListAnimator:
4014                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4015                            a.getResourceId(attr, 0)));
4016                    break;
4017                case R.styleable.View_backgroundTint:
4018                    // This will get applied later during setBackground().
4019                    mBackgroundTintList = a.getColorStateList(R.styleable.View_backgroundTint);
4020                    mHasBackgroundTint = true;
4021                    break;
4022                case R.styleable.View_backgroundTintMode:
4023                    // This will get applied later during setBackground().
4024                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4025                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4026                    break;
4027            }
4028        }
4029
4030        setOverScrollMode(overScrollMode);
4031
4032        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4033        // the resolved layout direction). Those cached values will be used later during padding
4034        // resolution.
4035        mUserPaddingStart = startPadding;
4036        mUserPaddingEnd = endPadding;
4037
4038        if (background != null) {
4039            setBackground(background);
4040        }
4041
4042        // setBackground above will record that padding is currently provided by the background.
4043        // If we have padding specified via xml, record that here instead and use it.
4044        mLeftPaddingDefined = leftPaddingDefined;
4045        mRightPaddingDefined = rightPaddingDefined;
4046
4047        if (padding >= 0) {
4048            leftPadding = padding;
4049            topPadding = padding;
4050            rightPadding = padding;
4051            bottomPadding = padding;
4052            mUserPaddingLeftInitial = padding;
4053            mUserPaddingRightInitial = padding;
4054        }
4055
4056        if (isRtlCompatibilityMode()) {
4057            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4058            // left / right padding are used if defined (meaning here nothing to do). If they are not
4059            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4060            // start / end and resolve them as left / right (layout direction is not taken into account).
4061            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4062            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4063            // defined.
4064            if (!mLeftPaddingDefined && startPaddingDefined) {
4065                leftPadding = startPadding;
4066            }
4067            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4068            if (!mRightPaddingDefined && endPaddingDefined) {
4069                rightPadding = endPadding;
4070            }
4071            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4072        } else {
4073            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4074            // values defined. Otherwise, left /right values are used.
4075            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4076            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4077            // defined.
4078            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4079
4080            if (mLeftPaddingDefined && !hasRelativePadding) {
4081                mUserPaddingLeftInitial = leftPadding;
4082            }
4083            if (mRightPaddingDefined && !hasRelativePadding) {
4084                mUserPaddingRightInitial = rightPadding;
4085            }
4086        }
4087
4088        internalSetPadding(
4089                mUserPaddingLeftInitial,
4090                topPadding >= 0 ? topPadding : mPaddingTop,
4091                mUserPaddingRightInitial,
4092                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4093
4094        if (viewFlagMasks != 0) {
4095            setFlags(viewFlagValues, viewFlagMasks);
4096        }
4097
4098        if (initializeScrollbars) {
4099            initializeScrollbarsInternal(a);
4100        }
4101
4102        a.recycle();
4103
4104        // Needs to be called after mViewFlags is set
4105        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4106            recomputePadding();
4107        }
4108
4109        if (x != 0 || y != 0) {
4110            scrollTo(x, y);
4111        }
4112
4113        if (transformSet) {
4114            setTranslationX(tx);
4115            setTranslationY(ty);
4116            setTranslationZ(tz);
4117            setElevation(elevation);
4118            setRotation(rotation);
4119            setRotationX(rotationX);
4120            setRotationY(rotationY);
4121            setScaleX(sx);
4122            setScaleY(sy);
4123        }
4124
4125        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4126            setScrollContainer(true);
4127        }
4128
4129        computeOpaqueFlags();
4130    }
4131
4132    /**
4133     * Non-public constructor for use in testing
4134     */
4135    View() {
4136        mResources = null;
4137        mRenderNode = RenderNode.create(getClass().getName());
4138    }
4139
4140    public String toString() {
4141        StringBuilder out = new StringBuilder(128);
4142        out.append(getClass().getName());
4143        out.append('{');
4144        out.append(Integer.toHexString(System.identityHashCode(this)));
4145        out.append(' ');
4146        switch (mViewFlags&VISIBILITY_MASK) {
4147            case VISIBLE: out.append('V'); break;
4148            case INVISIBLE: out.append('I'); break;
4149            case GONE: out.append('G'); break;
4150            default: out.append('.'); break;
4151        }
4152        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4153        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4154        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4155        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4156        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4157        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4158        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4159        out.append(' ');
4160        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4161        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4162        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4163        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4164            out.append('p');
4165        } else {
4166            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4167        }
4168        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4169        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4170        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4171        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4172        out.append(' ');
4173        out.append(mLeft);
4174        out.append(',');
4175        out.append(mTop);
4176        out.append('-');
4177        out.append(mRight);
4178        out.append(',');
4179        out.append(mBottom);
4180        final int id = getId();
4181        if (id != NO_ID) {
4182            out.append(" #");
4183            out.append(Integer.toHexString(id));
4184            final Resources r = mResources;
4185            if (Resources.resourceHasPackage(id) && r != null) {
4186                try {
4187                    String pkgname;
4188                    switch (id&0xff000000) {
4189                        case 0x7f000000:
4190                            pkgname="app";
4191                            break;
4192                        case 0x01000000:
4193                            pkgname="android";
4194                            break;
4195                        default:
4196                            pkgname = r.getResourcePackageName(id);
4197                            break;
4198                    }
4199                    String typename = r.getResourceTypeName(id);
4200                    String entryname = r.getResourceEntryName(id);
4201                    out.append(" ");
4202                    out.append(pkgname);
4203                    out.append(":");
4204                    out.append(typename);
4205                    out.append("/");
4206                    out.append(entryname);
4207                } catch (Resources.NotFoundException e) {
4208                }
4209            }
4210        }
4211        out.append("}");
4212        return out.toString();
4213    }
4214
4215    /**
4216     * <p>
4217     * Initializes the fading edges from a given set of styled attributes. This
4218     * method should be called by subclasses that need fading edges and when an
4219     * instance of these subclasses is created programmatically rather than
4220     * being inflated from XML. This method is automatically called when the XML
4221     * is inflated.
4222     * </p>
4223     *
4224     * @param a the styled attributes set to initialize the fading edges from
4225     */
4226    protected void initializeFadingEdge(TypedArray a) {
4227        // This method probably shouldn't have been included in the SDK to begin with.
4228        // It relies on 'a' having been initialized using an attribute filter array that is
4229        // not publicly available to the SDK. The old method has been renamed
4230        // to initializeFadingEdgeInternal and hidden for framework use only;
4231        // this one initializes using defaults to make it safe to call for apps.
4232
4233        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4234
4235        initializeFadingEdgeInternal(arr);
4236
4237        arr.recycle();
4238    }
4239
4240    /**
4241     * <p>
4242     * Initializes the fading edges from a given set of styled attributes. This
4243     * method should be called by subclasses that need fading edges and when an
4244     * instance of these subclasses is created programmatically rather than
4245     * being inflated from XML. This method is automatically called when the XML
4246     * is inflated.
4247     * </p>
4248     *
4249     * @param a the styled attributes set to initialize the fading edges from
4250     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4251     */
4252    protected void initializeFadingEdgeInternal(TypedArray a) {
4253        initScrollCache();
4254
4255        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4256                R.styleable.View_fadingEdgeLength,
4257                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4258    }
4259
4260    /**
4261     * Returns the size of the vertical faded edges used to indicate that more
4262     * content in this view is visible.
4263     *
4264     * @return The size in pixels of the vertical faded edge or 0 if vertical
4265     *         faded edges are not enabled for this view.
4266     * @attr ref android.R.styleable#View_fadingEdgeLength
4267     */
4268    public int getVerticalFadingEdgeLength() {
4269        if (isVerticalFadingEdgeEnabled()) {
4270            ScrollabilityCache cache = mScrollCache;
4271            if (cache != null) {
4272                return cache.fadingEdgeLength;
4273            }
4274        }
4275        return 0;
4276    }
4277
4278    /**
4279     * Set the size of the faded edge used to indicate that more content in this
4280     * view is available.  Will not change whether the fading edge is enabled; use
4281     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4282     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4283     * for the vertical or horizontal fading edges.
4284     *
4285     * @param length The size in pixels of the faded edge used to indicate that more
4286     *        content in this view is visible.
4287     */
4288    public void setFadingEdgeLength(int length) {
4289        initScrollCache();
4290        mScrollCache.fadingEdgeLength = length;
4291    }
4292
4293    /**
4294     * Returns the size of the horizontal faded edges used to indicate that more
4295     * content in this view is visible.
4296     *
4297     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4298     *         faded edges are not enabled for this view.
4299     * @attr ref android.R.styleable#View_fadingEdgeLength
4300     */
4301    public int getHorizontalFadingEdgeLength() {
4302        if (isHorizontalFadingEdgeEnabled()) {
4303            ScrollabilityCache cache = mScrollCache;
4304            if (cache != null) {
4305                return cache.fadingEdgeLength;
4306            }
4307        }
4308        return 0;
4309    }
4310
4311    /**
4312     * Returns the width of the vertical scrollbar.
4313     *
4314     * @return The width in pixels of the vertical scrollbar or 0 if there
4315     *         is no vertical scrollbar.
4316     */
4317    public int getVerticalScrollbarWidth() {
4318        ScrollabilityCache cache = mScrollCache;
4319        if (cache != null) {
4320            ScrollBarDrawable scrollBar = cache.scrollBar;
4321            if (scrollBar != null) {
4322                int size = scrollBar.getSize(true);
4323                if (size <= 0) {
4324                    size = cache.scrollBarSize;
4325                }
4326                return size;
4327            }
4328            return 0;
4329        }
4330        return 0;
4331    }
4332
4333    /**
4334     * Returns the height of the horizontal scrollbar.
4335     *
4336     * @return The height in pixels of the horizontal scrollbar or 0 if
4337     *         there is no horizontal scrollbar.
4338     */
4339    protected int getHorizontalScrollbarHeight() {
4340        ScrollabilityCache cache = mScrollCache;
4341        if (cache != null) {
4342            ScrollBarDrawable scrollBar = cache.scrollBar;
4343            if (scrollBar != null) {
4344                int size = scrollBar.getSize(false);
4345                if (size <= 0) {
4346                    size = cache.scrollBarSize;
4347                }
4348                return size;
4349            }
4350            return 0;
4351        }
4352        return 0;
4353    }
4354
4355    /**
4356     * <p>
4357     * Initializes the scrollbars from a given set of styled attributes. This
4358     * method should be called by subclasses that need scrollbars and when an
4359     * instance of these subclasses is created programmatically rather than
4360     * being inflated from XML. This method is automatically called when the XML
4361     * is inflated.
4362     * </p>
4363     *
4364     * @param a the styled attributes set to initialize the scrollbars from
4365     */
4366    protected void initializeScrollbars(TypedArray a) {
4367        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4368        // using the View filter array which is not available to the SDK. As such, internal
4369        // framework usage now uses initializeScrollbarsInternal and we grab a default
4370        // TypedArray with the right filter instead here.
4371        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4372
4373        initializeScrollbarsInternal(arr);
4374
4375        // We ignored the method parameter. Recycle the one we actually did use.
4376        arr.recycle();
4377    }
4378
4379    /**
4380     * <p>
4381     * Initializes the scrollbars from a given set of styled attributes. This
4382     * method should be called by subclasses that need scrollbars and when an
4383     * instance of these subclasses is created programmatically rather than
4384     * being inflated from XML. This method is automatically called when the XML
4385     * is inflated.
4386     * </p>
4387     *
4388     * @param a the styled attributes set to initialize the scrollbars from
4389     * @hide
4390     */
4391    protected void initializeScrollbarsInternal(TypedArray a) {
4392        initScrollCache();
4393
4394        final ScrollabilityCache scrollabilityCache = mScrollCache;
4395
4396        if (scrollabilityCache.scrollBar == null) {
4397            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4398        }
4399
4400        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4401
4402        if (!fadeScrollbars) {
4403            scrollabilityCache.state = ScrollabilityCache.ON;
4404        }
4405        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4406
4407
4408        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4409                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4410                        .getScrollBarFadeDuration());
4411        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4412                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4413                ViewConfiguration.getScrollDefaultDelay());
4414
4415
4416        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4417                com.android.internal.R.styleable.View_scrollbarSize,
4418                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4419
4420        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4421        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4422
4423        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4424        if (thumb != null) {
4425            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4426        }
4427
4428        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4429                false);
4430        if (alwaysDraw) {
4431            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4432        }
4433
4434        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4435        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4436
4437        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4438        if (thumb != null) {
4439            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4440        }
4441
4442        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4443                false);
4444        if (alwaysDraw) {
4445            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4446        }
4447
4448        // Apply layout direction to the new Drawables if needed
4449        final int layoutDirection = getLayoutDirection();
4450        if (track != null) {
4451            track.setLayoutDirection(layoutDirection);
4452        }
4453        if (thumb != null) {
4454            thumb.setLayoutDirection(layoutDirection);
4455        }
4456
4457        // Re-apply user/background padding so that scrollbar(s) get added
4458        resolvePadding();
4459    }
4460
4461    /**
4462     * <p>
4463     * Initalizes the scrollability cache if necessary.
4464     * </p>
4465     */
4466    private void initScrollCache() {
4467        if (mScrollCache == null) {
4468            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4469        }
4470    }
4471
4472    private ScrollabilityCache getScrollCache() {
4473        initScrollCache();
4474        return mScrollCache;
4475    }
4476
4477    /**
4478     * Set the position of the vertical scroll bar. Should be one of
4479     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4480     * {@link #SCROLLBAR_POSITION_RIGHT}.
4481     *
4482     * @param position Where the vertical scroll bar should be positioned.
4483     */
4484    public void setVerticalScrollbarPosition(int position) {
4485        if (mVerticalScrollbarPosition != position) {
4486            mVerticalScrollbarPosition = position;
4487            computeOpaqueFlags();
4488            resolvePadding();
4489        }
4490    }
4491
4492    /**
4493     * @return The position where the vertical scroll bar will show, if applicable.
4494     * @see #setVerticalScrollbarPosition(int)
4495     */
4496    public int getVerticalScrollbarPosition() {
4497        return mVerticalScrollbarPosition;
4498    }
4499
4500    ListenerInfo getListenerInfo() {
4501        if (mListenerInfo != null) {
4502            return mListenerInfo;
4503        }
4504        mListenerInfo = new ListenerInfo();
4505        return mListenerInfo;
4506    }
4507
4508    /**
4509     * Register a callback to be invoked when focus of this view changed.
4510     *
4511     * @param l The callback that will run.
4512     */
4513    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4514        getListenerInfo().mOnFocusChangeListener = l;
4515    }
4516
4517    /**
4518     * Add a listener that will be called when the bounds of the view change due to
4519     * layout processing.
4520     *
4521     * @param listener The listener that will be called when layout bounds change.
4522     */
4523    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4524        ListenerInfo li = getListenerInfo();
4525        if (li.mOnLayoutChangeListeners == null) {
4526            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4527        }
4528        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4529            li.mOnLayoutChangeListeners.add(listener);
4530        }
4531    }
4532
4533    /**
4534     * Remove a listener for layout changes.
4535     *
4536     * @param listener The listener for layout bounds change.
4537     */
4538    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4539        ListenerInfo li = mListenerInfo;
4540        if (li == null || li.mOnLayoutChangeListeners == null) {
4541            return;
4542        }
4543        li.mOnLayoutChangeListeners.remove(listener);
4544    }
4545
4546    /**
4547     * Add a listener for attach state changes.
4548     *
4549     * This listener will be called whenever this view is attached or detached
4550     * from a window. Remove the listener using
4551     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4552     *
4553     * @param listener Listener to attach
4554     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4555     */
4556    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4557        ListenerInfo li = getListenerInfo();
4558        if (li.mOnAttachStateChangeListeners == null) {
4559            li.mOnAttachStateChangeListeners
4560                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4561        }
4562        li.mOnAttachStateChangeListeners.add(listener);
4563    }
4564
4565    /**
4566     * Remove a listener for attach state changes. The listener will receive no further
4567     * notification of window attach/detach events.
4568     *
4569     * @param listener Listener to remove
4570     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4571     */
4572    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4573        ListenerInfo li = mListenerInfo;
4574        if (li == null || li.mOnAttachStateChangeListeners == null) {
4575            return;
4576        }
4577        li.mOnAttachStateChangeListeners.remove(listener);
4578    }
4579
4580    /**
4581     * Returns the focus-change callback registered for this view.
4582     *
4583     * @return The callback, or null if one is not registered.
4584     */
4585    public OnFocusChangeListener getOnFocusChangeListener() {
4586        ListenerInfo li = mListenerInfo;
4587        return li != null ? li.mOnFocusChangeListener : null;
4588    }
4589
4590    /**
4591     * Register a callback to be invoked when this view is clicked. If this view is not
4592     * clickable, it becomes clickable.
4593     *
4594     * @param l The callback that will run
4595     *
4596     * @see #setClickable(boolean)
4597     */
4598    public void setOnClickListener(OnClickListener l) {
4599        if (!isClickable()) {
4600            setClickable(true);
4601        }
4602        getListenerInfo().mOnClickListener = l;
4603    }
4604
4605    /**
4606     * Return whether this view has an attached OnClickListener.  Returns
4607     * true if there is a listener, false if there is none.
4608     */
4609    public boolean hasOnClickListeners() {
4610        ListenerInfo li = mListenerInfo;
4611        return (li != null && li.mOnClickListener != null);
4612    }
4613
4614    /**
4615     * Register a callback to be invoked when this view is clicked and held. If this view is not
4616     * long clickable, it becomes long clickable.
4617     *
4618     * @param l The callback that will run
4619     *
4620     * @see #setLongClickable(boolean)
4621     */
4622    public void setOnLongClickListener(OnLongClickListener l) {
4623        if (!isLongClickable()) {
4624            setLongClickable(true);
4625        }
4626        getListenerInfo().mOnLongClickListener = l;
4627    }
4628
4629    /**
4630     * Register a callback to be invoked when the context menu for this view is
4631     * being built. If this view is not long clickable, it becomes long clickable.
4632     *
4633     * @param l The callback that will run
4634     *
4635     */
4636    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4637        if (!isLongClickable()) {
4638            setLongClickable(true);
4639        }
4640        getListenerInfo().mOnCreateContextMenuListener = l;
4641    }
4642
4643    /**
4644     * Call this view's OnClickListener, if it is defined.  Performs all normal
4645     * actions associated with clicking: reporting accessibility event, playing
4646     * a sound, etc.
4647     *
4648     * @return True there was an assigned OnClickListener that was called, false
4649     *         otherwise is returned.
4650     */
4651    public boolean performClick() {
4652        final boolean result;
4653        final ListenerInfo li = mListenerInfo;
4654        if (li != null && li.mOnClickListener != null) {
4655            playSoundEffect(SoundEffectConstants.CLICK);
4656            li.mOnClickListener.onClick(this);
4657            result = true;
4658        } else {
4659            result = false;
4660        }
4661
4662        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4663        return result;
4664    }
4665
4666    /**
4667     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4668     * this only calls the listener, and does not do any associated clicking
4669     * actions like reporting an accessibility event.
4670     *
4671     * @return True there was an assigned OnClickListener that was called, false
4672     *         otherwise is returned.
4673     */
4674    public boolean callOnClick() {
4675        ListenerInfo li = mListenerInfo;
4676        if (li != null && li.mOnClickListener != null) {
4677            li.mOnClickListener.onClick(this);
4678            return true;
4679        }
4680        return false;
4681    }
4682
4683    /**
4684     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4685     * OnLongClickListener did not consume the event.
4686     *
4687     * @return True if one of the above receivers consumed the event, false otherwise.
4688     */
4689    public boolean performLongClick() {
4690        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4691
4692        boolean handled = false;
4693        ListenerInfo li = mListenerInfo;
4694        if (li != null && li.mOnLongClickListener != null) {
4695            handled = li.mOnLongClickListener.onLongClick(View.this);
4696        }
4697        if (!handled) {
4698            handled = showContextMenu();
4699        }
4700        if (handled) {
4701            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4702        }
4703        return handled;
4704    }
4705
4706    /**
4707     * Performs button-related actions during a touch down event.
4708     *
4709     * @param event The event.
4710     * @return True if the down was consumed.
4711     *
4712     * @hide
4713     */
4714    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4715        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4716            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4717                return true;
4718            }
4719        }
4720        return false;
4721    }
4722
4723    /**
4724     * Bring up the context menu for this view.
4725     *
4726     * @return Whether a context menu was displayed.
4727     */
4728    public boolean showContextMenu() {
4729        return getParent().showContextMenuForChild(this);
4730    }
4731
4732    /**
4733     * Bring up the context menu for this view, referring to the item under the specified point.
4734     *
4735     * @param x The referenced x coordinate.
4736     * @param y The referenced y coordinate.
4737     * @param metaState The keyboard modifiers that were pressed.
4738     * @return Whether a context menu was displayed.
4739     *
4740     * @hide
4741     */
4742    public boolean showContextMenu(float x, float y, int metaState) {
4743        return showContextMenu();
4744    }
4745
4746    /**
4747     * Start an action mode.
4748     *
4749     * @param callback Callback that will control the lifecycle of the action mode
4750     * @return The new action mode if it is started, null otherwise
4751     *
4752     * @see ActionMode
4753     */
4754    public ActionMode startActionMode(ActionMode.Callback callback) {
4755        ViewParent parent = getParent();
4756        if (parent == null) return null;
4757        return parent.startActionModeForChild(this, callback);
4758    }
4759
4760    /**
4761     * Register a callback to be invoked when a hardware key is pressed in this view.
4762     * Key presses in software input methods will generally not trigger the methods of
4763     * this listener.
4764     * @param l the key listener to attach to this view
4765     */
4766    public void setOnKeyListener(OnKeyListener l) {
4767        getListenerInfo().mOnKeyListener = l;
4768    }
4769
4770    /**
4771     * Register a callback to be invoked when a touch event is sent to this view.
4772     * @param l the touch listener to attach to this view
4773     */
4774    public void setOnTouchListener(OnTouchListener l) {
4775        getListenerInfo().mOnTouchListener = l;
4776    }
4777
4778    /**
4779     * Register a callback to be invoked when a generic motion event is sent to this view.
4780     * @param l the generic motion listener to attach to this view
4781     */
4782    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4783        getListenerInfo().mOnGenericMotionListener = l;
4784    }
4785
4786    /**
4787     * Register a callback to be invoked when a hover event is sent to this view.
4788     * @param l the hover listener to attach to this view
4789     */
4790    public void setOnHoverListener(OnHoverListener l) {
4791        getListenerInfo().mOnHoverListener = l;
4792    }
4793
4794    /**
4795     * Register a drag event listener callback object for this View. The parameter is
4796     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4797     * View, the system calls the
4798     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4799     * @param l An implementation of {@link android.view.View.OnDragListener}.
4800     */
4801    public void setOnDragListener(OnDragListener l) {
4802        getListenerInfo().mOnDragListener = l;
4803    }
4804
4805    /**
4806     * Give this view focus. This will cause
4807     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4808     *
4809     * Note: this does not check whether this {@link View} should get focus, it just
4810     * gives it focus no matter what.  It should only be called internally by framework
4811     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4812     *
4813     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4814     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4815     *        focus moved when requestFocus() is called. It may not always
4816     *        apply, in which case use the default View.FOCUS_DOWN.
4817     * @param previouslyFocusedRect The rectangle of the view that had focus
4818     *        prior in this View's coordinate system.
4819     */
4820    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4821        if (DBG) {
4822            System.out.println(this + " requestFocus()");
4823        }
4824
4825        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4826            mPrivateFlags |= PFLAG_FOCUSED;
4827
4828            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4829
4830            if (mParent != null) {
4831                mParent.requestChildFocus(this, this);
4832            }
4833
4834            if (mAttachInfo != null) {
4835                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4836            }
4837
4838            onFocusChanged(true, direction, previouslyFocusedRect);
4839            manageFocusHotspot(true, oldFocus);
4840            refreshDrawableState();
4841        }
4842    }
4843
4844    /**
4845     * Forwards focus information to the background drawable, if necessary. When
4846     * the view is gaining focus, <code>v</code> is the previous focus holder.
4847     * When the view is losing focus, <code>v</code> is the next focus holder.
4848     *
4849     * @param focused whether this view is focused
4850     * @param v previous or the next focus holder, or null if none
4851     */
4852    private void manageFocusHotspot(boolean focused, View v) {
4853        final Rect r = new Rect();
4854        if (v != null && mAttachInfo != null) {
4855            v.getHotspotBounds(r);
4856            final int[] location = mAttachInfo.mTmpLocation;
4857            getLocationOnScreen(location);
4858            r.offset(-location[0], -location[1]);
4859        } else {
4860            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4861        }
4862
4863        final float x = r.exactCenterX();
4864        final float y = r.exactCenterY();
4865        drawableHotspotChanged(x, y);
4866    }
4867
4868    /**
4869     * Populates <code>outRect</code> with the hotspot bounds. By default,
4870     * the hotspot bounds are identical to the screen bounds.
4871     *
4872     * @param outRect rect to populate with hotspot bounds
4873     * @hide Only for internal use by views and widgets.
4874     */
4875    public void getHotspotBounds(Rect outRect) {
4876        final Drawable background = getBackground();
4877        if (background != null) {
4878            background.getHotspotBounds(outRect);
4879        } else {
4880            getBoundsOnScreen(outRect);
4881        }
4882    }
4883
4884    /**
4885     * Request that a rectangle of this view be visible on the screen,
4886     * scrolling if necessary just enough.
4887     *
4888     * <p>A View should call this if it maintains some notion of which part
4889     * of its content is interesting.  For example, a text editing view
4890     * should call this when its cursor moves.
4891     *
4892     * @param rectangle The rectangle.
4893     * @return Whether any parent scrolled.
4894     */
4895    public boolean requestRectangleOnScreen(Rect rectangle) {
4896        return requestRectangleOnScreen(rectangle, false);
4897    }
4898
4899    /**
4900     * Request that a rectangle of this view be visible on the screen,
4901     * scrolling if necessary just enough.
4902     *
4903     * <p>A View should call this if it maintains some notion of which part
4904     * of its content is interesting.  For example, a text editing view
4905     * should call this when its cursor moves.
4906     *
4907     * <p>When <code>immediate</code> is set to true, scrolling will not be
4908     * animated.
4909     *
4910     * @param rectangle The rectangle.
4911     * @param immediate True to forbid animated scrolling, false otherwise
4912     * @return Whether any parent scrolled.
4913     */
4914    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4915        if (mParent == null) {
4916            return false;
4917        }
4918
4919        View child = this;
4920
4921        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4922        position.set(rectangle);
4923
4924        ViewParent parent = mParent;
4925        boolean scrolled = false;
4926        while (parent != null) {
4927            rectangle.set((int) position.left, (int) position.top,
4928                    (int) position.right, (int) position.bottom);
4929
4930            scrolled |= parent.requestChildRectangleOnScreen(child,
4931                    rectangle, immediate);
4932
4933            if (!child.hasIdentityMatrix()) {
4934                child.getMatrix().mapRect(position);
4935            }
4936
4937            position.offset(child.mLeft, child.mTop);
4938
4939            if (!(parent instanceof View)) {
4940                break;
4941            }
4942
4943            View parentView = (View) parent;
4944
4945            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4946
4947            child = parentView;
4948            parent = child.getParent();
4949        }
4950
4951        return scrolled;
4952    }
4953
4954    /**
4955     * Called when this view wants to give up focus. If focus is cleared
4956     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4957     * <p>
4958     * <strong>Note:</strong> When a View clears focus the framework is trying
4959     * to give focus to the first focusable View from the top. Hence, if this
4960     * View is the first from the top that can take focus, then all callbacks
4961     * related to clearing focus will be invoked after wich the framework will
4962     * give focus to this view.
4963     * </p>
4964     */
4965    public void clearFocus() {
4966        if (DBG) {
4967            System.out.println(this + " clearFocus()");
4968        }
4969
4970        clearFocusInternal(null, true, true);
4971    }
4972
4973    /**
4974     * Clears focus from the view, optionally propagating the change up through
4975     * the parent hierarchy and requesting that the root view place new focus.
4976     *
4977     * @param propagate whether to propagate the change up through the parent
4978     *            hierarchy
4979     * @param refocus when propagate is true, specifies whether to request the
4980     *            root view place new focus
4981     */
4982    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4983        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4984            mPrivateFlags &= ~PFLAG_FOCUSED;
4985
4986            if (propagate && mParent != null) {
4987                mParent.clearChildFocus(this);
4988            }
4989
4990            onFocusChanged(false, 0, null);
4991
4992            manageFocusHotspot(false, focused);
4993            refreshDrawableState();
4994
4995            if (propagate && (!refocus || !rootViewRequestFocus())) {
4996                notifyGlobalFocusCleared(this);
4997            }
4998        }
4999    }
5000
5001    void notifyGlobalFocusCleared(View oldFocus) {
5002        if (oldFocus != null && mAttachInfo != null) {
5003            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5004        }
5005    }
5006
5007    boolean rootViewRequestFocus() {
5008        final View root = getRootView();
5009        return root != null && root.requestFocus();
5010    }
5011
5012    /**
5013     * Called internally by the view system when a new view is getting focus.
5014     * This is what clears the old focus.
5015     * <p>
5016     * <b>NOTE:</b> The parent view's focused child must be updated manually
5017     * after calling this method. Otherwise, the view hierarchy may be left in
5018     * an inconstent state.
5019     */
5020    void unFocus(View focused) {
5021        if (DBG) {
5022            System.out.println(this + " unFocus()");
5023        }
5024
5025        clearFocusInternal(focused, false, false);
5026    }
5027
5028    /**
5029     * Returns true if this view has focus iteself, or is the ancestor of the
5030     * view that has focus.
5031     *
5032     * @return True if this view has or contains focus, false otherwise.
5033     */
5034    @ViewDebug.ExportedProperty(category = "focus")
5035    public boolean hasFocus() {
5036        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5037    }
5038
5039    /**
5040     * Returns true if this view is focusable or if it contains a reachable View
5041     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5042     * is a View whose parents do not block descendants focus.
5043     *
5044     * Only {@link #VISIBLE} views are considered focusable.
5045     *
5046     * @return True if the view is focusable or if the view contains a focusable
5047     *         View, false otherwise.
5048     *
5049     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5050     * @see ViewGroup#getTouchscreenBlocksFocus()
5051     */
5052    public boolean hasFocusable() {
5053        if (!isFocusableInTouchMode()) {
5054            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5055                final ViewGroup g = (ViewGroup) p;
5056                if (g.shouldBlockFocusForTouchscreen()) {
5057                    return false;
5058                }
5059            }
5060        }
5061        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5062    }
5063
5064    /**
5065     * Called by the view system when the focus state of this view changes.
5066     * When the focus change event is caused by directional navigation, direction
5067     * and previouslyFocusedRect provide insight into where the focus is coming from.
5068     * When overriding, be sure to call up through to the super class so that
5069     * the standard focus handling will occur.
5070     *
5071     * @param gainFocus True if the View has focus; false otherwise.
5072     * @param direction The direction focus has moved when requestFocus()
5073     *                  is called to give this view focus. Values are
5074     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5075     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5076     *                  It may not always apply, in which case use the default.
5077     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5078     *        system, of the previously focused view.  If applicable, this will be
5079     *        passed in as finer grained information about where the focus is coming
5080     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5081     */
5082    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5083            @Nullable Rect previouslyFocusedRect) {
5084        if (gainFocus) {
5085            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5086        } else {
5087            notifyViewAccessibilityStateChangedIfNeeded(
5088                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5089        }
5090
5091        InputMethodManager imm = InputMethodManager.peekInstance();
5092        if (!gainFocus) {
5093            if (isPressed()) {
5094                setPressed(false);
5095            }
5096            if (imm != null && mAttachInfo != null
5097                    && mAttachInfo.mHasWindowFocus) {
5098                imm.focusOut(this);
5099            }
5100            onFocusLost();
5101        } else if (imm != null && mAttachInfo != null
5102                && mAttachInfo.mHasWindowFocus) {
5103            imm.focusIn(this);
5104        }
5105
5106        invalidate(true);
5107        ListenerInfo li = mListenerInfo;
5108        if (li != null && li.mOnFocusChangeListener != null) {
5109            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5110        }
5111
5112        if (mAttachInfo != null) {
5113            mAttachInfo.mKeyDispatchState.reset(this);
5114        }
5115    }
5116
5117    /**
5118     * Sends an accessibility event of the given type. If accessibility is
5119     * not enabled this method has no effect. The default implementation calls
5120     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5121     * to populate information about the event source (this View), then calls
5122     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5123     * populate the text content of the event source including its descendants,
5124     * and last calls
5125     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5126     * on its parent to resuest sending of the event to interested parties.
5127     * <p>
5128     * If an {@link AccessibilityDelegate} has been specified via calling
5129     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5130     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5131     * responsible for handling this call.
5132     * </p>
5133     *
5134     * @param eventType The type of the event to send, as defined by several types from
5135     * {@link android.view.accessibility.AccessibilityEvent}, such as
5136     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5137     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5138     *
5139     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5140     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5141     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5142     * @see AccessibilityDelegate
5143     */
5144    public void sendAccessibilityEvent(int eventType) {
5145        if (mAccessibilityDelegate != null) {
5146            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5147        } else {
5148            sendAccessibilityEventInternal(eventType);
5149        }
5150    }
5151
5152    /**
5153     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5154     * {@link AccessibilityEvent} to make an announcement which is related to some
5155     * sort of a context change for which none of the events representing UI transitions
5156     * is a good fit. For example, announcing a new page in a book. If accessibility
5157     * is not enabled this method does nothing.
5158     *
5159     * @param text The announcement text.
5160     */
5161    public void announceForAccessibility(CharSequence text) {
5162        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5163            AccessibilityEvent event = AccessibilityEvent.obtain(
5164                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5165            onInitializeAccessibilityEvent(event);
5166            event.getText().add(text);
5167            event.setContentDescription(null);
5168            mParent.requestSendAccessibilityEvent(this, event);
5169        }
5170    }
5171
5172    /**
5173     * @see #sendAccessibilityEvent(int)
5174     *
5175     * Note: Called from the default {@link AccessibilityDelegate}.
5176     */
5177    void sendAccessibilityEventInternal(int eventType) {
5178        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5179            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5180        }
5181    }
5182
5183    /**
5184     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5185     * takes as an argument an empty {@link AccessibilityEvent} and does not
5186     * perform a check whether accessibility is enabled.
5187     * <p>
5188     * If an {@link AccessibilityDelegate} has been specified via calling
5189     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5190     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5191     * is responsible for handling this call.
5192     * </p>
5193     *
5194     * @param event The event to send.
5195     *
5196     * @see #sendAccessibilityEvent(int)
5197     */
5198    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5199        if (mAccessibilityDelegate != null) {
5200            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5201        } else {
5202            sendAccessibilityEventUncheckedInternal(event);
5203        }
5204    }
5205
5206    /**
5207     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5208     *
5209     * Note: Called from the default {@link AccessibilityDelegate}.
5210     */
5211    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5212        if (!isShown()) {
5213            return;
5214        }
5215        onInitializeAccessibilityEvent(event);
5216        // Only a subset of accessibility events populates text content.
5217        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5218            dispatchPopulateAccessibilityEvent(event);
5219        }
5220        // In the beginning we called #isShown(), so we know that getParent() is not null.
5221        getParent().requestSendAccessibilityEvent(this, event);
5222    }
5223
5224    /**
5225     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5226     * to its children for adding their text content to the event. Note that the
5227     * event text is populated in a separate dispatch path since we add to the
5228     * event not only the text of the source but also the text of all its descendants.
5229     * A typical implementation will call
5230     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5231     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5232     * on each child. Override this method if custom population of the event text
5233     * content is required.
5234     * <p>
5235     * If an {@link AccessibilityDelegate} has been specified via calling
5236     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5237     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5238     * is responsible for handling this call.
5239     * </p>
5240     * <p>
5241     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5242     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5243     * </p>
5244     *
5245     * @param event The event.
5246     *
5247     * @return True if the event population was completed.
5248     */
5249    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5250        if (mAccessibilityDelegate != null) {
5251            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5252        } else {
5253            return dispatchPopulateAccessibilityEventInternal(event);
5254        }
5255    }
5256
5257    /**
5258     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5259     *
5260     * Note: Called from the default {@link AccessibilityDelegate}.
5261     */
5262    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5263        onPopulateAccessibilityEvent(event);
5264        return false;
5265    }
5266
5267    /**
5268     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5269     * giving a chance to this View to populate the accessibility event with its
5270     * text content. While this method is free to modify event
5271     * attributes other than text content, doing so should normally be performed in
5272     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5273     * <p>
5274     * Example: Adding formatted date string to an accessibility event in addition
5275     *          to the text added by the super implementation:
5276     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5277     *     super.onPopulateAccessibilityEvent(event);
5278     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5279     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5280     *         mCurrentDate.getTimeInMillis(), flags);
5281     *     event.getText().add(selectedDateUtterance);
5282     * }</pre>
5283     * <p>
5284     * If an {@link AccessibilityDelegate} has been specified via calling
5285     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5286     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5287     * is responsible for handling this call.
5288     * </p>
5289     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5290     * information to the event, in case the default implementation has basic information to add.
5291     * </p>
5292     *
5293     * @param event The accessibility event which to populate.
5294     *
5295     * @see #sendAccessibilityEvent(int)
5296     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5297     */
5298    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5299        if (mAccessibilityDelegate != null) {
5300            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5301        } else {
5302            onPopulateAccessibilityEventInternal(event);
5303        }
5304    }
5305
5306    /**
5307     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5308     *
5309     * Note: Called from the default {@link AccessibilityDelegate}.
5310     */
5311    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5312    }
5313
5314    /**
5315     * Initializes an {@link AccessibilityEvent} with information about
5316     * this View which is the event source. In other words, the source of
5317     * an accessibility event is the view whose state change triggered firing
5318     * the event.
5319     * <p>
5320     * Example: Setting the password property of an event in addition
5321     *          to properties set by the super implementation:
5322     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5323     *     super.onInitializeAccessibilityEvent(event);
5324     *     event.setPassword(true);
5325     * }</pre>
5326     * <p>
5327     * If an {@link AccessibilityDelegate} has been specified via calling
5328     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5329     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5330     * is responsible for handling this call.
5331     * </p>
5332     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5333     * information to the event, in case the default implementation has basic information to add.
5334     * </p>
5335     * @param event The event to initialize.
5336     *
5337     * @see #sendAccessibilityEvent(int)
5338     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5339     */
5340    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5341        if (mAccessibilityDelegate != null) {
5342            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5343        } else {
5344            onInitializeAccessibilityEventInternal(event);
5345        }
5346    }
5347
5348    /**
5349     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5350     *
5351     * Note: Called from the default {@link AccessibilityDelegate}.
5352     */
5353    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5354        event.setSource(this);
5355        event.setClassName(View.class.getName());
5356        event.setPackageName(getContext().getPackageName());
5357        event.setEnabled(isEnabled());
5358        event.setContentDescription(mContentDescription);
5359
5360        switch (event.getEventType()) {
5361            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5362                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5363                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5364                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5365                event.setItemCount(focusablesTempList.size());
5366                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5367                if (mAttachInfo != null) {
5368                    focusablesTempList.clear();
5369                }
5370            } break;
5371            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5372                CharSequence text = getIterableTextForAccessibility();
5373                if (text != null && text.length() > 0) {
5374                    event.setFromIndex(getAccessibilitySelectionStart());
5375                    event.setToIndex(getAccessibilitySelectionEnd());
5376                    event.setItemCount(text.length());
5377                }
5378            } break;
5379        }
5380    }
5381
5382    /**
5383     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5384     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5385     * This method is responsible for obtaining an accessibility node info from a
5386     * pool of reusable instances and calling
5387     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5388     * initialize the former.
5389     * <p>
5390     * Note: The client is responsible for recycling the obtained instance by calling
5391     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5392     * </p>
5393     *
5394     * @return A populated {@link AccessibilityNodeInfo}.
5395     *
5396     * @see AccessibilityNodeInfo
5397     */
5398    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5399        if (mAccessibilityDelegate != null) {
5400            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5401        } else {
5402            return createAccessibilityNodeInfoInternal();
5403        }
5404    }
5405
5406    /**
5407     * @see #createAccessibilityNodeInfo()
5408     */
5409    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5410        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5411        if (provider != null) {
5412            return provider.createAccessibilityNodeInfo(View.NO_ID);
5413        } else {
5414            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5415            onInitializeAccessibilityNodeInfo(info);
5416            return info;
5417        }
5418    }
5419
5420    /**
5421     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5422     * The base implementation sets:
5423     * <ul>
5424     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5425     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5426     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5427     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5428     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5429     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5430     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5431     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5432     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5433     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5434     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5435     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5436     * </ul>
5437     * <p>
5438     * Subclasses should override this method, call the super implementation,
5439     * and set additional attributes.
5440     * </p>
5441     * <p>
5442     * If an {@link AccessibilityDelegate} has been specified via calling
5443     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5444     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5445     * is responsible for handling this call.
5446     * </p>
5447     *
5448     * @param info The instance to initialize.
5449     */
5450    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5451        if (mAccessibilityDelegate != null) {
5452            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5453        } else {
5454            onInitializeAccessibilityNodeInfoInternal(info);
5455        }
5456    }
5457
5458    /**
5459     * Gets the location of this view in screen coordintates.
5460     *
5461     * @param outRect The output location
5462     * @hide
5463     */
5464    public void getBoundsOnScreen(Rect outRect) {
5465        if (mAttachInfo == null) {
5466            return;
5467        }
5468
5469        RectF position = mAttachInfo.mTmpTransformRect;
5470        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5471
5472        if (!hasIdentityMatrix()) {
5473            getMatrix().mapRect(position);
5474        }
5475
5476        position.offset(mLeft, mTop);
5477
5478        ViewParent parent = mParent;
5479        while (parent instanceof View) {
5480            View parentView = (View) parent;
5481
5482            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5483
5484            if (!parentView.hasIdentityMatrix()) {
5485                parentView.getMatrix().mapRect(position);
5486            }
5487
5488            position.offset(parentView.mLeft, parentView.mTop);
5489
5490            parent = parentView.mParent;
5491        }
5492
5493        if (parent instanceof ViewRootImpl) {
5494            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5495            position.offset(0, -viewRootImpl.mCurScrollY);
5496        }
5497
5498        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5499
5500        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5501                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5502    }
5503
5504    /**
5505     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5506     *
5507     * Note: Called from the default {@link AccessibilityDelegate}.
5508     */
5509    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5510        Rect bounds = mAttachInfo.mTmpInvalRect;
5511
5512        getDrawingRect(bounds);
5513        info.setBoundsInParent(bounds);
5514
5515        getBoundsOnScreen(bounds);
5516        info.setBoundsInScreen(bounds);
5517
5518        ViewParent parent = getParentForAccessibility();
5519        if (parent instanceof View) {
5520            info.setParent((View) parent);
5521        }
5522
5523        if (mID != View.NO_ID) {
5524            View rootView = getRootView();
5525            if (rootView == null) {
5526                rootView = this;
5527            }
5528            View label = rootView.findLabelForView(this, mID);
5529            if (label != null) {
5530                info.setLabeledBy(label);
5531            }
5532
5533            if ((mAttachInfo.mAccessibilityFetchFlags
5534                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5535                    && Resources.resourceHasPackage(mID)) {
5536                try {
5537                    String viewId = getResources().getResourceName(mID);
5538                    info.setViewIdResourceName(viewId);
5539                } catch (Resources.NotFoundException nfe) {
5540                    /* ignore */
5541                }
5542            }
5543        }
5544
5545        if (mLabelForId != View.NO_ID) {
5546            View rootView = getRootView();
5547            if (rootView == null) {
5548                rootView = this;
5549            }
5550            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5551            if (labeled != null) {
5552                info.setLabelFor(labeled);
5553            }
5554        }
5555
5556        info.setVisibleToUser(isVisibleToUser());
5557
5558        info.setPackageName(mContext.getPackageName());
5559        info.setClassName(View.class.getName());
5560        info.setContentDescription(getContentDescription());
5561
5562        info.setEnabled(isEnabled());
5563        info.setClickable(isClickable());
5564        info.setFocusable(isFocusable());
5565        info.setFocused(isFocused());
5566        info.setAccessibilityFocused(isAccessibilityFocused());
5567        info.setSelected(isSelected());
5568        info.setLongClickable(isLongClickable());
5569        info.setLiveRegion(getAccessibilityLiveRegion());
5570
5571        // TODO: These make sense only if we are in an AdapterView but all
5572        // views can be selected. Maybe from accessibility perspective
5573        // we should report as selectable view in an AdapterView.
5574        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5575        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5576
5577        if (isFocusable()) {
5578            if (isFocused()) {
5579                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5580            } else {
5581                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5582            }
5583        }
5584
5585        if (!isAccessibilityFocused()) {
5586            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5587        } else {
5588            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5589        }
5590
5591        if (isClickable() && isEnabled()) {
5592            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5593        }
5594
5595        if (isLongClickable() && isEnabled()) {
5596            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5597        }
5598
5599        CharSequence text = getIterableTextForAccessibility();
5600        if (text != null && text.length() > 0) {
5601            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5602
5603            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5604            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5605            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5606            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5607                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5608                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5609        }
5610    }
5611
5612    private View findLabelForView(View view, int labeledId) {
5613        if (mMatchLabelForPredicate == null) {
5614            mMatchLabelForPredicate = new MatchLabelForPredicate();
5615        }
5616        mMatchLabelForPredicate.mLabeledId = labeledId;
5617        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5618    }
5619
5620    /**
5621     * Computes whether this view is visible to the user. Such a view is
5622     * attached, visible, all its predecessors are visible, it is not clipped
5623     * entirely by its predecessors, and has an alpha greater than zero.
5624     *
5625     * @return Whether the view is visible on the screen.
5626     *
5627     * @hide
5628     */
5629    protected boolean isVisibleToUser() {
5630        return isVisibleToUser(null);
5631    }
5632
5633    /**
5634     * Computes whether the given portion of this view is visible to the user.
5635     * Such a view is attached, visible, all its predecessors are visible,
5636     * has an alpha greater than zero, and the specified portion is not
5637     * clipped entirely by its predecessors.
5638     *
5639     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5640     *                    <code>null</code>, and the entire view will be tested in this case.
5641     *                    When <code>true</code> is returned by the function, the actual visible
5642     *                    region will be stored in this parameter; that is, if boundInView is fully
5643     *                    contained within the view, no modification will be made, otherwise regions
5644     *                    outside of the visible area of the view will be clipped.
5645     *
5646     * @return Whether the specified portion of the view is visible on the screen.
5647     *
5648     * @hide
5649     */
5650    protected boolean isVisibleToUser(Rect boundInView) {
5651        if (mAttachInfo != null) {
5652            // Attached to invisible window means this view is not visible.
5653            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5654                return false;
5655            }
5656            // An invisible predecessor or one with alpha zero means
5657            // that this view is not visible to the user.
5658            Object current = this;
5659            while (current instanceof View) {
5660                View view = (View) current;
5661                // We have attach info so this view is attached and there is no
5662                // need to check whether we reach to ViewRootImpl on the way up.
5663                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5664                        view.getVisibility() != VISIBLE) {
5665                    return false;
5666                }
5667                current = view.mParent;
5668            }
5669            // Check if the view is entirely covered by its predecessors.
5670            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5671            Point offset = mAttachInfo.mPoint;
5672            if (!getGlobalVisibleRect(visibleRect, offset)) {
5673                return false;
5674            }
5675            // Check if the visible portion intersects the rectangle of interest.
5676            if (boundInView != null) {
5677                visibleRect.offset(-offset.x, -offset.y);
5678                return boundInView.intersect(visibleRect);
5679            }
5680            return true;
5681        }
5682        return false;
5683    }
5684
5685    /**
5686     * Returns the delegate for implementing accessibility support via
5687     * composition. For more details see {@link AccessibilityDelegate}.
5688     *
5689     * @return The delegate, or null if none set.
5690     *
5691     * @hide
5692     */
5693    public AccessibilityDelegate getAccessibilityDelegate() {
5694        return mAccessibilityDelegate;
5695    }
5696
5697    /**
5698     * Sets a delegate for implementing accessibility support via composition as
5699     * opposed to inheritance. The delegate's primary use is for implementing
5700     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5701     *
5702     * @param delegate The delegate instance.
5703     *
5704     * @see AccessibilityDelegate
5705     */
5706    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5707        mAccessibilityDelegate = delegate;
5708    }
5709
5710    /**
5711     * Gets the provider for managing a virtual view hierarchy rooted at this View
5712     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5713     * that explore the window content.
5714     * <p>
5715     * If this method returns an instance, this instance is responsible for managing
5716     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5717     * View including the one representing the View itself. Similarly the returned
5718     * instance is responsible for performing accessibility actions on any virtual
5719     * view or the root view itself.
5720     * </p>
5721     * <p>
5722     * If an {@link AccessibilityDelegate} has been specified via calling
5723     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5724     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5725     * is responsible for handling this call.
5726     * </p>
5727     *
5728     * @return The provider.
5729     *
5730     * @see AccessibilityNodeProvider
5731     */
5732    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5733        if (mAccessibilityDelegate != null) {
5734            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5735        } else {
5736            return null;
5737        }
5738    }
5739
5740    /**
5741     * Gets the unique identifier of this view on the screen for accessibility purposes.
5742     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5743     *
5744     * @return The view accessibility id.
5745     *
5746     * @hide
5747     */
5748    public int getAccessibilityViewId() {
5749        if (mAccessibilityViewId == NO_ID) {
5750            mAccessibilityViewId = sNextAccessibilityViewId++;
5751        }
5752        return mAccessibilityViewId;
5753    }
5754
5755    /**
5756     * Gets the unique identifier of the window in which this View reseides.
5757     *
5758     * @return The window accessibility id.
5759     *
5760     * @hide
5761     */
5762    public int getAccessibilityWindowId() {
5763        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5764                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5765    }
5766
5767    /**
5768     * Gets the {@link View} description. It briefly describes the view and is
5769     * primarily used for accessibility support. Set this property to enable
5770     * better accessibility support for your application. This is especially
5771     * true for views that do not have textual representation (For example,
5772     * ImageButton).
5773     *
5774     * @return The content description.
5775     *
5776     * @attr ref android.R.styleable#View_contentDescription
5777     */
5778    @ViewDebug.ExportedProperty(category = "accessibility")
5779    public CharSequence getContentDescription() {
5780        return mContentDescription;
5781    }
5782
5783    /**
5784     * Sets the {@link View} description. It briefly describes the view and is
5785     * primarily used for accessibility support. Set this property to enable
5786     * better accessibility support for your application. This is especially
5787     * true for views that do not have textual representation (For example,
5788     * ImageButton).
5789     *
5790     * @param contentDescription The content description.
5791     *
5792     * @attr ref android.R.styleable#View_contentDescription
5793     */
5794    @RemotableViewMethod
5795    public void setContentDescription(CharSequence contentDescription) {
5796        if (mContentDescription == null) {
5797            if (contentDescription == null) {
5798                return;
5799            }
5800        } else if (mContentDescription.equals(contentDescription)) {
5801            return;
5802        }
5803        mContentDescription = contentDescription;
5804        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5805        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5806            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5807            notifySubtreeAccessibilityStateChangedIfNeeded();
5808        } else {
5809            notifyViewAccessibilityStateChangedIfNeeded(
5810                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5811        }
5812    }
5813
5814    /**
5815     * Gets the id of a view for which this view serves as a label for
5816     * accessibility purposes.
5817     *
5818     * @return The labeled view id.
5819     */
5820    @ViewDebug.ExportedProperty(category = "accessibility")
5821    public int getLabelFor() {
5822        return mLabelForId;
5823    }
5824
5825    /**
5826     * Sets the id of a view for which this view serves as a label for
5827     * accessibility purposes.
5828     *
5829     * @param id The labeled view id.
5830     */
5831    @RemotableViewMethod
5832    public void setLabelFor(int id) {
5833        mLabelForId = id;
5834        if (mLabelForId != View.NO_ID
5835                && mID == View.NO_ID) {
5836            mID = generateViewId();
5837        }
5838    }
5839
5840    /**
5841     * Invoked whenever this view loses focus, either by losing window focus or by losing
5842     * focus within its window. This method can be used to clear any state tied to the
5843     * focus. For instance, if a button is held pressed with the trackball and the window
5844     * loses focus, this method can be used to cancel the press.
5845     *
5846     * Subclasses of View overriding this method should always call super.onFocusLost().
5847     *
5848     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5849     * @see #onWindowFocusChanged(boolean)
5850     *
5851     * @hide pending API council approval
5852     */
5853    protected void onFocusLost() {
5854        resetPressedState();
5855    }
5856
5857    private void resetPressedState() {
5858        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5859            return;
5860        }
5861
5862        if (isPressed()) {
5863            setPressed(false);
5864
5865            if (!mHasPerformedLongPress) {
5866                removeLongPressCallback();
5867            }
5868        }
5869    }
5870
5871    /**
5872     * Returns true if this view has focus
5873     *
5874     * @return True if this view has focus, false otherwise.
5875     */
5876    @ViewDebug.ExportedProperty(category = "focus")
5877    public boolean isFocused() {
5878        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5879    }
5880
5881    /**
5882     * Find the view in the hierarchy rooted at this view that currently has
5883     * focus.
5884     *
5885     * @return The view that currently has focus, or null if no focused view can
5886     *         be found.
5887     */
5888    public View findFocus() {
5889        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5890    }
5891
5892    /**
5893     * Indicates whether this view is one of the set of scrollable containers in
5894     * its window.
5895     *
5896     * @return whether this view is one of the set of scrollable containers in
5897     * its window
5898     *
5899     * @attr ref android.R.styleable#View_isScrollContainer
5900     */
5901    public boolean isScrollContainer() {
5902        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5903    }
5904
5905    /**
5906     * Change whether this view is one of the set of scrollable containers in
5907     * its window.  This will be used to determine whether the window can
5908     * resize or must pan when a soft input area is open -- scrollable
5909     * containers allow the window to use resize mode since the container
5910     * will appropriately shrink.
5911     *
5912     * @attr ref android.R.styleable#View_isScrollContainer
5913     */
5914    public void setScrollContainer(boolean isScrollContainer) {
5915        if (isScrollContainer) {
5916            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5917                mAttachInfo.mScrollContainers.add(this);
5918                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5919            }
5920            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5921        } else {
5922            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5923                mAttachInfo.mScrollContainers.remove(this);
5924            }
5925            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5926        }
5927    }
5928
5929    /**
5930     * Returns the quality of the drawing cache.
5931     *
5932     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5933     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5934     *
5935     * @see #setDrawingCacheQuality(int)
5936     * @see #setDrawingCacheEnabled(boolean)
5937     * @see #isDrawingCacheEnabled()
5938     *
5939     * @attr ref android.R.styleable#View_drawingCacheQuality
5940     */
5941    @DrawingCacheQuality
5942    public int getDrawingCacheQuality() {
5943        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5944    }
5945
5946    /**
5947     * Set the drawing cache quality of this view. This value is used only when the
5948     * drawing cache is enabled
5949     *
5950     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5951     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5952     *
5953     * @see #getDrawingCacheQuality()
5954     * @see #setDrawingCacheEnabled(boolean)
5955     * @see #isDrawingCacheEnabled()
5956     *
5957     * @attr ref android.R.styleable#View_drawingCacheQuality
5958     */
5959    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5960        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5961    }
5962
5963    /**
5964     * Returns whether the screen should remain on, corresponding to the current
5965     * value of {@link #KEEP_SCREEN_ON}.
5966     *
5967     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5968     *
5969     * @see #setKeepScreenOn(boolean)
5970     *
5971     * @attr ref android.R.styleable#View_keepScreenOn
5972     */
5973    public boolean getKeepScreenOn() {
5974        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5975    }
5976
5977    /**
5978     * Controls whether the screen should remain on, modifying the
5979     * value of {@link #KEEP_SCREEN_ON}.
5980     *
5981     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5982     *
5983     * @see #getKeepScreenOn()
5984     *
5985     * @attr ref android.R.styleable#View_keepScreenOn
5986     */
5987    public void setKeepScreenOn(boolean keepScreenOn) {
5988        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5989    }
5990
5991    /**
5992     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5993     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5994     *
5995     * @attr ref android.R.styleable#View_nextFocusLeft
5996     */
5997    public int getNextFocusLeftId() {
5998        return mNextFocusLeftId;
5999    }
6000
6001    /**
6002     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6003     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6004     * decide automatically.
6005     *
6006     * @attr ref android.R.styleable#View_nextFocusLeft
6007     */
6008    public void setNextFocusLeftId(int nextFocusLeftId) {
6009        mNextFocusLeftId = nextFocusLeftId;
6010    }
6011
6012    /**
6013     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6014     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6015     *
6016     * @attr ref android.R.styleable#View_nextFocusRight
6017     */
6018    public int getNextFocusRightId() {
6019        return mNextFocusRightId;
6020    }
6021
6022    /**
6023     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6024     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6025     * decide automatically.
6026     *
6027     * @attr ref android.R.styleable#View_nextFocusRight
6028     */
6029    public void setNextFocusRightId(int nextFocusRightId) {
6030        mNextFocusRightId = nextFocusRightId;
6031    }
6032
6033    /**
6034     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6035     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6036     *
6037     * @attr ref android.R.styleable#View_nextFocusUp
6038     */
6039    public int getNextFocusUpId() {
6040        return mNextFocusUpId;
6041    }
6042
6043    /**
6044     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6045     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6046     * decide automatically.
6047     *
6048     * @attr ref android.R.styleable#View_nextFocusUp
6049     */
6050    public void setNextFocusUpId(int nextFocusUpId) {
6051        mNextFocusUpId = nextFocusUpId;
6052    }
6053
6054    /**
6055     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6056     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6057     *
6058     * @attr ref android.R.styleable#View_nextFocusDown
6059     */
6060    public int getNextFocusDownId() {
6061        return mNextFocusDownId;
6062    }
6063
6064    /**
6065     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6066     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6067     * decide automatically.
6068     *
6069     * @attr ref android.R.styleable#View_nextFocusDown
6070     */
6071    public void setNextFocusDownId(int nextFocusDownId) {
6072        mNextFocusDownId = nextFocusDownId;
6073    }
6074
6075    /**
6076     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6077     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6078     *
6079     * @attr ref android.R.styleable#View_nextFocusForward
6080     */
6081    public int getNextFocusForwardId() {
6082        return mNextFocusForwardId;
6083    }
6084
6085    /**
6086     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6087     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6088     * decide automatically.
6089     *
6090     * @attr ref android.R.styleable#View_nextFocusForward
6091     */
6092    public void setNextFocusForwardId(int nextFocusForwardId) {
6093        mNextFocusForwardId = nextFocusForwardId;
6094    }
6095
6096    /**
6097     * Returns the visibility of this view and all of its ancestors
6098     *
6099     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6100     */
6101    public boolean isShown() {
6102        View current = this;
6103        //noinspection ConstantConditions
6104        do {
6105            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6106                return false;
6107            }
6108            ViewParent parent = current.mParent;
6109            if (parent == null) {
6110                return false; // We are not attached to the view root
6111            }
6112            if (!(parent instanceof View)) {
6113                return true;
6114            }
6115            current = (View) parent;
6116        } while (current != null);
6117
6118        return false;
6119    }
6120
6121    /**
6122     * Called by the view hierarchy when the content insets for a window have
6123     * changed, to allow it to adjust its content to fit within those windows.
6124     * The content insets tell you the space that the status bar, input method,
6125     * and other system windows infringe on the application's window.
6126     *
6127     * <p>You do not normally need to deal with this function, since the default
6128     * window decoration given to applications takes care of applying it to the
6129     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6130     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6131     * and your content can be placed under those system elements.  You can then
6132     * use this method within your view hierarchy if you have parts of your UI
6133     * which you would like to ensure are not being covered.
6134     *
6135     * <p>The default implementation of this method simply applies the content
6136     * insets to the view's padding, consuming that content (modifying the
6137     * insets to be 0), and returning true.  This behavior is off by default, but can
6138     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6139     *
6140     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6141     * insets object is propagated down the hierarchy, so any changes made to it will
6142     * be seen by all following views (including potentially ones above in
6143     * the hierarchy since this is a depth-first traversal).  The first view
6144     * that returns true will abort the entire traversal.
6145     *
6146     * <p>The default implementation works well for a situation where it is
6147     * used with a container that covers the entire window, allowing it to
6148     * apply the appropriate insets to its content on all edges.  If you need
6149     * a more complicated layout (such as two different views fitting system
6150     * windows, one on the top of the window, and one on the bottom),
6151     * you can override the method and handle the insets however you would like.
6152     * Note that the insets provided by the framework are always relative to the
6153     * far edges of the window, not accounting for the location of the called view
6154     * within that window.  (In fact when this method is called you do not yet know
6155     * where the layout will place the view, as it is done before layout happens.)
6156     *
6157     * <p>Note: unlike many View methods, there is no dispatch phase to this
6158     * call.  If you are overriding it in a ViewGroup and want to allow the
6159     * call to continue to your children, you must be sure to call the super
6160     * implementation.
6161     *
6162     * <p>Here is a sample layout that makes use of fitting system windows
6163     * to have controls for a video view placed inside of the window decorations
6164     * that it hides and shows.  This can be used with code like the second
6165     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6166     *
6167     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6168     *
6169     * @param insets Current content insets of the window.  Prior to
6170     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6171     * the insets or else you and Android will be unhappy.
6172     *
6173     * @return {@code true} if this view applied the insets and it should not
6174     * continue propagating further down the hierarchy, {@code false} otherwise.
6175     * @see #getFitsSystemWindows()
6176     * @see #setFitsSystemWindows(boolean)
6177     * @see #setSystemUiVisibility(int)
6178     *
6179     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6180     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6181     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6182     * to implement handling their own insets.
6183     */
6184    protected boolean fitSystemWindows(Rect insets) {
6185        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6186            if (insets == null) {
6187                // Null insets by definition have already been consumed.
6188                // This call cannot apply insets since there are none to apply,
6189                // so return false.
6190                return false;
6191            }
6192            // If we're not in the process of dispatching the newer apply insets call,
6193            // that means we're not in the compatibility path. Dispatch into the newer
6194            // apply insets path and take things from there.
6195            try {
6196                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6197                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6198            } finally {
6199                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6200            }
6201        } else {
6202            // We're being called from the newer apply insets path.
6203            // Perform the standard fallback behavior.
6204            return fitSystemWindowsInt(insets);
6205        }
6206    }
6207
6208    private boolean fitSystemWindowsInt(Rect insets) {
6209        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6210            mUserPaddingStart = UNDEFINED_PADDING;
6211            mUserPaddingEnd = UNDEFINED_PADDING;
6212            Rect localInsets = sThreadLocal.get();
6213            if (localInsets == null) {
6214                localInsets = new Rect();
6215                sThreadLocal.set(localInsets);
6216            }
6217            boolean res = computeFitSystemWindows(insets, localInsets);
6218            mUserPaddingLeftInitial = localInsets.left;
6219            mUserPaddingRightInitial = localInsets.right;
6220            internalSetPadding(localInsets.left, localInsets.top,
6221                    localInsets.right, localInsets.bottom);
6222            return res;
6223        }
6224        return false;
6225    }
6226
6227    /**
6228     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6229     *
6230     * <p>This method should be overridden by views that wish to apply a policy different from or
6231     * in addition to the default behavior. Clients that wish to force a view subtree
6232     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6233     *
6234     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6235     * it will be called during dispatch instead of this method. The listener may optionally
6236     * call this method from its own implementation if it wishes to apply the view's default
6237     * insets policy in addition to its own.</p>
6238     *
6239     * <p>Implementations of this method should either return the insets parameter unchanged
6240     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6241     * that this view applied itself. This allows new inset types added in future platform
6242     * versions to pass through existing implementations unchanged without being erroneously
6243     * consumed.</p>
6244     *
6245     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6246     * property is set then the view will consume the system window insets and apply them
6247     * as padding for the view.</p>
6248     *
6249     * @param insets Insets to apply
6250     * @return The supplied insets with any applied insets consumed
6251     */
6252    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6253        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6254            // We weren't called from within a direct call to fitSystemWindows,
6255            // call into it as a fallback in case we're in a class that overrides it
6256            // and has logic to perform.
6257            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6258                return insets.consumeSystemWindowInsets();
6259            }
6260        } else {
6261            // We were called from within a direct call to fitSystemWindows.
6262            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6263                return insets.consumeSystemWindowInsets();
6264            }
6265        }
6266        return insets;
6267    }
6268
6269    /**
6270     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6271     * window insets to this view. The listener's
6272     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6273     * method will be called instead of the view's
6274     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6275     *
6276     * @param listener Listener to set
6277     *
6278     * @see #onApplyWindowInsets(WindowInsets)
6279     */
6280    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6281        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6282    }
6283
6284    /**
6285     * Request to apply the given window insets to this view or another view in its subtree.
6286     *
6287     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6288     * obscured by window decorations or overlays. This can include the status and navigation bars,
6289     * action bars, input methods and more. New inset categories may be added in the future.
6290     * The method returns the insets provided minus any that were applied by this view or its
6291     * children.</p>
6292     *
6293     * <p>Clients wishing to provide custom behavior should override the
6294     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6295     * {@link OnApplyWindowInsetsListener} via the
6296     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6297     * method.</p>
6298     *
6299     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6300     * </p>
6301     *
6302     * @param insets Insets to apply
6303     * @return The provided insets minus the insets that were consumed
6304     */
6305    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6306        try {
6307            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6308            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6309                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6310            } else {
6311                return onApplyWindowInsets(insets);
6312            }
6313        } finally {
6314            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6315        }
6316    }
6317
6318    /**
6319     * @hide Compute the insets that should be consumed by this view and the ones
6320     * that should propagate to those under it.
6321     */
6322    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6323        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6324                || mAttachInfo == null
6325                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6326                        && !mAttachInfo.mOverscanRequested)) {
6327            outLocalInsets.set(inoutInsets);
6328            inoutInsets.set(0, 0, 0, 0);
6329            return true;
6330        } else {
6331            // The application wants to take care of fitting system window for
6332            // the content...  however we still need to take care of any overscan here.
6333            final Rect overscan = mAttachInfo.mOverscanInsets;
6334            outLocalInsets.set(overscan);
6335            inoutInsets.left -= overscan.left;
6336            inoutInsets.top -= overscan.top;
6337            inoutInsets.right -= overscan.right;
6338            inoutInsets.bottom -= overscan.bottom;
6339            return false;
6340        }
6341    }
6342
6343    /**
6344     * Sets whether or not this view should account for system screen decorations
6345     * such as the status bar and inset its content; that is, controlling whether
6346     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6347     * executed.  See that method for more details.
6348     *
6349     * <p>Note that if you are providing your own implementation of
6350     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6351     * flag to true -- your implementation will be overriding the default
6352     * implementation that checks this flag.
6353     *
6354     * @param fitSystemWindows If true, then the default implementation of
6355     * {@link #fitSystemWindows(Rect)} will be executed.
6356     *
6357     * @attr ref android.R.styleable#View_fitsSystemWindows
6358     * @see #getFitsSystemWindows()
6359     * @see #fitSystemWindows(Rect)
6360     * @see #setSystemUiVisibility(int)
6361     */
6362    public void setFitsSystemWindows(boolean fitSystemWindows) {
6363        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6364    }
6365
6366    /**
6367     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6368     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6369     * will be executed.
6370     *
6371     * @return {@code true} if the default implementation of
6372     * {@link #fitSystemWindows(Rect)} will be executed.
6373     *
6374     * @attr ref android.R.styleable#View_fitsSystemWindows
6375     * @see #setFitsSystemWindows(boolean)
6376     * @see #fitSystemWindows(Rect)
6377     * @see #setSystemUiVisibility(int)
6378     */
6379    public boolean getFitsSystemWindows() {
6380        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6381    }
6382
6383    /** @hide */
6384    public boolean fitsSystemWindows() {
6385        return getFitsSystemWindows();
6386    }
6387
6388    /**
6389     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6390     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6391     */
6392    public void requestFitSystemWindows() {
6393        if (mParent != null) {
6394            mParent.requestFitSystemWindows();
6395        }
6396    }
6397
6398    /**
6399     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6400     */
6401    public void requestApplyInsets() {
6402        requestFitSystemWindows();
6403    }
6404
6405    /**
6406     * For use by PhoneWindow to make its own system window fitting optional.
6407     * @hide
6408     */
6409    public void makeOptionalFitsSystemWindows() {
6410        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6411    }
6412
6413    /**
6414     * Returns the visibility status for this view.
6415     *
6416     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6417     * @attr ref android.R.styleable#View_visibility
6418     */
6419    @ViewDebug.ExportedProperty(mapping = {
6420        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6421        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6422        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6423    })
6424    @Visibility
6425    public int getVisibility() {
6426        return mViewFlags & VISIBILITY_MASK;
6427    }
6428
6429    /**
6430     * Set the enabled state of this view.
6431     *
6432     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6433     * @attr ref android.R.styleable#View_visibility
6434     */
6435    @RemotableViewMethod
6436    public void setVisibility(@Visibility int visibility) {
6437        setFlags(visibility, VISIBILITY_MASK);
6438        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6439    }
6440
6441    /**
6442     * Returns the enabled status for this view. The interpretation of the
6443     * enabled state varies by subclass.
6444     *
6445     * @return True if this view is enabled, false otherwise.
6446     */
6447    @ViewDebug.ExportedProperty
6448    public boolean isEnabled() {
6449        return (mViewFlags & ENABLED_MASK) == ENABLED;
6450    }
6451
6452    /**
6453     * Set the enabled state of this view. The interpretation of the enabled
6454     * state varies by subclass.
6455     *
6456     * @param enabled True if this view is enabled, false otherwise.
6457     */
6458    @RemotableViewMethod
6459    public void setEnabled(boolean enabled) {
6460        if (enabled == isEnabled()) return;
6461
6462        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6463
6464        /*
6465         * The View most likely has to change its appearance, so refresh
6466         * the drawable state.
6467         */
6468        refreshDrawableState();
6469
6470        // Invalidate too, since the default behavior for views is to be
6471        // be drawn at 50% alpha rather than to change the drawable.
6472        invalidate(true);
6473
6474        if (!enabled) {
6475            cancelPendingInputEvents();
6476        }
6477    }
6478
6479    /**
6480     * Set whether this view can receive the focus.
6481     *
6482     * Setting this to false will also ensure that this view is not focusable
6483     * in touch mode.
6484     *
6485     * @param focusable If true, this view can receive the focus.
6486     *
6487     * @see #setFocusableInTouchMode(boolean)
6488     * @attr ref android.R.styleable#View_focusable
6489     */
6490    public void setFocusable(boolean focusable) {
6491        if (!focusable) {
6492            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6493        }
6494        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6495    }
6496
6497    /**
6498     * Set whether this view can receive focus while in touch mode.
6499     *
6500     * Setting this to true will also ensure that this view is focusable.
6501     *
6502     * @param focusableInTouchMode If true, this view can receive the focus while
6503     *   in touch mode.
6504     *
6505     * @see #setFocusable(boolean)
6506     * @attr ref android.R.styleable#View_focusableInTouchMode
6507     */
6508    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6509        // Focusable in touch mode should always be set before the focusable flag
6510        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6511        // which, in touch mode, will not successfully request focus on this view
6512        // because the focusable in touch mode flag is not set
6513        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6514        if (focusableInTouchMode) {
6515            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6516        }
6517    }
6518
6519    /**
6520     * Set whether this view should have sound effects enabled for events such as
6521     * clicking and touching.
6522     *
6523     * <p>You may wish to disable sound effects for a view if you already play sounds,
6524     * for instance, a dial key that plays dtmf tones.
6525     *
6526     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6527     * @see #isSoundEffectsEnabled()
6528     * @see #playSoundEffect(int)
6529     * @attr ref android.R.styleable#View_soundEffectsEnabled
6530     */
6531    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6532        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6533    }
6534
6535    /**
6536     * @return whether this view should have sound effects enabled for events such as
6537     *     clicking and touching.
6538     *
6539     * @see #setSoundEffectsEnabled(boolean)
6540     * @see #playSoundEffect(int)
6541     * @attr ref android.R.styleable#View_soundEffectsEnabled
6542     */
6543    @ViewDebug.ExportedProperty
6544    public boolean isSoundEffectsEnabled() {
6545        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6546    }
6547
6548    /**
6549     * Set whether this view should have haptic feedback for events such as
6550     * long presses.
6551     *
6552     * <p>You may wish to disable haptic feedback if your view already controls
6553     * its own haptic feedback.
6554     *
6555     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6556     * @see #isHapticFeedbackEnabled()
6557     * @see #performHapticFeedback(int)
6558     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6559     */
6560    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6561        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6562    }
6563
6564    /**
6565     * @return whether this view should have haptic feedback enabled for events
6566     * long presses.
6567     *
6568     * @see #setHapticFeedbackEnabled(boolean)
6569     * @see #performHapticFeedback(int)
6570     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6571     */
6572    @ViewDebug.ExportedProperty
6573    public boolean isHapticFeedbackEnabled() {
6574        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6575    }
6576
6577    /**
6578     * Returns the layout direction for this view.
6579     *
6580     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6581     *   {@link #LAYOUT_DIRECTION_RTL},
6582     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6583     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6584     *
6585     * @attr ref android.R.styleable#View_layoutDirection
6586     *
6587     * @hide
6588     */
6589    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6590        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6591        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6592        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6593        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6594    })
6595    @LayoutDir
6596    public int getRawLayoutDirection() {
6597        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6598    }
6599
6600    /**
6601     * Set the layout direction for this view. This will propagate a reset of layout direction
6602     * resolution to the view's children and resolve layout direction for this view.
6603     *
6604     * @param layoutDirection the layout direction to set. Should be one of:
6605     *
6606     * {@link #LAYOUT_DIRECTION_LTR},
6607     * {@link #LAYOUT_DIRECTION_RTL},
6608     * {@link #LAYOUT_DIRECTION_INHERIT},
6609     * {@link #LAYOUT_DIRECTION_LOCALE}.
6610     *
6611     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6612     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6613     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6614     *
6615     * @attr ref android.R.styleable#View_layoutDirection
6616     */
6617    @RemotableViewMethod
6618    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6619        if (getRawLayoutDirection() != layoutDirection) {
6620            // Reset the current layout direction and the resolved one
6621            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6622            resetRtlProperties();
6623            // Set the new layout direction (filtered)
6624            mPrivateFlags2 |=
6625                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6626            // We need to resolve all RTL properties as they all depend on layout direction
6627            resolveRtlPropertiesIfNeeded();
6628            requestLayout();
6629            invalidate(true);
6630        }
6631    }
6632
6633    /**
6634     * Returns the resolved layout direction for this view.
6635     *
6636     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6637     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6638     *
6639     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6640     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6641     *
6642     * @attr ref android.R.styleable#View_layoutDirection
6643     */
6644    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6645        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6646        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6647    })
6648    @ResolvedLayoutDir
6649    public int getLayoutDirection() {
6650        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6651        if (targetSdkVersion < JELLY_BEAN_MR1) {
6652            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6653            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6654        }
6655        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6656                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6657    }
6658
6659    /**
6660     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6661     * layout attribute and/or the inherited value from the parent
6662     *
6663     * @return true if the layout is right-to-left.
6664     *
6665     * @hide
6666     */
6667    @ViewDebug.ExportedProperty(category = "layout")
6668    public boolean isLayoutRtl() {
6669        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6670    }
6671
6672    /**
6673     * Indicates whether the view is currently tracking transient state that the
6674     * app should not need to concern itself with saving and restoring, but that
6675     * the framework should take special note to preserve when possible.
6676     *
6677     * <p>A view with transient state cannot be trivially rebound from an external
6678     * data source, such as an adapter binding item views in a list. This may be
6679     * because the view is performing an animation, tracking user selection
6680     * of content, or similar.</p>
6681     *
6682     * @return true if the view has transient state
6683     */
6684    @ViewDebug.ExportedProperty(category = "layout")
6685    public boolean hasTransientState() {
6686        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6687    }
6688
6689    /**
6690     * Set whether this view is currently tracking transient state that the
6691     * framework should attempt to preserve when possible. This flag is reference counted,
6692     * so every call to setHasTransientState(true) should be paired with a later call
6693     * to setHasTransientState(false).
6694     *
6695     * <p>A view with transient state cannot be trivially rebound from an external
6696     * data source, such as an adapter binding item views in a list. This may be
6697     * because the view is performing an animation, tracking user selection
6698     * of content, or similar.</p>
6699     *
6700     * @param hasTransientState true if this view has transient state
6701     */
6702    public void setHasTransientState(boolean hasTransientState) {
6703        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6704                mTransientStateCount - 1;
6705        if (mTransientStateCount < 0) {
6706            mTransientStateCount = 0;
6707            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6708                    "unmatched pair of setHasTransientState calls");
6709        } else if ((hasTransientState && mTransientStateCount == 1) ||
6710                (!hasTransientState && mTransientStateCount == 0)) {
6711            // update flag if we've just incremented up from 0 or decremented down to 0
6712            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6713                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6714            if (mParent != null) {
6715                try {
6716                    mParent.childHasTransientStateChanged(this, hasTransientState);
6717                } catch (AbstractMethodError e) {
6718                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6719                            " does not fully implement ViewParent", e);
6720                }
6721            }
6722        }
6723    }
6724
6725    /**
6726     * Returns true if this view is currently attached to a window.
6727     */
6728    public boolean isAttachedToWindow() {
6729        return mAttachInfo != null;
6730    }
6731
6732    /**
6733     * Returns true if this view has been through at least one layout since it
6734     * was last attached to or detached from a window.
6735     */
6736    public boolean isLaidOut() {
6737        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6738    }
6739
6740    /**
6741     * If this view doesn't do any drawing on its own, set this flag to
6742     * allow further optimizations. By default, this flag is not set on
6743     * View, but could be set on some View subclasses such as ViewGroup.
6744     *
6745     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6746     * you should clear this flag.
6747     *
6748     * @param willNotDraw whether or not this View draw on its own
6749     */
6750    public void setWillNotDraw(boolean willNotDraw) {
6751        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6752    }
6753
6754    /**
6755     * Returns whether or not this View draws on its own.
6756     *
6757     * @return true if this view has nothing to draw, false otherwise
6758     */
6759    @ViewDebug.ExportedProperty(category = "drawing")
6760    public boolean willNotDraw() {
6761        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6762    }
6763
6764    /**
6765     * When a View's drawing cache is enabled, drawing is redirected to an
6766     * offscreen bitmap. Some views, like an ImageView, must be able to
6767     * bypass this mechanism if they already draw a single bitmap, to avoid
6768     * unnecessary usage of the memory.
6769     *
6770     * @param willNotCacheDrawing true if this view does not cache its
6771     *        drawing, false otherwise
6772     */
6773    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6774        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6775    }
6776
6777    /**
6778     * Returns whether or not this View can cache its drawing or not.
6779     *
6780     * @return true if this view does not cache its drawing, false otherwise
6781     */
6782    @ViewDebug.ExportedProperty(category = "drawing")
6783    public boolean willNotCacheDrawing() {
6784        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6785    }
6786
6787    /**
6788     * Indicates whether this view reacts to click events or not.
6789     *
6790     * @return true if the view is clickable, false otherwise
6791     *
6792     * @see #setClickable(boolean)
6793     * @attr ref android.R.styleable#View_clickable
6794     */
6795    @ViewDebug.ExportedProperty
6796    public boolean isClickable() {
6797        return (mViewFlags & CLICKABLE) == CLICKABLE;
6798    }
6799
6800    /**
6801     * Enables or disables click events for this view. When a view
6802     * is clickable it will change its state to "pressed" on every click.
6803     * Subclasses should set the view clickable to visually react to
6804     * user's clicks.
6805     *
6806     * @param clickable true to make the view clickable, false otherwise
6807     *
6808     * @see #isClickable()
6809     * @attr ref android.R.styleable#View_clickable
6810     */
6811    public void setClickable(boolean clickable) {
6812        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6813    }
6814
6815    /**
6816     * Indicates whether this view reacts to long click events or not.
6817     *
6818     * @return true if the view is long clickable, false otherwise
6819     *
6820     * @see #setLongClickable(boolean)
6821     * @attr ref android.R.styleable#View_longClickable
6822     */
6823    public boolean isLongClickable() {
6824        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6825    }
6826
6827    /**
6828     * Enables or disables long click events for this view. When a view is long
6829     * clickable it reacts to the user holding down the button for a longer
6830     * duration than a tap. This event can either launch the listener or a
6831     * context menu.
6832     *
6833     * @param longClickable true to make the view long clickable, false otherwise
6834     * @see #isLongClickable()
6835     * @attr ref android.R.styleable#View_longClickable
6836     */
6837    public void setLongClickable(boolean longClickable) {
6838        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6839    }
6840
6841    /**
6842     * Sets the pressed state for this view and provides a touch coordinate for
6843     * animation hinting.
6844     *
6845     * @param pressed Pass true to set the View's internal state to "pressed",
6846     *            or false to reverts the View's internal state from a
6847     *            previously set "pressed" state.
6848     * @param x The x coordinate of the touch that caused the press
6849     * @param y The y coordinate of the touch that caused the press
6850     */
6851    private void setPressed(boolean pressed, float x, float y) {
6852        if (pressed) {
6853            drawableHotspotChanged(x, y);
6854        }
6855
6856        setPressed(pressed);
6857    }
6858
6859    /**
6860     * Sets the pressed state for this view.
6861     *
6862     * @see #isClickable()
6863     * @see #setClickable(boolean)
6864     *
6865     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6866     *        the View's internal state from a previously set "pressed" state.
6867     */
6868    public void setPressed(boolean pressed) {
6869        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6870
6871        if (pressed) {
6872            mPrivateFlags |= PFLAG_PRESSED;
6873        } else {
6874            mPrivateFlags &= ~PFLAG_PRESSED;
6875        }
6876
6877        if (needsRefresh) {
6878            refreshDrawableState();
6879        }
6880        dispatchSetPressed(pressed);
6881    }
6882
6883    /**
6884     * Dispatch setPressed to all of this View's children.
6885     *
6886     * @see #setPressed(boolean)
6887     *
6888     * @param pressed The new pressed state
6889     */
6890    protected void dispatchSetPressed(boolean pressed) {
6891    }
6892
6893    /**
6894     * Indicates whether the view is currently in pressed state. Unless
6895     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6896     * the pressed state.
6897     *
6898     * @see #setPressed(boolean)
6899     * @see #isClickable()
6900     * @see #setClickable(boolean)
6901     *
6902     * @return true if the view is currently pressed, false otherwise
6903     */
6904    @ViewDebug.ExportedProperty
6905    public boolean isPressed() {
6906        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6907    }
6908
6909    /**
6910     * Indicates whether this view will save its state (that is,
6911     * whether its {@link #onSaveInstanceState} method will be called).
6912     *
6913     * @return Returns true if the view state saving is enabled, else false.
6914     *
6915     * @see #setSaveEnabled(boolean)
6916     * @attr ref android.R.styleable#View_saveEnabled
6917     */
6918    public boolean isSaveEnabled() {
6919        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6920    }
6921
6922    /**
6923     * Controls whether the saving of this view's state is
6924     * enabled (that is, whether its {@link #onSaveInstanceState} method
6925     * will be called).  Note that even if freezing is enabled, the
6926     * view still must have an id assigned to it (via {@link #setId(int)})
6927     * for its state to be saved.  This flag can only disable the
6928     * saving of this view; any child views may still have their state saved.
6929     *
6930     * @param enabled Set to false to <em>disable</em> state saving, or true
6931     * (the default) to allow it.
6932     *
6933     * @see #isSaveEnabled()
6934     * @see #setId(int)
6935     * @see #onSaveInstanceState()
6936     * @attr ref android.R.styleable#View_saveEnabled
6937     */
6938    public void setSaveEnabled(boolean enabled) {
6939        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6940    }
6941
6942    /**
6943     * Gets whether the framework should discard touches when the view's
6944     * window is obscured by another visible window.
6945     * Refer to the {@link View} security documentation for more details.
6946     *
6947     * @return True if touch filtering is enabled.
6948     *
6949     * @see #setFilterTouchesWhenObscured(boolean)
6950     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6951     */
6952    @ViewDebug.ExportedProperty
6953    public boolean getFilterTouchesWhenObscured() {
6954        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6955    }
6956
6957    /**
6958     * Sets whether the framework should discard touches when the view's
6959     * window is obscured by another visible window.
6960     * Refer to the {@link View} security documentation for more details.
6961     *
6962     * @param enabled True if touch filtering should be enabled.
6963     *
6964     * @see #getFilterTouchesWhenObscured
6965     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6966     */
6967    public void setFilterTouchesWhenObscured(boolean enabled) {
6968        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6969                FILTER_TOUCHES_WHEN_OBSCURED);
6970    }
6971
6972    /**
6973     * Indicates whether the entire hierarchy under this view will save its
6974     * state when a state saving traversal occurs from its parent.  The default
6975     * is true; if false, these views will not be saved unless
6976     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6977     *
6978     * @return Returns true if the view state saving from parent is enabled, else false.
6979     *
6980     * @see #setSaveFromParentEnabled(boolean)
6981     */
6982    public boolean isSaveFromParentEnabled() {
6983        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6984    }
6985
6986    /**
6987     * Controls whether the entire hierarchy under this view will save its
6988     * state when a state saving traversal occurs from its parent.  The default
6989     * is true; if false, these views will not be saved unless
6990     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6991     *
6992     * @param enabled Set to false to <em>disable</em> state saving, or true
6993     * (the default) to allow it.
6994     *
6995     * @see #isSaveFromParentEnabled()
6996     * @see #setId(int)
6997     * @see #onSaveInstanceState()
6998     */
6999    public void setSaveFromParentEnabled(boolean enabled) {
7000        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7001    }
7002
7003
7004    /**
7005     * Returns whether this View is able to take focus.
7006     *
7007     * @return True if this view can take focus, or false otherwise.
7008     * @attr ref android.R.styleable#View_focusable
7009     */
7010    @ViewDebug.ExportedProperty(category = "focus")
7011    public final boolean isFocusable() {
7012        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7013    }
7014
7015    /**
7016     * When a view is focusable, it may not want to take focus when in touch mode.
7017     * For example, a button would like focus when the user is navigating via a D-pad
7018     * so that the user can click on it, but once the user starts touching the screen,
7019     * the button shouldn't take focus
7020     * @return Whether the view is focusable in touch mode.
7021     * @attr ref android.R.styleable#View_focusableInTouchMode
7022     */
7023    @ViewDebug.ExportedProperty
7024    public final boolean isFocusableInTouchMode() {
7025        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7026    }
7027
7028    /**
7029     * Find the nearest view in the specified direction that can take focus.
7030     * This does not actually give focus to that view.
7031     *
7032     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7033     *
7034     * @return The nearest focusable in the specified direction, or null if none
7035     *         can be found.
7036     */
7037    public View focusSearch(@FocusRealDirection int direction) {
7038        if (mParent != null) {
7039            return mParent.focusSearch(this, direction);
7040        } else {
7041            return null;
7042        }
7043    }
7044
7045    /**
7046     * This method is the last chance for the focused view and its ancestors to
7047     * respond to an arrow key. This is called when the focused view did not
7048     * consume the key internally, nor could the view system find a new view in
7049     * the requested direction to give focus to.
7050     *
7051     * @param focused The currently focused view.
7052     * @param direction The direction focus wants to move. One of FOCUS_UP,
7053     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7054     * @return True if the this view consumed this unhandled move.
7055     */
7056    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7057        return false;
7058    }
7059
7060    /**
7061     * If a user manually specified the next view id for a particular direction,
7062     * use the root to look up the view.
7063     * @param root The root view of the hierarchy containing this view.
7064     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7065     * or FOCUS_BACKWARD.
7066     * @return The user specified next view, or null if there is none.
7067     */
7068    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7069        switch (direction) {
7070            case FOCUS_LEFT:
7071                if (mNextFocusLeftId == View.NO_ID) return null;
7072                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7073            case FOCUS_RIGHT:
7074                if (mNextFocusRightId == View.NO_ID) return null;
7075                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7076            case FOCUS_UP:
7077                if (mNextFocusUpId == View.NO_ID) return null;
7078                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7079            case FOCUS_DOWN:
7080                if (mNextFocusDownId == View.NO_ID) return null;
7081                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7082            case FOCUS_FORWARD:
7083                if (mNextFocusForwardId == View.NO_ID) return null;
7084                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7085            case FOCUS_BACKWARD: {
7086                if (mID == View.NO_ID) return null;
7087                final int id = mID;
7088                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7089                    @Override
7090                    public boolean apply(View t) {
7091                        return t.mNextFocusForwardId == id;
7092                    }
7093                });
7094            }
7095        }
7096        return null;
7097    }
7098
7099    private View findViewInsideOutShouldExist(View root, int id) {
7100        if (mMatchIdPredicate == null) {
7101            mMatchIdPredicate = new MatchIdPredicate();
7102        }
7103        mMatchIdPredicate.mId = id;
7104        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7105        if (result == null) {
7106            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7107        }
7108        return result;
7109    }
7110
7111    /**
7112     * Find and return all focusable views that are descendants of this view,
7113     * possibly including this view if it is focusable itself.
7114     *
7115     * @param direction The direction of the focus
7116     * @return A list of focusable views
7117     */
7118    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7119        ArrayList<View> result = new ArrayList<View>(24);
7120        addFocusables(result, direction);
7121        return result;
7122    }
7123
7124    /**
7125     * Add any focusable views that are descendants of this view (possibly
7126     * including this view if it is focusable itself) to views.  If we are in touch mode,
7127     * only add views that are also focusable in touch mode.
7128     *
7129     * @param views Focusable views found so far
7130     * @param direction The direction of the focus
7131     */
7132    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7133        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7134    }
7135
7136    /**
7137     * Adds any focusable views that are descendants of this view (possibly
7138     * including this view if it is focusable itself) to views. This method
7139     * adds all focusable views regardless if we are in touch mode or
7140     * only views focusable in touch mode if we are in touch mode or
7141     * only views that can take accessibility focus if accessibility is enabeld
7142     * depending on the focusable mode paramater.
7143     *
7144     * @param views Focusable views found so far or null if all we are interested is
7145     *        the number of focusables.
7146     * @param direction The direction of the focus.
7147     * @param focusableMode The type of focusables to be added.
7148     *
7149     * @see #FOCUSABLES_ALL
7150     * @see #FOCUSABLES_TOUCH_MODE
7151     */
7152    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7153            @FocusableMode int focusableMode) {
7154        if (views == null) {
7155            return;
7156        }
7157        if (!isFocusable()) {
7158            return;
7159        }
7160        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7161                && isInTouchMode() && !isFocusableInTouchMode()) {
7162            return;
7163        }
7164        views.add(this);
7165    }
7166
7167    /**
7168     * Finds the Views that contain given text. The containment is case insensitive.
7169     * The search is performed by either the text that the View renders or the content
7170     * description that describes the view for accessibility purposes and the view does
7171     * not render or both. Clients can specify how the search is to be performed via
7172     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7173     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7174     *
7175     * @param outViews The output list of matching Views.
7176     * @param searched The text to match against.
7177     *
7178     * @see #FIND_VIEWS_WITH_TEXT
7179     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7180     * @see #setContentDescription(CharSequence)
7181     */
7182    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7183            @FindViewFlags int flags) {
7184        if (getAccessibilityNodeProvider() != null) {
7185            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7186                outViews.add(this);
7187            }
7188        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7189                && (searched != null && searched.length() > 0)
7190                && (mContentDescription != null && mContentDescription.length() > 0)) {
7191            String searchedLowerCase = searched.toString().toLowerCase();
7192            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7193            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7194                outViews.add(this);
7195            }
7196        }
7197    }
7198
7199    /**
7200     * Find and return all touchable views that are descendants of this view,
7201     * possibly including this view if it is touchable itself.
7202     *
7203     * @return A list of touchable views
7204     */
7205    public ArrayList<View> getTouchables() {
7206        ArrayList<View> result = new ArrayList<View>();
7207        addTouchables(result);
7208        return result;
7209    }
7210
7211    /**
7212     * Add any touchable views that are descendants of this view (possibly
7213     * including this view if it is touchable itself) to views.
7214     *
7215     * @param views Touchable views found so far
7216     */
7217    public void addTouchables(ArrayList<View> views) {
7218        final int viewFlags = mViewFlags;
7219
7220        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7221                && (viewFlags & ENABLED_MASK) == ENABLED) {
7222            views.add(this);
7223        }
7224    }
7225
7226    /**
7227     * Returns whether this View is accessibility focused.
7228     *
7229     * @return True if this View is accessibility focused.
7230     */
7231    public boolean isAccessibilityFocused() {
7232        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7233    }
7234
7235    /**
7236     * Call this to try to give accessibility focus to this view.
7237     *
7238     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7239     * returns false or the view is no visible or the view already has accessibility
7240     * focus.
7241     *
7242     * See also {@link #focusSearch(int)}, which is what you call to say that you
7243     * have focus, and you want your parent to look for the next one.
7244     *
7245     * @return Whether this view actually took accessibility focus.
7246     *
7247     * @hide
7248     */
7249    public boolean requestAccessibilityFocus() {
7250        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7251        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7252            return false;
7253        }
7254        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7255            return false;
7256        }
7257        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7258            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7259            ViewRootImpl viewRootImpl = getViewRootImpl();
7260            if (viewRootImpl != null) {
7261                viewRootImpl.setAccessibilityFocus(this, null);
7262            }
7263            invalidate();
7264            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7265            return true;
7266        }
7267        return false;
7268    }
7269
7270    /**
7271     * Call this to try to clear accessibility focus of this view.
7272     *
7273     * See also {@link #focusSearch(int)}, which is what you call to say that you
7274     * have focus, and you want your parent to look for the next one.
7275     *
7276     * @hide
7277     */
7278    public void clearAccessibilityFocus() {
7279        clearAccessibilityFocusNoCallbacks();
7280        // Clear the global reference of accessibility focus if this
7281        // view or any of its descendants had accessibility focus.
7282        ViewRootImpl viewRootImpl = getViewRootImpl();
7283        if (viewRootImpl != null) {
7284            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7285            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7286                viewRootImpl.setAccessibilityFocus(null, null);
7287            }
7288        }
7289    }
7290
7291    private void sendAccessibilityHoverEvent(int eventType) {
7292        // Since we are not delivering to a client accessibility events from not
7293        // important views (unless the clinet request that) we need to fire the
7294        // event from the deepest view exposed to the client. As a consequence if
7295        // the user crosses a not exposed view the client will see enter and exit
7296        // of the exposed predecessor followed by and enter and exit of that same
7297        // predecessor when entering and exiting the not exposed descendant. This
7298        // is fine since the client has a clear idea which view is hovered at the
7299        // price of a couple more events being sent. This is a simple and
7300        // working solution.
7301        View source = this;
7302        while (true) {
7303            if (source.includeForAccessibility()) {
7304                source.sendAccessibilityEvent(eventType);
7305                return;
7306            }
7307            ViewParent parent = source.getParent();
7308            if (parent instanceof View) {
7309                source = (View) parent;
7310            } else {
7311                return;
7312            }
7313        }
7314    }
7315
7316    /**
7317     * Clears accessibility focus without calling any callback methods
7318     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7319     * is used for clearing accessibility focus when giving this focus to
7320     * another view.
7321     */
7322    void clearAccessibilityFocusNoCallbacks() {
7323        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7324            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7325            invalidate();
7326            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7327        }
7328    }
7329
7330    /**
7331     * Call this to try to give focus to a specific view or to one of its
7332     * descendants.
7333     *
7334     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7335     * false), or if it is focusable and it is not focusable in touch mode
7336     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7337     *
7338     * See also {@link #focusSearch(int)}, which is what you call to say that you
7339     * have focus, and you want your parent to look for the next one.
7340     *
7341     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7342     * {@link #FOCUS_DOWN} and <code>null</code>.
7343     *
7344     * @return Whether this view or one of its descendants actually took focus.
7345     */
7346    public final boolean requestFocus() {
7347        return requestFocus(View.FOCUS_DOWN);
7348    }
7349
7350    /**
7351     * Call this to try to give focus to a specific view or to one of its
7352     * descendants and give it a hint about what direction focus is heading.
7353     *
7354     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7355     * false), or if it is focusable and it is not focusable in touch mode
7356     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7357     *
7358     * See also {@link #focusSearch(int)}, which is what you call to say that you
7359     * have focus, and you want your parent to look for the next one.
7360     *
7361     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7362     * <code>null</code> set for the previously focused rectangle.
7363     *
7364     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7365     * @return Whether this view or one of its descendants actually took focus.
7366     */
7367    public final boolean requestFocus(int direction) {
7368        return requestFocus(direction, null);
7369    }
7370
7371    /**
7372     * Call this to try to give focus to a specific view or to one of its descendants
7373     * and give it hints about the direction and a specific rectangle that the focus
7374     * is coming from.  The rectangle can help give larger views a finer grained hint
7375     * about where focus is coming from, and therefore, where to show selection, or
7376     * forward focus change internally.
7377     *
7378     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7379     * false), or if it is focusable and it is not focusable in touch mode
7380     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7381     *
7382     * A View will not take focus if it is not visible.
7383     *
7384     * A View will not take focus if one of its parents has
7385     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7386     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7387     *
7388     * See also {@link #focusSearch(int)}, which is what you call to say that you
7389     * have focus, and you want your parent to look for the next one.
7390     *
7391     * You may wish to override this method if your custom {@link View} has an internal
7392     * {@link View} that it wishes to forward the request to.
7393     *
7394     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7395     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7396     *        to give a finer grained hint about where focus is coming from.  May be null
7397     *        if there is no hint.
7398     * @return Whether this view or one of its descendants actually took focus.
7399     */
7400    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7401        return requestFocusNoSearch(direction, previouslyFocusedRect);
7402    }
7403
7404    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7405        // need to be focusable
7406        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7407                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7408            return false;
7409        }
7410
7411        // need to be focusable in touch mode if in touch mode
7412        if (isInTouchMode() &&
7413            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7414               return false;
7415        }
7416
7417        // need to not have any parents blocking us
7418        if (hasAncestorThatBlocksDescendantFocus()) {
7419            return false;
7420        }
7421
7422        handleFocusGainInternal(direction, previouslyFocusedRect);
7423        return true;
7424    }
7425
7426    /**
7427     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7428     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7429     * touch mode to request focus when they are touched.
7430     *
7431     * @return Whether this view or one of its descendants actually took focus.
7432     *
7433     * @see #isInTouchMode()
7434     *
7435     */
7436    public final boolean requestFocusFromTouch() {
7437        // Leave touch mode if we need to
7438        if (isInTouchMode()) {
7439            ViewRootImpl viewRoot = getViewRootImpl();
7440            if (viewRoot != null) {
7441                viewRoot.ensureTouchMode(false);
7442            }
7443        }
7444        return requestFocus(View.FOCUS_DOWN);
7445    }
7446
7447    /**
7448     * @return Whether any ancestor of this view blocks descendant focus.
7449     */
7450    private boolean hasAncestorThatBlocksDescendantFocus() {
7451        final boolean focusableInTouchMode = isFocusableInTouchMode();
7452        ViewParent ancestor = mParent;
7453        while (ancestor instanceof ViewGroup) {
7454            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7455            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7456                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7457                return true;
7458            } else {
7459                ancestor = vgAncestor.getParent();
7460            }
7461        }
7462        return false;
7463    }
7464
7465    /**
7466     * Gets the mode for determining whether this View is important for accessibility
7467     * which is if it fires accessibility events and if it is reported to
7468     * accessibility services that query the screen.
7469     *
7470     * @return The mode for determining whether a View is important for accessibility.
7471     *
7472     * @attr ref android.R.styleable#View_importantForAccessibility
7473     *
7474     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7475     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7476     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7477     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7478     */
7479    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7480            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7481            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7482            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7483            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7484                    to = "noHideDescendants")
7485        })
7486    public int getImportantForAccessibility() {
7487        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7488                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7489    }
7490
7491    /**
7492     * Sets the live region mode for this view. This indicates to accessibility
7493     * services whether they should automatically notify the user about changes
7494     * to the view's content description or text, or to the content descriptions
7495     * or text of the view's children (where applicable).
7496     * <p>
7497     * For example, in a login screen with a TextView that displays an "incorrect
7498     * password" notification, that view should be marked as a live region with
7499     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7500     * <p>
7501     * To disable change notifications for this view, use
7502     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7503     * mode for most views.
7504     * <p>
7505     * To indicate that the user should be notified of changes, use
7506     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7507     * <p>
7508     * If the view's changes should interrupt ongoing speech and notify the user
7509     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7510     *
7511     * @param mode The live region mode for this view, one of:
7512     *        <ul>
7513     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7514     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7515     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7516     *        </ul>
7517     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7518     */
7519    public void setAccessibilityLiveRegion(int mode) {
7520        if (mode != getAccessibilityLiveRegion()) {
7521            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7522            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7523                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7524            notifyViewAccessibilityStateChangedIfNeeded(
7525                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7526        }
7527    }
7528
7529    /**
7530     * Gets the live region mode for this View.
7531     *
7532     * @return The live region mode for the view.
7533     *
7534     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7535     *
7536     * @see #setAccessibilityLiveRegion(int)
7537     */
7538    public int getAccessibilityLiveRegion() {
7539        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7540                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7541    }
7542
7543    /**
7544     * Sets how to determine whether this view is important for accessibility
7545     * which is if it fires accessibility events and if it is reported to
7546     * accessibility services that query the screen.
7547     *
7548     * @param mode How to determine whether this view is important for accessibility.
7549     *
7550     * @attr ref android.R.styleable#View_importantForAccessibility
7551     *
7552     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7553     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7554     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7555     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7556     */
7557    public void setImportantForAccessibility(int mode) {
7558        final int oldMode = getImportantForAccessibility();
7559        if (mode != oldMode) {
7560            // If we're moving between AUTO and another state, we might not need
7561            // to send a subtree changed notification. We'll store the computed
7562            // importance, since we'll need to check it later to make sure.
7563            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7564                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7565            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7566            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7567            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7568                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7569            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7570                notifySubtreeAccessibilityStateChangedIfNeeded();
7571            } else {
7572                notifyViewAccessibilityStateChangedIfNeeded(
7573                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7574            }
7575        }
7576    }
7577
7578    /**
7579     * Computes whether this view should be exposed for accessibility. In
7580     * general, views that are interactive or provide information are exposed
7581     * while views that serve only as containers are hidden.
7582     * <p>
7583     * If an ancestor of this view has importance
7584     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7585     * returns <code>false</code>.
7586     * <p>
7587     * Otherwise, the value is computed according to the view's
7588     * {@link #getImportantForAccessibility()} value:
7589     * <ol>
7590     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7591     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7592     * </code>
7593     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7594     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7595     * view satisfies any of the following:
7596     * <ul>
7597     * <li>Is actionable, e.g. {@link #isClickable()},
7598     * {@link #isLongClickable()}, or {@link #isFocusable()}
7599     * <li>Has an {@link AccessibilityDelegate}
7600     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7601     * {@link OnKeyListener}, etc.
7602     * <li>Is an accessibility live region, e.g.
7603     * {@link #getAccessibilityLiveRegion()} is not
7604     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7605     * </ul>
7606     * </ol>
7607     *
7608     * @return Whether the view is exposed for accessibility.
7609     * @see #setImportantForAccessibility(int)
7610     * @see #getImportantForAccessibility()
7611     */
7612    public boolean isImportantForAccessibility() {
7613        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7614                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7615        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7616                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7617            return false;
7618        }
7619
7620        // Check parent mode to ensure we're not hidden.
7621        ViewParent parent = mParent;
7622        while (parent instanceof View) {
7623            if (((View) parent).getImportantForAccessibility()
7624                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7625                return false;
7626            }
7627            parent = parent.getParent();
7628        }
7629
7630        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7631                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7632                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7633    }
7634
7635    /**
7636     * Gets the parent for accessibility purposes. Note that the parent for
7637     * accessibility is not necessary the immediate parent. It is the first
7638     * predecessor that is important for accessibility.
7639     *
7640     * @return The parent for accessibility purposes.
7641     */
7642    public ViewParent getParentForAccessibility() {
7643        if (mParent instanceof View) {
7644            View parentView = (View) mParent;
7645            if (parentView.includeForAccessibility()) {
7646                return mParent;
7647            } else {
7648                return mParent.getParentForAccessibility();
7649            }
7650        }
7651        return null;
7652    }
7653
7654    /**
7655     * Adds the children of a given View for accessibility. Since some Views are
7656     * not important for accessibility the children for accessibility are not
7657     * necessarily direct children of the view, rather they are the first level of
7658     * descendants important for accessibility.
7659     *
7660     * @param children The list of children for accessibility.
7661     */
7662    public void addChildrenForAccessibility(ArrayList<View> children) {
7663
7664    }
7665
7666    /**
7667     * Whether to regard this view for accessibility. A view is regarded for
7668     * accessibility if it is important for accessibility or the querying
7669     * accessibility service has explicitly requested that view not
7670     * important for accessibility are regarded.
7671     *
7672     * @return Whether to regard the view for accessibility.
7673     *
7674     * @hide
7675     */
7676    public boolean includeForAccessibility() {
7677        if (mAttachInfo != null) {
7678            return (mAttachInfo.mAccessibilityFetchFlags
7679                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7680                    || isImportantForAccessibility();
7681        }
7682        return false;
7683    }
7684
7685    /**
7686     * Returns whether the View is considered actionable from
7687     * accessibility perspective. Such view are important for
7688     * accessibility.
7689     *
7690     * @return True if the view is actionable for accessibility.
7691     *
7692     * @hide
7693     */
7694    public boolean isActionableForAccessibility() {
7695        return (isClickable() || isLongClickable() || isFocusable());
7696    }
7697
7698    /**
7699     * Returns whether the View has registered callbacks which makes it
7700     * important for accessibility.
7701     *
7702     * @return True if the view is actionable for accessibility.
7703     */
7704    private boolean hasListenersForAccessibility() {
7705        ListenerInfo info = getListenerInfo();
7706        return mTouchDelegate != null || info.mOnKeyListener != null
7707                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7708                || info.mOnHoverListener != null || info.mOnDragListener != null;
7709    }
7710
7711    /**
7712     * Notifies that the accessibility state of this view changed. The change
7713     * is local to this view and does not represent structural changes such
7714     * as children and parent. For example, the view became focusable. The
7715     * notification is at at most once every
7716     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7717     * to avoid unnecessary load to the system. Also once a view has a pending
7718     * notification this method is a NOP until the notification has been sent.
7719     *
7720     * @hide
7721     */
7722    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7723        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7724            return;
7725        }
7726        if (mSendViewStateChangedAccessibilityEvent == null) {
7727            mSendViewStateChangedAccessibilityEvent =
7728                    new SendViewStateChangedAccessibilityEvent();
7729        }
7730        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7731    }
7732
7733    /**
7734     * Notifies that the accessibility state of this view changed. The change
7735     * is *not* local to this view and does represent structural changes such
7736     * as children and parent. For example, the view size changed. The
7737     * notification is at at most once every
7738     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7739     * to avoid unnecessary load to the system. Also once a view has a pending
7740     * notification this method is a NOP until the notification has been sent.
7741     *
7742     * @hide
7743     */
7744    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7745        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7746            return;
7747        }
7748        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7749            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7750            if (mParent != null) {
7751                try {
7752                    mParent.notifySubtreeAccessibilityStateChanged(
7753                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7754                } catch (AbstractMethodError e) {
7755                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7756                            " does not fully implement ViewParent", e);
7757                }
7758            }
7759        }
7760    }
7761
7762    /**
7763     * Reset the flag indicating the accessibility state of the subtree rooted
7764     * at this view changed.
7765     */
7766    void resetSubtreeAccessibilityStateChanged() {
7767        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7768    }
7769
7770    /**
7771     * Performs the specified accessibility action on the view. For
7772     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7773     * <p>
7774     * If an {@link AccessibilityDelegate} has been specified via calling
7775     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7776     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7777     * is responsible for handling this call.
7778     * </p>
7779     *
7780     * @param action The action to perform.
7781     * @param arguments Optional action arguments.
7782     * @return Whether the action was performed.
7783     */
7784    public boolean performAccessibilityAction(int action, Bundle arguments) {
7785      if (mAccessibilityDelegate != null) {
7786          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7787      } else {
7788          return performAccessibilityActionInternal(action, arguments);
7789      }
7790    }
7791
7792   /**
7793    * @see #performAccessibilityAction(int, Bundle)
7794    *
7795    * Note: Called from the default {@link AccessibilityDelegate}.
7796    */
7797    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7798        switch (action) {
7799            case AccessibilityNodeInfo.ACTION_CLICK: {
7800                if (isClickable()) {
7801                    performClick();
7802                    return true;
7803                }
7804            } break;
7805            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7806                if (isLongClickable()) {
7807                    performLongClick();
7808                    return true;
7809                }
7810            } break;
7811            case AccessibilityNodeInfo.ACTION_FOCUS: {
7812                if (!hasFocus()) {
7813                    // Get out of touch mode since accessibility
7814                    // wants to move focus around.
7815                    getViewRootImpl().ensureTouchMode(false);
7816                    return requestFocus();
7817                }
7818            } break;
7819            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7820                if (hasFocus()) {
7821                    clearFocus();
7822                    return !isFocused();
7823                }
7824            } break;
7825            case AccessibilityNodeInfo.ACTION_SELECT: {
7826                if (!isSelected()) {
7827                    setSelected(true);
7828                    return isSelected();
7829                }
7830            } break;
7831            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7832                if (isSelected()) {
7833                    setSelected(false);
7834                    return !isSelected();
7835                }
7836            } break;
7837            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7838                if (!isAccessibilityFocused()) {
7839                    return requestAccessibilityFocus();
7840                }
7841            } break;
7842            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7843                if (isAccessibilityFocused()) {
7844                    clearAccessibilityFocus();
7845                    return true;
7846                }
7847            } break;
7848            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7849                if (arguments != null) {
7850                    final int granularity = arguments.getInt(
7851                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7852                    final boolean extendSelection = arguments.getBoolean(
7853                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7854                    return traverseAtGranularity(granularity, true, extendSelection);
7855                }
7856            } break;
7857            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7858                if (arguments != null) {
7859                    final int granularity = arguments.getInt(
7860                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7861                    final boolean extendSelection = arguments.getBoolean(
7862                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7863                    return traverseAtGranularity(granularity, false, extendSelection);
7864                }
7865            } break;
7866            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7867                CharSequence text = getIterableTextForAccessibility();
7868                if (text == null) {
7869                    return false;
7870                }
7871                final int start = (arguments != null) ? arguments.getInt(
7872                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7873                final int end = (arguments != null) ? arguments.getInt(
7874                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7875                // Only cursor position can be specified (selection length == 0)
7876                if ((getAccessibilitySelectionStart() != start
7877                        || getAccessibilitySelectionEnd() != end)
7878                        && (start == end)) {
7879                    setAccessibilitySelection(start, end);
7880                    notifyViewAccessibilityStateChangedIfNeeded(
7881                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7882                    return true;
7883                }
7884            } break;
7885        }
7886        return false;
7887    }
7888
7889    private boolean traverseAtGranularity(int granularity, boolean forward,
7890            boolean extendSelection) {
7891        CharSequence text = getIterableTextForAccessibility();
7892        if (text == null || text.length() == 0) {
7893            return false;
7894        }
7895        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7896        if (iterator == null) {
7897            return false;
7898        }
7899        int current = getAccessibilitySelectionEnd();
7900        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7901            current = forward ? 0 : text.length();
7902        }
7903        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7904        if (range == null) {
7905            return false;
7906        }
7907        final int segmentStart = range[0];
7908        final int segmentEnd = range[1];
7909        int selectionStart;
7910        int selectionEnd;
7911        if (extendSelection && isAccessibilitySelectionExtendable()) {
7912            selectionStart = getAccessibilitySelectionStart();
7913            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7914                selectionStart = forward ? segmentStart : segmentEnd;
7915            }
7916            selectionEnd = forward ? segmentEnd : segmentStart;
7917        } else {
7918            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7919        }
7920        setAccessibilitySelection(selectionStart, selectionEnd);
7921        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7922                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7923        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7924        return true;
7925    }
7926
7927    /**
7928     * Gets the text reported for accessibility purposes.
7929     *
7930     * @return The accessibility text.
7931     *
7932     * @hide
7933     */
7934    public CharSequence getIterableTextForAccessibility() {
7935        return getContentDescription();
7936    }
7937
7938    /**
7939     * Gets whether accessibility selection can be extended.
7940     *
7941     * @return If selection is extensible.
7942     *
7943     * @hide
7944     */
7945    public boolean isAccessibilitySelectionExtendable() {
7946        return false;
7947    }
7948
7949    /**
7950     * @hide
7951     */
7952    public int getAccessibilitySelectionStart() {
7953        return mAccessibilityCursorPosition;
7954    }
7955
7956    /**
7957     * @hide
7958     */
7959    public int getAccessibilitySelectionEnd() {
7960        return getAccessibilitySelectionStart();
7961    }
7962
7963    /**
7964     * @hide
7965     */
7966    public void setAccessibilitySelection(int start, int end) {
7967        if (start ==  end && end == mAccessibilityCursorPosition) {
7968            return;
7969        }
7970        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7971            mAccessibilityCursorPosition = start;
7972        } else {
7973            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7974        }
7975        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7976    }
7977
7978    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7979            int fromIndex, int toIndex) {
7980        if (mParent == null) {
7981            return;
7982        }
7983        AccessibilityEvent event = AccessibilityEvent.obtain(
7984                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7985        onInitializeAccessibilityEvent(event);
7986        onPopulateAccessibilityEvent(event);
7987        event.setFromIndex(fromIndex);
7988        event.setToIndex(toIndex);
7989        event.setAction(action);
7990        event.setMovementGranularity(granularity);
7991        mParent.requestSendAccessibilityEvent(this, event);
7992    }
7993
7994    /**
7995     * @hide
7996     */
7997    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7998        switch (granularity) {
7999            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8000                CharSequence text = getIterableTextForAccessibility();
8001                if (text != null && text.length() > 0) {
8002                    CharacterTextSegmentIterator iterator =
8003                        CharacterTextSegmentIterator.getInstance(
8004                                mContext.getResources().getConfiguration().locale);
8005                    iterator.initialize(text.toString());
8006                    return iterator;
8007                }
8008            } break;
8009            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8010                CharSequence text = getIterableTextForAccessibility();
8011                if (text != null && text.length() > 0) {
8012                    WordTextSegmentIterator iterator =
8013                        WordTextSegmentIterator.getInstance(
8014                                mContext.getResources().getConfiguration().locale);
8015                    iterator.initialize(text.toString());
8016                    return iterator;
8017                }
8018            } break;
8019            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8020                CharSequence text = getIterableTextForAccessibility();
8021                if (text != null && text.length() > 0) {
8022                    ParagraphTextSegmentIterator iterator =
8023                        ParagraphTextSegmentIterator.getInstance();
8024                    iterator.initialize(text.toString());
8025                    return iterator;
8026                }
8027            } break;
8028        }
8029        return null;
8030    }
8031
8032    /**
8033     * @hide
8034     */
8035    public void dispatchStartTemporaryDetach() {
8036        onStartTemporaryDetach();
8037    }
8038
8039    /**
8040     * This is called when a container is going to temporarily detach a child, with
8041     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8042     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8043     * {@link #onDetachedFromWindow()} when the container is done.
8044     */
8045    public void onStartTemporaryDetach() {
8046        removeUnsetPressCallback();
8047        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8048    }
8049
8050    /**
8051     * @hide
8052     */
8053    public void dispatchFinishTemporaryDetach() {
8054        onFinishTemporaryDetach();
8055    }
8056
8057    /**
8058     * Called after {@link #onStartTemporaryDetach} when the container is done
8059     * changing the view.
8060     */
8061    public void onFinishTemporaryDetach() {
8062    }
8063
8064    /**
8065     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8066     * for this view's window.  Returns null if the view is not currently attached
8067     * to the window.  Normally you will not need to use this directly, but
8068     * just use the standard high-level event callbacks like
8069     * {@link #onKeyDown(int, KeyEvent)}.
8070     */
8071    public KeyEvent.DispatcherState getKeyDispatcherState() {
8072        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8073    }
8074
8075    /**
8076     * Dispatch a key event before it is processed by any input method
8077     * associated with the view hierarchy.  This can be used to intercept
8078     * key events in special situations before the IME consumes them; a
8079     * typical example would be handling the BACK key to update the application's
8080     * UI instead of allowing the IME to see it and close itself.
8081     *
8082     * @param event The key event to be dispatched.
8083     * @return True if the event was handled, false otherwise.
8084     */
8085    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8086        return onKeyPreIme(event.getKeyCode(), event);
8087    }
8088
8089    /**
8090     * Dispatch a key event to the next view on the focus path. This path runs
8091     * from the top of the view tree down to the currently focused view. If this
8092     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8093     * the next node down the focus path. This method also fires any key
8094     * listeners.
8095     *
8096     * @param event The key event to be dispatched.
8097     * @return True if the event was handled, false otherwise.
8098     */
8099    public boolean dispatchKeyEvent(KeyEvent event) {
8100        if (mInputEventConsistencyVerifier != null) {
8101            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8102        }
8103
8104        // Give any attached key listener a first crack at the event.
8105        //noinspection SimplifiableIfStatement
8106        ListenerInfo li = mListenerInfo;
8107        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8108                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8109            return true;
8110        }
8111
8112        if (event.dispatch(this, mAttachInfo != null
8113                ? mAttachInfo.mKeyDispatchState : null, this)) {
8114            return true;
8115        }
8116
8117        if (mInputEventConsistencyVerifier != null) {
8118            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8119        }
8120        return false;
8121    }
8122
8123    /**
8124     * Dispatches a key shortcut event.
8125     *
8126     * @param event The key event to be dispatched.
8127     * @return True if the event was handled by the view, false otherwise.
8128     */
8129    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8130        return onKeyShortcut(event.getKeyCode(), event);
8131    }
8132
8133    /**
8134     * Pass the touch screen motion event down to the target view, or this
8135     * view if it is the target.
8136     *
8137     * @param event The motion event to be dispatched.
8138     * @return True if the event was handled by the view, false otherwise.
8139     */
8140    public boolean dispatchTouchEvent(MotionEvent event) {
8141        boolean result = false;
8142
8143        if (mInputEventConsistencyVerifier != null) {
8144            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8145        }
8146
8147        final int actionMasked = event.getActionMasked();
8148        if (actionMasked == MotionEvent.ACTION_DOWN) {
8149            // Defensive cleanup for new gesture
8150            stopNestedScroll();
8151        }
8152
8153        if (onFilterTouchEventForSecurity(event)) {
8154            //noinspection SimplifiableIfStatement
8155            ListenerInfo li = mListenerInfo;
8156            if (li != null && li.mOnTouchListener != null
8157                    && (mViewFlags & ENABLED_MASK) == ENABLED
8158                    && li.mOnTouchListener.onTouch(this, event)) {
8159                result = true;
8160            }
8161
8162            if (!result && onTouchEvent(event)) {
8163                result = true;
8164            }
8165        }
8166
8167        if (!result && mInputEventConsistencyVerifier != null) {
8168            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8169        }
8170
8171        // Clean up after nested scrolls if this is the end of a gesture;
8172        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8173        // of the gesture.
8174        if (actionMasked == MotionEvent.ACTION_UP ||
8175                actionMasked == MotionEvent.ACTION_CANCEL ||
8176                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8177            stopNestedScroll();
8178        }
8179
8180        return result;
8181    }
8182
8183    /**
8184     * Filter the touch event to apply security policies.
8185     *
8186     * @param event The motion event to be filtered.
8187     * @return True if the event should be dispatched, false if the event should be dropped.
8188     *
8189     * @see #getFilterTouchesWhenObscured
8190     */
8191    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8192        //noinspection RedundantIfStatement
8193        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8194                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8195            // Window is obscured, drop this touch.
8196            return false;
8197        }
8198        return true;
8199    }
8200
8201    /**
8202     * Pass a trackball motion event down to the focused view.
8203     *
8204     * @param event The motion event to be dispatched.
8205     * @return True if the event was handled by the view, false otherwise.
8206     */
8207    public boolean dispatchTrackballEvent(MotionEvent event) {
8208        if (mInputEventConsistencyVerifier != null) {
8209            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8210        }
8211
8212        return onTrackballEvent(event);
8213    }
8214
8215    /**
8216     * Dispatch a generic motion event.
8217     * <p>
8218     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8219     * are delivered to the view under the pointer.  All other generic motion events are
8220     * delivered to the focused view.  Hover events are handled specially and are delivered
8221     * to {@link #onHoverEvent(MotionEvent)}.
8222     * </p>
8223     *
8224     * @param event The motion event to be dispatched.
8225     * @return True if the event was handled by the view, false otherwise.
8226     */
8227    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8228        if (mInputEventConsistencyVerifier != null) {
8229            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8230        }
8231
8232        final int source = event.getSource();
8233        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8234            final int action = event.getAction();
8235            if (action == MotionEvent.ACTION_HOVER_ENTER
8236                    || action == MotionEvent.ACTION_HOVER_MOVE
8237                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8238                if (dispatchHoverEvent(event)) {
8239                    return true;
8240                }
8241            } else if (dispatchGenericPointerEvent(event)) {
8242                return true;
8243            }
8244        } else if (dispatchGenericFocusedEvent(event)) {
8245            return true;
8246        }
8247
8248        if (dispatchGenericMotionEventInternal(event)) {
8249            return true;
8250        }
8251
8252        if (mInputEventConsistencyVerifier != null) {
8253            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8254        }
8255        return false;
8256    }
8257
8258    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8259        //noinspection SimplifiableIfStatement
8260        ListenerInfo li = mListenerInfo;
8261        if (li != null && li.mOnGenericMotionListener != null
8262                && (mViewFlags & ENABLED_MASK) == ENABLED
8263                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8264            return true;
8265        }
8266
8267        if (onGenericMotionEvent(event)) {
8268            return true;
8269        }
8270
8271        if (mInputEventConsistencyVerifier != null) {
8272            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8273        }
8274        return false;
8275    }
8276
8277    /**
8278     * Dispatch a hover event.
8279     * <p>
8280     * Do not call this method directly.
8281     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8282     * </p>
8283     *
8284     * @param event The motion event to be dispatched.
8285     * @return True if the event was handled by the view, false otherwise.
8286     */
8287    protected boolean dispatchHoverEvent(MotionEvent event) {
8288        ListenerInfo li = mListenerInfo;
8289        //noinspection SimplifiableIfStatement
8290        if (li != null && li.mOnHoverListener != null
8291                && (mViewFlags & ENABLED_MASK) == ENABLED
8292                && li.mOnHoverListener.onHover(this, event)) {
8293            return true;
8294        }
8295
8296        return onHoverEvent(event);
8297    }
8298
8299    /**
8300     * Returns true if the view has a child to which it has recently sent
8301     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8302     * it does not have a hovered child, then it must be the innermost hovered view.
8303     * @hide
8304     */
8305    protected boolean hasHoveredChild() {
8306        return false;
8307    }
8308
8309    /**
8310     * Dispatch a generic motion event to the view under the first pointer.
8311     * <p>
8312     * Do not call this method directly.
8313     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8314     * </p>
8315     *
8316     * @param event The motion event to be dispatched.
8317     * @return True if the event was handled by the view, false otherwise.
8318     */
8319    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8320        return false;
8321    }
8322
8323    /**
8324     * Dispatch a generic motion event to the currently focused view.
8325     * <p>
8326     * Do not call this method directly.
8327     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8328     * </p>
8329     *
8330     * @param event The motion event to be dispatched.
8331     * @return True if the event was handled by the view, false otherwise.
8332     */
8333    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8334        return false;
8335    }
8336
8337    /**
8338     * Dispatch a pointer event.
8339     * <p>
8340     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8341     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8342     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8343     * and should not be expected to handle other pointing device features.
8344     * </p>
8345     *
8346     * @param event The motion event to be dispatched.
8347     * @return True if the event was handled by the view, false otherwise.
8348     * @hide
8349     */
8350    public final boolean dispatchPointerEvent(MotionEvent event) {
8351        if (event.isTouchEvent()) {
8352            return dispatchTouchEvent(event);
8353        } else {
8354            return dispatchGenericMotionEvent(event);
8355        }
8356    }
8357
8358    /**
8359     * Called when the window containing this view gains or loses window focus.
8360     * ViewGroups should override to route to their children.
8361     *
8362     * @param hasFocus True if the window containing this view now has focus,
8363     *        false otherwise.
8364     */
8365    public void dispatchWindowFocusChanged(boolean hasFocus) {
8366        onWindowFocusChanged(hasFocus);
8367    }
8368
8369    /**
8370     * Called when the window containing this view gains or loses focus.  Note
8371     * that this is separate from view focus: to receive key events, both
8372     * your view and its window must have focus.  If a window is displayed
8373     * on top of yours that takes input focus, then your own window will lose
8374     * focus but the view focus will remain unchanged.
8375     *
8376     * @param hasWindowFocus True if the window containing this view now has
8377     *        focus, false otherwise.
8378     */
8379    public void onWindowFocusChanged(boolean hasWindowFocus) {
8380        InputMethodManager imm = InputMethodManager.peekInstance();
8381        if (!hasWindowFocus) {
8382            if (isPressed()) {
8383                setPressed(false);
8384            }
8385            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8386                imm.focusOut(this);
8387            }
8388            removeLongPressCallback();
8389            removeTapCallback();
8390            onFocusLost();
8391        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8392            imm.focusIn(this);
8393        }
8394        refreshDrawableState();
8395    }
8396
8397    /**
8398     * Returns true if this view is in a window that currently has window focus.
8399     * Note that this is not the same as the view itself having focus.
8400     *
8401     * @return True if this view is in a window that currently has window focus.
8402     */
8403    public boolean hasWindowFocus() {
8404        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8405    }
8406
8407    /**
8408     * Dispatch a view visibility change down the view hierarchy.
8409     * ViewGroups should override to route to their children.
8410     * @param changedView The view whose visibility changed. Could be 'this' or
8411     * an ancestor view.
8412     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8413     * {@link #INVISIBLE} or {@link #GONE}.
8414     */
8415    protected void dispatchVisibilityChanged(@NonNull View changedView,
8416            @Visibility int visibility) {
8417        onVisibilityChanged(changedView, visibility);
8418    }
8419
8420    /**
8421     * Called when the visibility of the view or an ancestor of the view is changed.
8422     * @param changedView The view whose visibility changed. Could be 'this' or
8423     * an ancestor view.
8424     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8425     * {@link #INVISIBLE} or {@link #GONE}.
8426     */
8427    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8428        if (visibility == VISIBLE) {
8429            if (mAttachInfo != null) {
8430                initialAwakenScrollBars();
8431            } else {
8432                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8433            }
8434        }
8435    }
8436
8437    /**
8438     * Dispatch a hint about whether this view is displayed. For instance, when
8439     * a View moves out of the screen, it might receives a display hint indicating
8440     * the view is not displayed. Applications should not <em>rely</em> on this hint
8441     * as there is no guarantee that they will receive one.
8442     *
8443     * @param hint A hint about whether or not this view is displayed:
8444     * {@link #VISIBLE} or {@link #INVISIBLE}.
8445     */
8446    public void dispatchDisplayHint(@Visibility int hint) {
8447        onDisplayHint(hint);
8448    }
8449
8450    /**
8451     * Gives this view a hint about whether is displayed or not. For instance, when
8452     * a View moves out of the screen, it might receives a display hint indicating
8453     * the view is not displayed. Applications should not <em>rely</em> on this hint
8454     * as there is no guarantee that they will receive one.
8455     *
8456     * @param hint A hint about whether or not this view is displayed:
8457     * {@link #VISIBLE} or {@link #INVISIBLE}.
8458     */
8459    protected void onDisplayHint(@Visibility int hint) {
8460    }
8461
8462    /**
8463     * Dispatch a window visibility change down the view hierarchy.
8464     * ViewGroups should override to route to their children.
8465     *
8466     * @param visibility The new visibility of the window.
8467     *
8468     * @see #onWindowVisibilityChanged(int)
8469     */
8470    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8471        onWindowVisibilityChanged(visibility);
8472    }
8473
8474    /**
8475     * Called when the window containing has change its visibility
8476     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8477     * that this tells you whether or not your window is being made visible
8478     * to the window manager; this does <em>not</em> tell you whether or not
8479     * your window is obscured by other windows on the screen, even if it
8480     * is itself visible.
8481     *
8482     * @param visibility The new visibility of the window.
8483     */
8484    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8485        if (visibility == VISIBLE) {
8486            initialAwakenScrollBars();
8487        }
8488    }
8489
8490    /**
8491     * Returns the current visibility of the window this view is attached to
8492     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8493     *
8494     * @return Returns the current visibility of the view's window.
8495     */
8496    @Visibility
8497    public int getWindowVisibility() {
8498        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8499    }
8500
8501    /**
8502     * Retrieve the overall visible display size in which the window this view is
8503     * attached to has been positioned in.  This takes into account screen
8504     * decorations above the window, for both cases where the window itself
8505     * is being position inside of them or the window is being placed under
8506     * then and covered insets are used for the window to position its content
8507     * inside.  In effect, this tells you the available area where content can
8508     * be placed and remain visible to users.
8509     *
8510     * <p>This function requires an IPC back to the window manager to retrieve
8511     * the requested information, so should not be used in performance critical
8512     * code like drawing.
8513     *
8514     * @param outRect Filled in with the visible display frame.  If the view
8515     * is not attached to a window, this is simply the raw display size.
8516     */
8517    public void getWindowVisibleDisplayFrame(Rect outRect) {
8518        if (mAttachInfo != null) {
8519            try {
8520                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8521            } catch (RemoteException e) {
8522                return;
8523            }
8524            // XXX This is really broken, and probably all needs to be done
8525            // in the window manager, and we need to know more about whether
8526            // we want the area behind or in front of the IME.
8527            final Rect insets = mAttachInfo.mVisibleInsets;
8528            outRect.left += insets.left;
8529            outRect.top += insets.top;
8530            outRect.right -= insets.right;
8531            outRect.bottom -= insets.bottom;
8532            return;
8533        }
8534        // The view is not attached to a display so we don't have a context.
8535        // Make a best guess about the display size.
8536        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8537        d.getRectSize(outRect);
8538    }
8539
8540    /**
8541     * Dispatch a notification about a resource configuration change down
8542     * the view hierarchy.
8543     * ViewGroups should override to route to their children.
8544     *
8545     * @param newConfig The new resource configuration.
8546     *
8547     * @see #onConfigurationChanged(android.content.res.Configuration)
8548     */
8549    public void dispatchConfigurationChanged(Configuration newConfig) {
8550        onConfigurationChanged(newConfig);
8551    }
8552
8553    /**
8554     * Called when the current configuration of the resources being used
8555     * by the application have changed.  You can use this to decide when
8556     * to reload resources that can changed based on orientation and other
8557     * configuration characterstics.  You only need to use this if you are
8558     * not relying on the normal {@link android.app.Activity} mechanism of
8559     * recreating the activity instance upon a configuration change.
8560     *
8561     * @param newConfig The new resource configuration.
8562     */
8563    protected void onConfigurationChanged(Configuration newConfig) {
8564    }
8565
8566    /**
8567     * Private function to aggregate all per-view attributes in to the view
8568     * root.
8569     */
8570    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8571        performCollectViewAttributes(attachInfo, visibility);
8572    }
8573
8574    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8575        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8576            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8577                attachInfo.mKeepScreenOn = true;
8578            }
8579            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8580            ListenerInfo li = mListenerInfo;
8581            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8582                attachInfo.mHasSystemUiListeners = true;
8583            }
8584        }
8585    }
8586
8587    void needGlobalAttributesUpdate(boolean force) {
8588        final AttachInfo ai = mAttachInfo;
8589        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8590            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8591                    || ai.mHasSystemUiListeners) {
8592                ai.mRecomputeGlobalAttributes = true;
8593            }
8594        }
8595    }
8596
8597    /**
8598     * Returns whether the device is currently in touch mode.  Touch mode is entered
8599     * once the user begins interacting with the device by touch, and affects various
8600     * things like whether focus is always visible to the user.
8601     *
8602     * @return Whether the device is in touch mode.
8603     */
8604    @ViewDebug.ExportedProperty
8605    public boolean isInTouchMode() {
8606        if (mAttachInfo != null) {
8607            return mAttachInfo.mInTouchMode;
8608        } else {
8609            return ViewRootImpl.isInTouchMode();
8610        }
8611    }
8612
8613    /**
8614     * Returns the context the view is running in, through which it can
8615     * access the current theme, resources, etc.
8616     *
8617     * @return The view's Context.
8618     */
8619    @ViewDebug.CapturedViewProperty
8620    public final Context getContext() {
8621        return mContext;
8622    }
8623
8624    /**
8625     * Handle a key event before it is processed by any input method
8626     * associated with the view hierarchy.  This can be used to intercept
8627     * key events in special situations before the IME consumes them; a
8628     * typical example would be handling the BACK key to update the application's
8629     * UI instead of allowing the IME to see it and close itself.
8630     *
8631     * @param keyCode The value in event.getKeyCode().
8632     * @param event Description of the key event.
8633     * @return If you handled the event, return true. If you want to allow the
8634     *         event to be handled by the next receiver, return false.
8635     */
8636    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8637        return false;
8638    }
8639
8640    /**
8641     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8642     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8643     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8644     * is released, if the view is enabled and clickable.
8645     *
8646     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8647     * although some may elect to do so in some situations. Do not rely on this to
8648     * catch software key presses.
8649     *
8650     * @param keyCode A key code that represents the button pressed, from
8651     *                {@link android.view.KeyEvent}.
8652     * @param event   The KeyEvent object that defines the button action.
8653     */
8654    public boolean onKeyDown(int keyCode, KeyEvent event) {
8655        boolean result = false;
8656
8657        if (KeyEvent.isConfirmKey(keyCode)) {
8658            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8659                return true;
8660            }
8661            // Long clickable items don't necessarily have to be clickable
8662            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8663                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8664                    (event.getRepeatCount() == 0)) {
8665                setPressed(true);
8666                checkForLongClick(0);
8667                return true;
8668            }
8669        }
8670        return result;
8671    }
8672
8673    /**
8674     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8675     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8676     * the event).
8677     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8678     * although some may elect to do so in some situations. Do not rely on this to
8679     * catch software key presses.
8680     */
8681    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8682        return false;
8683    }
8684
8685    /**
8686     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8687     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8688     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8689     * {@link KeyEvent#KEYCODE_ENTER} is released.
8690     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8691     * although some may elect to do so in some situations. Do not rely on this to
8692     * catch software key presses.
8693     *
8694     * @param keyCode A key code that represents the button pressed, from
8695     *                {@link android.view.KeyEvent}.
8696     * @param event   The KeyEvent object that defines the button action.
8697     */
8698    public boolean onKeyUp(int keyCode, KeyEvent event) {
8699        if (KeyEvent.isConfirmKey(keyCode)) {
8700            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8701                return true;
8702            }
8703            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8704                setPressed(false);
8705
8706                if (!mHasPerformedLongPress) {
8707                    // This is a tap, so remove the longpress check
8708                    removeLongPressCallback();
8709                    return performClick();
8710                }
8711            }
8712        }
8713        return false;
8714    }
8715
8716    /**
8717     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8718     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8719     * the event).
8720     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8721     * although some may elect to do so in some situations. Do not rely on this to
8722     * catch software key presses.
8723     *
8724     * @param keyCode     A key code that represents the button pressed, from
8725     *                    {@link android.view.KeyEvent}.
8726     * @param repeatCount The number of times the action was made.
8727     * @param event       The KeyEvent object that defines the button action.
8728     */
8729    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8730        return false;
8731    }
8732
8733    /**
8734     * Called on the focused view when a key shortcut event is not handled.
8735     * Override this method to implement local key shortcuts for the View.
8736     * Key shortcuts can also be implemented by setting the
8737     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8738     *
8739     * @param keyCode The value in event.getKeyCode().
8740     * @param event Description of the key event.
8741     * @return If you handled the event, return true. If you want to allow the
8742     *         event to be handled by the next receiver, return false.
8743     */
8744    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8745        return false;
8746    }
8747
8748    /**
8749     * Check whether the called view is a text editor, in which case it
8750     * would make sense to automatically display a soft input window for
8751     * it.  Subclasses should override this if they implement
8752     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8753     * a call on that method would return a non-null InputConnection, and
8754     * they are really a first-class editor that the user would normally
8755     * start typing on when the go into a window containing your view.
8756     *
8757     * <p>The default implementation always returns false.  This does
8758     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8759     * will not be called or the user can not otherwise perform edits on your
8760     * view; it is just a hint to the system that this is not the primary
8761     * purpose of this view.
8762     *
8763     * @return Returns true if this view is a text editor, else false.
8764     */
8765    public boolean onCheckIsTextEditor() {
8766        return false;
8767    }
8768
8769    /**
8770     * Create a new InputConnection for an InputMethod to interact
8771     * with the view.  The default implementation returns null, since it doesn't
8772     * support input methods.  You can override this to implement such support.
8773     * This is only needed for views that take focus and text input.
8774     *
8775     * <p>When implementing this, you probably also want to implement
8776     * {@link #onCheckIsTextEditor()} to indicate you will return a
8777     * non-null InputConnection.</p>
8778     *
8779     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8780     * object correctly and in its entirety, so that the connected IME can rely
8781     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8782     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8783     * must be filled in with the correct cursor position for IMEs to work correctly
8784     * with your application.</p>
8785     *
8786     * @param outAttrs Fill in with attribute information about the connection.
8787     */
8788    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8789        return null;
8790    }
8791
8792    /**
8793     * Called by the {@link android.view.inputmethod.InputMethodManager}
8794     * when a view who is not the current
8795     * input connection target is trying to make a call on the manager.  The
8796     * default implementation returns false; you can override this to return
8797     * true for certain views if you are performing InputConnection proxying
8798     * to them.
8799     * @param view The View that is making the InputMethodManager call.
8800     * @return Return true to allow the call, false to reject.
8801     */
8802    public boolean checkInputConnectionProxy(View view) {
8803        return false;
8804    }
8805
8806    /**
8807     * Show the context menu for this view. It is not safe to hold on to the
8808     * menu after returning from this method.
8809     *
8810     * You should normally not overload this method. Overload
8811     * {@link #onCreateContextMenu(ContextMenu)} or define an
8812     * {@link OnCreateContextMenuListener} to add items to the context menu.
8813     *
8814     * @param menu The context menu to populate
8815     */
8816    public void createContextMenu(ContextMenu menu) {
8817        ContextMenuInfo menuInfo = getContextMenuInfo();
8818
8819        // Sets the current menu info so all items added to menu will have
8820        // my extra info set.
8821        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8822
8823        onCreateContextMenu(menu);
8824        ListenerInfo li = mListenerInfo;
8825        if (li != null && li.mOnCreateContextMenuListener != null) {
8826            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8827        }
8828
8829        // Clear the extra information so subsequent items that aren't mine don't
8830        // have my extra info.
8831        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8832
8833        if (mParent != null) {
8834            mParent.createContextMenu(menu);
8835        }
8836    }
8837
8838    /**
8839     * Views should implement this if they have extra information to associate
8840     * with the context menu. The return result is supplied as a parameter to
8841     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8842     * callback.
8843     *
8844     * @return Extra information about the item for which the context menu
8845     *         should be shown. This information will vary across different
8846     *         subclasses of View.
8847     */
8848    protected ContextMenuInfo getContextMenuInfo() {
8849        return null;
8850    }
8851
8852    /**
8853     * Views should implement this if the view itself is going to add items to
8854     * the context menu.
8855     *
8856     * @param menu the context menu to populate
8857     */
8858    protected void onCreateContextMenu(ContextMenu menu) {
8859    }
8860
8861    /**
8862     * Implement this method to handle trackball motion events.  The
8863     * <em>relative</em> movement of the trackball since the last event
8864     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8865     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8866     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8867     * they will often be fractional values, representing the more fine-grained
8868     * movement information available from a trackball).
8869     *
8870     * @param event The motion event.
8871     * @return True if the event was handled, false otherwise.
8872     */
8873    public boolean onTrackballEvent(MotionEvent event) {
8874        return false;
8875    }
8876
8877    /**
8878     * Implement this method to handle generic motion events.
8879     * <p>
8880     * Generic motion events describe joystick movements, mouse hovers, track pad
8881     * touches, scroll wheel movements and other input events.  The
8882     * {@link MotionEvent#getSource() source} of the motion event specifies
8883     * the class of input that was received.  Implementations of this method
8884     * must examine the bits in the source before processing the event.
8885     * The following code example shows how this is done.
8886     * </p><p>
8887     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8888     * are delivered to the view under the pointer.  All other generic motion events are
8889     * delivered to the focused view.
8890     * </p>
8891     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8892     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8893     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8894     *             // process the joystick movement...
8895     *             return true;
8896     *         }
8897     *     }
8898     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8899     *         switch (event.getAction()) {
8900     *             case MotionEvent.ACTION_HOVER_MOVE:
8901     *                 // process the mouse hover movement...
8902     *                 return true;
8903     *             case MotionEvent.ACTION_SCROLL:
8904     *                 // process the scroll wheel movement...
8905     *                 return true;
8906     *         }
8907     *     }
8908     *     return super.onGenericMotionEvent(event);
8909     * }</pre>
8910     *
8911     * @param event The generic motion event being processed.
8912     * @return True if the event was handled, false otherwise.
8913     */
8914    public boolean onGenericMotionEvent(MotionEvent event) {
8915        return false;
8916    }
8917
8918    /**
8919     * Implement this method to handle hover events.
8920     * <p>
8921     * This method is called whenever a pointer is hovering into, over, or out of the
8922     * bounds of a view and the view is not currently being touched.
8923     * Hover events are represented as pointer events with action
8924     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8925     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8926     * </p>
8927     * <ul>
8928     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8929     * when the pointer enters the bounds of the view.</li>
8930     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8931     * when the pointer has already entered the bounds of the view and has moved.</li>
8932     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8933     * when the pointer has exited the bounds of the view or when the pointer is
8934     * about to go down due to a button click, tap, or similar user action that
8935     * causes the view to be touched.</li>
8936     * </ul>
8937     * <p>
8938     * The view should implement this method to return true to indicate that it is
8939     * handling the hover event, such as by changing its drawable state.
8940     * </p><p>
8941     * The default implementation calls {@link #setHovered} to update the hovered state
8942     * of the view when a hover enter or hover exit event is received, if the view
8943     * is enabled and is clickable.  The default implementation also sends hover
8944     * accessibility events.
8945     * </p>
8946     *
8947     * @param event The motion event that describes the hover.
8948     * @return True if the view handled the hover event.
8949     *
8950     * @see #isHovered
8951     * @see #setHovered
8952     * @see #onHoverChanged
8953     */
8954    public boolean onHoverEvent(MotionEvent event) {
8955        // The root view may receive hover (or touch) events that are outside the bounds of
8956        // the window.  This code ensures that we only send accessibility events for
8957        // hovers that are actually within the bounds of the root view.
8958        final int action = event.getActionMasked();
8959        if (!mSendingHoverAccessibilityEvents) {
8960            if ((action == MotionEvent.ACTION_HOVER_ENTER
8961                    || action == MotionEvent.ACTION_HOVER_MOVE)
8962                    && !hasHoveredChild()
8963                    && pointInView(event.getX(), event.getY())) {
8964                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8965                mSendingHoverAccessibilityEvents = true;
8966            }
8967        } else {
8968            if (action == MotionEvent.ACTION_HOVER_EXIT
8969                    || (action == MotionEvent.ACTION_MOVE
8970                            && !pointInView(event.getX(), event.getY()))) {
8971                mSendingHoverAccessibilityEvents = false;
8972                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8973            }
8974        }
8975
8976        if (isHoverable()) {
8977            switch (action) {
8978                case MotionEvent.ACTION_HOVER_ENTER:
8979                    setHovered(true);
8980                    break;
8981                case MotionEvent.ACTION_HOVER_EXIT:
8982                    setHovered(false);
8983                    break;
8984            }
8985
8986            // Dispatch the event to onGenericMotionEvent before returning true.
8987            // This is to provide compatibility with existing applications that
8988            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8989            // break because of the new default handling for hoverable views
8990            // in onHoverEvent.
8991            // Note that onGenericMotionEvent will be called by default when
8992            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8993            dispatchGenericMotionEventInternal(event);
8994            // The event was already handled by calling setHovered(), so always
8995            // return true.
8996            return true;
8997        }
8998
8999        return false;
9000    }
9001
9002    /**
9003     * Returns true if the view should handle {@link #onHoverEvent}
9004     * by calling {@link #setHovered} to change its hovered state.
9005     *
9006     * @return True if the view is hoverable.
9007     */
9008    private boolean isHoverable() {
9009        final int viewFlags = mViewFlags;
9010        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9011            return false;
9012        }
9013
9014        return (viewFlags & CLICKABLE) == CLICKABLE
9015                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9016    }
9017
9018    /**
9019     * Returns true if the view is currently hovered.
9020     *
9021     * @return True if the view is currently hovered.
9022     *
9023     * @see #setHovered
9024     * @see #onHoverChanged
9025     */
9026    @ViewDebug.ExportedProperty
9027    public boolean isHovered() {
9028        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9029    }
9030
9031    /**
9032     * Sets whether the view is currently hovered.
9033     * <p>
9034     * Calling this method also changes the drawable state of the view.  This
9035     * enables the view to react to hover by using different drawable resources
9036     * to change its appearance.
9037     * </p><p>
9038     * The {@link #onHoverChanged} method is called when the hovered state changes.
9039     * </p>
9040     *
9041     * @param hovered True if the view is hovered.
9042     *
9043     * @see #isHovered
9044     * @see #onHoverChanged
9045     */
9046    public void setHovered(boolean hovered) {
9047        if (hovered) {
9048            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9049                mPrivateFlags |= PFLAG_HOVERED;
9050                refreshDrawableState();
9051                onHoverChanged(true);
9052            }
9053        } else {
9054            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9055                mPrivateFlags &= ~PFLAG_HOVERED;
9056                refreshDrawableState();
9057                onHoverChanged(false);
9058            }
9059        }
9060    }
9061
9062    /**
9063     * Implement this method to handle hover state changes.
9064     * <p>
9065     * This method is called whenever the hover state changes as a result of a
9066     * call to {@link #setHovered}.
9067     * </p>
9068     *
9069     * @param hovered The current hover state, as returned by {@link #isHovered}.
9070     *
9071     * @see #isHovered
9072     * @see #setHovered
9073     */
9074    public void onHoverChanged(boolean hovered) {
9075    }
9076
9077    /**
9078     * Implement this method to handle touch screen motion events.
9079     * <p>
9080     * If this method is used to detect click actions, it is recommended that
9081     * the actions be performed by implementing and calling
9082     * {@link #performClick()}. This will ensure consistent system behavior,
9083     * including:
9084     * <ul>
9085     * <li>obeying click sound preferences
9086     * <li>dispatching OnClickListener calls
9087     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9088     * accessibility features are enabled
9089     * </ul>
9090     *
9091     * @param event The motion event.
9092     * @return True if the event was handled, false otherwise.
9093     */
9094    public boolean onTouchEvent(MotionEvent event) {
9095        final float x = event.getX();
9096        final float y = event.getY();
9097        final int viewFlags = mViewFlags;
9098
9099        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9100            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9101                setPressed(false);
9102            }
9103            // A disabled view that is clickable still consumes the touch
9104            // events, it just doesn't respond to them.
9105            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9106                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9107        }
9108
9109        if (mTouchDelegate != null) {
9110            if (mTouchDelegate.onTouchEvent(event)) {
9111                return true;
9112            }
9113        }
9114
9115        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9116                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9117            switch (event.getAction()) {
9118                case MotionEvent.ACTION_UP:
9119                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9120                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9121                        // take focus if we don't have it already and we should in
9122                        // touch mode.
9123                        boolean focusTaken = false;
9124                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9125                            focusTaken = requestFocus();
9126                        }
9127
9128                        if (prepressed) {
9129                            // The button is being released before we actually
9130                            // showed it as pressed.  Make it show the pressed
9131                            // state now (before scheduling the click) to ensure
9132                            // the user sees it.
9133                            setPressed(true, x, y);
9134                       }
9135
9136                        if (!mHasPerformedLongPress) {
9137                            // This is a tap, so remove the longpress check
9138                            removeLongPressCallback();
9139
9140                            // Only perform take click actions if we were in the pressed state
9141                            if (!focusTaken) {
9142                                // Use a Runnable and post this rather than calling
9143                                // performClick directly. This lets other visual state
9144                                // of the view update before click actions start.
9145                                if (mPerformClick == null) {
9146                                    mPerformClick = new PerformClick();
9147                                }
9148                                if (!post(mPerformClick)) {
9149                                    performClick();
9150                                }
9151                            }
9152                        }
9153
9154                        if (mUnsetPressedState == null) {
9155                            mUnsetPressedState = new UnsetPressedState();
9156                        }
9157
9158                        if (prepressed) {
9159                            postDelayed(mUnsetPressedState,
9160                                    ViewConfiguration.getPressedStateDuration());
9161                        } else if (!post(mUnsetPressedState)) {
9162                            // If the post failed, unpress right now
9163                            mUnsetPressedState.run();
9164                        }
9165
9166                        removeTapCallback();
9167                    }
9168                    break;
9169
9170                case MotionEvent.ACTION_DOWN:
9171                    mHasPerformedLongPress = false;
9172
9173                    if (performButtonActionOnTouchDown(event)) {
9174                        break;
9175                    }
9176
9177                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9178                    boolean isInScrollingContainer = isInScrollingContainer();
9179
9180                    // For views inside a scrolling container, delay the pressed feedback for
9181                    // a short period in case this is a scroll.
9182                    if (isInScrollingContainer) {
9183                        mPrivateFlags |= PFLAG_PREPRESSED;
9184                        if (mPendingCheckForTap == null) {
9185                            mPendingCheckForTap = new CheckForTap();
9186                        }
9187                        mPendingCheckForTap.x = event.getX();
9188                        mPendingCheckForTap.y = event.getY();
9189                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9190                    } else {
9191                        // Not inside a scrolling container, so show the feedback right away
9192                        setPressed(true, x, y);
9193                        checkForLongClick(0);
9194                    }
9195                    break;
9196
9197                case MotionEvent.ACTION_CANCEL:
9198                    setPressed(false);
9199                    removeTapCallback();
9200                    removeLongPressCallback();
9201                    break;
9202
9203                case MotionEvent.ACTION_MOVE:
9204                    drawableHotspotChanged(x, y);
9205
9206                    // Be lenient about moving outside of buttons
9207                    if (!pointInView(x, y, mTouchSlop)) {
9208                        // Outside button
9209                        removeTapCallback();
9210                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9211                            // Remove any future long press/tap checks
9212                            removeLongPressCallback();
9213
9214                            setPressed(false);
9215                        }
9216                    }
9217                    break;
9218            }
9219
9220            return true;
9221        }
9222
9223        return false;
9224    }
9225
9226    /**
9227     * @hide
9228     */
9229    public boolean isInScrollingContainer() {
9230        ViewParent p = getParent();
9231        while (p != null && p instanceof ViewGroup) {
9232            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9233                return true;
9234            }
9235            p = p.getParent();
9236        }
9237        return false;
9238    }
9239
9240    /**
9241     * Remove the longpress detection timer.
9242     */
9243    private void removeLongPressCallback() {
9244        if (mPendingCheckForLongPress != null) {
9245          removeCallbacks(mPendingCheckForLongPress);
9246        }
9247    }
9248
9249    /**
9250     * Remove the pending click action
9251     */
9252    private void removePerformClickCallback() {
9253        if (mPerformClick != null) {
9254            removeCallbacks(mPerformClick);
9255        }
9256    }
9257
9258    /**
9259     * Remove the prepress detection timer.
9260     */
9261    private void removeUnsetPressCallback() {
9262        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9263            setPressed(false);
9264            removeCallbacks(mUnsetPressedState);
9265        }
9266    }
9267
9268    /**
9269     * Remove the tap detection timer.
9270     */
9271    private void removeTapCallback() {
9272        if (mPendingCheckForTap != null) {
9273            mPrivateFlags &= ~PFLAG_PREPRESSED;
9274            removeCallbacks(mPendingCheckForTap);
9275        }
9276    }
9277
9278    /**
9279     * Cancels a pending long press.  Your subclass can use this if you
9280     * want the context menu to come up if the user presses and holds
9281     * at the same place, but you don't want it to come up if they press
9282     * and then move around enough to cause scrolling.
9283     */
9284    public void cancelLongPress() {
9285        removeLongPressCallback();
9286
9287        /*
9288         * The prepressed state handled by the tap callback is a display
9289         * construct, but the tap callback will post a long press callback
9290         * less its own timeout. Remove it here.
9291         */
9292        removeTapCallback();
9293    }
9294
9295    /**
9296     * Remove the pending callback for sending a
9297     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9298     */
9299    private void removeSendViewScrolledAccessibilityEventCallback() {
9300        if (mSendViewScrolledAccessibilityEvent != null) {
9301            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9302            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9303        }
9304    }
9305
9306    /**
9307     * Sets the TouchDelegate for this View.
9308     */
9309    public void setTouchDelegate(TouchDelegate delegate) {
9310        mTouchDelegate = delegate;
9311    }
9312
9313    /**
9314     * Gets the TouchDelegate for this View.
9315     */
9316    public TouchDelegate getTouchDelegate() {
9317        return mTouchDelegate;
9318    }
9319
9320    /**
9321     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9322     *
9323     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9324     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9325     * available. This method should only be called for touch events.
9326     *
9327     * <p class="note">This api is not intended for most applications. Buffered dispatch
9328     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9329     * streams will not improve your input latency. Side effects include: increased latency,
9330     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9331     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9332     * you.</p>
9333     */
9334    public final void requestUnbufferedDispatch(MotionEvent event) {
9335        final int action = event.getAction();
9336        if (mAttachInfo == null
9337                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9338                || !event.isTouchEvent()) {
9339            return;
9340        }
9341        mAttachInfo.mUnbufferedDispatchRequested = true;
9342    }
9343
9344    /**
9345     * Set flags controlling behavior of this view.
9346     *
9347     * @param flags Constant indicating the value which should be set
9348     * @param mask Constant indicating the bit range that should be changed
9349     */
9350    void setFlags(int flags, int mask) {
9351        final boolean accessibilityEnabled =
9352                AccessibilityManager.getInstance(mContext).isEnabled();
9353        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9354
9355        int old = mViewFlags;
9356        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9357
9358        int changed = mViewFlags ^ old;
9359        if (changed == 0) {
9360            return;
9361        }
9362        int privateFlags = mPrivateFlags;
9363
9364        /* Check if the FOCUSABLE bit has changed */
9365        if (((changed & FOCUSABLE_MASK) != 0) &&
9366                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9367            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9368                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9369                /* Give up focus if we are no longer focusable */
9370                clearFocus();
9371            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9372                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9373                /*
9374                 * Tell the view system that we are now available to take focus
9375                 * if no one else already has it.
9376                 */
9377                if (mParent != null) mParent.focusableViewAvailable(this);
9378            }
9379        }
9380
9381        final int newVisibility = flags & VISIBILITY_MASK;
9382        if (newVisibility == VISIBLE) {
9383            if ((changed & VISIBILITY_MASK) != 0) {
9384                /*
9385                 * If this view is becoming visible, invalidate it in case it changed while
9386                 * it was not visible. Marking it drawn ensures that the invalidation will
9387                 * go through.
9388                 */
9389                mPrivateFlags |= PFLAG_DRAWN;
9390                invalidate(true);
9391
9392                needGlobalAttributesUpdate(true);
9393
9394                // a view becoming visible is worth notifying the parent
9395                // about in case nothing has focus.  even if this specific view
9396                // isn't focusable, it may contain something that is, so let
9397                // the root view try to give this focus if nothing else does.
9398                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9399                    mParent.focusableViewAvailable(this);
9400                }
9401            }
9402        }
9403
9404        /* Check if the GONE bit has changed */
9405        if ((changed & GONE) != 0) {
9406            needGlobalAttributesUpdate(false);
9407            requestLayout();
9408
9409            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9410                if (hasFocus()) clearFocus();
9411                clearAccessibilityFocus();
9412                destroyDrawingCache();
9413                if (mParent instanceof View) {
9414                    // GONE views noop invalidation, so invalidate the parent
9415                    ((View) mParent).invalidate(true);
9416                }
9417                // Mark the view drawn to ensure that it gets invalidated properly the next
9418                // time it is visible and gets invalidated
9419                mPrivateFlags |= PFLAG_DRAWN;
9420            }
9421            if (mAttachInfo != null) {
9422                mAttachInfo.mViewVisibilityChanged = true;
9423            }
9424        }
9425
9426        /* Check if the VISIBLE bit has changed */
9427        if ((changed & INVISIBLE) != 0) {
9428            needGlobalAttributesUpdate(false);
9429            /*
9430             * If this view is becoming invisible, set the DRAWN flag so that
9431             * the next invalidate() will not be skipped.
9432             */
9433            mPrivateFlags |= PFLAG_DRAWN;
9434
9435            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9436                // root view becoming invisible shouldn't clear focus and accessibility focus
9437                if (getRootView() != this) {
9438                    if (hasFocus()) clearFocus();
9439                    clearAccessibilityFocus();
9440                }
9441            }
9442            if (mAttachInfo != null) {
9443                mAttachInfo.mViewVisibilityChanged = true;
9444            }
9445        }
9446
9447        if ((changed & VISIBILITY_MASK) != 0) {
9448            // If the view is invisible, cleanup its display list to free up resources
9449            if (newVisibility != VISIBLE && mAttachInfo != null) {
9450                cleanupDraw();
9451            }
9452
9453            if (mParent instanceof ViewGroup) {
9454                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9455                        (changed & VISIBILITY_MASK), newVisibility);
9456                ((View) mParent).invalidate(true);
9457            } else if (mParent != null) {
9458                mParent.invalidateChild(this, null);
9459            }
9460            dispatchVisibilityChanged(this, newVisibility);
9461
9462            notifySubtreeAccessibilityStateChangedIfNeeded();
9463        }
9464
9465        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9466            destroyDrawingCache();
9467        }
9468
9469        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9470            destroyDrawingCache();
9471            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9472            invalidateParentCaches();
9473        }
9474
9475        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9476            destroyDrawingCache();
9477            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9478        }
9479
9480        if ((changed & DRAW_MASK) != 0) {
9481            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9482                if (mBackground != null) {
9483                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9484                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9485                } else {
9486                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9487                }
9488            } else {
9489                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9490            }
9491            requestLayout();
9492            invalidate(true);
9493        }
9494
9495        if ((changed & KEEP_SCREEN_ON) != 0) {
9496            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9497                mParent.recomputeViewAttributes(this);
9498            }
9499        }
9500
9501        if (accessibilityEnabled) {
9502            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9503                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9504                if (oldIncludeForAccessibility != includeForAccessibility()) {
9505                    notifySubtreeAccessibilityStateChangedIfNeeded();
9506                } else {
9507                    notifyViewAccessibilityStateChangedIfNeeded(
9508                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9509                }
9510            } else if ((changed & ENABLED_MASK) != 0) {
9511                notifyViewAccessibilityStateChangedIfNeeded(
9512                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9513            }
9514        }
9515    }
9516
9517    /**
9518     * Change the view's z order in the tree, so it's on top of other sibling
9519     * views. This ordering change may affect layout, if the parent container
9520     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9521     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9522     * method should be followed by calls to {@link #requestLayout()} and
9523     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9524     * with the new child ordering.
9525     *
9526     * @see ViewGroup#bringChildToFront(View)
9527     */
9528    public void bringToFront() {
9529        if (mParent != null) {
9530            mParent.bringChildToFront(this);
9531        }
9532    }
9533
9534    /**
9535     * This is called in response to an internal scroll in this view (i.e., the
9536     * view scrolled its own contents). This is typically as a result of
9537     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9538     * called.
9539     *
9540     * @param l Current horizontal scroll origin.
9541     * @param t Current vertical scroll origin.
9542     * @param oldl Previous horizontal scroll origin.
9543     * @param oldt Previous vertical scroll origin.
9544     */
9545    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9546        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9547            postSendViewScrolledAccessibilityEventCallback();
9548        }
9549
9550        mBackgroundSizeChanged = true;
9551
9552        final AttachInfo ai = mAttachInfo;
9553        if (ai != null) {
9554            ai.mViewScrollChanged = true;
9555        }
9556    }
9557
9558    /**
9559     * Interface definition for a callback to be invoked when the layout bounds of a view
9560     * changes due to layout processing.
9561     */
9562    public interface OnLayoutChangeListener {
9563        /**
9564         * Called when the layout bounds of a view changes due to layout processing.
9565         *
9566         * @param v The view whose bounds have changed.
9567         * @param left The new value of the view's left property.
9568         * @param top The new value of the view's top property.
9569         * @param right The new value of the view's right property.
9570         * @param bottom The new value of the view's bottom property.
9571         * @param oldLeft The previous value of the view's left property.
9572         * @param oldTop The previous value of the view's top property.
9573         * @param oldRight The previous value of the view's right property.
9574         * @param oldBottom The previous value of the view's bottom property.
9575         */
9576        void onLayoutChange(View v, int left, int top, int right, int bottom,
9577            int oldLeft, int oldTop, int oldRight, int oldBottom);
9578    }
9579
9580    /**
9581     * This is called during layout when the size of this view has changed. If
9582     * you were just added to the view hierarchy, you're called with the old
9583     * values of 0.
9584     *
9585     * @param w Current width of this view.
9586     * @param h Current height of this view.
9587     * @param oldw Old width of this view.
9588     * @param oldh Old height of this view.
9589     */
9590    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9591    }
9592
9593    /**
9594     * Called by draw to draw the child views. This may be overridden
9595     * by derived classes to gain control just before its children are drawn
9596     * (but after its own view has been drawn).
9597     * @param canvas the canvas on which to draw the view
9598     */
9599    protected void dispatchDraw(Canvas canvas) {
9600
9601    }
9602
9603    /**
9604     * Gets the parent of this view. Note that the parent is a
9605     * ViewParent and not necessarily a View.
9606     *
9607     * @return Parent of this view.
9608     */
9609    public final ViewParent getParent() {
9610        return mParent;
9611    }
9612
9613    /**
9614     * Set the horizontal scrolled position of your view. This will cause a call to
9615     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9616     * invalidated.
9617     * @param value the x position to scroll to
9618     */
9619    public void setScrollX(int value) {
9620        scrollTo(value, mScrollY);
9621    }
9622
9623    /**
9624     * Set the vertical scrolled position of your view. This will cause a call to
9625     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9626     * invalidated.
9627     * @param value the y position to scroll to
9628     */
9629    public void setScrollY(int value) {
9630        scrollTo(mScrollX, value);
9631    }
9632
9633    /**
9634     * Return the scrolled left position of this view. This is the left edge of
9635     * the displayed part of your view. You do not need to draw any pixels
9636     * farther left, since those are outside of the frame of your view on
9637     * screen.
9638     *
9639     * @return The left edge of the displayed part of your view, in pixels.
9640     */
9641    public final int getScrollX() {
9642        return mScrollX;
9643    }
9644
9645    /**
9646     * Return the scrolled top position of this view. This is the top edge of
9647     * the displayed part of your view. You do not need to draw any pixels above
9648     * it, since those are outside of the frame of your view on screen.
9649     *
9650     * @return The top edge of the displayed part of your view, in pixels.
9651     */
9652    public final int getScrollY() {
9653        return mScrollY;
9654    }
9655
9656    /**
9657     * Return the width of the your view.
9658     *
9659     * @return The width of your view, in pixels.
9660     */
9661    @ViewDebug.ExportedProperty(category = "layout")
9662    public final int getWidth() {
9663        return mRight - mLeft;
9664    }
9665
9666    /**
9667     * Return the height of your view.
9668     *
9669     * @return The height of your view, in pixels.
9670     */
9671    @ViewDebug.ExportedProperty(category = "layout")
9672    public final int getHeight() {
9673        return mBottom - mTop;
9674    }
9675
9676    /**
9677     * Return the visible drawing bounds of your view. Fills in the output
9678     * rectangle with the values from getScrollX(), getScrollY(),
9679     * getWidth(), and getHeight(). These bounds do not account for any
9680     * transformation properties currently set on the view, such as
9681     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9682     *
9683     * @param outRect The (scrolled) drawing bounds of the view.
9684     */
9685    public void getDrawingRect(Rect outRect) {
9686        outRect.left = mScrollX;
9687        outRect.top = mScrollY;
9688        outRect.right = mScrollX + (mRight - mLeft);
9689        outRect.bottom = mScrollY + (mBottom - mTop);
9690    }
9691
9692    /**
9693     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9694     * raw width component (that is the result is masked by
9695     * {@link #MEASURED_SIZE_MASK}).
9696     *
9697     * @return The raw measured width of this view.
9698     */
9699    public final int getMeasuredWidth() {
9700        return mMeasuredWidth & MEASURED_SIZE_MASK;
9701    }
9702
9703    /**
9704     * Return the full width measurement information for this view as computed
9705     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9706     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9707     * This should be used during measurement and layout calculations only. Use
9708     * {@link #getWidth()} to see how wide a view is after layout.
9709     *
9710     * @return The measured width of this view as a bit mask.
9711     */
9712    public final int getMeasuredWidthAndState() {
9713        return mMeasuredWidth;
9714    }
9715
9716    /**
9717     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9718     * raw width component (that is the result is masked by
9719     * {@link #MEASURED_SIZE_MASK}).
9720     *
9721     * @return The raw measured height of this view.
9722     */
9723    public final int getMeasuredHeight() {
9724        return mMeasuredHeight & MEASURED_SIZE_MASK;
9725    }
9726
9727    /**
9728     * Return the full height measurement information for this view as computed
9729     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9730     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9731     * This should be used during measurement and layout calculations only. Use
9732     * {@link #getHeight()} to see how wide a view is after layout.
9733     *
9734     * @return The measured width of this view as a bit mask.
9735     */
9736    public final int getMeasuredHeightAndState() {
9737        return mMeasuredHeight;
9738    }
9739
9740    /**
9741     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9742     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9743     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9744     * and the height component is at the shifted bits
9745     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9746     */
9747    public final int getMeasuredState() {
9748        return (mMeasuredWidth&MEASURED_STATE_MASK)
9749                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9750                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9751    }
9752
9753    /**
9754     * The transform matrix of this view, which is calculated based on the current
9755     * rotation, scale, and pivot properties.
9756     *
9757     * @see #getRotation()
9758     * @see #getScaleX()
9759     * @see #getScaleY()
9760     * @see #getPivotX()
9761     * @see #getPivotY()
9762     * @return The current transform matrix for the view
9763     */
9764    public Matrix getMatrix() {
9765        ensureTransformationInfo();
9766        final Matrix matrix = mTransformationInfo.mMatrix;
9767        mRenderNode.getMatrix(matrix);
9768        return matrix;
9769    }
9770
9771    /**
9772     * Returns true if the transform matrix is the identity matrix.
9773     * Recomputes the matrix if necessary.
9774     *
9775     * @return True if the transform matrix is the identity matrix, false otherwise.
9776     */
9777    final boolean hasIdentityMatrix() {
9778        return mRenderNode.hasIdentityMatrix();
9779    }
9780
9781    void ensureTransformationInfo() {
9782        if (mTransformationInfo == null) {
9783            mTransformationInfo = new TransformationInfo();
9784        }
9785    }
9786
9787   /**
9788     * Utility method to retrieve the inverse of the current mMatrix property.
9789     * We cache the matrix to avoid recalculating it when transform properties
9790     * have not changed.
9791     *
9792     * @return The inverse of the current matrix of this view.
9793     * @hide
9794     */
9795    public final Matrix getInverseMatrix() {
9796        ensureTransformationInfo();
9797        if (mTransformationInfo.mInverseMatrix == null) {
9798            mTransformationInfo.mInverseMatrix = new Matrix();
9799        }
9800        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9801        mRenderNode.getInverseMatrix(matrix);
9802        return matrix;
9803    }
9804
9805    /**
9806     * Gets the distance along the Z axis from the camera to this view.
9807     *
9808     * @see #setCameraDistance(float)
9809     *
9810     * @return The distance along the Z axis.
9811     */
9812    public float getCameraDistance() {
9813        final float dpi = mResources.getDisplayMetrics().densityDpi;
9814        return -(mRenderNode.getCameraDistance() * dpi);
9815    }
9816
9817    /**
9818     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9819     * views are drawn) from the camera to this view. The camera's distance
9820     * affects 3D transformations, for instance rotations around the X and Y
9821     * axis. If the rotationX or rotationY properties are changed and this view is
9822     * large (more than half the size of the screen), it is recommended to always
9823     * use a camera distance that's greater than the height (X axis rotation) or
9824     * the width (Y axis rotation) of this view.</p>
9825     *
9826     * <p>The distance of the camera from the view plane can have an affect on the
9827     * perspective distortion of the view when it is rotated around the x or y axis.
9828     * For example, a large distance will result in a large viewing angle, and there
9829     * will not be much perspective distortion of the view as it rotates. A short
9830     * distance may cause much more perspective distortion upon rotation, and can
9831     * also result in some drawing artifacts if the rotated view ends up partially
9832     * behind the camera (which is why the recommendation is to use a distance at
9833     * least as far as the size of the view, if the view is to be rotated.)</p>
9834     *
9835     * <p>The distance is expressed in "depth pixels." The default distance depends
9836     * on the screen density. For instance, on a medium density display, the
9837     * default distance is 1280. On a high density display, the default distance
9838     * is 1920.</p>
9839     *
9840     * <p>If you want to specify a distance that leads to visually consistent
9841     * results across various densities, use the following formula:</p>
9842     * <pre>
9843     * float scale = context.getResources().getDisplayMetrics().density;
9844     * view.setCameraDistance(distance * scale);
9845     * </pre>
9846     *
9847     * <p>The density scale factor of a high density display is 1.5,
9848     * and 1920 = 1280 * 1.5.</p>
9849     *
9850     * @param distance The distance in "depth pixels", if negative the opposite
9851     *        value is used
9852     *
9853     * @see #setRotationX(float)
9854     * @see #setRotationY(float)
9855     */
9856    public void setCameraDistance(float distance) {
9857        final float dpi = mResources.getDisplayMetrics().densityDpi;
9858
9859        invalidateViewProperty(true, false);
9860        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9861        invalidateViewProperty(false, false);
9862
9863        invalidateParentIfNeededAndWasQuickRejected();
9864    }
9865
9866    /**
9867     * The degrees that the view is rotated around the pivot point.
9868     *
9869     * @see #setRotation(float)
9870     * @see #getPivotX()
9871     * @see #getPivotY()
9872     *
9873     * @return The degrees of rotation.
9874     */
9875    @ViewDebug.ExportedProperty(category = "drawing")
9876    public float getRotation() {
9877        return mRenderNode.getRotation();
9878    }
9879
9880    /**
9881     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9882     * result in clockwise rotation.
9883     *
9884     * @param rotation The degrees of rotation.
9885     *
9886     * @see #getRotation()
9887     * @see #getPivotX()
9888     * @see #getPivotY()
9889     * @see #setRotationX(float)
9890     * @see #setRotationY(float)
9891     *
9892     * @attr ref android.R.styleable#View_rotation
9893     */
9894    public void setRotation(float rotation) {
9895        if (rotation != getRotation()) {
9896            // Double-invalidation is necessary to capture view's old and new areas
9897            invalidateViewProperty(true, false);
9898            mRenderNode.setRotation(rotation);
9899            invalidateViewProperty(false, true);
9900
9901            invalidateParentIfNeededAndWasQuickRejected();
9902            notifySubtreeAccessibilityStateChangedIfNeeded();
9903        }
9904    }
9905
9906    /**
9907     * The degrees that the view is rotated around the vertical axis through the pivot point.
9908     *
9909     * @see #getPivotX()
9910     * @see #getPivotY()
9911     * @see #setRotationY(float)
9912     *
9913     * @return The degrees of Y rotation.
9914     */
9915    @ViewDebug.ExportedProperty(category = "drawing")
9916    public float getRotationY() {
9917        return mRenderNode.getRotationY();
9918    }
9919
9920    /**
9921     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9922     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9923     * down the y axis.
9924     *
9925     * When rotating large views, it is recommended to adjust the camera distance
9926     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9927     *
9928     * @param rotationY The degrees of Y rotation.
9929     *
9930     * @see #getRotationY()
9931     * @see #getPivotX()
9932     * @see #getPivotY()
9933     * @see #setRotation(float)
9934     * @see #setRotationX(float)
9935     * @see #setCameraDistance(float)
9936     *
9937     * @attr ref android.R.styleable#View_rotationY
9938     */
9939    public void setRotationY(float rotationY) {
9940        if (rotationY != getRotationY()) {
9941            invalidateViewProperty(true, false);
9942            mRenderNode.setRotationY(rotationY);
9943            invalidateViewProperty(false, true);
9944
9945            invalidateParentIfNeededAndWasQuickRejected();
9946            notifySubtreeAccessibilityStateChangedIfNeeded();
9947        }
9948    }
9949
9950    /**
9951     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9952     *
9953     * @see #getPivotX()
9954     * @see #getPivotY()
9955     * @see #setRotationX(float)
9956     *
9957     * @return The degrees of X rotation.
9958     */
9959    @ViewDebug.ExportedProperty(category = "drawing")
9960    public float getRotationX() {
9961        return mRenderNode.getRotationX();
9962    }
9963
9964    /**
9965     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9966     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9967     * x axis.
9968     *
9969     * When rotating large views, it is recommended to adjust the camera distance
9970     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9971     *
9972     * @param rotationX The degrees of X rotation.
9973     *
9974     * @see #getRotationX()
9975     * @see #getPivotX()
9976     * @see #getPivotY()
9977     * @see #setRotation(float)
9978     * @see #setRotationY(float)
9979     * @see #setCameraDistance(float)
9980     *
9981     * @attr ref android.R.styleable#View_rotationX
9982     */
9983    public void setRotationX(float rotationX) {
9984        if (rotationX != getRotationX()) {
9985            invalidateViewProperty(true, false);
9986            mRenderNode.setRotationX(rotationX);
9987            invalidateViewProperty(false, true);
9988
9989            invalidateParentIfNeededAndWasQuickRejected();
9990            notifySubtreeAccessibilityStateChangedIfNeeded();
9991        }
9992    }
9993
9994    /**
9995     * The amount that the view is scaled in x around the pivot point, as a proportion of
9996     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9997     *
9998     * <p>By default, this is 1.0f.
9999     *
10000     * @see #getPivotX()
10001     * @see #getPivotY()
10002     * @return The scaling factor.
10003     */
10004    @ViewDebug.ExportedProperty(category = "drawing")
10005    public float getScaleX() {
10006        return mRenderNode.getScaleX();
10007    }
10008
10009    /**
10010     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10011     * the view's unscaled width. A value of 1 means that no scaling is applied.
10012     *
10013     * @param scaleX The scaling factor.
10014     * @see #getPivotX()
10015     * @see #getPivotY()
10016     *
10017     * @attr ref android.R.styleable#View_scaleX
10018     */
10019    public void setScaleX(float scaleX) {
10020        if (scaleX != getScaleX()) {
10021            invalidateViewProperty(true, false);
10022            mRenderNode.setScaleX(scaleX);
10023            invalidateViewProperty(false, true);
10024
10025            invalidateParentIfNeededAndWasQuickRejected();
10026            notifySubtreeAccessibilityStateChangedIfNeeded();
10027        }
10028    }
10029
10030    /**
10031     * The amount that the view is scaled in y around the pivot point, as a proportion of
10032     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10033     *
10034     * <p>By default, this is 1.0f.
10035     *
10036     * @see #getPivotX()
10037     * @see #getPivotY()
10038     * @return The scaling factor.
10039     */
10040    @ViewDebug.ExportedProperty(category = "drawing")
10041    public float getScaleY() {
10042        return mRenderNode.getScaleY();
10043    }
10044
10045    /**
10046     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10047     * the view's unscaled width. A value of 1 means that no scaling is applied.
10048     *
10049     * @param scaleY The scaling factor.
10050     * @see #getPivotX()
10051     * @see #getPivotY()
10052     *
10053     * @attr ref android.R.styleable#View_scaleY
10054     */
10055    public void setScaleY(float scaleY) {
10056        if (scaleY != getScaleY()) {
10057            invalidateViewProperty(true, false);
10058            mRenderNode.setScaleY(scaleY);
10059            invalidateViewProperty(false, true);
10060
10061            invalidateParentIfNeededAndWasQuickRejected();
10062            notifySubtreeAccessibilityStateChangedIfNeeded();
10063        }
10064    }
10065
10066    /**
10067     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10068     * and {@link #setScaleX(float) scaled}.
10069     *
10070     * @see #getRotation()
10071     * @see #getScaleX()
10072     * @see #getScaleY()
10073     * @see #getPivotY()
10074     * @return The x location of the pivot point.
10075     *
10076     * @attr ref android.R.styleable#View_transformPivotX
10077     */
10078    @ViewDebug.ExportedProperty(category = "drawing")
10079    public float getPivotX() {
10080        return mRenderNode.getPivotX();
10081    }
10082
10083    /**
10084     * Sets the x location of the point around which the view is
10085     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10086     * By default, the pivot point is centered on the object.
10087     * Setting this property disables this behavior and causes the view to use only the
10088     * explicitly set pivotX and pivotY values.
10089     *
10090     * @param pivotX The x location of the pivot point.
10091     * @see #getRotation()
10092     * @see #getScaleX()
10093     * @see #getScaleY()
10094     * @see #getPivotY()
10095     *
10096     * @attr ref android.R.styleable#View_transformPivotX
10097     */
10098    public void setPivotX(float pivotX) {
10099        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10100            invalidateViewProperty(true, false);
10101            mRenderNode.setPivotX(pivotX);
10102            invalidateViewProperty(false, true);
10103
10104            invalidateParentIfNeededAndWasQuickRejected();
10105        }
10106    }
10107
10108    /**
10109     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10110     * and {@link #setScaleY(float) scaled}.
10111     *
10112     * @see #getRotation()
10113     * @see #getScaleX()
10114     * @see #getScaleY()
10115     * @see #getPivotY()
10116     * @return The y location of the pivot point.
10117     *
10118     * @attr ref android.R.styleable#View_transformPivotY
10119     */
10120    @ViewDebug.ExportedProperty(category = "drawing")
10121    public float getPivotY() {
10122        return mRenderNode.getPivotY();
10123    }
10124
10125    /**
10126     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10127     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10128     * Setting this property disables this behavior and causes the view to use only the
10129     * explicitly set pivotX and pivotY values.
10130     *
10131     * @param pivotY The y location of the pivot point.
10132     * @see #getRotation()
10133     * @see #getScaleX()
10134     * @see #getScaleY()
10135     * @see #getPivotY()
10136     *
10137     * @attr ref android.R.styleable#View_transformPivotY
10138     */
10139    public void setPivotY(float pivotY) {
10140        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10141            invalidateViewProperty(true, false);
10142            mRenderNode.setPivotY(pivotY);
10143            invalidateViewProperty(false, true);
10144
10145            invalidateParentIfNeededAndWasQuickRejected();
10146        }
10147    }
10148
10149    /**
10150     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10151     * completely transparent and 1 means the view is completely opaque.
10152     *
10153     * <p>By default this is 1.0f.
10154     * @return The opacity of the view.
10155     */
10156    @ViewDebug.ExportedProperty(category = "drawing")
10157    public float getAlpha() {
10158        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10159    }
10160
10161    /**
10162     * Returns whether this View has content which overlaps.
10163     *
10164     * <p>This function, intended to be overridden by specific View types, is an optimization when
10165     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10166     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10167     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10168     * directly. An example of overlapping rendering is a TextView with a background image, such as
10169     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10170     * ImageView with only the foreground image. The default implementation returns true; subclasses
10171     * should override if they have cases which can be optimized.</p>
10172     *
10173     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10174     * necessitates that a View return true if it uses the methods internally without passing the
10175     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10176     *
10177     * @return true if the content in this view might overlap, false otherwise.
10178     */
10179    public boolean hasOverlappingRendering() {
10180        return true;
10181    }
10182
10183    /**
10184     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10185     * completely transparent and 1 means the view is completely opaque.</p>
10186     *
10187     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10188     * performance implications, especially for large views. It is best to use the alpha property
10189     * sparingly and transiently, as in the case of fading animations.</p>
10190     *
10191     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10192     * strongly recommended for performance reasons to either override
10193     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10194     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10195     *
10196     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10197     * responsible for applying the opacity itself.</p>
10198     *
10199     * <p>Note that if the view is backed by a
10200     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10201     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10202     * 1.0 will supercede the alpha of the layer paint.</p>
10203     *
10204     * @param alpha The opacity of the view.
10205     *
10206     * @see #hasOverlappingRendering()
10207     * @see #setLayerType(int, android.graphics.Paint)
10208     *
10209     * @attr ref android.R.styleable#View_alpha
10210     */
10211    public void setAlpha(float alpha) {
10212        ensureTransformationInfo();
10213        if (mTransformationInfo.mAlpha != alpha) {
10214            mTransformationInfo.mAlpha = alpha;
10215            if (onSetAlpha((int) (alpha * 255))) {
10216                mPrivateFlags |= PFLAG_ALPHA_SET;
10217                // subclass is handling alpha - don't optimize rendering cache invalidation
10218                invalidateParentCaches();
10219                invalidate(true);
10220            } else {
10221                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10222                invalidateViewProperty(true, false);
10223                mRenderNode.setAlpha(getFinalAlpha());
10224                notifyViewAccessibilityStateChangedIfNeeded(
10225                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10226            }
10227        }
10228    }
10229
10230    /**
10231     * Faster version of setAlpha() which performs the same steps except there are
10232     * no calls to invalidate(). The caller of this function should perform proper invalidation
10233     * on the parent and this object. The return value indicates whether the subclass handles
10234     * alpha (the return value for onSetAlpha()).
10235     *
10236     * @param alpha The new value for the alpha property
10237     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10238     *         the new value for the alpha property is different from the old value
10239     */
10240    boolean setAlphaNoInvalidation(float alpha) {
10241        ensureTransformationInfo();
10242        if (mTransformationInfo.mAlpha != alpha) {
10243            mTransformationInfo.mAlpha = alpha;
10244            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10245            if (subclassHandlesAlpha) {
10246                mPrivateFlags |= PFLAG_ALPHA_SET;
10247                return true;
10248            } else {
10249                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10250                mRenderNode.setAlpha(getFinalAlpha());
10251            }
10252        }
10253        return false;
10254    }
10255
10256    /**
10257     * This property is hidden and intended only for use by the Fade transition, which
10258     * animates it to produce a visual translucency that does not side-effect (or get
10259     * affected by) the real alpha property. This value is composited with the other
10260     * alpha value (and the AlphaAnimation value, when that is present) to produce
10261     * a final visual translucency result, which is what is passed into the DisplayList.
10262     *
10263     * @hide
10264     */
10265    public void setTransitionAlpha(float alpha) {
10266        ensureTransformationInfo();
10267        if (mTransformationInfo.mTransitionAlpha != alpha) {
10268            mTransformationInfo.mTransitionAlpha = alpha;
10269            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10270            invalidateViewProperty(true, false);
10271            mRenderNode.setAlpha(getFinalAlpha());
10272        }
10273    }
10274
10275    /**
10276     * Calculates the visual alpha of this view, which is a combination of the actual
10277     * alpha value and the transitionAlpha value (if set).
10278     */
10279    private float getFinalAlpha() {
10280        if (mTransformationInfo != null) {
10281            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10282        }
10283        return 1;
10284    }
10285
10286    /**
10287     * This property is hidden and intended only for use by the Fade transition, which
10288     * animates it to produce a visual translucency that does not side-effect (or get
10289     * affected by) the real alpha property. This value is composited with the other
10290     * alpha value (and the AlphaAnimation value, when that is present) to produce
10291     * a final visual translucency result, which is what is passed into the DisplayList.
10292     *
10293     * @hide
10294     */
10295    @ViewDebug.ExportedProperty(category = "drawing")
10296    public float getTransitionAlpha() {
10297        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10298    }
10299
10300    /**
10301     * Top position of this view relative to its parent.
10302     *
10303     * @return The top of this view, in pixels.
10304     */
10305    @ViewDebug.CapturedViewProperty
10306    public final int getTop() {
10307        return mTop;
10308    }
10309
10310    /**
10311     * Sets the top position of this view relative to its parent. This method is meant to be called
10312     * by the layout system and should not generally be called otherwise, because the property
10313     * may be changed at any time by the layout.
10314     *
10315     * @param top The top of this view, in pixels.
10316     */
10317    public final void setTop(int top) {
10318        if (top != mTop) {
10319            final boolean matrixIsIdentity = hasIdentityMatrix();
10320            if (matrixIsIdentity) {
10321                if (mAttachInfo != null) {
10322                    int minTop;
10323                    int yLoc;
10324                    if (top < mTop) {
10325                        minTop = top;
10326                        yLoc = top - mTop;
10327                    } else {
10328                        minTop = mTop;
10329                        yLoc = 0;
10330                    }
10331                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10332                }
10333            } else {
10334                // Double-invalidation is necessary to capture view's old and new areas
10335                invalidate(true);
10336            }
10337
10338            int width = mRight - mLeft;
10339            int oldHeight = mBottom - mTop;
10340
10341            mTop = top;
10342            mRenderNode.setTop(mTop);
10343
10344            sizeChange(width, mBottom - mTop, width, oldHeight);
10345
10346            if (!matrixIsIdentity) {
10347                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10348                invalidate(true);
10349            }
10350            mBackgroundSizeChanged = true;
10351            invalidateParentIfNeeded();
10352            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10353                // View was rejected last time it was drawn by its parent; this may have changed
10354                invalidateParentIfNeeded();
10355            }
10356        }
10357    }
10358
10359    /**
10360     * Bottom position of this view relative to its parent.
10361     *
10362     * @return The bottom of this view, in pixels.
10363     */
10364    @ViewDebug.CapturedViewProperty
10365    public final int getBottom() {
10366        return mBottom;
10367    }
10368
10369    /**
10370     * True if this view has changed since the last time being drawn.
10371     *
10372     * @return The dirty state of this view.
10373     */
10374    public boolean isDirty() {
10375        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10376    }
10377
10378    /**
10379     * Sets the bottom position of this view relative to its parent. This method is meant to be
10380     * called by the layout system and should not generally be called otherwise, because the
10381     * property may be changed at any time by the layout.
10382     *
10383     * @param bottom The bottom of this view, in pixels.
10384     */
10385    public final void setBottom(int bottom) {
10386        if (bottom != mBottom) {
10387            final boolean matrixIsIdentity = hasIdentityMatrix();
10388            if (matrixIsIdentity) {
10389                if (mAttachInfo != null) {
10390                    int maxBottom;
10391                    if (bottom < mBottom) {
10392                        maxBottom = mBottom;
10393                    } else {
10394                        maxBottom = bottom;
10395                    }
10396                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10397                }
10398            } else {
10399                // Double-invalidation is necessary to capture view's old and new areas
10400                invalidate(true);
10401            }
10402
10403            int width = mRight - mLeft;
10404            int oldHeight = mBottom - mTop;
10405
10406            mBottom = bottom;
10407            mRenderNode.setBottom(mBottom);
10408
10409            sizeChange(width, mBottom - mTop, width, oldHeight);
10410
10411            if (!matrixIsIdentity) {
10412                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10413                invalidate(true);
10414            }
10415            mBackgroundSizeChanged = true;
10416            invalidateParentIfNeeded();
10417            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10418                // View was rejected last time it was drawn by its parent; this may have changed
10419                invalidateParentIfNeeded();
10420            }
10421        }
10422    }
10423
10424    /**
10425     * Left position of this view relative to its parent.
10426     *
10427     * @return The left edge of this view, in pixels.
10428     */
10429    @ViewDebug.CapturedViewProperty
10430    public final int getLeft() {
10431        return mLeft;
10432    }
10433
10434    /**
10435     * Sets the left position of this view relative to its parent. This method is meant to be called
10436     * by the layout system and should not generally be called otherwise, because the property
10437     * may be changed at any time by the layout.
10438     *
10439     * @param left The left of this view, in pixels.
10440     */
10441    public final void setLeft(int left) {
10442        if (left != mLeft) {
10443            final boolean matrixIsIdentity = hasIdentityMatrix();
10444            if (matrixIsIdentity) {
10445                if (mAttachInfo != null) {
10446                    int minLeft;
10447                    int xLoc;
10448                    if (left < mLeft) {
10449                        minLeft = left;
10450                        xLoc = left - mLeft;
10451                    } else {
10452                        minLeft = mLeft;
10453                        xLoc = 0;
10454                    }
10455                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10456                }
10457            } else {
10458                // Double-invalidation is necessary to capture view's old and new areas
10459                invalidate(true);
10460            }
10461
10462            int oldWidth = mRight - mLeft;
10463            int height = mBottom - mTop;
10464
10465            mLeft = left;
10466            mRenderNode.setLeft(left);
10467
10468            sizeChange(mRight - mLeft, height, oldWidth, height);
10469
10470            if (!matrixIsIdentity) {
10471                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10472                invalidate(true);
10473            }
10474            mBackgroundSizeChanged = true;
10475            invalidateParentIfNeeded();
10476            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10477                // View was rejected last time it was drawn by its parent; this may have changed
10478                invalidateParentIfNeeded();
10479            }
10480        }
10481    }
10482
10483    /**
10484     * Right position of this view relative to its parent.
10485     *
10486     * @return The right edge of this view, in pixels.
10487     */
10488    @ViewDebug.CapturedViewProperty
10489    public final int getRight() {
10490        return mRight;
10491    }
10492
10493    /**
10494     * Sets the right position of this view relative to its parent. This method is meant to be called
10495     * by the layout system and should not generally be called otherwise, because the property
10496     * may be changed at any time by the layout.
10497     *
10498     * @param right The right of this view, in pixels.
10499     */
10500    public final void setRight(int right) {
10501        if (right != mRight) {
10502            final boolean matrixIsIdentity = hasIdentityMatrix();
10503            if (matrixIsIdentity) {
10504                if (mAttachInfo != null) {
10505                    int maxRight;
10506                    if (right < mRight) {
10507                        maxRight = mRight;
10508                    } else {
10509                        maxRight = right;
10510                    }
10511                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10512                }
10513            } else {
10514                // Double-invalidation is necessary to capture view's old and new areas
10515                invalidate(true);
10516            }
10517
10518            int oldWidth = mRight - mLeft;
10519            int height = mBottom - mTop;
10520
10521            mRight = right;
10522            mRenderNode.setRight(mRight);
10523
10524            sizeChange(mRight - mLeft, height, oldWidth, height);
10525
10526            if (!matrixIsIdentity) {
10527                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10528                invalidate(true);
10529            }
10530            mBackgroundSizeChanged = true;
10531            invalidateParentIfNeeded();
10532            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10533                // View was rejected last time it was drawn by its parent; this may have changed
10534                invalidateParentIfNeeded();
10535            }
10536        }
10537    }
10538
10539    /**
10540     * The visual x position of this view, in pixels. This is equivalent to the
10541     * {@link #setTranslationX(float) translationX} property plus the current
10542     * {@link #getLeft() left} property.
10543     *
10544     * @return The visual x position of this view, in pixels.
10545     */
10546    @ViewDebug.ExportedProperty(category = "drawing")
10547    public float getX() {
10548        return mLeft + getTranslationX();
10549    }
10550
10551    /**
10552     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10553     * {@link #setTranslationX(float) translationX} property to be the difference between
10554     * the x value passed in and the current {@link #getLeft() left} property.
10555     *
10556     * @param x The visual x position of this view, in pixels.
10557     */
10558    public void setX(float x) {
10559        setTranslationX(x - mLeft);
10560    }
10561
10562    /**
10563     * The visual y position of this view, in pixels. This is equivalent to the
10564     * {@link #setTranslationY(float) translationY} property plus the current
10565     * {@link #getTop() top} property.
10566     *
10567     * @return The visual y position of this view, in pixels.
10568     */
10569    @ViewDebug.ExportedProperty(category = "drawing")
10570    public float getY() {
10571        return mTop + getTranslationY();
10572    }
10573
10574    /**
10575     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10576     * {@link #setTranslationY(float) translationY} property to be the difference between
10577     * the y value passed in and the current {@link #getTop() top} property.
10578     *
10579     * @param y The visual y position of this view, in pixels.
10580     */
10581    public void setY(float y) {
10582        setTranslationY(y - mTop);
10583    }
10584
10585    /**
10586     * The visual z position of this view, in pixels. This is equivalent to the
10587     * {@link #setTranslationZ(float) translationZ} property plus the current
10588     * {@link #getElevation() elevation} property.
10589     *
10590     * @return The visual z position of this view, in pixels.
10591     */
10592    @ViewDebug.ExportedProperty(category = "drawing")
10593    public float getZ() {
10594        return getElevation() + getTranslationZ();
10595    }
10596
10597    /**
10598     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10599     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10600     * the x value passed in and the current {@link #getElevation() elevation} property.
10601     *
10602     * @param z The visual z position of this view, in pixels.
10603     */
10604    public void setZ(float z) {
10605        setTranslationZ(z - getElevation());
10606    }
10607
10608    /**
10609     * The base elevation of this view relative to its parent, in pixels.
10610     *
10611     * @return The base depth position of the view, in pixels.
10612     */
10613    @ViewDebug.ExportedProperty(category = "drawing")
10614    public float getElevation() {
10615        return mRenderNode.getElevation();
10616    }
10617
10618    /**
10619     * Sets the base elevation of this view, in pixels.
10620     *
10621     * @attr ref android.R.styleable#View_elevation
10622     */
10623    public void setElevation(float elevation) {
10624        if (elevation != getElevation()) {
10625            invalidateViewProperty(true, false);
10626            mRenderNode.setElevation(elevation);
10627            invalidateViewProperty(false, true);
10628
10629            invalidateParentIfNeededAndWasQuickRejected();
10630        }
10631    }
10632
10633    /**
10634     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10635     * This position is post-layout, in addition to wherever the object's
10636     * layout placed it.
10637     *
10638     * @return The horizontal position of this view relative to its left position, in pixels.
10639     */
10640    @ViewDebug.ExportedProperty(category = "drawing")
10641    public float getTranslationX() {
10642        return mRenderNode.getTranslationX();
10643    }
10644
10645    /**
10646     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10647     * This effectively positions the object post-layout, in addition to wherever the object's
10648     * layout placed it.
10649     *
10650     * @param translationX The horizontal position of this view relative to its left position,
10651     * in pixels.
10652     *
10653     * @attr ref android.R.styleable#View_translationX
10654     */
10655    public void setTranslationX(float translationX) {
10656        if (translationX != getTranslationX()) {
10657            invalidateViewProperty(true, false);
10658            mRenderNode.setTranslationX(translationX);
10659            invalidateViewProperty(false, true);
10660
10661            invalidateParentIfNeededAndWasQuickRejected();
10662            notifySubtreeAccessibilityStateChangedIfNeeded();
10663        }
10664    }
10665
10666    /**
10667     * The vertical location of this view relative to its {@link #getTop() top} position.
10668     * This position is post-layout, in addition to wherever the object's
10669     * layout placed it.
10670     *
10671     * @return The vertical position of this view relative to its top position,
10672     * in pixels.
10673     */
10674    @ViewDebug.ExportedProperty(category = "drawing")
10675    public float getTranslationY() {
10676        return mRenderNode.getTranslationY();
10677    }
10678
10679    /**
10680     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10681     * This effectively positions the object post-layout, in addition to wherever the object's
10682     * layout placed it.
10683     *
10684     * @param translationY The vertical position of this view relative to its top position,
10685     * in pixels.
10686     *
10687     * @attr ref android.R.styleable#View_translationY
10688     */
10689    public void setTranslationY(float translationY) {
10690        if (translationY != getTranslationY()) {
10691            invalidateViewProperty(true, false);
10692            mRenderNode.setTranslationY(translationY);
10693            invalidateViewProperty(false, true);
10694
10695            invalidateParentIfNeededAndWasQuickRejected();
10696        }
10697    }
10698
10699    /**
10700     * The depth location of this view relative to its {@link #getElevation() elevation}.
10701     *
10702     * @return The depth of this view relative to its elevation.
10703     */
10704    @ViewDebug.ExportedProperty(category = "drawing")
10705    public float getTranslationZ() {
10706        return mRenderNode.getTranslationZ();
10707    }
10708
10709    /**
10710     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10711     *
10712     * @attr ref android.R.styleable#View_translationZ
10713     */
10714    public void setTranslationZ(float translationZ) {
10715        if (translationZ != getTranslationZ()) {
10716            invalidateViewProperty(true, false);
10717            mRenderNode.setTranslationZ(translationZ);
10718            invalidateViewProperty(false, true);
10719
10720            invalidateParentIfNeededAndWasQuickRejected();
10721        }
10722    }
10723
10724    /**
10725     * Returns the current StateListAnimator if exists.
10726     *
10727     * @return StateListAnimator or null if it does not exists
10728     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10729     */
10730    public StateListAnimator getStateListAnimator() {
10731        return mStateListAnimator;
10732    }
10733
10734    /**
10735     * Attaches the provided StateListAnimator to this View.
10736     * <p>
10737     * Any previously attached StateListAnimator will be detached.
10738     *
10739     * @param stateListAnimator The StateListAnimator to update the view
10740     * @see {@link android.animation.StateListAnimator}
10741     */
10742    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10743        if (mStateListAnimator == stateListAnimator) {
10744            return;
10745        }
10746        if (mStateListAnimator != null) {
10747            mStateListAnimator.setTarget(null);
10748        }
10749        mStateListAnimator = stateListAnimator;
10750        if (stateListAnimator != null) {
10751            stateListAnimator.setTarget(this);
10752            if (isAttachedToWindow()) {
10753                stateListAnimator.setState(getDrawableState());
10754            }
10755        }
10756    }
10757
10758    /**
10759     * Deprecated, pending removal
10760     *
10761     * @hide
10762     */
10763    @Deprecated
10764    public void setOutline(@Nullable Outline outline) {}
10765
10766    /**
10767     * Returns whether the Outline should be used to clip the contents of the View.
10768     * <p>
10769     * Note that this flag will only be respected if the View's Outline returns true from
10770     * {@link Outline#canClip()}.
10771     *
10772     * @see #setOutlineProvider(ViewOutlineProvider)
10773     * @see #setClipToOutline(boolean)
10774     */
10775    public final boolean getClipToOutline() {
10776        return mRenderNode.getClipToOutline();
10777    }
10778
10779    /**
10780     * Sets whether the View's Outline should be used to clip the contents of the View.
10781     * <p>
10782     * Note that this flag will only be respected if the View's Outline returns true from
10783     * {@link Outline#canClip()}.
10784     *
10785     * @see #setOutlineProvider(ViewOutlineProvider)
10786     * @see #getClipToOutline()
10787     */
10788    public void setClipToOutline(boolean clipToOutline) {
10789        damageInParent();
10790        if (getClipToOutline() != clipToOutline) {
10791            mRenderNode.setClipToOutline(clipToOutline);
10792        }
10793    }
10794
10795    /**
10796     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10797     * the shape of the shadow it casts, and enables outline clipping.
10798     * <p>
10799     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10800     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10801     * outline provider with this method allows this behavior to be overridden.
10802     * <p>
10803     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10804     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10805     * <p>
10806     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10807     *
10808     * @see #setClipToOutline(boolean)
10809     * @see #getClipToOutline()
10810     * @see #getOutlineProvider()
10811     */
10812    public void setOutlineProvider(ViewOutlineProvider provider) {
10813        mOutlineProvider = provider;
10814        invalidateOutline();
10815    }
10816
10817    /**
10818     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10819     * that defines the shape of the shadow it casts, and enables outline clipping.
10820     *
10821     * @see #setOutlineProvider(ViewOutlineProvider)
10822     */
10823    public ViewOutlineProvider getOutlineProvider() {
10824        return mOutlineProvider;
10825    }
10826
10827    /**
10828     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10829     *
10830     * @see #setOutlineProvider(ViewOutlineProvider)
10831     */
10832    public void invalidateOutline() {
10833        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10834        if (mAttachInfo == null) return;
10835
10836        if (mOutlineProvider == null) {
10837            // no provider, remove outline
10838            mRenderNode.setOutline(null);
10839        } else {
10840            final Outline outline = mAttachInfo.mTmpOutline;
10841            outline.setEmpty();
10842            outline.setAlpha(1.0f);
10843
10844            mOutlineProvider.getOutline(this, outline);
10845            mRenderNode.setOutline(outline);
10846        }
10847
10848        notifySubtreeAccessibilityStateChangedIfNeeded();
10849        invalidateViewProperty(false, false);
10850    }
10851
10852    /** @hide */
10853    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
10854        mRenderNode.setRevealClip(shouldClip, x, y, radius);
10855        invalidateViewProperty(false, false);
10856    }
10857
10858    /**
10859     * Hit rectangle in parent's coordinates
10860     *
10861     * @param outRect The hit rectangle of the view.
10862     */
10863    public void getHitRect(Rect outRect) {
10864        if (hasIdentityMatrix() || mAttachInfo == null) {
10865            outRect.set(mLeft, mTop, mRight, mBottom);
10866        } else {
10867            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10868            tmpRect.set(0, 0, getWidth(), getHeight());
10869            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10870            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10871                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10872        }
10873    }
10874
10875    /**
10876     * Determines whether the given point, in local coordinates is inside the view.
10877     */
10878    /*package*/ final boolean pointInView(float localX, float localY) {
10879        return localX >= 0 && localX < (mRight - mLeft)
10880                && localY >= 0 && localY < (mBottom - mTop);
10881    }
10882
10883    /**
10884     * Utility method to determine whether the given point, in local coordinates,
10885     * is inside the view, where the area of the view is expanded by the slop factor.
10886     * This method is called while processing touch-move events to determine if the event
10887     * is still within the view.
10888     *
10889     * @hide
10890     */
10891    public boolean pointInView(float localX, float localY, float slop) {
10892        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10893                localY < ((mBottom - mTop) + slop);
10894    }
10895
10896    /**
10897     * When a view has focus and the user navigates away from it, the next view is searched for
10898     * starting from the rectangle filled in by this method.
10899     *
10900     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10901     * of the view.  However, if your view maintains some idea of internal selection,
10902     * such as a cursor, or a selected row or column, you should override this method and
10903     * fill in a more specific rectangle.
10904     *
10905     * @param r The rectangle to fill in, in this view's coordinates.
10906     */
10907    public void getFocusedRect(Rect r) {
10908        getDrawingRect(r);
10909    }
10910
10911    /**
10912     * If some part of this view is not clipped by any of its parents, then
10913     * return that area in r in global (root) coordinates. To convert r to local
10914     * coordinates (without taking possible View rotations into account), offset
10915     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10916     * If the view is completely clipped or translated out, return false.
10917     *
10918     * @param r If true is returned, r holds the global coordinates of the
10919     *        visible portion of this view.
10920     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10921     *        between this view and its root. globalOffet may be null.
10922     * @return true if r is non-empty (i.e. part of the view is visible at the
10923     *         root level.
10924     */
10925    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10926        int width = mRight - mLeft;
10927        int height = mBottom - mTop;
10928        if (width > 0 && height > 0) {
10929            r.set(0, 0, width, height);
10930            if (globalOffset != null) {
10931                globalOffset.set(-mScrollX, -mScrollY);
10932            }
10933            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10934        }
10935        return false;
10936    }
10937
10938    public final boolean getGlobalVisibleRect(Rect r) {
10939        return getGlobalVisibleRect(r, null);
10940    }
10941
10942    public final boolean getLocalVisibleRect(Rect r) {
10943        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10944        if (getGlobalVisibleRect(r, offset)) {
10945            r.offset(-offset.x, -offset.y); // make r local
10946            return true;
10947        }
10948        return false;
10949    }
10950
10951    /**
10952     * Offset this view's vertical location by the specified number of pixels.
10953     *
10954     * @param offset the number of pixels to offset the view by
10955     */
10956    public void offsetTopAndBottom(int offset) {
10957        if (offset != 0) {
10958            final boolean matrixIsIdentity = hasIdentityMatrix();
10959            if (matrixIsIdentity) {
10960                if (isHardwareAccelerated()) {
10961                    invalidateViewProperty(false, false);
10962                } else {
10963                    final ViewParent p = mParent;
10964                    if (p != null && mAttachInfo != null) {
10965                        final Rect r = mAttachInfo.mTmpInvalRect;
10966                        int minTop;
10967                        int maxBottom;
10968                        int yLoc;
10969                        if (offset < 0) {
10970                            minTop = mTop + offset;
10971                            maxBottom = mBottom;
10972                            yLoc = offset;
10973                        } else {
10974                            minTop = mTop;
10975                            maxBottom = mBottom + offset;
10976                            yLoc = 0;
10977                        }
10978                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10979                        p.invalidateChild(this, r);
10980                    }
10981                }
10982            } else {
10983                invalidateViewProperty(false, false);
10984            }
10985
10986            mTop += offset;
10987            mBottom += offset;
10988            mRenderNode.offsetTopAndBottom(offset);
10989            if (isHardwareAccelerated()) {
10990                invalidateViewProperty(false, false);
10991            } else {
10992                if (!matrixIsIdentity) {
10993                    invalidateViewProperty(false, true);
10994                }
10995                invalidateParentIfNeeded();
10996            }
10997            notifySubtreeAccessibilityStateChangedIfNeeded();
10998        }
10999    }
11000
11001    /**
11002     * Offset this view's horizontal location by the specified amount of pixels.
11003     *
11004     * @param offset the number of pixels to offset the view by
11005     */
11006    public void offsetLeftAndRight(int offset) {
11007        if (offset != 0) {
11008            final boolean matrixIsIdentity = hasIdentityMatrix();
11009            if (matrixIsIdentity) {
11010                if (isHardwareAccelerated()) {
11011                    invalidateViewProperty(false, false);
11012                } else {
11013                    final ViewParent p = mParent;
11014                    if (p != null && mAttachInfo != null) {
11015                        final Rect r = mAttachInfo.mTmpInvalRect;
11016                        int minLeft;
11017                        int maxRight;
11018                        if (offset < 0) {
11019                            minLeft = mLeft + offset;
11020                            maxRight = mRight;
11021                        } else {
11022                            minLeft = mLeft;
11023                            maxRight = mRight + offset;
11024                        }
11025                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11026                        p.invalidateChild(this, r);
11027                    }
11028                }
11029            } else {
11030                invalidateViewProperty(false, false);
11031            }
11032
11033            mLeft += offset;
11034            mRight += offset;
11035            mRenderNode.offsetLeftAndRight(offset);
11036            if (isHardwareAccelerated()) {
11037                invalidateViewProperty(false, false);
11038            } else {
11039                if (!matrixIsIdentity) {
11040                    invalidateViewProperty(false, true);
11041                }
11042                invalidateParentIfNeeded();
11043            }
11044            notifySubtreeAccessibilityStateChangedIfNeeded();
11045        }
11046    }
11047
11048    /**
11049     * Get the LayoutParams associated with this view. All views should have
11050     * layout parameters. These supply parameters to the <i>parent</i> of this
11051     * view specifying how it should be arranged. There are many subclasses of
11052     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11053     * of ViewGroup that are responsible for arranging their children.
11054     *
11055     * This method may return null if this View is not attached to a parent
11056     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11057     * was not invoked successfully. When a View is attached to a parent
11058     * ViewGroup, this method must not return null.
11059     *
11060     * @return The LayoutParams associated with this view, or null if no
11061     *         parameters have been set yet
11062     */
11063    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11064    public ViewGroup.LayoutParams getLayoutParams() {
11065        return mLayoutParams;
11066    }
11067
11068    /**
11069     * Set the layout parameters associated with this view. These supply
11070     * parameters to the <i>parent</i> of this view specifying how it should be
11071     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11072     * correspond to the different subclasses of ViewGroup that are responsible
11073     * for arranging their children.
11074     *
11075     * @param params The layout parameters for this view, cannot be null
11076     */
11077    public void setLayoutParams(ViewGroup.LayoutParams params) {
11078        if (params == null) {
11079            throw new NullPointerException("Layout parameters cannot be null");
11080        }
11081        mLayoutParams = params;
11082        resolveLayoutParams();
11083        if (mParent instanceof ViewGroup) {
11084            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11085        }
11086        requestLayout();
11087    }
11088
11089    /**
11090     * Resolve the layout parameters depending on the resolved layout direction
11091     *
11092     * @hide
11093     */
11094    public void resolveLayoutParams() {
11095        if (mLayoutParams != null) {
11096            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11097        }
11098    }
11099
11100    /**
11101     * Set the scrolled position of your view. This will cause a call to
11102     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11103     * invalidated.
11104     * @param x the x position to scroll to
11105     * @param y the y position to scroll to
11106     */
11107    public void scrollTo(int x, int y) {
11108        if (mScrollX != x || mScrollY != y) {
11109            int oldX = mScrollX;
11110            int oldY = mScrollY;
11111            mScrollX = x;
11112            mScrollY = y;
11113            invalidateParentCaches();
11114            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11115            if (!awakenScrollBars()) {
11116                postInvalidateOnAnimation();
11117            }
11118        }
11119    }
11120
11121    /**
11122     * Move the scrolled position of your view. This will cause a call to
11123     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11124     * invalidated.
11125     * @param x the amount of pixels to scroll by horizontally
11126     * @param y the amount of pixels to scroll by vertically
11127     */
11128    public void scrollBy(int x, int y) {
11129        scrollTo(mScrollX + x, mScrollY + y);
11130    }
11131
11132    /**
11133     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11134     * animation to fade the scrollbars out after a default delay. If a subclass
11135     * provides animated scrolling, the start delay should equal the duration
11136     * of the scrolling animation.</p>
11137     *
11138     * <p>The animation starts only if at least one of the scrollbars is
11139     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11140     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11141     * this method returns true, and false otherwise. If the animation is
11142     * started, this method calls {@link #invalidate()}; in that case the
11143     * caller should not call {@link #invalidate()}.</p>
11144     *
11145     * <p>This method should be invoked every time a subclass directly updates
11146     * the scroll parameters.</p>
11147     *
11148     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11149     * and {@link #scrollTo(int, int)}.</p>
11150     *
11151     * @return true if the animation is played, false otherwise
11152     *
11153     * @see #awakenScrollBars(int)
11154     * @see #scrollBy(int, int)
11155     * @see #scrollTo(int, int)
11156     * @see #isHorizontalScrollBarEnabled()
11157     * @see #isVerticalScrollBarEnabled()
11158     * @see #setHorizontalScrollBarEnabled(boolean)
11159     * @see #setVerticalScrollBarEnabled(boolean)
11160     */
11161    protected boolean awakenScrollBars() {
11162        return mScrollCache != null &&
11163                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11164    }
11165
11166    /**
11167     * Trigger the scrollbars to draw.
11168     * This method differs from awakenScrollBars() only in its default duration.
11169     * initialAwakenScrollBars() will show the scroll bars for longer than
11170     * usual to give the user more of a chance to notice them.
11171     *
11172     * @return true if the animation is played, false otherwise.
11173     */
11174    private boolean initialAwakenScrollBars() {
11175        return mScrollCache != null &&
11176                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11177    }
11178
11179    /**
11180     * <p>
11181     * Trigger the scrollbars to draw. When invoked this method starts an
11182     * animation to fade the scrollbars out after a fixed delay. If a subclass
11183     * provides animated scrolling, the start delay should equal the duration of
11184     * the scrolling animation.
11185     * </p>
11186     *
11187     * <p>
11188     * The animation starts only if at least one of the scrollbars is enabled,
11189     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11190     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11191     * this method returns true, and false otherwise. If the animation is
11192     * started, this method calls {@link #invalidate()}; in that case the caller
11193     * should not call {@link #invalidate()}.
11194     * </p>
11195     *
11196     * <p>
11197     * This method should be invoked everytime a subclass directly updates the
11198     * scroll parameters.
11199     * </p>
11200     *
11201     * @param startDelay the delay, in milliseconds, after which the animation
11202     *        should start; when the delay is 0, the animation starts
11203     *        immediately
11204     * @return true if the animation is played, false otherwise
11205     *
11206     * @see #scrollBy(int, int)
11207     * @see #scrollTo(int, int)
11208     * @see #isHorizontalScrollBarEnabled()
11209     * @see #isVerticalScrollBarEnabled()
11210     * @see #setHorizontalScrollBarEnabled(boolean)
11211     * @see #setVerticalScrollBarEnabled(boolean)
11212     */
11213    protected boolean awakenScrollBars(int startDelay) {
11214        return awakenScrollBars(startDelay, true);
11215    }
11216
11217    /**
11218     * <p>
11219     * Trigger the scrollbars to draw. When invoked this method starts an
11220     * animation to fade the scrollbars out after a fixed delay. If a subclass
11221     * provides animated scrolling, the start delay should equal the duration of
11222     * the scrolling animation.
11223     * </p>
11224     *
11225     * <p>
11226     * The animation starts only if at least one of the scrollbars is enabled,
11227     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11228     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11229     * this method returns true, and false otherwise. If the animation is
11230     * started, this method calls {@link #invalidate()} if the invalidate parameter
11231     * is set to true; in that case the caller
11232     * should not call {@link #invalidate()}.
11233     * </p>
11234     *
11235     * <p>
11236     * This method should be invoked everytime a subclass directly updates the
11237     * scroll parameters.
11238     * </p>
11239     *
11240     * @param startDelay the delay, in milliseconds, after which the animation
11241     *        should start; when the delay is 0, the animation starts
11242     *        immediately
11243     *
11244     * @param invalidate Wheter this method should call invalidate
11245     *
11246     * @return true if the animation is played, false otherwise
11247     *
11248     * @see #scrollBy(int, int)
11249     * @see #scrollTo(int, int)
11250     * @see #isHorizontalScrollBarEnabled()
11251     * @see #isVerticalScrollBarEnabled()
11252     * @see #setHorizontalScrollBarEnabled(boolean)
11253     * @see #setVerticalScrollBarEnabled(boolean)
11254     */
11255    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11256        final ScrollabilityCache scrollCache = mScrollCache;
11257
11258        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11259            return false;
11260        }
11261
11262        if (scrollCache.scrollBar == null) {
11263            scrollCache.scrollBar = new ScrollBarDrawable();
11264        }
11265
11266        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11267
11268            if (invalidate) {
11269                // Invalidate to show the scrollbars
11270                postInvalidateOnAnimation();
11271            }
11272
11273            if (scrollCache.state == ScrollabilityCache.OFF) {
11274                // FIXME: this is copied from WindowManagerService.
11275                // We should get this value from the system when it
11276                // is possible to do so.
11277                final int KEY_REPEAT_FIRST_DELAY = 750;
11278                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11279            }
11280
11281            // Tell mScrollCache when we should start fading. This may
11282            // extend the fade start time if one was already scheduled
11283            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11284            scrollCache.fadeStartTime = fadeStartTime;
11285            scrollCache.state = ScrollabilityCache.ON;
11286
11287            // Schedule our fader to run, unscheduling any old ones first
11288            if (mAttachInfo != null) {
11289                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11290                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11291            }
11292
11293            return true;
11294        }
11295
11296        return false;
11297    }
11298
11299    /**
11300     * Do not invalidate views which are not visible and which are not running an animation. They
11301     * will not get drawn and they should not set dirty flags as if they will be drawn
11302     */
11303    private boolean skipInvalidate() {
11304        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11305                (!(mParent instanceof ViewGroup) ||
11306                        !((ViewGroup) mParent).isViewTransitioning(this));
11307    }
11308
11309    /**
11310     * Mark the area defined by dirty as needing to be drawn. If the view is
11311     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11312     * point in the future.
11313     * <p>
11314     * This must be called from a UI thread. To call from a non-UI thread, call
11315     * {@link #postInvalidate()}.
11316     * <p>
11317     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11318     * {@code dirty}.
11319     *
11320     * @param dirty the rectangle representing the bounds of the dirty region
11321     */
11322    public void invalidate(Rect dirty) {
11323        final int scrollX = mScrollX;
11324        final int scrollY = mScrollY;
11325        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11326                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11327    }
11328
11329    /**
11330     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11331     * coordinates of the dirty rect are relative to the view. If the view is
11332     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11333     * point in the future.
11334     * <p>
11335     * This must be called from a UI thread. To call from a non-UI thread, call
11336     * {@link #postInvalidate()}.
11337     *
11338     * @param l the left position of the dirty region
11339     * @param t the top position of the dirty region
11340     * @param r the right position of the dirty region
11341     * @param b the bottom position of the dirty region
11342     */
11343    public void invalidate(int l, int t, int r, int b) {
11344        final int scrollX = mScrollX;
11345        final int scrollY = mScrollY;
11346        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11347    }
11348
11349    /**
11350     * Invalidate the whole view. If the view is visible,
11351     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11352     * the future.
11353     * <p>
11354     * This must be called from a UI thread. To call from a non-UI thread, call
11355     * {@link #postInvalidate()}.
11356     */
11357    public void invalidate() {
11358        invalidate(true);
11359    }
11360
11361    /**
11362     * This is where the invalidate() work actually happens. A full invalidate()
11363     * causes the drawing cache to be invalidated, but this function can be
11364     * called with invalidateCache set to false to skip that invalidation step
11365     * for cases that do not need it (for example, a component that remains at
11366     * the same dimensions with the same content).
11367     *
11368     * @param invalidateCache Whether the drawing cache for this view should be
11369     *            invalidated as well. This is usually true for a full
11370     *            invalidate, but may be set to false if the View's contents or
11371     *            dimensions have not changed.
11372     */
11373    void invalidate(boolean invalidateCache) {
11374        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11375    }
11376
11377    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11378            boolean fullInvalidate) {
11379        if (mGhostView != null) {
11380            mGhostView.invalidate(invalidateCache);
11381            return;
11382        }
11383
11384        if (skipInvalidate()) {
11385            return;
11386        }
11387
11388        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11389                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11390                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11391                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11392            if (fullInvalidate) {
11393                mLastIsOpaque = isOpaque();
11394                mPrivateFlags &= ~PFLAG_DRAWN;
11395            }
11396
11397            mPrivateFlags |= PFLAG_DIRTY;
11398
11399            if (invalidateCache) {
11400                mPrivateFlags |= PFLAG_INVALIDATED;
11401                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11402            }
11403
11404            // Propagate the damage rectangle to the parent view.
11405            final AttachInfo ai = mAttachInfo;
11406            final ViewParent p = mParent;
11407            if (p != null && ai != null && l < r && t < b) {
11408                final Rect damage = ai.mTmpInvalRect;
11409                damage.set(l, t, r, b);
11410                p.invalidateChild(this, damage);
11411            }
11412
11413            // Damage the entire projection receiver, if necessary.
11414            if (mBackground != null && mBackground.isProjected()) {
11415                final View receiver = getProjectionReceiver();
11416                if (receiver != null) {
11417                    receiver.damageInParent();
11418                }
11419            }
11420
11421            // Damage the entire IsolatedZVolume receiving this view's shadow.
11422            if (isHardwareAccelerated() && getZ() != 0) {
11423                damageShadowReceiver();
11424            }
11425        }
11426    }
11427
11428    /**
11429     * @return this view's projection receiver, or {@code null} if none exists
11430     */
11431    private View getProjectionReceiver() {
11432        ViewParent p = getParent();
11433        while (p != null && p instanceof View) {
11434            final View v = (View) p;
11435            if (v.isProjectionReceiver()) {
11436                return v;
11437            }
11438            p = p.getParent();
11439        }
11440
11441        return null;
11442    }
11443
11444    /**
11445     * @return whether the view is a projection receiver
11446     */
11447    private boolean isProjectionReceiver() {
11448        return mBackground != null;
11449    }
11450
11451    /**
11452     * Damage area of the screen that can be covered by this View's shadow.
11453     *
11454     * This method will guarantee that any changes to shadows cast by a View
11455     * are damaged on the screen for future redraw.
11456     */
11457    private void damageShadowReceiver() {
11458        final AttachInfo ai = mAttachInfo;
11459        if (ai != null) {
11460            ViewParent p = getParent();
11461            if (p != null && p instanceof ViewGroup) {
11462                final ViewGroup vg = (ViewGroup) p;
11463                vg.damageInParent();
11464            }
11465        }
11466    }
11467
11468    /**
11469     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11470     * set any flags or handle all of the cases handled by the default invalidation methods.
11471     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11472     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11473     * walk up the hierarchy, transforming the dirty rect as necessary.
11474     *
11475     * The method also handles normal invalidation logic if display list properties are not
11476     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11477     * backup approach, to handle these cases used in the various property-setting methods.
11478     *
11479     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11480     * are not being used in this view
11481     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11482     * list properties are not being used in this view
11483     */
11484    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11485        if (!isHardwareAccelerated()
11486                || !mRenderNode.isValid()
11487                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11488            if (invalidateParent) {
11489                invalidateParentCaches();
11490            }
11491            if (forceRedraw) {
11492                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11493            }
11494            invalidate(false);
11495        } else {
11496            damageInParent();
11497        }
11498        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11499            damageShadowReceiver();
11500        }
11501    }
11502
11503    /**
11504     * Tells the parent view to damage this view's bounds.
11505     *
11506     * @hide
11507     */
11508    protected void damageInParent() {
11509        final AttachInfo ai = mAttachInfo;
11510        final ViewParent p = mParent;
11511        if (p != null && ai != null) {
11512            final Rect r = ai.mTmpInvalRect;
11513            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11514            if (mParent instanceof ViewGroup) {
11515                ((ViewGroup) mParent).damageChild(this, r);
11516            } else {
11517                mParent.invalidateChild(this, r);
11518            }
11519        }
11520    }
11521
11522    /**
11523     * Utility method to transform a given Rect by the current matrix of this view.
11524     */
11525    void transformRect(final Rect rect) {
11526        if (!getMatrix().isIdentity()) {
11527            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11528            boundingRect.set(rect);
11529            getMatrix().mapRect(boundingRect);
11530            rect.set((int) Math.floor(boundingRect.left),
11531                    (int) Math.floor(boundingRect.top),
11532                    (int) Math.ceil(boundingRect.right),
11533                    (int) Math.ceil(boundingRect.bottom));
11534        }
11535    }
11536
11537    /**
11538     * Used to indicate that the parent of this view should clear its caches. This functionality
11539     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11540     * which is necessary when various parent-managed properties of the view change, such as
11541     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11542     * clears the parent caches and does not causes an invalidate event.
11543     *
11544     * @hide
11545     */
11546    protected void invalidateParentCaches() {
11547        if (mParent instanceof View) {
11548            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11549        }
11550    }
11551
11552    /**
11553     * Used to indicate that the parent of this view should be invalidated. This functionality
11554     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11555     * which is necessary when various parent-managed properties of the view change, such as
11556     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11557     * an invalidation event to the parent.
11558     *
11559     * @hide
11560     */
11561    protected void invalidateParentIfNeeded() {
11562        if (isHardwareAccelerated() && mParent instanceof View) {
11563            ((View) mParent).invalidate(true);
11564        }
11565    }
11566
11567    /**
11568     * @hide
11569     */
11570    protected void invalidateParentIfNeededAndWasQuickRejected() {
11571        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11572            // View was rejected last time it was drawn by its parent; this may have changed
11573            invalidateParentIfNeeded();
11574        }
11575    }
11576
11577    /**
11578     * Indicates whether this View is opaque. An opaque View guarantees that it will
11579     * draw all the pixels overlapping its bounds using a fully opaque color.
11580     *
11581     * Subclasses of View should override this method whenever possible to indicate
11582     * whether an instance is opaque. Opaque Views are treated in a special way by
11583     * the View hierarchy, possibly allowing it to perform optimizations during
11584     * invalidate/draw passes.
11585     *
11586     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11587     */
11588    @ViewDebug.ExportedProperty(category = "drawing")
11589    public boolean isOpaque() {
11590        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11591                getFinalAlpha() >= 1.0f;
11592    }
11593
11594    /**
11595     * @hide
11596     */
11597    protected void computeOpaqueFlags() {
11598        // Opaque if:
11599        //   - Has a background
11600        //   - Background is opaque
11601        //   - Doesn't have scrollbars or scrollbars overlay
11602
11603        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11604            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11605        } else {
11606            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11607        }
11608
11609        final int flags = mViewFlags;
11610        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11611                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11612                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11613            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11614        } else {
11615            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11616        }
11617    }
11618
11619    /**
11620     * @hide
11621     */
11622    protected boolean hasOpaqueScrollbars() {
11623        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11624    }
11625
11626    /**
11627     * @return A handler associated with the thread running the View. This
11628     * handler can be used to pump events in the UI events queue.
11629     */
11630    public Handler getHandler() {
11631        final AttachInfo attachInfo = mAttachInfo;
11632        if (attachInfo != null) {
11633            return attachInfo.mHandler;
11634        }
11635        return null;
11636    }
11637
11638    /**
11639     * Gets the view root associated with the View.
11640     * @return The view root, or null if none.
11641     * @hide
11642     */
11643    public ViewRootImpl getViewRootImpl() {
11644        if (mAttachInfo != null) {
11645            return mAttachInfo.mViewRootImpl;
11646        }
11647        return null;
11648    }
11649
11650    /**
11651     * @hide
11652     */
11653    public HardwareRenderer getHardwareRenderer() {
11654        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11655    }
11656
11657    /**
11658     * <p>Causes the Runnable to be added to the message queue.
11659     * The runnable will be run on the user interface thread.</p>
11660     *
11661     * @param action The Runnable that will be executed.
11662     *
11663     * @return Returns true if the Runnable was successfully placed in to the
11664     *         message queue.  Returns false on failure, usually because the
11665     *         looper processing the message queue is exiting.
11666     *
11667     * @see #postDelayed
11668     * @see #removeCallbacks
11669     */
11670    public boolean post(Runnable action) {
11671        final AttachInfo attachInfo = mAttachInfo;
11672        if (attachInfo != null) {
11673            return attachInfo.mHandler.post(action);
11674        }
11675        // Assume that post will succeed later
11676        ViewRootImpl.getRunQueue().post(action);
11677        return true;
11678    }
11679
11680    /**
11681     * <p>Causes the Runnable to be added to the message queue, to be run
11682     * after the specified amount of time elapses.
11683     * The runnable will be run on the user interface thread.</p>
11684     *
11685     * @param action The Runnable that will be executed.
11686     * @param delayMillis The delay (in milliseconds) until the Runnable
11687     *        will be executed.
11688     *
11689     * @return true if the Runnable was successfully placed in to the
11690     *         message queue.  Returns false on failure, usually because the
11691     *         looper processing the message queue is exiting.  Note that a
11692     *         result of true does not mean the Runnable will be processed --
11693     *         if the looper is quit before the delivery time of the message
11694     *         occurs then the message will be dropped.
11695     *
11696     * @see #post
11697     * @see #removeCallbacks
11698     */
11699    public boolean postDelayed(Runnable action, long delayMillis) {
11700        final AttachInfo attachInfo = mAttachInfo;
11701        if (attachInfo != null) {
11702            return attachInfo.mHandler.postDelayed(action, delayMillis);
11703        }
11704        // Assume that post will succeed later
11705        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11706        return true;
11707    }
11708
11709    /**
11710     * <p>Causes the Runnable to execute on the next animation time step.
11711     * The runnable will be run on the user interface thread.</p>
11712     *
11713     * @param action The Runnable that will be executed.
11714     *
11715     * @see #postOnAnimationDelayed
11716     * @see #removeCallbacks
11717     */
11718    public void postOnAnimation(Runnable action) {
11719        final AttachInfo attachInfo = mAttachInfo;
11720        if (attachInfo != null) {
11721            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11722                    Choreographer.CALLBACK_ANIMATION, action, null);
11723        } else {
11724            // Assume that post will succeed later
11725            ViewRootImpl.getRunQueue().post(action);
11726        }
11727    }
11728
11729    /**
11730     * <p>Causes the Runnable to execute on the next animation time step,
11731     * after the specified amount of time elapses.
11732     * The runnable will be run on the user interface thread.</p>
11733     *
11734     * @param action The Runnable that will be executed.
11735     * @param delayMillis The delay (in milliseconds) until the Runnable
11736     *        will be executed.
11737     *
11738     * @see #postOnAnimation
11739     * @see #removeCallbacks
11740     */
11741    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11742        final AttachInfo attachInfo = mAttachInfo;
11743        if (attachInfo != null) {
11744            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11745                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11746        } else {
11747            // Assume that post will succeed later
11748            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11749        }
11750    }
11751
11752    /**
11753     * <p>Removes the specified Runnable from the message queue.</p>
11754     *
11755     * @param action The Runnable to remove from the message handling queue
11756     *
11757     * @return true if this view could ask the Handler to remove the Runnable,
11758     *         false otherwise. When the returned value is true, the Runnable
11759     *         may or may not have been actually removed from the message queue
11760     *         (for instance, if the Runnable was not in the queue already.)
11761     *
11762     * @see #post
11763     * @see #postDelayed
11764     * @see #postOnAnimation
11765     * @see #postOnAnimationDelayed
11766     */
11767    public boolean removeCallbacks(Runnable action) {
11768        if (action != null) {
11769            final AttachInfo attachInfo = mAttachInfo;
11770            if (attachInfo != null) {
11771                attachInfo.mHandler.removeCallbacks(action);
11772                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11773                        Choreographer.CALLBACK_ANIMATION, action, null);
11774            }
11775            // Assume that post will succeed later
11776            ViewRootImpl.getRunQueue().removeCallbacks(action);
11777        }
11778        return true;
11779    }
11780
11781    /**
11782     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11783     * Use this to invalidate the View from a non-UI thread.</p>
11784     *
11785     * <p>This method can be invoked from outside of the UI thread
11786     * only when this View is attached to a window.</p>
11787     *
11788     * @see #invalidate()
11789     * @see #postInvalidateDelayed(long)
11790     */
11791    public void postInvalidate() {
11792        postInvalidateDelayed(0);
11793    }
11794
11795    /**
11796     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11797     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11798     *
11799     * <p>This method can be invoked from outside of the UI thread
11800     * only when this View is attached to a window.</p>
11801     *
11802     * @param left The left coordinate of the rectangle to invalidate.
11803     * @param top The top coordinate of the rectangle to invalidate.
11804     * @param right The right coordinate of the rectangle to invalidate.
11805     * @param bottom The bottom coordinate of the rectangle to invalidate.
11806     *
11807     * @see #invalidate(int, int, int, int)
11808     * @see #invalidate(Rect)
11809     * @see #postInvalidateDelayed(long, int, int, int, int)
11810     */
11811    public void postInvalidate(int left, int top, int right, int bottom) {
11812        postInvalidateDelayed(0, left, top, right, bottom);
11813    }
11814
11815    /**
11816     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11817     * loop. Waits for the specified amount of time.</p>
11818     *
11819     * <p>This method can be invoked from outside of the UI thread
11820     * only when this View is attached to a window.</p>
11821     *
11822     * @param delayMilliseconds the duration in milliseconds to delay the
11823     *         invalidation by
11824     *
11825     * @see #invalidate()
11826     * @see #postInvalidate()
11827     */
11828    public void postInvalidateDelayed(long delayMilliseconds) {
11829        // We try only with the AttachInfo because there's no point in invalidating
11830        // if we are not attached to our window
11831        final AttachInfo attachInfo = mAttachInfo;
11832        if (attachInfo != null) {
11833            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11834        }
11835    }
11836
11837    /**
11838     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11839     * through the event loop. Waits for the specified amount of time.</p>
11840     *
11841     * <p>This method can be invoked from outside of the UI thread
11842     * only when this View is attached to a window.</p>
11843     *
11844     * @param delayMilliseconds the duration in milliseconds to delay the
11845     *         invalidation by
11846     * @param left The left coordinate of the rectangle to invalidate.
11847     * @param top The top coordinate of the rectangle to invalidate.
11848     * @param right The right coordinate of the rectangle to invalidate.
11849     * @param bottom The bottom coordinate of the rectangle to invalidate.
11850     *
11851     * @see #invalidate(int, int, int, int)
11852     * @see #invalidate(Rect)
11853     * @see #postInvalidate(int, int, int, int)
11854     */
11855    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11856            int right, int bottom) {
11857
11858        // We try only with the AttachInfo because there's no point in invalidating
11859        // if we are not attached to our window
11860        final AttachInfo attachInfo = mAttachInfo;
11861        if (attachInfo != null) {
11862            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11863            info.target = this;
11864            info.left = left;
11865            info.top = top;
11866            info.right = right;
11867            info.bottom = bottom;
11868
11869            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11870        }
11871    }
11872
11873    /**
11874     * <p>Cause an invalidate to happen on the next animation time step, typically the
11875     * next display frame.</p>
11876     *
11877     * <p>This method can be invoked from outside of the UI thread
11878     * only when this View is attached to a window.</p>
11879     *
11880     * @see #invalidate()
11881     */
11882    public void postInvalidateOnAnimation() {
11883        // We try only with the AttachInfo because there's no point in invalidating
11884        // if we are not attached to our window
11885        final AttachInfo attachInfo = mAttachInfo;
11886        if (attachInfo != null) {
11887            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11888        }
11889    }
11890
11891    /**
11892     * <p>Cause an invalidate of the specified area to happen on the next animation
11893     * time step, typically the next display frame.</p>
11894     *
11895     * <p>This method can be invoked from outside of the UI thread
11896     * only when this View is attached to a window.</p>
11897     *
11898     * @param left The left coordinate of the rectangle to invalidate.
11899     * @param top The top coordinate of the rectangle to invalidate.
11900     * @param right The right coordinate of the rectangle to invalidate.
11901     * @param bottom The bottom coordinate of the rectangle to invalidate.
11902     *
11903     * @see #invalidate(int, int, int, int)
11904     * @see #invalidate(Rect)
11905     */
11906    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11907        // We try only with the AttachInfo because there's no point in invalidating
11908        // if we are not attached to our window
11909        final AttachInfo attachInfo = mAttachInfo;
11910        if (attachInfo != null) {
11911            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11912            info.target = this;
11913            info.left = left;
11914            info.top = top;
11915            info.right = right;
11916            info.bottom = bottom;
11917
11918            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11919        }
11920    }
11921
11922    /**
11923     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11924     * This event is sent at most once every
11925     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11926     */
11927    private void postSendViewScrolledAccessibilityEventCallback() {
11928        if (mSendViewScrolledAccessibilityEvent == null) {
11929            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11930        }
11931        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11932            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11933            postDelayed(mSendViewScrolledAccessibilityEvent,
11934                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11935        }
11936    }
11937
11938    /**
11939     * Called by a parent to request that a child update its values for mScrollX
11940     * and mScrollY if necessary. This will typically be done if the child is
11941     * animating a scroll using a {@link android.widget.Scroller Scroller}
11942     * object.
11943     */
11944    public void computeScroll() {
11945    }
11946
11947    /**
11948     * <p>Indicate whether the horizontal edges are faded when the view is
11949     * scrolled horizontally.</p>
11950     *
11951     * @return true if the horizontal edges should are faded on scroll, false
11952     *         otherwise
11953     *
11954     * @see #setHorizontalFadingEdgeEnabled(boolean)
11955     *
11956     * @attr ref android.R.styleable#View_requiresFadingEdge
11957     */
11958    public boolean isHorizontalFadingEdgeEnabled() {
11959        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11960    }
11961
11962    /**
11963     * <p>Define whether the horizontal edges should be faded when this view
11964     * is scrolled horizontally.</p>
11965     *
11966     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11967     *                                    be faded when the view is scrolled
11968     *                                    horizontally
11969     *
11970     * @see #isHorizontalFadingEdgeEnabled()
11971     *
11972     * @attr ref android.R.styleable#View_requiresFadingEdge
11973     */
11974    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11975        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11976            if (horizontalFadingEdgeEnabled) {
11977                initScrollCache();
11978            }
11979
11980            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11981        }
11982    }
11983
11984    /**
11985     * <p>Indicate whether the vertical edges are faded when the view is
11986     * scrolled horizontally.</p>
11987     *
11988     * @return true if the vertical edges should are faded on scroll, false
11989     *         otherwise
11990     *
11991     * @see #setVerticalFadingEdgeEnabled(boolean)
11992     *
11993     * @attr ref android.R.styleable#View_requiresFadingEdge
11994     */
11995    public boolean isVerticalFadingEdgeEnabled() {
11996        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11997    }
11998
11999    /**
12000     * <p>Define whether the vertical edges should be faded when this view
12001     * is scrolled vertically.</p>
12002     *
12003     * @param verticalFadingEdgeEnabled true if the vertical edges should
12004     *                                  be faded when the view is scrolled
12005     *                                  vertically
12006     *
12007     * @see #isVerticalFadingEdgeEnabled()
12008     *
12009     * @attr ref android.R.styleable#View_requiresFadingEdge
12010     */
12011    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12012        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12013            if (verticalFadingEdgeEnabled) {
12014                initScrollCache();
12015            }
12016
12017            mViewFlags ^= FADING_EDGE_VERTICAL;
12018        }
12019    }
12020
12021    /**
12022     * Returns the strength, or intensity, of the top faded edge. The strength is
12023     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12024     * returns 0.0 or 1.0 but no value in between.
12025     *
12026     * Subclasses should override this method to provide a smoother fade transition
12027     * when scrolling occurs.
12028     *
12029     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12030     */
12031    protected float getTopFadingEdgeStrength() {
12032        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12033    }
12034
12035    /**
12036     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12037     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12038     * returns 0.0 or 1.0 but no value in between.
12039     *
12040     * Subclasses should override this method to provide a smoother fade transition
12041     * when scrolling occurs.
12042     *
12043     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12044     */
12045    protected float getBottomFadingEdgeStrength() {
12046        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12047                computeVerticalScrollRange() ? 1.0f : 0.0f;
12048    }
12049
12050    /**
12051     * Returns the strength, or intensity, of the left faded edge. The strength is
12052     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12053     * returns 0.0 or 1.0 but no value in between.
12054     *
12055     * Subclasses should override this method to provide a smoother fade transition
12056     * when scrolling occurs.
12057     *
12058     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12059     */
12060    protected float getLeftFadingEdgeStrength() {
12061        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12062    }
12063
12064    /**
12065     * Returns the strength, or intensity, of the right faded edge. The strength is
12066     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12067     * returns 0.0 or 1.0 but no value in between.
12068     *
12069     * Subclasses should override this method to provide a smoother fade transition
12070     * when scrolling occurs.
12071     *
12072     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12073     */
12074    protected float getRightFadingEdgeStrength() {
12075        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12076                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12077    }
12078
12079    /**
12080     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12081     * scrollbar is not drawn by default.</p>
12082     *
12083     * @return true if the horizontal scrollbar should be painted, false
12084     *         otherwise
12085     *
12086     * @see #setHorizontalScrollBarEnabled(boolean)
12087     */
12088    public boolean isHorizontalScrollBarEnabled() {
12089        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12090    }
12091
12092    /**
12093     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12094     * scrollbar is not drawn by default.</p>
12095     *
12096     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12097     *                                   be painted
12098     *
12099     * @see #isHorizontalScrollBarEnabled()
12100     */
12101    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12102        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12103            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12104            computeOpaqueFlags();
12105            resolvePadding();
12106        }
12107    }
12108
12109    /**
12110     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12111     * scrollbar is not drawn by default.</p>
12112     *
12113     * @return true if the vertical scrollbar should be painted, false
12114     *         otherwise
12115     *
12116     * @see #setVerticalScrollBarEnabled(boolean)
12117     */
12118    public boolean isVerticalScrollBarEnabled() {
12119        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12120    }
12121
12122    /**
12123     * <p>Define whether the vertical scrollbar should be drawn or not. The
12124     * scrollbar is not drawn by default.</p>
12125     *
12126     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12127     *                                 be painted
12128     *
12129     * @see #isVerticalScrollBarEnabled()
12130     */
12131    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12132        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12133            mViewFlags ^= SCROLLBARS_VERTICAL;
12134            computeOpaqueFlags();
12135            resolvePadding();
12136        }
12137    }
12138
12139    /**
12140     * @hide
12141     */
12142    protected void recomputePadding() {
12143        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12144    }
12145
12146    /**
12147     * Define whether scrollbars will fade when the view is not scrolling.
12148     *
12149     * @param fadeScrollbars wheter to enable fading
12150     *
12151     * @attr ref android.R.styleable#View_fadeScrollbars
12152     */
12153    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12154        initScrollCache();
12155        final ScrollabilityCache scrollabilityCache = mScrollCache;
12156        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12157        if (fadeScrollbars) {
12158            scrollabilityCache.state = ScrollabilityCache.OFF;
12159        } else {
12160            scrollabilityCache.state = ScrollabilityCache.ON;
12161        }
12162    }
12163
12164    /**
12165     *
12166     * Returns true if scrollbars will fade when this view is not scrolling
12167     *
12168     * @return true if scrollbar fading is enabled
12169     *
12170     * @attr ref android.R.styleable#View_fadeScrollbars
12171     */
12172    public boolean isScrollbarFadingEnabled() {
12173        return mScrollCache != null && mScrollCache.fadeScrollBars;
12174    }
12175
12176    /**
12177     *
12178     * Returns the delay before scrollbars fade.
12179     *
12180     * @return the delay before scrollbars fade
12181     *
12182     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12183     */
12184    public int getScrollBarDefaultDelayBeforeFade() {
12185        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12186                mScrollCache.scrollBarDefaultDelayBeforeFade;
12187    }
12188
12189    /**
12190     * Define the delay before scrollbars fade.
12191     *
12192     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12193     *
12194     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12195     */
12196    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12197        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12198    }
12199
12200    /**
12201     *
12202     * Returns the scrollbar fade duration.
12203     *
12204     * @return the scrollbar fade duration
12205     *
12206     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12207     */
12208    public int getScrollBarFadeDuration() {
12209        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12210                mScrollCache.scrollBarFadeDuration;
12211    }
12212
12213    /**
12214     * Define the scrollbar fade duration.
12215     *
12216     * @param scrollBarFadeDuration - the scrollbar fade duration
12217     *
12218     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12219     */
12220    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12221        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12222    }
12223
12224    /**
12225     *
12226     * Returns the scrollbar size.
12227     *
12228     * @return the scrollbar size
12229     *
12230     * @attr ref android.R.styleable#View_scrollbarSize
12231     */
12232    public int getScrollBarSize() {
12233        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12234                mScrollCache.scrollBarSize;
12235    }
12236
12237    /**
12238     * Define the scrollbar size.
12239     *
12240     * @param scrollBarSize - the scrollbar size
12241     *
12242     * @attr ref android.R.styleable#View_scrollbarSize
12243     */
12244    public void setScrollBarSize(int scrollBarSize) {
12245        getScrollCache().scrollBarSize = scrollBarSize;
12246    }
12247
12248    /**
12249     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12250     * inset. When inset, they add to the padding of the view. And the scrollbars
12251     * can be drawn inside the padding area or on the edge of the view. For example,
12252     * if a view has a background drawable and you want to draw the scrollbars
12253     * inside the padding specified by the drawable, you can use
12254     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12255     * appear at the edge of the view, ignoring the padding, then you can use
12256     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12257     * @param style the style of the scrollbars. Should be one of
12258     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12259     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12260     * @see #SCROLLBARS_INSIDE_OVERLAY
12261     * @see #SCROLLBARS_INSIDE_INSET
12262     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12263     * @see #SCROLLBARS_OUTSIDE_INSET
12264     *
12265     * @attr ref android.R.styleable#View_scrollbarStyle
12266     */
12267    public void setScrollBarStyle(@ScrollBarStyle int style) {
12268        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12269            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12270            computeOpaqueFlags();
12271            resolvePadding();
12272        }
12273    }
12274
12275    /**
12276     * <p>Returns the current scrollbar style.</p>
12277     * @return the current scrollbar style
12278     * @see #SCROLLBARS_INSIDE_OVERLAY
12279     * @see #SCROLLBARS_INSIDE_INSET
12280     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12281     * @see #SCROLLBARS_OUTSIDE_INSET
12282     *
12283     * @attr ref android.R.styleable#View_scrollbarStyle
12284     */
12285    @ViewDebug.ExportedProperty(mapping = {
12286            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12287            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12288            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12289            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12290    })
12291    @ScrollBarStyle
12292    public int getScrollBarStyle() {
12293        return mViewFlags & SCROLLBARS_STYLE_MASK;
12294    }
12295
12296    /**
12297     * <p>Compute the horizontal range that the horizontal scrollbar
12298     * represents.</p>
12299     *
12300     * <p>The range is expressed in arbitrary units that must be the same as the
12301     * units used by {@link #computeHorizontalScrollExtent()} and
12302     * {@link #computeHorizontalScrollOffset()}.</p>
12303     *
12304     * <p>The default range is the drawing width of this view.</p>
12305     *
12306     * @return the total horizontal range represented by the horizontal
12307     *         scrollbar
12308     *
12309     * @see #computeHorizontalScrollExtent()
12310     * @see #computeHorizontalScrollOffset()
12311     * @see android.widget.ScrollBarDrawable
12312     */
12313    protected int computeHorizontalScrollRange() {
12314        return getWidth();
12315    }
12316
12317    /**
12318     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12319     * within the horizontal range. This value is used to compute the position
12320     * of the thumb within the scrollbar's track.</p>
12321     *
12322     * <p>The range is expressed in arbitrary units that must be the same as the
12323     * units used by {@link #computeHorizontalScrollRange()} and
12324     * {@link #computeHorizontalScrollExtent()}.</p>
12325     *
12326     * <p>The default offset is the scroll offset of this view.</p>
12327     *
12328     * @return the horizontal offset of the scrollbar's thumb
12329     *
12330     * @see #computeHorizontalScrollRange()
12331     * @see #computeHorizontalScrollExtent()
12332     * @see android.widget.ScrollBarDrawable
12333     */
12334    protected int computeHorizontalScrollOffset() {
12335        return mScrollX;
12336    }
12337
12338    /**
12339     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12340     * within the horizontal range. This value is used to compute the length
12341     * of the thumb within the scrollbar's track.</p>
12342     *
12343     * <p>The range is expressed in arbitrary units that must be the same as the
12344     * units used by {@link #computeHorizontalScrollRange()} and
12345     * {@link #computeHorizontalScrollOffset()}.</p>
12346     *
12347     * <p>The default extent is the drawing width of this view.</p>
12348     *
12349     * @return the horizontal extent of the scrollbar's thumb
12350     *
12351     * @see #computeHorizontalScrollRange()
12352     * @see #computeHorizontalScrollOffset()
12353     * @see android.widget.ScrollBarDrawable
12354     */
12355    protected int computeHorizontalScrollExtent() {
12356        return getWidth();
12357    }
12358
12359    /**
12360     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12361     *
12362     * <p>The range is expressed in arbitrary units that must be the same as the
12363     * units used by {@link #computeVerticalScrollExtent()} and
12364     * {@link #computeVerticalScrollOffset()}.</p>
12365     *
12366     * @return the total vertical range represented by the vertical scrollbar
12367     *
12368     * <p>The default range is the drawing height of this view.</p>
12369     *
12370     * @see #computeVerticalScrollExtent()
12371     * @see #computeVerticalScrollOffset()
12372     * @see android.widget.ScrollBarDrawable
12373     */
12374    protected int computeVerticalScrollRange() {
12375        return getHeight();
12376    }
12377
12378    /**
12379     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12380     * within the horizontal range. This value is used to compute the position
12381     * of the thumb within the scrollbar's track.</p>
12382     *
12383     * <p>The range is expressed in arbitrary units that must be the same as the
12384     * units used by {@link #computeVerticalScrollRange()} and
12385     * {@link #computeVerticalScrollExtent()}.</p>
12386     *
12387     * <p>The default offset is the scroll offset of this view.</p>
12388     *
12389     * @return the vertical offset of the scrollbar's thumb
12390     *
12391     * @see #computeVerticalScrollRange()
12392     * @see #computeVerticalScrollExtent()
12393     * @see android.widget.ScrollBarDrawable
12394     */
12395    protected int computeVerticalScrollOffset() {
12396        return mScrollY;
12397    }
12398
12399    /**
12400     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12401     * within the vertical range. This value is used to compute the length
12402     * of the thumb within the scrollbar's track.</p>
12403     *
12404     * <p>The range is expressed in arbitrary units that must be the same as the
12405     * units used by {@link #computeVerticalScrollRange()} and
12406     * {@link #computeVerticalScrollOffset()}.</p>
12407     *
12408     * <p>The default extent is the drawing height of this view.</p>
12409     *
12410     * @return the vertical extent of the scrollbar's thumb
12411     *
12412     * @see #computeVerticalScrollRange()
12413     * @see #computeVerticalScrollOffset()
12414     * @see android.widget.ScrollBarDrawable
12415     */
12416    protected int computeVerticalScrollExtent() {
12417        return getHeight();
12418    }
12419
12420    /**
12421     * Check if this view can be scrolled horizontally in a certain direction.
12422     *
12423     * @param direction Negative to check scrolling left, positive to check scrolling right.
12424     * @return true if this view can be scrolled in the specified direction, false otherwise.
12425     */
12426    public boolean canScrollHorizontally(int direction) {
12427        final int offset = computeHorizontalScrollOffset();
12428        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12429        if (range == 0) return false;
12430        if (direction < 0) {
12431            return offset > 0;
12432        } else {
12433            return offset < range - 1;
12434        }
12435    }
12436
12437    /**
12438     * Check if this view can be scrolled vertically in a certain direction.
12439     *
12440     * @param direction Negative to check scrolling up, positive to check scrolling down.
12441     * @return true if this view can be scrolled in the specified direction, false otherwise.
12442     */
12443    public boolean canScrollVertically(int direction) {
12444        final int offset = computeVerticalScrollOffset();
12445        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12446        if (range == 0) return false;
12447        if (direction < 0) {
12448            return offset > 0;
12449        } else {
12450            return offset < range - 1;
12451        }
12452    }
12453
12454    /**
12455     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12456     * scrollbars are painted only if they have been awakened first.</p>
12457     *
12458     * @param canvas the canvas on which to draw the scrollbars
12459     *
12460     * @see #awakenScrollBars(int)
12461     */
12462    protected final void onDrawScrollBars(Canvas canvas) {
12463        // scrollbars are drawn only when the animation is running
12464        final ScrollabilityCache cache = mScrollCache;
12465        if (cache != null) {
12466
12467            int state = cache.state;
12468
12469            if (state == ScrollabilityCache.OFF) {
12470                return;
12471            }
12472
12473            boolean invalidate = false;
12474
12475            if (state == ScrollabilityCache.FADING) {
12476                // We're fading -- get our fade interpolation
12477                if (cache.interpolatorValues == null) {
12478                    cache.interpolatorValues = new float[1];
12479                }
12480
12481                float[] values = cache.interpolatorValues;
12482
12483                // Stops the animation if we're done
12484                if (cache.scrollBarInterpolator.timeToValues(values) ==
12485                        Interpolator.Result.FREEZE_END) {
12486                    cache.state = ScrollabilityCache.OFF;
12487                } else {
12488                    cache.scrollBar.setAlpha(Math.round(values[0]));
12489                }
12490
12491                // This will make the scroll bars inval themselves after
12492                // drawing. We only want this when we're fading so that
12493                // we prevent excessive redraws
12494                invalidate = true;
12495            } else {
12496                // We're just on -- but we may have been fading before so
12497                // reset alpha
12498                cache.scrollBar.setAlpha(255);
12499            }
12500
12501
12502            final int viewFlags = mViewFlags;
12503
12504            final boolean drawHorizontalScrollBar =
12505                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12506            final boolean drawVerticalScrollBar =
12507                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12508                && !isVerticalScrollBarHidden();
12509
12510            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12511                final int width = mRight - mLeft;
12512                final int height = mBottom - mTop;
12513
12514                final ScrollBarDrawable scrollBar = cache.scrollBar;
12515
12516                final int scrollX = mScrollX;
12517                final int scrollY = mScrollY;
12518                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12519
12520                int left;
12521                int top;
12522                int right;
12523                int bottom;
12524
12525                if (drawHorizontalScrollBar) {
12526                    int size = scrollBar.getSize(false);
12527                    if (size <= 0) {
12528                        size = cache.scrollBarSize;
12529                    }
12530
12531                    scrollBar.setParameters(computeHorizontalScrollRange(),
12532                                            computeHorizontalScrollOffset(),
12533                                            computeHorizontalScrollExtent(), false);
12534                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12535                            getVerticalScrollbarWidth() : 0;
12536                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12537                    left = scrollX + (mPaddingLeft & inside);
12538                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12539                    bottom = top + size;
12540                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12541                    if (invalidate) {
12542                        invalidate(left, top, right, bottom);
12543                    }
12544                }
12545
12546                if (drawVerticalScrollBar) {
12547                    int size = scrollBar.getSize(true);
12548                    if (size <= 0) {
12549                        size = cache.scrollBarSize;
12550                    }
12551
12552                    scrollBar.setParameters(computeVerticalScrollRange(),
12553                                            computeVerticalScrollOffset(),
12554                                            computeVerticalScrollExtent(), true);
12555                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12556                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12557                        verticalScrollbarPosition = isLayoutRtl() ?
12558                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12559                    }
12560                    switch (verticalScrollbarPosition) {
12561                        default:
12562                        case SCROLLBAR_POSITION_RIGHT:
12563                            left = scrollX + width - size - (mUserPaddingRight & inside);
12564                            break;
12565                        case SCROLLBAR_POSITION_LEFT:
12566                            left = scrollX + (mUserPaddingLeft & inside);
12567                            break;
12568                    }
12569                    top = scrollY + (mPaddingTop & inside);
12570                    right = left + size;
12571                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12572                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12573                    if (invalidate) {
12574                        invalidate(left, top, right, bottom);
12575                    }
12576                }
12577            }
12578        }
12579    }
12580
12581    /**
12582     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12583     * FastScroller is visible.
12584     * @return whether to temporarily hide the vertical scrollbar
12585     * @hide
12586     */
12587    protected boolean isVerticalScrollBarHidden() {
12588        return false;
12589    }
12590
12591    /**
12592     * <p>Draw the horizontal scrollbar if
12593     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12594     *
12595     * @param canvas the canvas on which to draw the scrollbar
12596     * @param scrollBar the scrollbar's drawable
12597     *
12598     * @see #isHorizontalScrollBarEnabled()
12599     * @see #computeHorizontalScrollRange()
12600     * @see #computeHorizontalScrollExtent()
12601     * @see #computeHorizontalScrollOffset()
12602     * @see android.widget.ScrollBarDrawable
12603     * @hide
12604     */
12605    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12606            int l, int t, int r, int b) {
12607        scrollBar.setBounds(l, t, r, b);
12608        scrollBar.draw(canvas);
12609    }
12610
12611    /**
12612     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12613     * returns true.</p>
12614     *
12615     * @param canvas the canvas on which to draw the scrollbar
12616     * @param scrollBar the scrollbar's drawable
12617     *
12618     * @see #isVerticalScrollBarEnabled()
12619     * @see #computeVerticalScrollRange()
12620     * @see #computeVerticalScrollExtent()
12621     * @see #computeVerticalScrollOffset()
12622     * @see android.widget.ScrollBarDrawable
12623     * @hide
12624     */
12625    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12626            int l, int t, int r, int b) {
12627        scrollBar.setBounds(l, t, r, b);
12628        scrollBar.draw(canvas);
12629    }
12630
12631    /**
12632     * Implement this to do your drawing.
12633     *
12634     * @param canvas the canvas on which the background will be drawn
12635     */
12636    protected void onDraw(Canvas canvas) {
12637    }
12638
12639    /*
12640     * Caller is responsible for calling requestLayout if necessary.
12641     * (This allows addViewInLayout to not request a new layout.)
12642     */
12643    void assignParent(ViewParent parent) {
12644        if (mParent == null) {
12645            mParent = parent;
12646        } else if (parent == null) {
12647            mParent = null;
12648        } else {
12649            throw new RuntimeException("view " + this + " being added, but"
12650                    + " it already has a parent");
12651        }
12652    }
12653
12654    /**
12655     * This is called when the view is attached to a window.  At this point it
12656     * has a Surface and will start drawing.  Note that this function is
12657     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12658     * however it may be called any time before the first onDraw -- including
12659     * before or after {@link #onMeasure(int, int)}.
12660     *
12661     * @see #onDetachedFromWindow()
12662     */
12663    protected void onAttachedToWindow() {
12664        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12665            mParent.requestTransparentRegion(this);
12666        }
12667
12668        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12669            initialAwakenScrollBars();
12670            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12671        }
12672
12673        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12674
12675        jumpDrawablesToCurrentState();
12676
12677        resetSubtreeAccessibilityStateChanged();
12678
12679        invalidateOutline();
12680
12681        if (isFocused()) {
12682            InputMethodManager imm = InputMethodManager.peekInstance();
12683            imm.focusIn(this);
12684        }
12685    }
12686
12687    /**
12688     * Resolve all RTL related properties.
12689     *
12690     * @return true if resolution of RTL properties has been done
12691     *
12692     * @hide
12693     */
12694    public boolean resolveRtlPropertiesIfNeeded() {
12695        if (!needRtlPropertiesResolution()) return false;
12696
12697        // Order is important here: LayoutDirection MUST be resolved first
12698        if (!isLayoutDirectionResolved()) {
12699            resolveLayoutDirection();
12700            resolveLayoutParams();
12701        }
12702        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12703        if (!isTextDirectionResolved()) {
12704            resolveTextDirection();
12705        }
12706        if (!isTextAlignmentResolved()) {
12707            resolveTextAlignment();
12708        }
12709        // Should resolve Drawables before Padding because we need the layout direction of the
12710        // Drawable to correctly resolve Padding.
12711        if (!isDrawablesResolved()) {
12712            resolveDrawables();
12713        }
12714        if (!isPaddingResolved()) {
12715            resolvePadding();
12716        }
12717        onRtlPropertiesChanged(getLayoutDirection());
12718        return true;
12719    }
12720
12721    /**
12722     * Reset resolution of all RTL related properties.
12723     *
12724     * @hide
12725     */
12726    public void resetRtlProperties() {
12727        resetResolvedLayoutDirection();
12728        resetResolvedTextDirection();
12729        resetResolvedTextAlignment();
12730        resetResolvedPadding();
12731        resetResolvedDrawables();
12732    }
12733
12734    /**
12735     * @see #onScreenStateChanged(int)
12736     */
12737    void dispatchScreenStateChanged(int screenState) {
12738        onScreenStateChanged(screenState);
12739    }
12740
12741    /**
12742     * This method is called whenever the state of the screen this view is
12743     * attached to changes. A state change will usually occurs when the screen
12744     * turns on or off (whether it happens automatically or the user does it
12745     * manually.)
12746     *
12747     * @param screenState The new state of the screen. Can be either
12748     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12749     */
12750    public void onScreenStateChanged(int screenState) {
12751    }
12752
12753    /**
12754     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12755     */
12756    private boolean hasRtlSupport() {
12757        return mContext.getApplicationInfo().hasRtlSupport();
12758    }
12759
12760    /**
12761     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12762     * RTL not supported)
12763     */
12764    private boolean isRtlCompatibilityMode() {
12765        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12766        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12767    }
12768
12769    /**
12770     * @return true if RTL properties need resolution.
12771     *
12772     */
12773    private boolean needRtlPropertiesResolution() {
12774        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12775    }
12776
12777    /**
12778     * Called when any RTL property (layout direction or text direction or text alignment) has
12779     * been changed.
12780     *
12781     * Subclasses need to override this method to take care of cached information that depends on the
12782     * resolved layout direction, or to inform child views that inherit their layout direction.
12783     *
12784     * The default implementation does nothing.
12785     *
12786     * @param layoutDirection the direction of the layout
12787     *
12788     * @see #LAYOUT_DIRECTION_LTR
12789     * @see #LAYOUT_DIRECTION_RTL
12790     */
12791    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12792    }
12793
12794    /**
12795     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12796     * that the parent directionality can and will be resolved before its children.
12797     *
12798     * @return true if resolution has been done, false otherwise.
12799     *
12800     * @hide
12801     */
12802    public boolean resolveLayoutDirection() {
12803        // Clear any previous layout direction resolution
12804        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12805
12806        if (hasRtlSupport()) {
12807            // Set resolved depending on layout direction
12808            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12809                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12810                case LAYOUT_DIRECTION_INHERIT:
12811                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12812                    // later to get the correct resolved value
12813                    if (!canResolveLayoutDirection()) return false;
12814
12815                    // Parent has not yet resolved, LTR is still the default
12816                    try {
12817                        if (!mParent.isLayoutDirectionResolved()) return false;
12818
12819                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12820                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12821                        }
12822                    } catch (AbstractMethodError e) {
12823                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12824                                " does not fully implement ViewParent", e);
12825                    }
12826                    break;
12827                case LAYOUT_DIRECTION_RTL:
12828                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12829                    break;
12830                case LAYOUT_DIRECTION_LOCALE:
12831                    if((LAYOUT_DIRECTION_RTL ==
12832                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12833                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12834                    }
12835                    break;
12836                default:
12837                    // Nothing to do, LTR by default
12838            }
12839        }
12840
12841        // Set to resolved
12842        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12843        return true;
12844    }
12845
12846    /**
12847     * Check if layout direction resolution can be done.
12848     *
12849     * @return true if layout direction resolution can be done otherwise return false.
12850     */
12851    public boolean canResolveLayoutDirection() {
12852        switch (getRawLayoutDirection()) {
12853            case LAYOUT_DIRECTION_INHERIT:
12854                if (mParent != null) {
12855                    try {
12856                        return mParent.canResolveLayoutDirection();
12857                    } catch (AbstractMethodError e) {
12858                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12859                                " does not fully implement ViewParent", e);
12860                    }
12861                }
12862                return false;
12863
12864            default:
12865                return true;
12866        }
12867    }
12868
12869    /**
12870     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12871     * {@link #onMeasure(int, int)}.
12872     *
12873     * @hide
12874     */
12875    public void resetResolvedLayoutDirection() {
12876        // Reset the current resolved bits
12877        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12878    }
12879
12880    /**
12881     * @return true if the layout direction is inherited.
12882     *
12883     * @hide
12884     */
12885    public boolean isLayoutDirectionInherited() {
12886        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12887    }
12888
12889    /**
12890     * @return true if layout direction has been resolved.
12891     */
12892    public boolean isLayoutDirectionResolved() {
12893        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12894    }
12895
12896    /**
12897     * Return if padding has been resolved
12898     *
12899     * @hide
12900     */
12901    boolean isPaddingResolved() {
12902        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12903    }
12904
12905    /**
12906     * Resolves padding depending on layout direction, if applicable, and
12907     * recomputes internal padding values to adjust for scroll bars.
12908     *
12909     * @hide
12910     */
12911    public void resolvePadding() {
12912        final int resolvedLayoutDirection = getLayoutDirection();
12913
12914        if (!isRtlCompatibilityMode()) {
12915            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12916            // If start / end padding are defined, they will be resolved (hence overriding) to
12917            // left / right or right / left depending on the resolved layout direction.
12918            // If start / end padding are not defined, use the left / right ones.
12919            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12920                Rect padding = sThreadLocal.get();
12921                if (padding == null) {
12922                    padding = new Rect();
12923                    sThreadLocal.set(padding);
12924                }
12925                mBackground.getPadding(padding);
12926                if (!mLeftPaddingDefined) {
12927                    mUserPaddingLeftInitial = padding.left;
12928                }
12929                if (!mRightPaddingDefined) {
12930                    mUserPaddingRightInitial = padding.right;
12931                }
12932            }
12933            switch (resolvedLayoutDirection) {
12934                case LAYOUT_DIRECTION_RTL:
12935                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12936                        mUserPaddingRight = mUserPaddingStart;
12937                    } else {
12938                        mUserPaddingRight = mUserPaddingRightInitial;
12939                    }
12940                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12941                        mUserPaddingLeft = mUserPaddingEnd;
12942                    } else {
12943                        mUserPaddingLeft = mUserPaddingLeftInitial;
12944                    }
12945                    break;
12946                case LAYOUT_DIRECTION_LTR:
12947                default:
12948                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12949                        mUserPaddingLeft = mUserPaddingStart;
12950                    } else {
12951                        mUserPaddingLeft = mUserPaddingLeftInitial;
12952                    }
12953                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12954                        mUserPaddingRight = mUserPaddingEnd;
12955                    } else {
12956                        mUserPaddingRight = mUserPaddingRightInitial;
12957                    }
12958            }
12959
12960            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12961        }
12962
12963        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12964        onRtlPropertiesChanged(resolvedLayoutDirection);
12965
12966        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12967    }
12968
12969    /**
12970     * Reset the resolved layout direction.
12971     *
12972     * @hide
12973     */
12974    public void resetResolvedPadding() {
12975        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12976    }
12977
12978    /**
12979     * This is called when the view is detached from a window.  At this point it
12980     * no longer has a surface for drawing.
12981     *
12982     * @see #onAttachedToWindow()
12983     */
12984    protected void onDetachedFromWindow() {
12985    }
12986
12987    /**
12988     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12989     * after onDetachedFromWindow().
12990     *
12991     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12992     * The super method should be called at the end of the overriden method to ensure
12993     * subclasses are destroyed first
12994     *
12995     * @hide
12996     */
12997    protected void onDetachedFromWindowInternal() {
12998        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12999        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13000
13001        removeUnsetPressCallback();
13002        removeLongPressCallback();
13003        removePerformClickCallback();
13004        removeSendViewScrolledAccessibilityEventCallback();
13005        stopNestedScroll();
13006
13007        destroyDrawingCache();
13008
13009        cleanupDraw();
13010        mCurrentAnimation = null;
13011    }
13012
13013    private void cleanupDraw() {
13014        resetDisplayList();
13015        if (mAttachInfo != null) {
13016            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13017        }
13018    }
13019
13020    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13021    }
13022
13023    /**
13024     * @return The number of times this view has been attached to a window
13025     */
13026    protected int getWindowAttachCount() {
13027        return mWindowAttachCount;
13028    }
13029
13030    /**
13031     * Retrieve a unique token identifying the window this view is attached to.
13032     * @return Return the window's token for use in
13033     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13034     */
13035    public IBinder getWindowToken() {
13036        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13037    }
13038
13039    /**
13040     * Retrieve the {@link WindowId} for the window this view is
13041     * currently attached to.
13042     */
13043    public WindowId getWindowId() {
13044        if (mAttachInfo == null) {
13045            return null;
13046        }
13047        if (mAttachInfo.mWindowId == null) {
13048            try {
13049                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13050                        mAttachInfo.mWindowToken);
13051                mAttachInfo.mWindowId = new WindowId(
13052                        mAttachInfo.mIWindowId);
13053            } catch (RemoteException e) {
13054            }
13055        }
13056        return mAttachInfo.mWindowId;
13057    }
13058
13059    /**
13060     * Retrieve a unique token identifying the top-level "real" window of
13061     * the window that this view is attached to.  That is, this is like
13062     * {@link #getWindowToken}, except if the window this view in is a panel
13063     * window (attached to another containing window), then the token of
13064     * the containing window is returned instead.
13065     *
13066     * @return Returns the associated window token, either
13067     * {@link #getWindowToken()} or the containing window's token.
13068     */
13069    public IBinder getApplicationWindowToken() {
13070        AttachInfo ai = mAttachInfo;
13071        if (ai != null) {
13072            IBinder appWindowToken = ai.mPanelParentWindowToken;
13073            if (appWindowToken == null) {
13074                appWindowToken = ai.mWindowToken;
13075            }
13076            return appWindowToken;
13077        }
13078        return null;
13079    }
13080
13081    /**
13082     * Gets the logical display to which the view's window has been attached.
13083     *
13084     * @return The logical display, or null if the view is not currently attached to a window.
13085     */
13086    public Display getDisplay() {
13087        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13088    }
13089
13090    /**
13091     * Retrieve private session object this view hierarchy is using to
13092     * communicate with the window manager.
13093     * @return the session object to communicate with the window manager
13094     */
13095    /*package*/ IWindowSession getWindowSession() {
13096        return mAttachInfo != null ? mAttachInfo.mSession : null;
13097    }
13098
13099    /**
13100     * @param info the {@link android.view.View.AttachInfo} to associated with
13101     *        this view
13102     */
13103    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13104        //System.out.println("Attached! " + this);
13105        mAttachInfo = info;
13106        if (mOverlay != null) {
13107            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13108        }
13109        mWindowAttachCount++;
13110        // We will need to evaluate the drawable state at least once.
13111        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13112        if (mFloatingTreeObserver != null) {
13113            info.mTreeObserver.merge(mFloatingTreeObserver);
13114            mFloatingTreeObserver = null;
13115        }
13116        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13117            mAttachInfo.mScrollContainers.add(this);
13118            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13119        }
13120        performCollectViewAttributes(mAttachInfo, visibility);
13121        onAttachedToWindow();
13122
13123        ListenerInfo li = mListenerInfo;
13124        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13125                li != null ? li.mOnAttachStateChangeListeners : null;
13126        if (listeners != null && listeners.size() > 0) {
13127            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13128            // perform the dispatching. The iterator is a safe guard against listeners that
13129            // could mutate the list by calling the various add/remove methods. This prevents
13130            // the array from being modified while we iterate it.
13131            for (OnAttachStateChangeListener listener : listeners) {
13132                listener.onViewAttachedToWindow(this);
13133            }
13134        }
13135
13136        int vis = info.mWindowVisibility;
13137        if (vis != GONE) {
13138            onWindowVisibilityChanged(vis);
13139        }
13140        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13141            // If nobody has evaluated the drawable state yet, then do it now.
13142            refreshDrawableState();
13143        }
13144        needGlobalAttributesUpdate(false);
13145    }
13146
13147    void dispatchDetachedFromWindow() {
13148        AttachInfo info = mAttachInfo;
13149        if (info != null) {
13150            int vis = info.mWindowVisibility;
13151            if (vis != GONE) {
13152                onWindowVisibilityChanged(GONE);
13153            }
13154        }
13155
13156        onDetachedFromWindow();
13157        onDetachedFromWindowInternal();
13158
13159        ListenerInfo li = mListenerInfo;
13160        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13161                li != null ? li.mOnAttachStateChangeListeners : null;
13162        if (listeners != null && listeners.size() > 0) {
13163            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13164            // perform the dispatching. The iterator is a safe guard against listeners that
13165            // could mutate the list by calling the various add/remove methods. This prevents
13166            // the array from being modified while we iterate it.
13167            for (OnAttachStateChangeListener listener : listeners) {
13168                listener.onViewDetachedFromWindow(this);
13169            }
13170        }
13171
13172        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13173            mAttachInfo.mScrollContainers.remove(this);
13174            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13175        }
13176
13177        mAttachInfo = null;
13178        if (mOverlay != null) {
13179            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13180        }
13181    }
13182
13183    /**
13184     * Cancel any deferred high-level input events that were previously posted to the event queue.
13185     *
13186     * <p>Many views post high-level events such as click handlers to the event queue
13187     * to run deferred in order to preserve a desired user experience - clearing visible
13188     * pressed states before executing, etc. This method will abort any events of this nature
13189     * that are currently in flight.</p>
13190     *
13191     * <p>Custom views that generate their own high-level deferred input events should override
13192     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13193     *
13194     * <p>This will also cancel pending input events for any child views.</p>
13195     *
13196     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13197     * This will not impact newer events posted after this call that may occur as a result of
13198     * lower-level input events still waiting in the queue. If you are trying to prevent
13199     * double-submitted  events for the duration of some sort of asynchronous transaction
13200     * you should also take other steps to protect against unexpected double inputs e.g. calling
13201     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13202     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13203     */
13204    public final void cancelPendingInputEvents() {
13205        dispatchCancelPendingInputEvents();
13206    }
13207
13208    /**
13209     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13210     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13211     */
13212    void dispatchCancelPendingInputEvents() {
13213        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13214        onCancelPendingInputEvents();
13215        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13216            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13217                    " did not call through to super.onCancelPendingInputEvents()");
13218        }
13219    }
13220
13221    /**
13222     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13223     * a parent view.
13224     *
13225     * <p>This method is responsible for removing any pending high-level input events that were
13226     * posted to the event queue to run later. Custom view classes that post their own deferred
13227     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13228     * {@link android.os.Handler} should override this method, call
13229     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13230     * </p>
13231     */
13232    public void onCancelPendingInputEvents() {
13233        removePerformClickCallback();
13234        cancelLongPress();
13235        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13236    }
13237
13238    /**
13239     * Store this view hierarchy's frozen state into the given container.
13240     *
13241     * @param container The SparseArray in which to save the view's state.
13242     *
13243     * @see #restoreHierarchyState(android.util.SparseArray)
13244     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13245     * @see #onSaveInstanceState()
13246     */
13247    public void saveHierarchyState(SparseArray<Parcelable> container) {
13248        dispatchSaveInstanceState(container);
13249    }
13250
13251    /**
13252     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13253     * this view and its children. May be overridden to modify how freezing happens to a
13254     * view's children; for example, some views may want to not store state for their children.
13255     *
13256     * @param container The SparseArray in which to save the view's state.
13257     *
13258     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13259     * @see #saveHierarchyState(android.util.SparseArray)
13260     * @see #onSaveInstanceState()
13261     */
13262    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13263        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13264            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13265            Parcelable state = onSaveInstanceState();
13266            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13267                throw new IllegalStateException(
13268                        "Derived class did not call super.onSaveInstanceState()");
13269            }
13270            if (state != null) {
13271                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13272                // + ": " + state);
13273                container.put(mID, state);
13274            }
13275        }
13276    }
13277
13278    /**
13279     * Hook allowing a view to generate a representation of its internal state
13280     * that can later be used to create a new instance with that same state.
13281     * This state should only contain information that is not persistent or can
13282     * not be reconstructed later. For example, you will never store your
13283     * current position on screen because that will be computed again when a
13284     * new instance of the view is placed in its view hierarchy.
13285     * <p>
13286     * Some examples of things you may store here: the current cursor position
13287     * in a text view (but usually not the text itself since that is stored in a
13288     * content provider or other persistent storage), the currently selected
13289     * item in a list view.
13290     *
13291     * @return Returns a Parcelable object containing the view's current dynamic
13292     *         state, or null if there is nothing interesting to save. The
13293     *         default implementation returns null.
13294     * @see #onRestoreInstanceState(android.os.Parcelable)
13295     * @see #saveHierarchyState(android.util.SparseArray)
13296     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13297     * @see #setSaveEnabled(boolean)
13298     */
13299    protected Parcelable onSaveInstanceState() {
13300        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13301        return BaseSavedState.EMPTY_STATE;
13302    }
13303
13304    /**
13305     * Restore this view hierarchy's frozen state from the given container.
13306     *
13307     * @param container The SparseArray which holds previously frozen states.
13308     *
13309     * @see #saveHierarchyState(android.util.SparseArray)
13310     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13311     * @see #onRestoreInstanceState(android.os.Parcelable)
13312     */
13313    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13314        dispatchRestoreInstanceState(container);
13315    }
13316
13317    /**
13318     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13319     * state for this view and its children. May be overridden to modify how restoring
13320     * happens to a view's children; for example, some views may want to not store state
13321     * for their children.
13322     *
13323     * @param container The SparseArray which holds previously saved state.
13324     *
13325     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13326     * @see #restoreHierarchyState(android.util.SparseArray)
13327     * @see #onRestoreInstanceState(android.os.Parcelable)
13328     */
13329    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13330        if (mID != NO_ID) {
13331            Parcelable state = container.get(mID);
13332            if (state != null) {
13333                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13334                // + ": " + state);
13335                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13336                onRestoreInstanceState(state);
13337                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13338                    throw new IllegalStateException(
13339                            "Derived class did not call super.onRestoreInstanceState()");
13340                }
13341            }
13342        }
13343    }
13344
13345    /**
13346     * Hook allowing a view to re-apply a representation of its internal state that had previously
13347     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13348     * null state.
13349     *
13350     * @param state The frozen state that had previously been returned by
13351     *        {@link #onSaveInstanceState}.
13352     *
13353     * @see #onSaveInstanceState()
13354     * @see #restoreHierarchyState(android.util.SparseArray)
13355     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13356     */
13357    protected void onRestoreInstanceState(Parcelable state) {
13358        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13359        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13360            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13361                    + "received " + state.getClass().toString() + " instead. This usually happens "
13362                    + "when two views of different type have the same id in the same hierarchy. "
13363                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13364                    + "other views do not use the same id.");
13365        }
13366    }
13367
13368    /**
13369     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13370     *
13371     * @return the drawing start time in milliseconds
13372     */
13373    public long getDrawingTime() {
13374        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13375    }
13376
13377    /**
13378     * <p>Enables or disables the duplication of the parent's state into this view. When
13379     * duplication is enabled, this view gets its drawable state from its parent rather
13380     * than from its own internal properties.</p>
13381     *
13382     * <p>Note: in the current implementation, setting this property to true after the
13383     * view was added to a ViewGroup might have no effect at all. This property should
13384     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13385     *
13386     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13387     * property is enabled, an exception will be thrown.</p>
13388     *
13389     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13390     * parent, these states should not be affected by this method.</p>
13391     *
13392     * @param enabled True to enable duplication of the parent's drawable state, false
13393     *                to disable it.
13394     *
13395     * @see #getDrawableState()
13396     * @see #isDuplicateParentStateEnabled()
13397     */
13398    public void setDuplicateParentStateEnabled(boolean enabled) {
13399        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13400    }
13401
13402    /**
13403     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13404     *
13405     * @return True if this view's drawable state is duplicated from the parent,
13406     *         false otherwise
13407     *
13408     * @see #getDrawableState()
13409     * @see #setDuplicateParentStateEnabled(boolean)
13410     */
13411    public boolean isDuplicateParentStateEnabled() {
13412        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13413    }
13414
13415    /**
13416     * <p>Specifies the type of layer backing this view. The layer can be
13417     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13418     * {@link #LAYER_TYPE_HARDWARE}.</p>
13419     *
13420     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13421     * instance that controls how the layer is composed on screen. The following
13422     * properties of the paint are taken into account when composing the layer:</p>
13423     * <ul>
13424     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13425     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13426     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13427     * </ul>
13428     *
13429     * <p>If this view has an alpha value set to < 1.0 by calling
13430     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13431     * by this view's alpha value.</p>
13432     *
13433     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13434     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13435     * for more information on when and how to use layers.</p>
13436     *
13437     * @param layerType The type of layer to use with this view, must be one of
13438     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13439     *        {@link #LAYER_TYPE_HARDWARE}
13440     * @param paint The paint used to compose the layer. This argument is optional
13441     *        and can be null. It is ignored when the layer type is
13442     *        {@link #LAYER_TYPE_NONE}
13443     *
13444     * @see #getLayerType()
13445     * @see #LAYER_TYPE_NONE
13446     * @see #LAYER_TYPE_SOFTWARE
13447     * @see #LAYER_TYPE_HARDWARE
13448     * @see #setAlpha(float)
13449     *
13450     * @attr ref android.R.styleable#View_layerType
13451     */
13452    public void setLayerType(int layerType, Paint paint) {
13453        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13454            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13455                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13456        }
13457
13458        boolean typeChanged = mRenderNode.setLayerType(layerType);
13459
13460        if (!typeChanged) {
13461            setLayerPaint(paint);
13462            return;
13463        }
13464
13465        // Destroy any previous software drawing cache if needed
13466        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13467            destroyDrawingCache();
13468        }
13469
13470        mLayerType = layerType;
13471        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13472        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13473        mRenderNode.setLayerPaint(mLayerPaint);
13474
13475        // draw() behaves differently if we are on a layer, so we need to
13476        // invalidate() here
13477        invalidateParentCaches();
13478        invalidate(true);
13479    }
13480
13481    /**
13482     * Updates the {@link Paint} object used with the current layer (used only if the current
13483     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13484     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13485     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13486     * ensure that the view gets redrawn immediately.
13487     *
13488     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13489     * instance that controls how the layer is composed on screen. The following
13490     * properties of the paint are taken into account when composing the layer:</p>
13491     * <ul>
13492     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13493     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13494     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13495     * </ul>
13496     *
13497     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13498     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13499     *
13500     * @param paint The paint used to compose the layer. This argument is optional
13501     *        and can be null. It is ignored when the layer type is
13502     *        {@link #LAYER_TYPE_NONE}
13503     *
13504     * @see #setLayerType(int, android.graphics.Paint)
13505     */
13506    public void setLayerPaint(Paint paint) {
13507        int layerType = getLayerType();
13508        if (layerType != LAYER_TYPE_NONE) {
13509            mLayerPaint = paint == null ? new Paint() : paint;
13510            if (layerType == LAYER_TYPE_HARDWARE) {
13511                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13512                    invalidateViewProperty(false, false);
13513                }
13514            } else {
13515                invalidate();
13516            }
13517        }
13518    }
13519
13520    /**
13521     * Indicates whether this view has a static layer. A view with layer type
13522     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13523     * dynamic.
13524     */
13525    boolean hasStaticLayer() {
13526        return true;
13527    }
13528
13529    /**
13530     * Indicates what type of layer is currently associated with this view. By default
13531     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13532     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13533     * for more information on the different types of layers.
13534     *
13535     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13536     *         {@link #LAYER_TYPE_HARDWARE}
13537     *
13538     * @see #setLayerType(int, android.graphics.Paint)
13539     * @see #buildLayer()
13540     * @see #LAYER_TYPE_NONE
13541     * @see #LAYER_TYPE_SOFTWARE
13542     * @see #LAYER_TYPE_HARDWARE
13543     */
13544    public int getLayerType() {
13545        return mLayerType;
13546    }
13547
13548    /**
13549     * Forces this view's layer to be created and this view to be rendered
13550     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13551     * invoking this method will have no effect.
13552     *
13553     * This method can for instance be used to render a view into its layer before
13554     * starting an animation. If this view is complex, rendering into the layer
13555     * before starting the animation will avoid skipping frames.
13556     *
13557     * @throws IllegalStateException If this view is not attached to a window
13558     *
13559     * @see #setLayerType(int, android.graphics.Paint)
13560     */
13561    public void buildLayer() {
13562        if (mLayerType == LAYER_TYPE_NONE) return;
13563
13564        final AttachInfo attachInfo = mAttachInfo;
13565        if (attachInfo == null) {
13566            throw new IllegalStateException("This view must be attached to a window first");
13567        }
13568
13569        if (getWidth() == 0 || getHeight() == 0) {
13570            return;
13571        }
13572
13573        switch (mLayerType) {
13574            case LAYER_TYPE_HARDWARE:
13575                // The only part of a hardware layer we can build in response to
13576                // this call is to ensure the display list is up to date.
13577                // The actual rendering of the display list into the layer must
13578                // be done at playback time
13579                updateDisplayListIfDirty();
13580                break;
13581            case LAYER_TYPE_SOFTWARE:
13582                buildDrawingCache(true);
13583                break;
13584        }
13585    }
13586
13587    /**
13588     * If this View draws with a HardwareLayer, returns it.
13589     * Otherwise returns null
13590     *
13591     * TODO: Only TextureView uses this, can we eliminate it?
13592     */
13593    HardwareLayer getHardwareLayer() {
13594        return null;
13595    }
13596
13597    /**
13598     * Destroys all hardware rendering resources. This method is invoked
13599     * when the system needs to reclaim resources. Upon execution of this
13600     * method, you should free any OpenGL resources created by the view.
13601     *
13602     * Note: you <strong>must</strong> call
13603     * <code>super.destroyHardwareResources()</code> when overriding
13604     * this method.
13605     *
13606     * @hide
13607     */
13608    protected void destroyHardwareResources() {
13609        // Although the Layer will be destroyed by RenderNode, we want to release
13610        // the staging display list, which is also a signal to RenderNode that it's
13611        // safe to free its copy of the display list as it knows that we will
13612        // push an updated DisplayList if we try to draw again
13613        resetDisplayList();
13614    }
13615
13616    /**
13617     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13618     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13619     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13620     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13621     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13622     * null.</p>
13623     *
13624     * <p>Enabling the drawing cache is similar to
13625     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13626     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13627     * drawing cache has no effect on rendering because the system uses a different mechanism
13628     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13629     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13630     * for information on how to enable software and hardware layers.</p>
13631     *
13632     * <p>This API can be used to manually generate
13633     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13634     * {@link #getDrawingCache()}.</p>
13635     *
13636     * @param enabled true to enable the drawing cache, false otherwise
13637     *
13638     * @see #isDrawingCacheEnabled()
13639     * @see #getDrawingCache()
13640     * @see #buildDrawingCache()
13641     * @see #setLayerType(int, android.graphics.Paint)
13642     */
13643    public void setDrawingCacheEnabled(boolean enabled) {
13644        mCachingFailed = false;
13645        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13646    }
13647
13648    /**
13649     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13650     *
13651     * @return true if the drawing cache is enabled
13652     *
13653     * @see #setDrawingCacheEnabled(boolean)
13654     * @see #getDrawingCache()
13655     */
13656    @ViewDebug.ExportedProperty(category = "drawing")
13657    public boolean isDrawingCacheEnabled() {
13658        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13659    }
13660
13661    /**
13662     * Debugging utility which recursively outputs the dirty state of a view and its
13663     * descendants.
13664     *
13665     * @hide
13666     */
13667    @SuppressWarnings({"UnusedDeclaration"})
13668    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13669        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13670                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13671                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13672                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13673        if (clear) {
13674            mPrivateFlags &= clearMask;
13675        }
13676        if (this instanceof ViewGroup) {
13677            ViewGroup parent = (ViewGroup) this;
13678            final int count = parent.getChildCount();
13679            for (int i = 0; i < count; i++) {
13680                final View child = parent.getChildAt(i);
13681                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13682            }
13683        }
13684    }
13685
13686    /**
13687     * This method is used by ViewGroup to cause its children to restore or recreate their
13688     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13689     * to recreate its own display list, which would happen if it went through the normal
13690     * draw/dispatchDraw mechanisms.
13691     *
13692     * @hide
13693     */
13694    protected void dispatchGetDisplayList() {}
13695
13696    /**
13697     * A view that is not attached or hardware accelerated cannot create a display list.
13698     * This method checks these conditions and returns the appropriate result.
13699     *
13700     * @return true if view has the ability to create a display list, false otherwise.
13701     *
13702     * @hide
13703     */
13704    public boolean canHaveDisplayList() {
13705        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13706    }
13707
13708    private void updateDisplayListIfDirty() {
13709        final RenderNode renderNode = mRenderNode;
13710        if (!canHaveDisplayList()) {
13711            // can't populate RenderNode, don't try
13712            return;
13713        }
13714
13715        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13716                || !renderNode.isValid()
13717                || (mRecreateDisplayList)) {
13718            // Don't need to recreate the display list, just need to tell our
13719            // children to restore/recreate theirs
13720            if (renderNode.isValid()
13721                    && !mRecreateDisplayList) {
13722                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13723                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13724                dispatchGetDisplayList();
13725
13726                return; // no work needed
13727            }
13728
13729            // If we got here, we're recreating it. Mark it as such to ensure that
13730            // we copy in child display lists into ours in drawChild()
13731            mRecreateDisplayList = true;
13732
13733            int width = mRight - mLeft;
13734            int height = mBottom - mTop;
13735            int layerType = getLayerType();
13736
13737            final HardwareCanvas canvas = renderNode.start(width, height);
13738            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13739
13740            try {
13741                final HardwareLayer layer = getHardwareLayer();
13742                if (layer != null && layer.isValid()) {
13743                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13744                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13745                    buildDrawingCache(true);
13746                    Bitmap cache = getDrawingCache(true);
13747                    if (cache != null) {
13748                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13749                    }
13750                } else {
13751                    computeScroll();
13752
13753                    canvas.translate(-mScrollX, -mScrollY);
13754                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13755                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13756
13757                    // Fast path for layouts with no backgrounds
13758                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13759                        dispatchDraw(canvas);
13760                        if (mOverlay != null && !mOverlay.isEmpty()) {
13761                            mOverlay.getOverlayView().draw(canvas);
13762                        }
13763                    } else {
13764                        draw(canvas);
13765                    }
13766                }
13767            } finally {
13768                renderNode.end(canvas);
13769                setDisplayListProperties(renderNode);
13770            }
13771        } else {
13772            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13773            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13774        }
13775    }
13776
13777    /**
13778     * Returns a RenderNode with View draw content recorded, which can be
13779     * used to draw this view again without executing its draw method.
13780     *
13781     * @return A RenderNode ready to replay, or null if caching is not enabled.
13782     *
13783     * @hide
13784     */
13785    public RenderNode getDisplayList() {
13786        updateDisplayListIfDirty();
13787        return mRenderNode;
13788    }
13789
13790    private void resetDisplayList() {
13791        if (mRenderNode.isValid()) {
13792            mRenderNode.destroyDisplayListData();
13793        }
13794
13795        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13796            mBackgroundRenderNode.destroyDisplayListData();
13797        }
13798    }
13799
13800    /**
13801     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13802     *
13803     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13804     *
13805     * @see #getDrawingCache(boolean)
13806     */
13807    public Bitmap getDrawingCache() {
13808        return getDrawingCache(false);
13809    }
13810
13811    /**
13812     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13813     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13814     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13815     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13816     * request the drawing cache by calling this method and draw it on screen if the
13817     * returned bitmap is not null.</p>
13818     *
13819     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13820     * this method will create a bitmap of the same size as this view. Because this bitmap
13821     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13822     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13823     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13824     * size than the view. This implies that your application must be able to handle this
13825     * size.</p>
13826     *
13827     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13828     *        the current density of the screen when the application is in compatibility
13829     *        mode.
13830     *
13831     * @return A bitmap representing this view or null if cache is disabled.
13832     *
13833     * @see #setDrawingCacheEnabled(boolean)
13834     * @see #isDrawingCacheEnabled()
13835     * @see #buildDrawingCache(boolean)
13836     * @see #destroyDrawingCache()
13837     */
13838    public Bitmap getDrawingCache(boolean autoScale) {
13839        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13840            return null;
13841        }
13842        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13843            buildDrawingCache(autoScale);
13844        }
13845        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13846    }
13847
13848    /**
13849     * <p>Frees the resources used by the drawing cache. If you call
13850     * {@link #buildDrawingCache()} manually without calling
13851     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13852     * should cleanup the cache with this method afterwards.</p>
13853     *
13854     * @see #setDrawingCacheEnabled(boolean)
13855     * @see #buildDrawingCache()
13856     * @see #getDrawingCache()
13857     */
13858    public void destroyDrawingCache() {
13859        if (mDrawingCache != null) {
13860            mDrawingCache.recycle();
13861            mDrawingCache = null;
13862        }
13863        if (mUnscaledDrawingCache != null) {
13864            mUnscaledDrawingCache.recycle();
13865            mUnscaledDrawingCache = null;
13866        }
13867    }
13868
13869    /**
13870     * Setting a solid background color for the drawing cache's bitmaps will improve
13871     * performance and memory usage. Note, though that this should only be used if this
13872     * view will always be drawn on top of a solid color.
13873     *
13874     * @param color The background color to use for the drawing cache's bitmap
13875     *
13876     * @see #setDrawingCacheEnabled(boolean)
13877     * @see #buildDrawingCache()
13878     * @see #getDrawingCache()
13879     */
13880    public void setDrawingCacheBackgroundColor(int color) {
13881        if (color != mDrawingCacheBackgroundColor) {
13882            mDrawingCacheBackgroundColor = color;
13883            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13884        }
13885    }
13886
13887    /**
13888     * @see #setDrawingCacheBackgroundColor(int)
13889     *
13890     * @return The background color to used for the drawing cache's bitmap
13891     */
13892    public int getDrawingCacheBackgroundColor() {
13893        return mDrawingCacheBackgroundColor;
13894    }
13895
13896    /**
13897     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13898     *
13899     * @see #buildDrawingCache(boolean)
13900     */
13901    public void buildDrawingCache() {
13902        buildDrawingCache(false);
13903    }
13904
13905    /**
13906     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13907     *
13908     * <p>If you call {@link #buildDrawingCache()} manually without calling
13909     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13910     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13911     *
13912     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13913     * this method will create a bitmap of the same size as this view. Because this bitmap
13914     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13915     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13916     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13917     * size than the view. This implies that your application must be able to handle this
13918     * size.</p>
13919     *
13920     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13921     * you do not need the drawing cache bitmap, calling this method will increase memory
13922     * usage and cause the view to be rendered in software once, thus negatively impacting
13923     * performance.</p>
13924     *
13925     * @see #getDrawingCache()
13926     * @see #destroyDrawingCache()
13927     */
13928    public void buildDrawingCache(boolean autoScale) {
13929        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13930                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13931            mCachingFailed = false;
13932
13933            int width = mRight - mLeft;
13934            int height = mBottom - mTop;
13935
13936            final AttachInfo attachInfo = mAttachInfo;
13937            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13938
13939            if (autoScale && scalingRequired) {
13940                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13941                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13942            }
13943
13944            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13945            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13946            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13947
13948            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13949            final long drawingCacheSize =
13950                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13951            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13952                if (width > 0 && height > 0) {
13953                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13954                            + projectedBitmapSize + " bytes, only "
13955                            + drawingCacheSize + " available");
13956                }
13957                destroyDrawingCache();
13958                mCachingFailed = true;
13959                return;
13960            }
13961
13962            boolean clear = true;
13963            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13964
13965            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13966                Bitmap.Config quality;
13967                if (!opaque) {
13968                    // Never pick ARGB_4444 because it looks awful
13969                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13970                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13971                        case DRAWING_CACHE_QUALITY_AUTO:
13972                        case DRAWING_CACHE_QUALITY_LOW:
13973                        case DRAWING_CACHE_QUALITY_HIGH:
13974                        default:
13975                            quality = Bitmap.Config.ARGB_8888;
13976                            break;
13977                    }
13978                } else {
13979                    // Optimization for translucent windows
13980                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13981                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13982                }
13983
13984                // Try to cleanup memory
13985                if (bitmap != null) bitmap.recycle();
13986
13987                try {
13988                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13989                            width, height, quality);
13990                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13991                    if (autoScale) {
13992                        mDrawingCache = bitmap;
13993                    } else {
13994                        mUnscaledDrawingCache = bitmap;
13995                    }
13996                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13997                } catch (OutOfMemoryError e) {
13998                    // If there is not enough memory to create the bitmap cache, just
13999                    // ignore the issue as bitmap caches are not required to draw the
14000                    // view hierarchy
14001                    if (autoScale) {
14002                        mDrawingCache = null;
14003                    } else {
14004                        mUnscaledDrawingCache = null;
14005                    }
14006                    mCachingFailed = true;
14007                    return;
14008                }
14009
14010                clear = drawingCacheBackgroundColor != 0;
14011            }
14012
14013            Canvas canvas;
14014            if (attachInfo != null) {
14015                canvas = attachInfo.mCanvas;
14016                if (canvas == null) {
14017                    canvas = new Canvas();
14018                }
14019                canvas.setBitmap(bitmap);
14020                // Temporarily clobber the cached Canvas in case one of our children
14021                // is also using a drawing cache. Without this, the children would
14022                // steal the canvas by attaching their own bitmap to it and bad, bad
14023                // thing would happen (invisible views, corrupted drawings, etc.)
14024                attachInfo.mCanvas = null;
14025            } else {
14026                // This case should hopefully never or seldom happen
14027                canvas = new Canvas(bitmap);
14028            }
14029
14030            if (clear) {
14031                bitmap.eraseColor(drawingCacheBackgroundColor);
14032            }
14033
14034            computeScroll();
14035            final int restoreCount = canvas.save();
14036
14037            if (autoScale && scalingRequired) {
14038                final float scale = attachInfo.mApplicationScale;
14039                canvas.scale(scale, scale);
14040            }
14041
14042            canvas.translate(-mScrollX, -mScrollY);
14043
14044            mPrivateFlags |= PFLAG_DRAWN;
14045            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14046                    mLayerType != LAYER_TYPE_NONE) {
14047                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14048            }
14049
14050            // Fast path for layouts with no backgrounds
14051            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14052                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14053                dispatchDraw(canvas);
14054                if (mOverlay != null && !mOverlay.isEmpty()) {
14055                    mOverlay.getOverlayView().draw(canvas);
14056                }
14057            } else {
14058                draw(canvas);
14059            }
14060
14061            canvas.restoreToCount(restoreCount);
14062            canvas.setBitmap(null);
14063
14064            if (attachInfo != null) {
14065                // Restore the cached Canvas for our siblings
14066                attachInfo.mCanvas = canvas;
14067            }
14068        }
14069    }
14070
14071    /**
14072     * Create a snapshot of the view into a bitmap.  We should probably make
14073     * some form of this public, but should think about the API.
14074     */
14075    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14076        int width = mRight - mLeft;
14077        int height = mBottom - mTop;
14078
14079        final AttachInfo attachInfo = mAttachInfo;
14080        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14081        width = (int) ((width * scale) + 0.5f);
14082        height = (int) ((height * scale) + 0.5f);
14083
14084        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14085                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14086        if (bitmap == null) {
14087            throw new OutOfMemoryError();
14088        }
14089
14090        Resources resources = getResources();
14091        if (resources != null) {
14092            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14093        }
14094
14095        Canvas canvas;
14096        if (attachInfo != null) {
14097            canvas = attachInfo.mCanvas;
14098            if (canvas == null) {
14099                canvas = new Canvas();
14100            }
14101            canvas.setBitmap(bitmap);
14102            // Temporarily clobber the cached Canvas in case one of our children
14103            // is also using a drawing cache. Without this, the children would
14104            // steal the canvas by attaching their own bitmap to it and bad, bad
14105            // things would happen (invisible views, corrupted drawings, etc.)
14106            attachInfo.mCanvas = null;
14107        } else {
14108            // This case should hopefully never or seldom happen
14109            canvas = new Canvas(bitmap);
14110        }
14111
14112        if ((backgroundColor & 0xff000000) != 0) {
14113            bitmap.eraseColor(backgroundColor);
14114        }
14115
14116        computeScroll();
14117        final int restoreCount = canvas.save();
14118        canvas.scale(scale, scale);
14119        canvas.translate(-mScrollX, -mScrollY);
14120
14121        // Temporarily remove the dirty mask
14122        int flags = mPrivateFlags;
14123        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14124
14125        // Fast path for layouts with no backgrounds
14126        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14127            dispatchDraw(canvas);
14128            if (mOverlay != null && !mOverlay.isEmpty()) {
14129                mOverlay.getOverlayView().draw(canvas);
14130            }
14131        } else {
14132            draw(canvas);
14133        }
14134
14135        mPrivateFlags = flags;
14136
14137        canvas.restoreToCount(restoreCount);
14138        canvas.setBitmap(null);
14139
14140        if (attachInfo != null) {
14141            // Restore the cached Canvas for our siblings
14142            attachInfo.mCanvas = canvas;
14143        }
14144
14145        return bitmap;
14146    }
14147
14148    /**
14149     * Indicates whether this View is currently in edit mode. A View is usually
14150     * in edit mode when displayed within a developer tool. For instance, if
14151     * this View is being drawn by a visual user interface builder, this method
14152     * should return true.
14153     *
14154     * Subclasses should check the return value of this method to provide
14155     * different behaviors if their normal behavior might interfere with the
14156     * host environment. For instance: the class spawns a thread in its
14157     * constructor, the drawing code relies on device-specific features, etc.
14158     *
14159     * This method is usually checked in the drawing code of custom widgets.
14160     *
14161     * @return True if this View is in edit mode, false otherwise.
14162     */
14163    public boolean isInEditMode() {
14164        return false;
14165    }
14166
14167    /**
14168     * If the View draws content inside its padding and enables fading edges,
14169     * it needs to support padding offsets. Padding offsets are added to the
14170     * fading edges to extend the length of the fade so that it covers pixels
14171     * drawn inside the padding.
14172     *
14173     * Subclasses of this class should override this method if they need
14174     * to draw content inside the padding.
14175     *
14176     * @return True if padding offset must be applied, false otherwise.
14177     *
14178     * @see #getLeftPaddingOffset()
14179     * @see #getRightPaddingOffset()
14180     * @see #getTopPaddingOffset()
14181     * @see #getBottomPaddingOffset()
14182     *
14183     * @since CURRENT
14184     */
14185    protected boolean isPaddingOffsetRequired() {
14186        return false;
14187    }
14188
14189    /**
14190     * Amount by which to extend the left fading region. Called only when
14191     * {@link #isPaddingOffsetRequired()} returns true.
14192     *
14193     * @return The left padding offset in pixels.
14194     *
14195     * @see #isPaddingOffsetRequired()
14196     *
14197     * @since CURRENT
14198     */
14199    protected int getLeftPaddingOffset() {
14200        return 0;
14201    }
14202
14203    /**
14204     * Amount by which to extend the right fading region. Called only when
14205     * {@link #isPaddingOffsetRequired()} returns true.
14206     *
14207     * @return The right padding offset in pixels.
14208     *
14209     * @see #isPaddingOffsetRequired()
14210     *
14211     * @since CURRENT
14212     */
14213    protected int getRightPaddingOffset() {
14214        return 0;
14215    }
14216
14217    /**
14218     * Amount by which to extend the top fading region. Called only when
14219     * {@link #isPaddingOffsetRequired()} returns true.
14220     *
14221     * @return The top padding offset in pixels.
14222     *
14223     * @see #isPaddingOffsetRequired()
14224     *
14225     * @since CURRENT
14226     */
14227    protected int getTopPaddingOffset() {
14228        return 0;
14229    }
14230
14231    /**
14232     * Amount by which to extend the bottom fading region. Called only when
14233     * {@link #isPaddingOffsetRequired()} returns true.
14234     *
14235     * @return The bottom padding offset in pixels.
14236     *
14237     * @see #isPaddingOffsetRequired()
14238     *
14239     * @since CURRENT
14240     */
14241    protected int getBottomPaddingOffset() {
14242        return 0;
14243    }
14244
14245    /**
14246     * @hide
14247     * @param offsetRequired
14248     */
14249    protected int getFadeTop(boolean offsetRequired) {
14250        int top = mPaddingTop;
14251        if (offsetRequired) top += getTopPaddingOffset();
14252        return top;
14253    }
14254
14255    /**
14256     * @hide
14257     * @param offsetRequired
14258     */
14259    protected int getFadeHeight(boolean offsetRequired) {
14260        int padding = mPaddingTop;
14261        if (offsetRequired) padding += getTopPaddingOffset();
14262        return mBottom - mTop - mPaddingBottom - padding;
14263    }
14264
14265    /**
14266     * <p>Indicates whether this view is attached to a hardware accelerated
14267     * window or not.</p>
14268     *
14269     * <p>Even if this method returns true, it does not mean that every call
14270     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14271     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14272     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14273     * window is hardware accelerated,
14274     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14275     * return false, and this method will return true.</p>
14276     *
14277     * @return True if the view is attached to a window and the window is
14278     *         hardware accelerated; false in any other case.
14279     */
14280    @ViewDebug.ExportedProperty(category = "drawing")
14281    public boolean isHardwareAccelerated() {
14282        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14283    }
14284
14285    /**
14286     * Sets a rectangular area on this view to which the view will be clipped
14287     * when it is drawn. Setting the value to null will remove the clip bounds
14288     * and the view will draw normally, using its full bounds.
14289     *
14290     * @param clipBounds The rectangular area, in the local coordinates of
14291     * this view, to which future drawing operations will be clipped.
14292     */
14293    public void setClipBounds(Rect clipBounds) {
14294        if (clipBounds != null) {
14295            if (clipBounds.equals(mClipBounds)) {
14296                return;
14297            }
14298            if (mClipBounds == null) {
14299                invalidate();
14300                mClipBounds = new Rect(clipBounds);
14301            } else {
14302                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14303                        Math.min(mClipBounds.top, clipBounds.top),
14304                        Math.max(mClipBounds.right, clipBounds.right),
14305                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14306                mClipBounds.set(clipBounds);
14307            }
14308        } else {
14309            if (mClipBounds != null) {
14310                invalidate();
14311                mClipBounds = null;
14312            }
14313        }
14314        mRenderNode.setClipBounds(mClipBounds);
14315    }
14316
14317    /**
14318     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14319     *
14320     * @return A copy of the current clip bounds if clip bounds are set,
14321     * otherwise null.
14322     */
14323    public Rect getClipBounds() {
14324        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14325    }
14326
14327    /**
14328     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14329     * case of an active Animation being run on the view.
14330     */
14331    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14332            Animation a, boolean scalingRequired) {
14333        Transformation invalidationTransform;
14334        final int flags = parent.mGroupFlags;
14335        final boolean initialized = a.isInitialized();
14336        if (!initialized) {
14337            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14338            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14339            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14340            onAnimationStart();
14341        }
14342
14343        final Transformation t = parent.getChildTransformation();
14344        boolean more = a.getTransformation(drawingTime, t, 1f);
14345        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14346            if (parent.mInvalidationTransformation == null) {
14347                parent.mInvalidationTransformation = new Transformation();
14348            }
14349            invalidationTransform = parent.mInvalidationTransformation;
14350            a.getTransformation(drawingTime, invalidationTransform, 1f);
14351        } else {
14352            invalidationTransform = t;
14353        }
14354
14355        if (more) {
14356            if (!a.willChangeBounds()) {
14357                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14358                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14359                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14360                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14361                    // The child need to draw an animation, potentially offscreen, so
14362                    // make sure we do not cancel invalidate requests
14363                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14364                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14365                }
14366            } else {
14367                if (parent.mInvalidateRegion == null) {
14368                    parent.mInvalidateRegion = new RectF();
14369                }
14370                final RectF region = parent.mInvalidateRegion;
14371                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14372                        invalidationTransform);
14373
14374                // The child need to draw an animation, potentially offscreen, so
14375                // make sure we do not cancel invalidate requests
14376                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14377
14378                final int left = mLeft + (int) region.left;
14379                final int top = mTop + (int) region.top;
14380                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14381                        top + (int) (region.height() + .5f));
14382            }
14383        }
14384        return more;
14385    }
14386
14387    /**
14388     * This method is called by getDisplayList() when a display list is recorded for a View.
14389     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14390     */
14391    void setDisplayListProperties(RenderNode renderNode) {
14392        if (renderNode != null) {
14393            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14394            if (mParent instanceof ViewGroup) {
14395                renderNode.setClipToBounds(
14396                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14397            }
14398            float alpha = 1;
14399            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14400                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14401                ViewGroup parentVG = (ViewGroup) mParent;
14402                final Transformation t = parentVG.getChildTransformation();
14403                if (parentVG.getChildStaticTransformation(this, t)) {
14404                    final int transformType = t.getTransformationType();
14405                    if (transformType != Transformation.TYPE_IDENTITY) {
14406                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14407                            alpha = t.getAlpha();
14408                        }
14409                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14410                            renderNode.setStaticMatrix(t.getMatrix());
14411                        }
14412                    }
14413                }
14414            }
14415            if (mTransformationInfo != null) {
14416                alpha *= getFinalAlpha();
14417                if (alpha < 1) {
14418                    final int multipliedAlpha = (int) (255 * alpha);
14419                    if (onSetAlpha(multipliedAlpha)) {
14420                        alpha = 1;
14421                    }
14422                }
14423                renderNode.setAlpha(alpha);
14424            } else if (alpha < 1) {
14425                renderNode.setAlpha(alpha);
14426            }
14427        }
14428    }
14429
14430    /**
14431     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14432     * This draw() method is an implementation detail and is not intended to be overridden or
14433     * to be called from anywhere else other than ViewGroup.drawChild().
14434     */
14435    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14436        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14437        boolean more = false;
14438        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14439        final int flags = parent.mGroupFlags;
14440
14441        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14442            parent.getChildTransformation().clear();
14443            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14444        }
14445
14446        Transformation transformToApply = null;
14447        boolean concatMatrix = false;
14448
14449        boolean scalingRequired = false;
14450        boolean caching;
14451        int layerType = getLayerType();
14452
14453        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14454        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14455                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14456            caching = true;
14457            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14458            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14459        } else {
14460            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14461        }
14462
14463        final Animation a = getAnimation();
14464        if (a != null) {
14465            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14466            concatMatrix = a.willChangeTransformationMatrix();
14467            if (concatMatrix) {
14468                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14469            }
14470            transformToApply = parent.getChildTransformation();
14471        } else {
14472            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14473                // No longer animating: clear out old animation matrix
14474                mRenderNode.setAnimationMatrix(null);
14475                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14476            }
14477            if (!usingRenderNodeProperties &&
14478                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14479                final Transformation t = parent.getChildTransformation();
14480                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14481                if (hasTransform) {
14482                    final int transformType = t.getTransformationType();
14483                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14484                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14485                }
14486            }
14487        }
14488
14489        concatMatrix |= !childHasIdentityMatrix;
14490
14491        // Sets the flag as early as possible to allow draw() implementations
14492        // to call invalidate() successfully when doing animations
14493        mPrivateFlags |= PFLAG_DRAWN;
14494
14495        if (!concatMatrix &&
14496                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14497                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14498                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14499                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14500            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14501            return more;
14502        }
14503        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14504
14505        if (hardwareAccelerated) {
14506            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14507            // retain the flag's value temporarily in the mRecreateDisplayList flag
14508            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14509            mPrivateFlags &= ~PFLAG_INVALIDATED;
14510        }
14511
14512        RenderNode renderNode = null;
14513        Bitmap cache = null;
14514        boolean hasDisplayList = false;
14515        if (caching) {
14516            if (!hardwareAccelerated) {
14517                if (layerType != LAYER_TYPE_NONE) {
14518                    layerType = LAYER_TYPE_SOFTWARE;
14519                    buildDrawingCache(true);
14520                }
14521                cache = getDrawingCache(true);
14522            } else {
14523                switch (layerType) {
14524                    case LAYER_TYPE_SOFTWARE:
14525                        if (usingRenderNodeProperties) {
14526                            hasDisplayList = canHaveDisplayList();
14527                        } else {
14528                            buildDrawingCache(true);
14529                            cache = getDrawingCache(true);
14530                        }
14531                        break;
14532                    case LAYER_TYPE_HARDWARE:
14533                        if (usingRenderNodeProperties) {
14534                            hasDisplayList = canHaveDisplayList();
14535                        }
14536                        break;
14537                    case LAYER_TYPE_NONE:
14538                        // Delay getting the display list until animation-driven alpha values are
14539                        // set up and possibly passed on to the view
14540                        hasDisplayList = canHaveDisplayList();
14541                        break;
14542                }
14543            }
14544        }
14545        usingRenderNodeProperties &= hasDisplayList;
14546        if (usingRenderNodeProperties) {
14547            renderNode = getDisplayList();
14548            if (!renderNode.isValid()) {
14549                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14550                // to getDisplayList(), the display list will be marked invalid and we should not
14551                // try to use it again.
14552                renderNode = null;
14553                hasDisplayList = false;
14554                usingRenderNodeProperties = false;
14555            }
14556        }
14557
14558        int sx = 0;
14559        int sy = 0;
14560        if (!hasDisplayList) {
14561            computeScroll();
14562            sx = mScrollX;
14563            sy = mScrollY;
14564        }
14565
14566        final boolean hasNoCache = cache == null || hasDisplayList;
14567        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14568                layerType != LAYER_TYPE_HARDWARE;
14569
14570        int restoreTo = -1;
14571        if (!usingRenderNodeProperties || transformToApply != null) {
14572            restoreTo = canvas.save();
14573        }
14574        if (offsetForScroll) {
14575            canvas.translate(mLeft - sx, mTop - sy);
14576        } else {
14577            if (!usingRenderNodeProperties) {
14578                canvas.translate(mLeft, mTop);
14579            }
14580            if (scalingRequired) {
14581                if (usingRenderNodeProperties) {
14582                    // TODO: Might not need this if we put everything inside the DL
14583                    restoreTo = canvas.save();
14584                }
14585                // mAttachInfo cannot be null, otherwise scalingRequired == false
14586                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14587                canvas.scale(scale, scale);
14588            }
14589        }
14590
14591        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14592        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14593                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14594            if (transformToApply != null || !childHasIdentityMatrix) {
14595                int transX = 0;
14596                int transY = 0;
14597
14598                if (offsetForScroll) {
14599                    transX = -sx;
14600                    transY = -sy;
14601                }
14602
14603                if (transformToApply != null) {
14604                    if (concatMatrix) {
14605                        if (usingRenderNodeProperties) {
14606                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14607                        } else {
14608                            // Undo the scroll translation, apply the transformation matrix,
14609                            // then redo the scroll translate to get the correct result.
14610                            canvas.translate(-transX, -transY);
14611                            canvas.concat(transformToApply.getMatrix());
14612                            canvas.translate(transX, transY);
14613                        }
14614                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14615                    }
14616
14617                    float transformAlpha = transformToApply.getAlpha();
14618                    if (transformAlpha < 1) {
14619                        alpha *= transformAlpha;
14620                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14621                    }
14622                }
14623
14624                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14625                    canvas.translate(-transX, -transY);
14626                    canvas.concat(getMatrix());
14627                    canvas.translate(transX, transY);
14628                }
14629            }
14630
14631            // Deal with alpha if it is or used to be <1
14632            if (alpha < 1 ||
14633                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14634                if (alpha < 1) {
14635                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14636                } else {
14637                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14638                }
14639                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14640                if (hasNoCache) {
14641                    final int multipliedAlpha = (int) (255 * alpha);
14642                    if (!onSetAlpha(multipliedAlpha)) {
14643                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14644                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14645                                layerType != LAYER_TYPE_NONE) {
14646                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14647                        }
14648                        if (usingRenderNodeProperties) {
14649                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14650                        } else  if (layerType == LAYER_TYPE_NONE) {
14651                            final int scrollX = hasDisplayList ? 0 : sx;
14652                            final int scrollY = hasDisplayList ? 0 : sy;
14653                            canvas.saveLayerAlpha(scrollX, scrollY,
14654                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14655                                    multipliedAlpha, layerFlags);
14656                        }
14657                    } else {
14658                        // Alpha is handled by the child directly, clobber the layer's alpha
14659                        mPrivateFlags |= PFLAG_ALPHA_SET;
14660                    }
14661                }
14662            }
14663        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14664            onSetAlpha(255);
14665            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14666        }
14667
14668        if (!usingRenderNodeProperties) {
14669            // apply clips directly, since RenderNode won't do it for this draw
14670            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14671                    && cache == null) {
14672                if (offsetForScroll) {
14673                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14674                } else {
14675                    if (!scalingRequired || cache == null) {
14676                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14677                    } else {
14678                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14679                    }
14680                }
14681            }
14682
14683            if (mClipBounds != null) {
14684                // clip bounds ignore scroll
14685                canvas.clipRect(mClipBounds);
14686            }
14687        }
14688
14689
14690
14691        if (!usingRenderNodeProperties && hasDisplayList) {
14692            renderNode = getDisplayList();
14693            if (!renderNode.isValid()) {
14694                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14695                // to getDisplayList(), the display list will be marked invalid and we should not
14696                // try to use it again.
14697                renderNode = null;
14698                hasDisplayList = false;
14699            }
14700        }
14701
14702        if (hasNoCache) {
14703            boolean layerRendered = false;
14704            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14705                final HardwareLayer layer = getHardwareLayer();
14706                if (layer != null && layer.isValid()) {
14707                    mLayerPaint.setAlpha((int) (alpha * 255));
14708                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14709                    layerRendered = true;
14710                } else {
14711                    final int scrollX = hasDisplayList ? 0 : sx;
14712                    final int scrollY = hasDisplayList ? 0 : sy;
14713                    canvas.saveLayer(scrollX, scrollY,
14714                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14715                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14716                }
14717            }
14718
14719            if (!layerRendered) {
14720                if (!hasDisplayList) {
14721                    // Fast path for layouts with no backgrounds
14722                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14723                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14724                        dispatchDraw(canvas);
14725                    } else {
14726                        draw(canvas);
14727                    }
14728                } else {
14729                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14730                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14731                }
14732            }
14733        } else if (cache != null) {
14734            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14735            Paint cachePaint;
14736
14737            if (layerType == LAYER_TYPE_NONE) {
14738                cachePaint = parent.mCachePaint;
14739                if (cachePaint == null) {
14740                    cachePaint = new Paint();
14741                    cachePaint.setDither(false);
14742                    parent.mCachePaint = cachePaint;
14743                }
14744                if (alpha < 1) {
14745                    cachePaint.setAlpha((int) (alpha * 255));
14746                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14747                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14748                    cachePaint.setAlpha(255);
14749                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14750                }
14751            } else {
14752                cachePaint = mLayerPaint;
14753                cachePaint.setAlpha((int) (alpha * 255));
14754            }
14755            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14756        }
14757
14758        if (restoreTo >= 0) {
14759            canvas.restoreToCount(restoreTo);
14760        }
14761
14762        if (a != null && !more) {
14763            if (!hardwareAccelerated && !a.getFillAfter()) {
14764                onSetAlpha(255);
14765            }
14766            parent.finishAnimatingView(this, a);
14767        }
14768
14769        if (more && hardwareAccelerated) {
14770            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14771                // alpha animations should cause the child to recreate its display list
14772                invalidate(true);
14773            }
14774        }
14775
14776        mRecreateDisplayList = false;
14777
14778        return more;
14779    }
14780
14781    /**
14782     * Manually render this view (and all of its children) to the given Canvas.
14783     * The view must have already done a full layout before this function is
14784     * called.  When implementing a view, implement
14785     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14786     * If you do need to override this method, call the superclass version.
14787     *
14788     * @param canvas The Canvas to which the View is rendered.
14789     */
14790    public void draw(Canvas canvas) {
14791        final int privateFlags = mPrivateFlags;
14792        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14793                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14794        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14795
14796        /*
14797         * Draw traversal performs several drawing steps which must be executed
14798         * in the appropriate order:
14799         *
14800         *      1. Draw the background
14801         *      2. If necessary, save the canvas' layers to prepare for fading
14802         *      3. Draw view's content
14803         *      4. Draw children
14804         *      5. If necessary, draw the fading edges and restore layers
14805         *      6. Draw decorations (scrollbars for instance)
14806         */
14807
14808        // Step 1, draw the background, if needed
14809        int saveCount;
14810
14811        if (!dirtyOpaque) {
14812            drawBackground(canvas);
14813        }
14814
14815        // skip step 2 & 5 if possible (common case)
14816        final int viewFlags = mViewFlags;
14817        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14818        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14819        if (!verticalEdges && !horizontalEdges) {
14820            // Step 3, draw the content
14821            if (!dirtyOpaque) onDraw(canvas);
14822
14823            // Step 4, draw the children
14824            dispatchDraw(canvas);
14825
14826            // Step 6, draw decorations (scrollbars)
14827            onDrawScrollBars(canvas);
14828
14829            if (mOverlay != null && !mOverlay.isEmpty()) {
14830                mOverlay.getOverlayView().dispatchDraw(canvas);
14831            }
14832
14833            // we're done...
14834            return;
14835        }
14836
14837        /*
14838         * Here we do the full fledged routine...
14839         * (this is an uncommon case where speed matters less,
14840         * this is why we repeat some of the tests that have been
14841         * done above)
14842         */
14843
14844        boolean drawTop = false;
14845        boolean drawBottom = false;
14846        boolean drawLeft = false;
14847        boolean drawRight = false;
14848
14849        float topFadeStrength = 0.0f;
14850        float bottomFadeStrength = 0.0f;
14851        float leftFadeStrength = 0.0f;
14852        float rightFadeStrength = 0.0f;
14853
14854        // Step 2, save the canvas' layers
14855        int paddingLeft = mPaddingLeft;
14856
14857        final boolean offsetRequired = isPaddingOffsetRequired();
14858        if (offsetRequired) {
14859            paddingLeft += getLeftPaddingOffset();
14860        }
14861
14862        int left = mScrollX + paddingLeft;
14863        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14864        int top = mScrollY + getFadeTop(offsetRequired);
14865        int bottom = top + getFadeHeight(offsetRequired);
14866
14867        if (offsetRequired) {
14868            right += getRightPaddingOffset();
14869            bottom += getBottomPaddingOffset();
14870        }
14871
14872        final ScrollabilityCache scrollabilityCache = mScrollCache;
14873        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14874        int length = (int) fadeHeight;
14875
14876        // clip the fade length if top and bottom fades overlap
14877        // overlapping fades produce odd-looking artifacts
14878        if (verticalEdges && (top + length > bottom - length)) {
14879            length = (bottom - top) / 2;
14880        }
14881
14882        // also clip horizontal fades if necessary
14883        if (horizontalEdges && (left + length > right - length)) {
14884            length = (right - left) / 2;
14885        }
14886
14887        if (verticalEdges) {
14888            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14889            drawTop = topFadeStrength * fadeHeight > 1.0f;
14890            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14891            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14892        }
14893
14894        if (horizontalEdges) {
14895            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14896            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14897            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14898            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14899        }
14900
14901        saveCount = canvas.getSaveCount();
14902
14903        int solidColor = getSolidColor();
14904        if (solidColor == 0) {
14905            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14906
14907            if (drawTop) {
14908                canvas.saveLayer(left, top, right, top + length, null, flags);
14909            }
14910
14911            if (drawBottom) {
14912                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14913            }
14914
14915            if (drawLeft) {
14916                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14917            }
14918
14919            if (drawRight) {
14920                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14921            }
14922        } else {
14923            scrollabilityCache.setFadeColor(solidColor);
14924        }
14925
14926        // Step 3, draw the content
14927        if (!dirtyOpaque) onDraw(canvas);
14928
14929        // Step 4, draw the children
14930        dispatchDraw(canvas);
14931
14932        // Step 5, draw the fade effect and restore layers
14933        final Paint p = scrollabilityCache.paint;
14934        final Matrix matrix = scrollabilityCache.matrix;
14935        final Shader fade = scrollabilityCache.shader;
14936
14937        if (drawTop) {
14938            matrix.setScale(1, fadeHeight * topFadeStrength);
14939            matrix.postTranslate(left, top);
14940            fade.setLocalMatrix(matrix);
14941            p.setShader(fade);
14942            canvas.drawRect(left, top, right, top + length, p);
14943        }
14944
14945        if (drawBottom) {
14946            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14947            matrix.postRotate(180);
14948            matrix.postTranslate(left, bottom);
14949            fade.setLocalMatrix(matrix);
14950            p.setShader(fade);
14951            canvas.drawRect(left, bottom - length, right, bottom, p);
14952        }
14953
14954        if (drawLeft) {
14955            matrix.setScale(1, fadeHeight * leftFadeStrength);
14956            matrix.postRotate(-90);
14957            matrix.postTranslate(left, top);
14958            fade.setLocalMatrix(matrix);
14959            p.setShader(fade);
14960            canvas.drawRect(left, top, left + length, bottom, p);
14961        }
14962
14963        if (drawRight) {
14964            matrix.setScale(1, fadeHeight * rightFadeStrength);
14965            matrix.postRotate(90);
14966            matrix.postTranslate(right, top);
14967            fade.setLocalMatrix(matrix);
14968            p.setShader(fade);
14969            canvas.drawRect(right - length, top, right, bottom, p);
14970        }
14971
14972        canvas.restoreToCount(saveCount);
14973
14974        // Step 6, draw decorations (scrollbars)
14975        onDrawScrollBars(canvas);
14976
14977        if (mOverlay != null && !mOverlay.isEmpty()) {
14978            mOverlay.getOverlayView().dispatchDraw(canvas);
14979        }
14980    }
14981
14982    /**
14983     * Draws the background onto the specified canvas.
14984     *
14985     * @param canvas Canvas on which to draw the background
14986     */
14987    private void drawBackground(Canvas canvas) {
14988        final Drawable background = mBackground;
14989        if (background == null) {
14990            return;
14991        }
14992
14993        if (mBackgroundSizeChanged) {
14994            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14995            mBackgroundSizeChanged = false;
14996            invalidateOutline();
14997        }
14998
14999        // Attempt to use a display list if requested.
15000        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15001                && mAttachInfo.mHardwareRenderer != null) {
15002            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15003
15004            final RenderNode displayList = mBackgroundRenderNode;
15005            if (displayList != null && displayList.isValid()) {
15006                setBackgroundDisplayListProperties(displayList);
15007                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15008                return;
15009            }
15010        }
15011
15012        final int scrollX = mScrollX;
15013        final int scrollY = mScrollY;
15014        if ((scrollX | scrollY) == 0) {
15015            background.draw(canvas);
15016        } else {
15017            canvas.translate(scrollX, scrollY);
15018            background.draw(canvas);
15019            canvas.translate(-scrollX, -scrollY);
15020        }
15021    }
15022
15023    /**
15024     * Set up background drawable display list properties.
15025     *
15026     * @param displayList Valid display list for the background drawable
15027     */
15028    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15029        displayList.setTranslationX(mScrollX);
15030        displayList.setTranslationY(mScrollY);
15031    }
15032
15033    /**
15034     * Creates a new display list or updates the existing display list for the
15035     * specified Drawable.
15036     *
15037     * @param drawable Drawable for which to create a display list
15038     * @param renderNode Existing RenderNode, or {@code null}
15039     * @return A valid display list for the specified drawable
15040     */
15041    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15042        if (renderNode == null) {
15043            renderNode = RenderNode.create(drawable.getClass().getName());
15044        }
15045
15046        final Rect bounds = drawable.getBounds();
15047        final int width = bounds.width();
15048        final int height = bounds.height();
15049        final HardwareCanvas canvas = renderNode.start(width, height);
15050        try {
15051            drawable.draw(canvas);
15052        } finally {
15053            renderNode.end(canvas);
15054        }
15055
15056        // Set up drawable properties that are view-independent.
15057        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15058        renderNode.setProjectBackwards(drawable.isProjected());
15059        renderNode.setProjectionReceiver(true);
15060        renderNode.setClipToBounds(false);
15061        return renderNode;
15062    }
15063
15064    /**
15065     * Returns the overlay for this view, creating it if it does not yet exist.
15066     * Adding drawables to the overlay will cause them to be displayed whenever
15067     * the view itself is redrawn. Objects in the overlay should be actively
15068     * managed: remove them when they should not be displayed anymore. The
15069     * overlay will always have the same size as its host view.
15070     *
15071     * <p>Note: Overlays do not currently work correctly with {@link
15072     * SurfaceView} or {@link TextureView}; contents in overlays for these
15073     * types of views may not display correctly.</p>
15074     *
15075     * @return The ViewOverlay object for this view.
15076     * @see ViewOverlay
15077     */
15078    public ViewOverlay getOverlay() {
15079        if (mOverlay == null) {
15080            mOverlay = new ViewOverlay(mContext, this);
15081        }
15082        return mOverlay;
15083    }
15084
15085    /**
15086     * Override this if your view is known to always be drawn on top of a solid color background,
15087     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15088     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15089     * should be set to 0xFF.
15090     *
15091     * @see #setVerticalFadingEdgeEnabled(boolean)
15092     * @see #setHorizontalFadingEdgeEnabled(boolean)
15093     *
15094     * @return The known solid color background for this view, or 0 if the color may vary
15095     */
15096    @ViewDebug.ExportedProperty(category = "drawing")
15097    public int getSolidColor() {
15098        return 0;
15099    }
15100
15101    /**
15102     * Build a human readable string representation of the specified view flags.
15103     *
15104     * @param flags the view flags to convert to a string
15105     * @return a String representing the supplied flags
15106     */
15107    private static String printFlags(int flags) {
15108        String output = "";
15109        int numFlags = 0;
15110        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15111            output += "TAKES_FOCUS";
15112            numFlags++;
15113        }
15114
15115        switch (flags & VISIBILITY_MASK) {
15116        case INVISIBLE:
15117            if (numFlags > 0) {
15118                output += " ";
15119            }
15120            output += "INVISIBLE";
15121            // USELESS HERE numFlags++;
15122            break;
15123        case GONE:
15124            if (numFlags > 0) {
15125                output += " ";
15126            }
15127            output += "GONE";
15128            // USELESS HERE numFlags++;
15129            break;
15130        default:
15131            break;
15132        }
15133        return output;
15134    }
15135
15136    /**
15137     * Build a human readable string representation of the specified private
15138     * view flags.
15139     *
15140     * @param privateFlags the private view flags to convert to a string
15141     * @return a String representing the supplied flags
15142     */
15143    private static String printPrivateFlags(int privateFlags) {
15144        String output = "";
15145        int numFlags = 0;
15146
15147        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15148            output += "WANTS_FOCUS";
15149            numFlags++;
15150        }
15151
15152        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15153            if (numFlags > 0) {
15154                output += " ";
15155            }
15156            output += "FOCUSED";
15157            numFlags++;
15158        }
15159
15160        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15161            if (numFlags > 0) {
15162                output += " ";
15163            }
15164            output += "SELECTED";
15165            numFlags++;
15166        }
15167
15168        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15169            if (numFlags > 0) {
15170                output += " ";
15171            }
15172            output += "IS_ROOT_NAMESPACE";
15173            numFlags++;
15174        }
15175
15176        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15177            if (numFlags > 0) {
15178                output += " ";
15179            }
15180            output += "HAS_BOUNDS";
15181            numFlags++;
15182        }
15183
15184        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15185            if (numFlags > 0) {
15186                output += " ";
15187            }
15188            output += "DRAWN";
15189            // USELESS HERE numFlags++;
15190        }
15191        return output;
15192    }
15193
15194    /**
15195     * <p>Indicates whether or not this view's layout will be requested during
15196     * the next hierarchy layout pass.</p>
15197     *
15198     * @return true if the layout will be forced during next layout pass
15199     */
15200    public boolean isLayoutRequested() {
15201        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15202    }
15203
15204    /**
15205     * Return true if o is a ViewGroup that is laying out using optical bounds.
15206     * @hide
15207     */
15208    public static boolean isLayoutModeOptical(Object o) {
15209        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15210    }
15211
15212    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15213        Insets parentInsets = mParent instanceof View ?
15214                ((View) mParent).getOpticalInsets() : Insets.NONE;
15215        Insets childInsets = getOpticalInsets();
15216        return setFrame(
15217                left   + parentInsets.left - childInsets.left,
15218                top    + parentInsets.top  - childInsets.top,
15219                right  + parentInsets.left + childInsets.right,
15220                bottom + parentInsets.top  + childInsets.bottom);
15221    }
15222
15223    /**
15224     * Assign a size and position to a view and all of its
15225     * descendants
15226     *
15227     * <p>This is the second phase of the layout mechanism.
15228     * (The first is measuring). In this phase, each parent calls
15229     * layout on all of its children to position them.
15230     * This is typically done using the child measurements
15231     * that were stored in the measure pass().</p>
15232     *
15233     * <p>Derived classes should not override this method.
15234     * Derived classes with children should override
15235     * onLayout. In that method, they should
15236     * call layout on each of their children.</p>
15237     *
15238     * @param l Left position, relative to parent
15239     * @param t Top position, relative to parent
15240     * @param r Right position, relative to parent
15241     * @param b Bottom position, relative to parent
15242     */
15243    @SuppressWarnings({"unchecked"})
15244    public void layout(int l, int t, int r, int b) {
15245        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15246            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15247            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15248        }
15249
15250        int oldL = mLeft;
15251        int oldT = mTop;
15252        int oldB = mBottom;
15253        int oldR = mRight;
15254
15255        boolean changed = isLayoutModeOptical(mParent) ?
15256                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15257
15258        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15259            onLayout(changed, l, t, r, b);
15260            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15261
15262            ListenerInfo li = mListenerInfo;
15263            if (li != null && li.mOnLayoutChangeListeners != null) {
15264                ArrayList<OnLayoutChangeListener> listenersCopy =
15265                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15266                int numListeners = listenersCopy.size();
15267                for (int i = 0; i < numListeners; ++i) {
15268                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15269                }
15270            }
15271        }
15272
15273        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15274        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15275    }
15276
15277    /**
15278     * Called from layout when this view should
15279     * assign a size and position to each of its children.
15280     *
15281     * Derived classes with children should override
15282     * this method and call layout on each of
15283     * their children.
15284     * @param changed This is a new size or position for this view
15285     * @param left Left position, relative to parent
15286     * @param top Top position, relative to parent
15287     * @param right Right position, relative to parent
15288     * @param bottom Bottom position, relative to parent
15289     */
15290    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15291    }
15292
15293    /**
15294     * Assign a size and position to this view.
15295     *
15296     * This is called from layout.
15297     *
15298     * @param left Left position, relative to parent
15299     * @param top Top position, relative to parent
15300     * @param right Right position, relative to parent
15301     * @param bottom Bottom position, relative to parent
15302     * @return true if the new size and position are different than the
15303     *         previous ones
15304     * {@hide}
15305     */
15306    protected boolean setFrame(int left, int top, int right, int bottom) {
15307        boolean changed = false;
15308
15309        if (DBG) {
15310            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15311                    + right + "," + bottom + ")");
15312        }
15313
15314        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15315            changed = true;
15316
15317            // Remember our drawn bit
15318            int drawn = mPrivateFlags & PFLAG_DRAWN;
15319
15320            int oldWidth = mRight - mLeft;
15321            int oldHeight = mBottom - mTop;
15322            int newWidth = right - left;
15323            int newHeight = bottom - top;
15324            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15325
15326            // Invalidate our old position
15327            invalidate(sizeChanged);
15328
15329            mLeft = left;
15330            mTop = top;
15331            mRight = right;
15332            mBottom = bottom;
15333            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15334
15335            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15336
15337
15338            if (sizeChanged) {
15339                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15340            }
15341
15342            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15343                // If we are visible, force the DRAWN bit to on so that
15344                // this invalidate will go through (at least to our parent).
15345                // This is because someone may have invalidated this view
15346                // before this call to setFrame came in, thereby clearing
15347                // the DRAWN bit.
15348                mPrivateFlags |= PFLAG_DRAWN;
15349                invalidate(sizeChanged);
15350                // parent display list may need to be recreated based on a change in the bounds
15351                // of any child
15352                invalidateParentCaches();
15353            }
15354
15355            // Reset drawn bit to original value (invalidate turns it off)
15356            mPrivateFlags |= drawn;
15357
15358            mBackgroundSizeChanged = true;
15359
15360            notifySubtreeAccessibilityStateChangedIfNeeded();
15361        }
15362        return changed;
15363    }
15364
15365    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15366        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15367        if (mOverlay != null) {
15368            mOverlay.getOverlayView().setRight(newWidth);
15369            mOverlay.getOverlayView().setBottom(newHeight);
15370        }
15371        invalidateOutline();
15372    }
15373
15374    /**
15375     * Finalize inflating a view from XML.  This is called as the last phase
15376     * of inflation, after all child views have been added.
15377     *
15378     * <p>Even if the subclass overrides onFinishInflate, they should always be
15379     * sure to call the super method, so that we get called.
15380     */
15381    protected void onFinishInflate() {
15382    }
15383
15384    /**
15385     * Returns the resources associated with this view.
15386     *
15387     * @return Resources object.
15388     */
15389    public Resources getResources() {
15390        return mResources;
15391    }
15392
15393    /**
15394     * Invalidates the specified Drawable.
15395     *
15396     * @param drawable the drawable to invalidate
15397     */
15398    @Override
15399    public void invalidateDrawable(@NonNull Drawable drawable) {
15400        if (verifyDrawable(drawable)) {
15401            final Rect dirty = drawable.getDirtyBounds();
15402            final int scrollX = mScrollX;
15403            final int scrollY = mScrollY;
15404
15405            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15406                    dirty.right + scrollX, dirty.bottom + scrollY);
15407
15408            invalidateOutline();
15409        }
15410    }
15411
15412    /**
15413     * Schedules an action on a drawable to occur at a specified time.
15414     *
15415     * @param who the recipient of the action
15416     * @param what the action to run on the drawable
15417     * @param when the time at which the action must occur. Uses the
15418     *        {@link SystemClock#uptimeMillis} timebase.
15419     */
15420    @Override
15421    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15422        if (verifyDrawable(who) && what != null) {
15423            final long delay = when - SystemClock.uptimeMillis();
15424            if (mAttachInfo != null) {
15425                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15426                        Choreographer.CALLBACK_ANIMATION, what, who,
15427                        Choreographer.subtractFrameDelay(delay));
15428            } else {
15429                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15430            }
15431        }
15432    }
15433
15434    /**
15435     * Cancels a scheduled action on a drawable.
15436     *
15437     * @param who the recipient of the action
15438     * @param what the action to cancel
15439     */
15440    @Override
15441    public void unscheduleDrawable(Drawable who, Runnable what) {
15442        if (verifyDrawable(who) && what != null) {
15443            if (mAttachInfo != null) {
15444                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15445                        Choreographer.CALLBACK_ANIMATION, what, who);
15446            }
15447            ViewRootImpl.getRunQueue().removeCallbacks(what);
15448        }
15449    }
15450
15451    /**
15452     * Unschedule any events associated with the given Drawable.  This can be
15453     * used when selecting a new Drawable into a view, so that the previous
15454     * one is completely unscheduled.
15455     *
15456     * @param who The Drawable to unschedule.
15457     *
15458     * @see #drawableStateChanged
15459     */
15460    public void unscheduleDrawable(Drawable who) {
15461        if (mAttachInfo != null && who != null) {
15462            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15463                    Choreographer.CALLBACK_ANIMATION, null, who);
15464        }
15465    }
15466
15467    /**
15468     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15469     * that the View directionality can and will be resolved before its Drawables.
15470     *
15471     * Will call {@link View#onResolveDrawables} when resolution is done.
15472     *
15473     * @hide
15474     */
15475    protected void resolveDrawables() {
15476        // Drawables resolution may need to happen before resolving the layout direction (which is
15477        // done only during the measure() call).
15478        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15479        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15480        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15481        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15482        // direction to be resolved as its resolved value will be the same as its raw value.
15483        if (!isLayoutDirectionResolved() &&
15484                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15485            return;
15486        }
15487
15488        final int layoutDirection = isLayoutDirectionResolved() ?
15489                getLayoutDirection() : getRawLayoutDirection();
15490
15491        if (mBackground != null) {
15492            mBackground.setLayoutDirection(layoutDirection);
15493        }
15494        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15495        onResolveDrawables(layoutDirection);
15496    }
15497
15498    /**
15499     * Called when layout direction has been resolved.
15500     *
15501     * The default implementation does nothing.
15502     *
15503     * @param layoutDirection The resolved layout direction.
15504     *
15505     * @see #LAYOUT_DIRECTION_LTR
15506     * @see #LAYOUT_DIRECTION_RTL
15507     *
15508     * @hide
15509     */
15510    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15511    }
15512
15513    /**
15514     * @hide
15515     */
15516    protected void resetResolvedDrawables() {
15517        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15518    }
15519
15520    private boolean isDrawablesResolved() {
15521        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15522    }
15523
15524    /**
15525     * If your view subclass is displaying its own Drawable objects, it should
15526     * override this function and return true for any Drawable it is
15527     * displaying.  This allows animations for those drawables to be
15528     * scheduled.
15529     *
15530     * <p>Be sure to call through to the super class when overriding this
15531     * function.
15532     *
15533     * @param who The Drawable to verify.  Return true if it is one you are
15534     *            displaying, else return the result of calling through to the
15535     *            super class.
15536     *
15537     * @return boolean If true than the Drawable is being displayed in the
15538     *         view; else false and it is not allowed to animate.
15539     *
15540     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15541     * @see #drawableStateChanged()
15542     */
15543    protected boolean verifyDrawable(Drawable who) {
15544        return who == mBackground;
15545    }
15546
15547    /**
15548     * This function is called whenever the state of the view changes in such
15549     * a way that it impacts the state of drawables being shown.
15550     * <p>
15551     * If the View has a StateListAnimator, it will also be called to run necessary state
15552     * change animations.
15553     * <p>
15554     * Be sure to call through to the superclass when overriding this function.
15555     *
15556     * @see Drawable#setState(int[])
15557     */
15558    protected void drawableStateChanged() {
15559        final Drawable d = mBackground;
15560        if (d != null && d.isStateful()) {
15561            d.setState(getDrawableState());
15562        }
15563
15564        if (mStateListAnimator != null) {
15565            mStateListAnimator.setState(getDrawableState());
15566        }
15567    }
15568
15569    /**
15570     * This function is called whenever the view hotspot changes and needs to
15571     * be propagated to drawables managed by the view.
15572     * <p>
15573     * Be sure to call through to the superclass when overriding this function.
15574     *
15575     * @param x hotspot x coordinate
15576     * @param y hotspot y coordinate
15577     */
15578    public void drawableHotspotChanged(float x, float y) {
15579        if (mBackground != null) {
15580            mBackground.setHotspot(x, y);
15581        }
15582    }
15583
15584    /**
15585     * Call this to force a view to update its drawable state. This will cause
15586     * drawableStateChanged to be called on this view. Views that are interested
15587     * in the new state should call getDrawableState.
15588     *
15589     * @see #drawableStateChanged
15590     * @see #getDrawableState
15591     */
15592    public void refreshDrawableState() {
15593        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15594        drawableStateChanged();
15595
15596        ViewParent parent = mParent;
15597        if (parent != null) {
15598            parent.childDrawableStateChanged(this);
15599        }
15600    }
15601
15602    /**
15603     * Return an array of resource IDs of the drawable states representing the
15604     * current state of the view.
15605     *
15606     * @return The current drawable state
15607     *
15608     * @see Drawable#setState(int[])
15609     * @see #drawableStateChanged()
15610     * @see #onCreateDrawableState(int)
15611     */
15612    public final int[] getDrawableState() {
15613        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15614            return mDrawableState;
15615        } else {
15616            mDrawableState = onCreateDrawableState(0);
15617            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15618            return mDrawableState;
15619        }
15620    }
15621
15622    /**
15623     * Generate the new {@link android.graphics.drawable.Drawable} state for
15624     * this view. This is called by the view
15625     * system when the cached Drawable state is determined to be invalid.  To
15626     * retrieve the current state, you should use {@link #getDrawableState}.
15627     *
15628     * @param extraSpace if non-zero, this is the number of extra entries you
15629     * would like in the returned array in which you can place your own
15630     * states.
15631     *
15632     * @return Returns an array holding the current {@link Drawable} state of
15633     * the view.
15634     *
15635     * @see #mergeDrawableStates(int[], int[])
15636     */
15637    protected int[] onCreateDrawableState(int extraSpace) {
15638        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15639                mParent instanceof View) {
15640            return ((View) mParent).onCreateDrawableState(extraSpace);
15641        }
15642
15643        int[] drawableState;
15644
15645        int privateFlags = mPrivateFlags;
15646
15647        int viewStateIndex = 0;
15648        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15649        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15650        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15651        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15652        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15653        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15654        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15655                HardwareRenderer.isAvailable()) {
15656            // This is set if HW acceleration is requested, even if the current
15657            // process doesn't allow it.  This is just to allow app preview
15658            // windows to better match their app.
15659            viewStateIndex |= VIEW_STATE_ACCELERATED;
15660        }
15661        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15662
15663        final int privateFlags2 = mPrivateFlags2;
15664        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15665        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15666
15667        drawableState = VIEW_STATE_SETS[viewStateIndex];
15668
15669        //noinspection ConstantIfStatement
15670        if (false) {
15671            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15672            Log.i("View", toString()
15673                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15674                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15675                    + " fo=" + hasFocus()
15676                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15677                    + " wf=" + hasWindowFocus()
15678                    + ": " + Arrays.toString(drawableState));
15679        }
15680
15681        if (extraSpace == 0) {
15682            return drawableState;
15683        }
15684
15685        final int[] fullState;
15686        if (drawableState != null) {
15687            fullState = new int[drawableState.length + extraSpace];
15688            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15689        } else {
15690            fullState = new int[extraSpace];
15691        }
15692
15693        return fullState;
15694    }
15695
15696    /**
15697     * Merge your own state values in <var>additionalState</var> into the base
15698     * state values <var>baseState</var> that were returned by
15699     * {@link #onCreateDrawableState(int)}.
15700     *
15701     * @param baseState The base state values returned by
15702     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15703     * own additional state values.
15704     *
15705     * @param additionalState The additional state values you would like
15706     * added to <var>baseState</var>; this array is not modified.
15707     *
15708     * @return As a convenience, the <var>baseState</var> array you originally
15709     * passed into the function is returned.
15710     *
15711     * @see #onCreateDrawableState(int)
15712     */
15713    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15714        final int N = baseState.length;
15715        int i = N - 1;
15716        while (i >= 0 && baseState[i] == 0) {
15717            i--;
15718        }
15719        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15720        return baseState;
15721    }
15722
15723    /**
15724     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15725     * on all Drawable objects associated with this view.
15726     * <p>
15727     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15728     * attached to this view.
15729     */
15730    public void jumpDrawablesToCurrentState() {
15731        if (mBackground != null) {
15732            mBackground.jumpToCurrentState();
15733        }
15734        if (mStateListAnimator != null) {
15735            mStateListAnimator.jumpToCurrentState();
15736        }
15737    }
15738
15739    /**
15740     * Sets the background color for this view.
15741     * @param color the color of the background
15742     */
15743    @RemotableViewMethod
15744    public void setBackgroundColor(int color) {
15745        if (mBackground instanceof ColorDrawable) {
15746            ((ColorDrawable) mBackground.mutate()).setColor(color);
15747            computeOpaqueFlags();
15748            mBackgroundResource = 0;
15749        } else {
15750            setBackground(new ColorDrawable(color));
15751        }
15752    }
15753
15754    /**
15755     * Set the background to a given resource. The resource should refer to
15756     * a Drawable object or 0 to remove the background.
15757     * @param resid The identifier of the resource.
15758     *
15759     * @attr ref android.R.styleable#View_background
15760     */
15761    @RemotableViewMethod
15762    public void setBackgroundResource(int resid) {
15763        if (resid != 0 && resid == mBackgroundResource) {
15764            return;
15765        }
15766
15767        Drawable d = null;
15768        if (resid != 0) {
15769            d = mContext.getDrawable(resid);
15770        }
15771        setBackground(d);
15772
15773        mBackgroundResource = resid;
15774    }
15775
15776    /**
15777     * Set the background to a given Drawable, or remove the background. If the
15778     * background has padding, this View's padding is set to the background's
15779     * padding. However, when a background is removed, this View's padding isn't
15780     * touched. If setting the padding is desired, please use
15781     * {@link #setPadding(int, int, int, int)}.
15782     *
15783     * @param background The Drawable to use as the background, or null to remove the
15784     *        background
15785     */
15786    public void setBackground(Drawable background) {
15787        //noinspection deprecation
15788        setBackgroundDrawable(background);
15789    }
15790
15791    /**
15792     * @deprecated use {@link #setBackground(Drawable)} instead
15793     */
15794    @Deprecated
15795    public void setBackgroundDrawable(Drawable background) {
15796        computeOpaqueFlags();
15797
15798        if (background == mBackground) {
15799            return;
15800        }
15801
15802        boolean requestLayout = false;
15803
15804        mBackgroundResource = 0;
15805
15806        /*
15807         * Regardless of whether we're setting a new background or not, we want
15808         * to clear the previous drawable.
15809         */
15810        if (mBackground != null) {
15811            mBackground.setCallback(null);
15812            unscheduleDrawable(mBackground);
15813        }
15814
15815        if (background != null) {
15816            Rect padding = sThreadLocal.get();
15817            if (padding == null) {
15818                padding = new Rect();
15819                sThreadLocal.set(padding);
15820            }
15821            resetResolvedDrawables();
15822            background.setLayoutDirection(getLayoutDirection());
15823            if (background.getPadding(padding)) {
15824                resetResolvedPadding();
15825                switch (background.getLayoutDirection()) {
15826                    case LAYOUT_DIRECTION_RTL:
15827                        mUserPaddingLeftInitial = padding.right;
15828                        mUserPaddingRightInitial = padding.left;
15829                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15830                        break;
15831                    case LAYOUT_DIRECTION_LTR:
15832                    default:
15833                        mUserPaddingLeftInitial = padding.left;
15834                        mUserPaddingRightInitial = padding.right;
15835                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15836                }
15837                mLeftPaddingDefined = false;
15838                mRightPaddingDefined = false;
15839            }
15840
15841            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15842            // if it has a different minimum size, we should layout again
15843            if (mBackground == null
15844                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15845                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15846                requestLayout = true;
15847            }
15848
15849            background.setCallback(this);
15850            if (background.isStateful()) {
15851                background.setState(getDrawableState());
15852            }
15853            background.setVisible(getVisibility() == VISIBLE, false);
15854            mBackground = background;
15855
15856            applyBackgroundTint();
15857
15858            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15859                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15860                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15861                requestLayout = true;
15862            }
15863        } else {
15864            /* Remove the background */
15865            mBackground = null;
15866
15867            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15868                /*
15869                 * This view ONLY drew the background before and we're removing
15870                 * the background, so now it won't draw anything
15871                 * (hence we SKIP_DRAW)
15872                 */
15873                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15874                mPrivateFlags |= PFLAG_SKIP_DRAW;
15875            }
15876
15877            /*
15878             * When the background is set, we try to apply its padding to this
15879             * View. When the background is removed, we don't touch this View's
15880             * padding. This is noted in the Javadocs. Hence, we don't need to
15881             * requestLayout(), the invalidate() below is sufficient.
15882             */
15883
15884            // The old background's minimum size could have affected this
15885            // View's layout, so let's requestLayout
15886            requestLayout = true;
15887        }
15888
15889        computeOpaqueFlags();
15890
15891        if (requestLayout) {
15892            requestLayout();
15893        }
15894
15895        mBackgroundSizeChanged = true;
15896        invalidate(true);
15897    }
15898
15899    /**
15900     * Gets the background drawable
15901     *
15902     * @return The drawable used as the background for this view, if any.
15903     *
15904     * @see #setBackground(Drawable)
15905     *
15906     * @attr ref android.R.styleable#View_background
15907     */
15908    public Drawable getBackground() {
15909        return mBackground;
15910    }
15911
15912    /**
15913     * Applies a tint to the background drawable. Does not modify the current tint
15914     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15915     * <p>
15916     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15917     * mutate the drawable and apply the specified tint and tint mode using
15918     * {@link Drawable#setTintList(ColorStateList)}.
15919     *
15920     * @param tint the tint to apply, may be {@code null} to clear tint
15921     *
15922     * @attr ref android.R.styleable#View_backgroundTint
15923     * @see #getBackgroundTintList()
15924     * @see Drawable#setTintList(ColorStateList)
15925     */
15926    public void setBackgroundTintList(@Nullable ColorStateList tint) {
15927        mBackgroundTintList = tint;
15928        mHasBackgroundTint = true;
15929
15930        applyBackgroundTint();
15931    }
15932
15933    /**
15934     * @return the tint applied to the background drawable
15935     * @attr ref android.R.styleable#View_backgroundTint
15936     * @see #setBackgroundTintList(ColorStateList)
15937     */
15938    @Nullable
15939    public ColorStateList getBackgroundTintList() {
15940        return mBackgroundTintList;
15941    }
15942
15943    /**
15944     * Specifies the blending mode used to apply the tint specified by
15945     * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable.
15946     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15947     *
15948     * @param tintMode the blending mode used to apply the tint, may be
15949     *                 {@code null} to clear tint
15950     * @attr ref android.R.styleable#View_backgroundTintMode
15951     * @see #getBackgroundTintMode()
15952     * @see Drawable#setTintMode(PorterDuff.Mode)
15953     */
15954    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15955        mBackgroundTintMode = tintMode;
15956
15957        applyBackgroundTint();
15958    }
15959
15960    /**
15961     * @return the blending mode used to apply the tint to the background drawable
15962     * @attr ref android.R.styleable#View_backgroundTintMode
15963     * @see #setBackgroundTintMode(PorterDuff.Mode)
15964     */
15965    @Nullable
15966    public PorterDuff.Mode getBackgroundTintMode() {
15967        return mBackgroundTintMode;
15968    }
15969
15970    private void applyBackgroundTint() {
15971        if (mBackground != null && mHasBackgroundTint) {
15972            mBackground = mBackground.mutate();
15973            mBackground.setTintList(mBackgroundTintList);
15974            mBackground.setTintMode(mBackgroundTintMode);
15975        }
15976    }
15977
15978    /**
15979     * Sets the padding. The view may add on the space required to display
15980     * the scrollbars, depending on the style and visibility of the scrollbars.
15981     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15982     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15983     * from the values set in this call.
15984     *
15985     * @attr ref android.R.styleable#View_padding
15986     * @attr ref android.R.styleable#View_paddingBottom
15987     * @attr ref android.R.styleable#View_paddingLeft
15988     * @attr ref android.R.styleable#View_paddingRight
15989     * @attr ref android.R.styleable#View_paddingTop
15990     * @param left the left padding in pixels
15991     * @param top the top padding in pixels
15992     * @param right the right padding in pixels
15993     * @param bottom the bottom padding in pixels
15994     */
15995    public void setPadding(int left, int top, int right, int bottom) {
15996        resetResolvedPadding();
15997
15998        mUserPaddingStart = UNDEFINED_PADDING;
15999        mUserPaddingEnd = UNDEFINED_PADDING;
16000
16001        mUserPaddingLeftInitial = left;
16002        mUserPaddingRightInitial = right;
16003
16004        mLeftPaddingDefined = true;
16005        mRightPaddingDefined = true;
16006
16007        internalSetPadding(left, top, right, bottom);
16008    }
16009
16010    /**
16011     * @hide
16012     */
16013    protected void internalSetPadding(int left, int top, int right, int bottom) {
16014        mUserPaddingLeft = left;
16015        mUserPaddingRight = right;
16016        mUserPaddingBottom = bottom;
16017
16018        final int viewFlags = mViewFlags;
16019        boolean changed = false;
16020
16021        // Common case is there are no scroll bars.
16022        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16023            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16024                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16025                        ? 0 : getVerticalScrollbarWidth();
16026                switch (mVerticalScrollbarPosition) {
16027                    case SCROLLBAR_POSITION_DEFAULT:
16028                        if (isLayoutRtl()) {
16029                            left += offset;
16030                        } else {
16031                            right += offset;
16032                        }
16033                        break;
16034                    case SCROLLBAR_POSITION_RIGHT:
16035                        right += offset;
16036                        break;
16037                    case SCROLLBAR_POSITION_LEFT:
16038                        left += offset;
16039                        break;
16040                }
16041            }
16042            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16043                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16044                        ? 0 : getHorizontalScrollbarHeight();
16045            }
16046        }
16047
16048        if (mPaddingLeft != left) {
16049            changed = true;
16050            mPaddingLeft = left;
16051        }
16052        if (mPaddingTop != top) {
16053            changed = true;
16054            mPaddingTop = top;
16055        }
16056        if (mPaddingRight != right) {
16057            changed = true;
16058            mPaddingRight = right;
16059        }
16060        if (mPaddingBottom != bottom) {
16061            changed = true;
16062            mPaddingBottom = bottom;
16063        }
16064
16065        if (changed) {
16066            requestLayout();
16067        }
16068    }
16069
16070    /**
16071     * Sets the relative padding. The view may add on the space required to display
16072     * the scrollbars, depending on the style and visibility of the scrollbars.
16073     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16074     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16075     * from the values set in this call.
16076     *
16077     * @attr ref android.R.styleable#View_padding
16078     * @attr ref android.R.styleable#View_paddingBottom
16079     * @attr ref android.R.styleable#View_paddingStart
16080     * @attr ref android.R.styleable#View_paddingEnd
16081     * @attr ref android.R.styleable#View_paddingTop
16082     * @param start the start padding in pixels
16083     * @param top the top padding in pixels
16084     * @param end the end padding in pixels
16085     * @param bottom the bottom padding in pixels
16086     */
16087    public void setPaddingRelative(int start, int top, int end, int bottom) {
16088        resetResolvedPadding();
16089
16090        mUserPaddingStart = start;
16091        mUserPaddingEnd = end;
16092        mLeftPaddingDefined = true;
16093        mRightPaddingDefined = true;
16094
16095        switch(getLayoutDirection()) {
16096            case LAYOUT_DIRECTION_RTL:
16097                mUserPaddingLeftInitial = end;
16098                mUserPaddingRightInitial = start;
16099                internalSetPadding(end, top, start, bottom);
16100                break;
16101            case LAYOUT_DIRECTION_LTR:
16102            default:
16103                mUserPaddingLeftInitial = start;
16104                mUserPaddingRightInitial = end;
16105                internalSetPadding(start, top, end, bottom);
16106        }
16107    }
16108
16109    /**
16110     * Returns the top padding of this view.
16111     *
16112     * @return the top padding in pixels
16113     */
16114    public int getPaddingTop() {
16115        return mPaddingTop;
16116    }
16117
16118    /**
16119     * Returns the bottom padding of this view. If there are inset and enabled
16120     * scrollbars, this value may include the space required to display the
16121     * scrollbars as well.
16122     *
16123     * @return the bottom padding in pixels
16124     */
16125    public int getPaddingBottom() {
16126        return mPaddingBottom;
16127    }
16128
16129    /**
16130     * Returns the left padding of this view. If there are inset and enabled
16131     * scrollbars, this value may include the space required to display the
16132     * scrollbars as well.
16133     *
16134     * @return the left padding in pixels
16135     */
16136    public int getPaddingLeft() {
16137        if (!isPaddingResolved()) {
16138            resolvePadding();
16139        }
16140        return mPaddingLeft;
16141    }
16142
16143    /**
16144     * Returns the start padding of this view depending on its resolved layout direction.
16145     * If there are inset and enabled scrollbars, this value may include the space
16146     * required to display the scrollbars as well.
16147     *
16148     * @return the start padding in pixels
16149     */
16150    public int getPaddingStart() {
16151        if (!isPaddingResolved()) {
16152            resolvePadding();
16153        }
16154        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16155                mPaddingRight : mPaddingLeft;
16156    }
16157
16158    /**
16159     * Returns the right padding of this view. If there are inset and enabled
16160     * scrollbars, this value may include the space required to display the
16161     * scrollbars as well.
16162     *
16163     * @return the right padding in pixels
16164     */
16165    public int getPaddingRight() {
16166        if (!isPaddingResolved()) {
16167            resolvePadding();
16168        }
16169        return mPaddingRight;
16170    }
16171
16172    /**
16173     * Returns the end padding of this view depending on its resolved layout direction.
16174     * If there are inset and enabled scrollbars, this value may include the space
16175     * required to display the scrollbars as well.
16176     *
16177     * @return the end padding in pixels
16178     */
16179    public int getPaddingEnd() {
16180        if (!isPaddingResolved()) {
16181            resolvePadding();
16182        }
16183        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16184                mPaddingLeft : mPaddingRight;
16185    }
16186
16187    /**
16188     * Return if the padding as been set thru relative values
16189     * {@link #setPaddingRelative(int, int, int, int)} or thru
16190     * @attr ref android.R.styleable#View_paddingStart or
16191     * @attr ref android.R.styleable#View_paddingEnd
16192     *
16193     * @return true if the padding is relative or false if it is not.
16194     */
16195    public boolean isPaddingRelative() {
16196        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16197    }
16198
16199    Insets computeOpticalInsets() {
16200        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16201    }
16202
16203    /**
16204     * @hide
16205     */
16206    public void resetPaddingToInitialValues() {
16207        if (isRtlCompatibilityMode()) {
16208            mPaddingLeft = mUserPaddingLeftInitial;
16209            mPaddingRight = mUserPaddingRightInitial;
16210            return;
16211        }
16212        if (isLayoutRtl()) {
16213            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16214            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16215        } else {
16216            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16217            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16218        }
16219    }
16220
16221    /**
16222     * @hide
16223     */
16224    public Insets getOpticalInsets() {
16225        if (mLayoutInsets == null) {
16226            mLayoutInsets = computeOpticalInsets();
16227        }
16228        return mLayoutInsets;
16229    }
16230
16231    /**
16232     * Set this view's optical insets.
16233     *
16234     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16235     * property. Views that compute their own optical insets should call it as part of measurement.
16236     * This method does not request layout. If you are setting optical insets outside of
16237     * measure/layout itself you will want to call requestLayout() yourself.
16238     * </p>
16239     * @hide
16240     */
16241    public void setOpticalInsets(Insets insets) {
16242        mLayoutInsets = insets;
16243    }
16244
16245    /**
16246     * Changes the selection state of this view. A view can be selected or not.
16247     * Note that selection is not the same as focus. Views are typically
16248     * selected in the context of an AdapterView like ListView or GridView;
16249     * the selected view is the view that is highlighted.
16250     *
16251     * @param selected true if the view must be selected, false otherwise
16252     */
16253    public void setSelected(boolean selected) {
16254        //noinspection DoubleNegation
16255        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16256            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16257            if (!selected) resetPressedState();
16258            invalidate(true);
16259            refreshDrawableState();
16260            dispatchSetSelected(selected);
16261            notifyViewAccessibilityStateChangedIfNeeded(
16262                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16263        }
16264    }
16265
16266    /**
16267     * Dispatch setSelected to all of this View's children.
16268     *
16269     * @see #setSelected(boolean)
16270     *
16271     * @param selected The new selected state
16272     */
16273    protected void dispatchSetSelected(boolean selected) {
16274    }
16275
16276    /**
16277     * Indicates the selection state of this view.
16278     *
16279     * @return true if the view is selected, false otherwise
16280     */
16281    @ViewDebug.ExportedProperty
16282    public boolean isSelected() {
16283        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16284    }
16285
16286    /**
16287     * Changes the activated state of this view. A view can be activated or not.
16288     * Note that activation is not the same as selection.  Selection is
16289     * a transient property, representing the view (hierarchy) the user is
16290     * currently interacting with.  Activation is a longer-term state that the
16291     * user can move views in and out of.  For example, in a list view with
16292     * single or multiple selection enabled, the views in the current selection
16293     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16294     * here.)  The activated state is propagated down to children of the view it
16295     * is set on.
16296     *
16297     * @param activated true if the view must be activated, false otherwise
16298     */
16299    public void setActivated(boolean activated) {
16300        //noinspection DoubleNegation
16301        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16302            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16303            invalidate(true);
16304            refreshDrawableState();
16305            dispatchSetActivated(activated);
16306        }
16307    }
16308
16309    /**
16310     * Dispatch setActivated to all of this View's children.
16311     *
16312     * @see #setActivated(boolean)
16313     *
16314     * @param activated The new activated state
16315     */
16316    protected void dispatchSetActivated(boolean activated) {
16317    }
16318
16319    /**
16320     * Indicates the activation state of this view.
16321     *
16322     * @return true if the view is activated, false otherwise
16323     */
16324    @ViewDebug.ExportedProperty
16325    public boolean isActivated() {
16326        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16327    }
16328
16329    /**
16330     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16331     * observer can be used to get notifications when global events, like
16332     * layout, happen.
16333     *
16334     * The returned ViewTreeObserver observer is not guaranteed to remain
16335     * valid for the lifetime of this View. If the caller of this method keeps
16336     * a long-lived reference to ViewTreeObserver, it should always check for
16337     * the return value of {@link ViewTreeObserver#isAlive()}.
16338     *
16339     * @return The ViewTreeObserver for this view's hierarchy.
16340     */
16341    public ViewTreeObserver getViewTreeObserver() {
16342        if (mAttachInfo != null) {
16343            return mAttachInfo.mTreeObserver;
16344        }
16345        if (mFloatingTreeObserver == null) {
16346            mFloatingTreeObserver = new ViewTreeObserver();
16347        }
16348        return mFloatingTreeObserver;
16349    }
16350
16351    /**
16352     * <p>Finds the topmost view in the current view hierarchy.</p>
16353     *
16354     * @return the topmost view containing this view
16355     */
16356    public View getRootView() {
16357        if (mAttachInfo != null) {
16358            final View v = mAttachInfo.mRootView;
16359            if (v != null) {
16360                return v;
16361            }
16362        }
16363
16364        View parent = this;
16365
16366        while (parent.mParent != null && parent.mParent instanceof View) {
16367            parent = (View) parent.mParent;
16368        }
16369
16370        return parent;
16371    }
16372
16373    /**
16374     * Transforms a motion event from view-local coordinates to on-screen
16375     * coordinates.
16376     *
16377     * @param ev the view-local motion event
16378     * @return false if the transformation could not be applied
16379     * @hide
16380     */
16381    public boolean toGlobalMotionEvent(MotionEvent ev) {
16382        final AttachInfo info = mAttachInfo;
16383        if (info == null) {
16384            return false;
16385        }
16386
16387        final Matrix m = info.mTmpMatrix;
16388        m.set(Matrix.IDENTITY_MATRIX);
16389        transformMatrixToGlobal(m);
16390        ev.transform(m);
16391        return true;
16392    }
16393
16394    /**
16395     * Transforms a motion event from on-screen coordinates to view-local
16396     * coordinates.
16397     *
16398     * @param ev the on-screen motion event
16399     * @return false if the transformation could not be applied
16400     * @hide
16401     */
16402    public boolean toLocalMotionEvent(MotionEvent ev) {
16403        final AttachInfo info = mAttachInfo;
16404        if (info == null) {
16405            return false;
16406        }
16407
16408        final Matrix m = info.mTmpMatrix;
16409        m.set(Matrix.IDENTITY_MATRIX);
16410        transformMatrixToLocal(m);
16411        ev.transform(m);
16412        return true;
16413    }
16414
16415    /**
16416     * Modifies the input matrix such that it maps view-local coordinates to
16417     * on-screen coordinates.
16418     *
16419     * @param m input matrix to modify
16420     * @hide
16421     */
16422    public void transformMatrixToGlobal(Matrix m) {
16423        final ViewParent parent = mParent;
16424        if (parent instanceof View) {
16425            final View vp = (View) parent;
16426            vp.transformMatrixToGlobal(m);
16427            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16428        } else if (parent instanceof ViewRootImpl) {
16429            final ViewRootImpl vr = (ViewRootImpl) parent;
16430            vr.transformMatrixToGlobal(m);
16431            m.preTranslate(0, -vr.mCurScrollY);
16432        }
16433
16434        m.preTranslate(mLeft, mTop);
16435
16436        if (!hasIdentityMatrix()) {
16437            m.preConcat(getMatrix());
16438        }
16439    }
16440
16441    /**
16442     * Modifies the input matrix such that it maps on-screen coordinates to
16443     * view-local coordinates.
16444     *
16445     * @param m input matrix to modify
16446     * @hide
16447     */
16448    public void transformMatrixToLocal(Matrix m) {
16449        final ViewParent parent = mParent;
16450        if (parent instanceof View) {
16451            final View vp = (View) parent;
16452            vp.transformMatrixToLocal(m);
16453            m.postTranslate(vp.mScrollX, vp.mScrollY);
16454        } else if (parent instanceof ViewRootImpl) {
16455            final ViewRootImpl vr = (ViewRootImpl) parent;
16456            vr.transformMatrixToLocal(m);
16457            m.postTranslate(0, vr.mCurScrollY);
16458        }
16459
16460        m.postTranslate(-mLeft, -mTop);
16461
16462        if (!hasIdentityMatrix()) {
16463            m.postConcat(getInverseMatrix());
16464        }
16465    }
16466
16467    /**
16468     * @hide
16469     */
16470    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16471            @ViewDebug.IntToString(from = 0, to = "x"),
16472            @ViewDebug.IntToString(from = 1, to = "y")
16473    })
16474    public int[] getLocationOnScreen() {
16475        int[] location = new int[2];
16476        getLocationOnScreen(location);
16477        return location;
16478    }
16479
16480    /**
16481     * <p>Computes the coordinates of this view on the screen. The argument
16482     * must be an array of two integers. After the method returns, the array
16483     * contains the x and y location in that order.</p>
16484     *
16485     * @param location an array of two integers in which to hold the coordinates
16486     */
16487    public void getLocationOnScreen(int[] location) {
16488        getLocationInWindow(location);
16489
16490        final AttachInfo info = mAttachInfo;
16491        if (info != null) {
16492            location[0] += info.mWindowLeft;
16493            location[1] += info.mWindowTop;
16494        }
16495    }
16496
16497    /**
16498     * <p>Computes the coordinates of this view in its window. The argument
16499     * must be an array of two integers. After the method returns, the array
16500     * contains the x and y location in that order.</p>
16501     *
16502     * @param location an array of two integers in which to hold the coordinates
16503     */
16504    public void getLocationInWindow(int[] location) {
16505        if (location == null || location.length < 2) {
16506            throw new IllegalArgumentException("location must be an array of two integers");
16507        }
16508
16509        if (mAttachInfo == null) {
16510            // When the view is not attached to a window, this method does not make sense
16511            location[0] = location[1] = 0;
16512            return;
16513        }
16514
16515        float[] position = mAttachInfo.mTmpTransformLocation;
16516        position[0] = position[1] = 0.0f;
16517
16518        if (!hasIdentityMatrix()) {
16519            getMatrix().mapPoints(position);
16520        }
16521
16522        position[0] += mLeft;
16523        position[1] += mTop;
16524
16525        ViewParent viewParent = mParent;
16526        while (viewParent instanceof View) {
16527            final View view = (View) viewParent;
16528
16529            position[0] -= view.mScrollX;
16530            position[1] -= view.mScrollY;
16531
16532            if (!view.hasIdentityMatrix()) {
16533                view.getMatrix().mapPoints(position);
16534            }
16535
16536            position[0] += view.mLeft;
16537            position[1] += view.mTop;
16538
16539            viewParent = view.mParent;
16540         }
16541
16542        if (viewParent instanceof ViewRootImpl) {
16543            // *cough*
16544            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16545            position[1] -= vr.mCurScrollY;
16546        }
16547
16548        location[0] = (int) (position[0] + 0.5f);
16549        location[1] = (int) (position[1] + 0.5f);
16550    }
16551
16552    /**
16553     * {@hide}
16554     * @param id the id of the view to be found
16555     * @return the view of the specified id, null if cannot be found
16556     */
16557    protected View findViewTraversal(int id) {
16558        if (id == mID) {
16559            return this;
16560        }
16561        return null;
16562    }
16563
16564    /**
16565     * {@hide}
16566     * @param tag the tag of the view to be found
16567     * @return the view of specified tag, null if cannot be found
16568     */
16569    protected View findViewWithTagTraversal(Object tag) {
16570        if (tag != null && tag.equals(mTag)) {
16571            return this;
16572        }
16573        return null;
16574    }
16575
16576    /**
16577     * {@hide}
16578     * @param predicate The predicate to evaluate.
16579     * @param childToSkip If not null, ignores this child during the recursive traversal.
16580     * @return The first view that matches the predicate or null.
16581     */
16582    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16583        if (predicate.apply(this)) {
16584            return this;
16585        }
16586        return null;
16587    }
16588
16589    /**
16590     * Look for a child view with the given id.  If this view has the given
16591     * id, return this view.
16592     *
16593     * @param id The id to search for.
16594     * @return The view that has the given id in the hierarchy or null
16595     */
16596    public final View findViewById(int id) {
16597        if (id < 0) {
16598            return null;
16599        }
16600        return findViewTraversal(id);
16601    }
16602
16603    /**
16604     * Finds a view by its unuque and stable accessibility id.
16605     *
16606     * @param accessibilityId The searched accessibility id.
16607     * @return The found view.
16608     */
16609    final View findViewByAccessibilityId(int accessibilityId) {
16610        if (accessibilityId < 0) {
16611            return null;
16612        }
16613        return findViewByAccessibilityIdTraversal(accessibilityId);
16614    }
16615
16616    /**
16617     * Performs the traversal to find a view by its unuque and stable accessibility id.
16618     *
16619     * <strong>Note:</strong>This method does not stop at the root namespace
16620     * boundary since the user can touch the screen at an arbitrary location
16621     * potentially crossing the root namespace bounday which will send an
16622     * accessibility event to accessibility services and they should be able
16623     * to obtain the event source. Also accessibility ids are guaranteed to be
16624     * unique in the window.
16625     *
16626     * @param accessibilityId The accessibility id.
16627     * @return The found view.
16628     *
16629     * @hide
16630     */
16631    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16632        if (getAccessibilityViewId() == accessibilityId) {
16633            return this;
16634        }
16635        return null;
16636    }
16637
16638    /**
16639     * Look for a child view with the given tag.  If this view has the given
16640     * tag, return this view.
16641     *
16642     * @param tag The tag to search for, using "tag.equals(getTag())".
16643     * @return The View that has the given tag in the hierarchy or null
16644     */
16645    public final View findViewWithTag(Object tag) {
16646        if (tag == null) {
16647            return null;
16648        }
16649        return findViewWithTagTraversal(tag);
16650    }
16651
16652    /**
16653     * {@hide}
16654     * Look for a child view that matches the specified predicate.
16655     * If this view matches the predicate, return this view.
16656     *
16657     * @param predicate The predicate to evaluate.
16658     * @return The first view that matches the predicate or null.
16659     */
16660    public final View findViewByPredicate(Predicate<View> predicate) {
16661        return findViewByPredicateTraversal(predicate, null);
16662    }
16663
16664    /**
16665     * {@hide}
16666     * Look for a child view that matches the specified predicate,
16667     * starting with the specified view and its descendents and then
16668     * recusively searching the ancestors and siblings of that view
16669     * until this view is reached.
16670     *
16671     * This method is useful in cases where the predicate does not match
16672     * a single unique view (perhaps multiple views use the same id)
16673     * and we are trying to find the view that is "closest" in scope to the
16674     * starting view.
16675     *
16676     * @param start The view to start from.
16677     * @param predicate The predicate to evaluate.
16678     * @return The first view that matches the predicate or null.
16679     */
16680    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16681        View childToSkip = null;
16682        for (;;) {
16683            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16684            if (view != null || start == this) {
16685                return view;
16686            }
16687
16688            ViewParent parent = start.getParent();
16689            if (parent == null || !(parent instanceof View)) {
16690                return null;
16691            }
16692
16693            childToSkip = start;
16694            start = (View) parent;
16695        }
16696    }
16697
16698    /**
16699     * Sets the identifier for this view. The identifier does not have to be
16700     * unique in this view's hierarchy. The identifier should be a positive
16701     * number.
16702     *
16703     * @see #NO_ID
16704     * @see #getId()
16705     * @see #findViewById(int)
16706     *
16707     * @param id a number used to identify the view
16708     *
16709     * @attr ref android.R.styleable#View_id
16710     */
16711    public void setId(int id) {
16712        mID = id;
16713        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16714            mID = generateViewId();
16715        }
16716    }
16717
16718    /**
16719     * {@hide}
16720     *
16721     * @param isRoot true if the view belongs to the root namespace, false
16722     *        otherwise
16723     */
16724    public void setIsRootNamespace(boolean isRoot) {
16725        if (isRoot) {
16726            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16727        } else {
16728            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16729        }
16730    }
16731
16732    /**
16733     * {@hide}
16734     *
16735     * @return true if the view belongs to the root namespace, false otherwise
16736     */
16737    public boolean isRootNamespace() {
16738        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16739    }
16740
16741    /**
16742     * Returns this view's identifier.
16743     *
16744     * @return a positive integer used to identify the view or {@link #NO_ID}
16745     *         if the view has no ID
16746     *
16747     * @see #setId(int)
16748     * @see #findViewById(int)
16749     * @attr ref android.R.styleable#View_id
16750     */
16751    @ViewDebug.CapturedViewProperty
16752    public int getId() {
16753        return mID;
16754    }
16755
16756    /**
16757     * Returns this view's tag.
16758     *
16759     * @return the Object stored in this view as a tag, or {@code null} if not
16760     *         set
16761     *
16762     * @see #setTag(Object)
16763     * @see #getTag(int)
16764     */
16765    @ViewDebug.ExportedProperty
16766    public Object getTag() {
16767        return mTag;
16768    }
16769
16770    /**
16771     * Sets the tag associated with this view. A tag can be used to mark
16772     * a view in its hierarchy and does not have to be unique within the
16773     * hierarchy. Tags can also be used to store data within a view without
16774     * resorting to another data structure.
16775     *
16776     * @param tag an Object to tag the view with
16777     *
16778     * @see #getTag()
16779     * @see #setTag(int, Object)
16780     */
16781    public void setTag(final Object tag) {
16782        mTag = tag;
16783    }
16784
16785    /**
16786     * Returns the tag associated with this view and the specified key.
16787     *
16788     * @param key The key identifying the tag
16789     *
16790     * @return the Object stored in this view as a tag, or {@code null} if not
16791     *         set
16792     *
16793     * @see #setTag(int, Object)
16794     * @see #getTag()
16795     */
16796    public Object getTag(int key) {
16797        if (mKeyedTags != null) return mKeyedTags.get(key);
16798        return null;
16799    }
16800
16801    /**
16802     * Sets a tag associated with this view and a key. A tag can be used
16803     * to mark a view in its hierarchy and does not have to be unique within
16804     * the hierarchy. Tags can also be used to store data within a view
16805     * without resorting to another data structure.
16806     *
16807     * The specified key should be an id declared in the resources of the
16808     * application to ensure it is unique (see the <a
16809     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16810     * Keys identified as belonging to
16811     * the Android framework or not associated with any package will cause
16812     * an {@link IllegalArgumentException} to be thrown.
16813     *
16814     * @param key The key identifying the tag
16815     * @param tag An Object to tag the view with
16816     *
16817     * @throws IllegalArgumentException If they specified key is not valid
16818     *
16819     * @see #setTag(Object)
16820     * @see #getTag(int)
16821     */
16822    public void setTag(int key, final Object tag) {
16823        // If the package id is 0x00 or 0x01, it's either an undefined package
16824        // or a framework id
16825        if ((key >>> 24) < 2) {
16826            throw new IllegalArgumentException("The key must be an application-specific "
16827                    + "resource id.");
16828        }
16829
16830        setKeyedTag(key, tag);
16831    }
16832
16833    /**
16834     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16835     * framework id.
16836     *
16837     * @hide
16838     */
16839    public void setTagInternal(int key, Object tag) {
16840        if ((key >>> 24) != 0x1) {
16841            throw new IllegalArgumentException("The key must be a framework-specific "
16842                    + "resource id.");
16843        }
16844
16845        setKeyedTag(key, tag);
16846    }
16847
16848    private void setKeyedTag(int key, Object tag) {
16849        if (mKeyedTags == null) {
16850            mKeyedTags = new SparseArray<Object>(2);
16851        }
16852
16853        mKeyedTags.put(key, tag);
16854    }
16855
16856    /**
16857     * Prints information about this view in the log output, with the tag
16858     * {@link #VIEW_LOG_TAG}.
16859     *
16860     * @hide
16861     */
16862    public void debug() {
16863        debug(0);
16864    }
16865
16866    /**
16867     * Prints information about this view in the log output, with the tag
16868     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16869     * indentation defined by the <code>depth</code>.
16870     *
16871     * @param depth the indentation level
16872     *
16873     * @hide
16874     */
16875    protected void debug(int depth) {
16876        String output = debugIndent(depth - 1);
16877
16878        output += "+ " + this;
16879        int id = getId();
16880        if (id != -1) {
16881            output += " (id=" + id + ")";
16882        }
16883        Object tag = getTag();
16884        if (tag != null) {
16885            output += " (tag=" + tag + ")";
16886        }
16887        Log.d(VIEW_LOG_TAG, output);
16888
16889        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16890            output = debugIndent(depth) + " FOCUSED";
16891            Log.d(VIEW_LOG_TAG, output);
16892        }
16893
16894        output = debugIndent(depth);
16895        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16896                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16897                + "} ";
16898        Log.d(VIEW_LOG_TAG, output);
16899
16900        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16901                || mPaddingBottom != 0) {
16902            output = debugIndent(depth);
16903            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16904                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16905            Log.d(VIEW_LOG_TAG, output);
16906        }
16907
16908        output = debugIndent(depth);
16909        output += "mMeasureWidth=" + mMeasuredWidth +
16910                " mMeasureHeight=" + mMeasuredHeight;
16911        Log.d(VIEW_LOG_TAG, output);
16912
16913        output = debugIndent(depth);
16914        if (mLayoutParams == null) {
16915            output += "BAD! no layout params";
16916        } else {
16917            output = mLayoutParams.debug(output);
16918        }
16919        Log.d(VIEW_LOG_TAG, output);
16920
16921        output = debugIndent(depth);
16922        output += "flags={";
16923        output += View.printFlags(mViewFlags);
16924        output += "}";
16925        Log.d(VIEW_LOG_TAG, output);
16926
16927        output = debugIndent(depth);
16928        output += "privateFlags={";
16929        output += View.printPrivateFlags(mPrivateFlags);
16930        output += "}";
16931        Log.d(VIEW_LOG_TAG, output);
16932    }
16933
16934    /**
16935     * Creates a string of whitespaces used for indentation.
16936     *
16937     * @param depth the indentation level
16938     * @return a String containing (depth * 2 + 3) * 2 white spaces
16939     *
16940     * @hide
16941     */
16942    protected static String debugIndent(int depth) {
16943        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16944        for (int i = 0; i < (depth * 2) + 3; i++) {
16945            spaces.append(' ').append(' ');
16946        }
16947        return spaces.toString();
16948    }
16949
16950    /**
16951     * <p>Return the offset of the widget's text baseline from the widget's top
16952     * boundary. If this widget does not support baseline alignment, this
16953     * method returns -1. </p>
16954     *
16955     * @return the offset of the baseline within the widget's bounds or -1
16956     *         if baseline alignment is not supported
16957     */
16958    @ViewDebug.ExportedProperty(category = "layout")
16959    public int getBaseline() {
16960        return -1;
16961    }
16962
16963    /**
16964     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16965     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16966     * a layout pass.
16967     *
16968     * @return whether the view hierarchy is currently undergoing a layout pass
16969     */
16970    public boolean isInLayout() {
16971        ViewRootImpl viewRoot = getViewRootImpl();
16972        return (viewRoot != null && viewRoot.isInLayout());
16973    }
16974
16975    /**
16976     * Call this when something has changed which has invalidated the
16977     * layout of this view. This will schedule a layout pass of the view
16978     * tree. This should not be called while the view hierarchy is currently in a layout
16979     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16980     * end of the current layout pass (and then layout will run again) or after the current
16981     * frame is drawn and the next layout occurs.
16982     *
16983     * <p>Subclasses which override this method should call the superclass method to
16984     * handle possible request-during-layout errors correctly.</p>
16985     */
16986    public void requestLayout() {
16987        if (mMeasureCache != null) mMeasureCache.clear();
16988
16989        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16990            // Only trigger request-during-layout logic if this is the view requesting it,
16991            // not the views in its parent hierarchy
16992            ViewRootImpl viewRoot = getViewRootImpl();
16993            if (viewRoot != null && viewRoot.isInLayout()) {
16994                if (!viewRoot.requestLayoutDuringLayout(this)) {
16995                    return;
16996                }
16997            }
16998            mAttachInfo.mViewRequestingLayout = this;
16999        }
17000
17001        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17002        mPrivateFlags |= PFLAG_INVALIDATED;
17003
17004        if (mParent != null && !mParent.isLayoutRequested()) {
17005            mParent.requestLayout();
17006        }
17007        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17008            mAttachInfo.mViewRequestingLayout = null;
17009        }
17010    }
17011
17012    /**
17013     * Forces this view to be laid out during the next layout pass.
17014     * This method does not call requestLayout() or forceLayout()
17015     * on the parent.
17016     */
17017    public void forceLayout() {
17018        if (mMeasureCache != null) mMeasureCache.clear();
17019
17020        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17021        mPrivateFlags |= PFLAG_INVALIDATED;
17022    }
17023
17024    /**
17025     * <p>
17026     * This is called to find out how big a view should be. The parent
17027     * supplies constraint information in the width and height parameters.
17028     * </p>
17029     *
17030     * <p>
17031     * The actual measurement work of a view is performed in
17032     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17033     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17034     * </p>
17035     *
17036     *
17037     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17038     *        parent
17039     * @param heightMeasureSpec Vertical space requirements as imposed by the
17040     *        parent
17041     *
17042     * @see #onMeasure(int, int)
17043     */
17044    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17045        boolean optical = isLayoutModeOptical(this);
17046        if (optical != isLayoutModeOptical(mParent)) {
17047            Insets insets = getOpticalInsets();
17048            int oWidth  = insets.left + insets.right;
17049            int oHeight = insets.top  + insets.bottom;
17050            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17051            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17052        }
17053
17054        // Suppress sign extension for the low bytes
17055        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17056        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17057
17058        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17059                widthMeasureSpec != mOldWidthMeasureSpec ||
17060                heightMeasureSpec != mOldHeightMeasureSpec) {
17061
17062            // first clears the measured dimension flag
17063            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17064
17065            resolveRtlPropertiesIfNeeded();
17066
17067            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17068                    mMeasureCache.indexOfKey(key);
17069            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17070                // measure ourselves, this should set the measured dimension flag back
17071                onMeasure(widthMeasureSpec, heightMeasureSpec);
17072                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17073            } else {
17074                long value = mMeasureCache.valueAt(cacheIndex);
17075                // Casting a long to int drops the high 32 bits, no mask needed
17076                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17077                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17078            }
17079
17080            // flag not set, setMeasuredDimension() was not invoked, we raise
17081            // an exception to warn the developer
17082            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17083                throw new IllegalStateException("onMeasure() did not set the"
17084                        + " measured dimension by calling"
17085                        + " setMeasuredDimension()");
17086            }
17087
17088            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17089        }
17090
17091        mOldWidthMeasureSpec = widthMeasureSpec;
17092        mOldHeightMeasureSpec = heightMeasureSpec;
17093
17094        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17095                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17096    }
17097
17098    /**
17099     * <p>
17100     * Measure the view and its content to determine the measured width and the
17101     * measured height. This method is invoked by {@link #measure(int, int)} and
17102     * should be overriden by subclasses to provide accurate and efficient
17103     * measurement of their contents.
17104     * </p>
17105     *
17106     * <p>
17107     * <strong>CONTRACT:</strong> When overriding this method, you
17108     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17109     * measured width and height of this view. Failure to do so will trigger an
17110     * <code>IllegalStateException</code>, thrown by
17111     * {@link #measure(int, int)}. Calling the superclass'
17112     * {@link #onMeasure(int, int)} is a valid use.
17113     * </p>
17114     *
17115     * <p>
17116     * The base class implementation of measure defaults to the background size,
17117     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17118     * override {@link #onMeasure(int, int)} to provide better measurements of
17119     * their content.
17120     * </p>
17121     *
17122     * <p>
17123     * If this method is overridden, it is the subclass's responsibility to make
17124     * sure the measured height and width are at least the view's minimum height
17125     * and width ({@link #getSuggestedMinimumHeight()} and
17126     * {@link #getSuggestedMinimumWidth()}).
17127     * </p>
17128     *
17129     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17130     *                         The requirements are encoded with
17131     *                         {@link android.view.View.MeasureSpec}.
17132     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17133     *                         The requirements are encoded with
17134     *                         {@link android.view.View.MeasureSpec}.
17135     *
17136     * @see #getMeasuredWidth()
17137     * @see #getMeasuredHeight()
17138     * @see #setMeasuredDimension(int, int)
17139     * @see #getSuggestedMinimumHeight()
17140     * @see #getSuggestedMinimumWidth()
17141     * @see android.view.View.MeasureSpec#getMode(int)
17142     * @see android.view.View.MeasureSpec#getSize(int)
17143     */
17144    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17145        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17146                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17147    }
17148
17149    /**
17150     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17151     * measured width and measured height. Failing to do so will trigger an
17152     * exception at measurement time.</p>
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    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17162        boolean optical = isLayoutModeOptical(this);
17163        if (optical != isLayoutModeOptical(mParent)) {
17164            Insets insets = getOpticalInsets();
17165            int opticalWidth  = insets.left + insets.right;
17166            int opticalHeight = insets.top  + insets.bottom;
17167
17168            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17169            measuredHeight += optical ? opticalHeight : -opticalHeight;
17170        }
17171        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17172    }
17173
17174    /**
17175     * Sets the measured dimension without extra processing for things like optical bounds.
17176     * Useful for reapplying consistent values that have already been cooked with adjustments
17177     * for optical bounds, etc. such as those from the measurement cache.
17178     *
17179     * @param measuredWidth The measured width of this view.  May be a complex
17180     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17181     * {@link #MEASURED_STATE_TOO_SMALL}.
17182     * @param measuredHeight The measured height of this view.  May be a complex
17183     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17184     * {@link #MEASURED_STATE_TOO_SMALL}.
17185     */
17186    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17187        mMeasuredWidth = measuredWidth;
17188        mMeasuredHeight = measuredHeight;
17189
17190        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17191    }
17192
17193    /**
17194     * Merge two states as returned by {@link #getMeasuredState()}.
17195     * @param curState The current state as returned from a view or the result
17196     * of combining multiple views.
17197     * @param newState The new view state to combine.
17198     * @return Returns a new integer reflecting the combination of the two
17199     * states.
17200     */
17201    public static int combineMeasuredStates(int curState, int newState) {
17202        return curState | newState;
17203    }
17204
17205    /**
17206     * Version of {@link #resolveSizeAndState(int, int, int)}
17207     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17208     */
17209    public static int resolveSize(int size, int measureSpec) {
17210        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17211    }
17212
17213    /**
17214     * Utility to reconcile a desired size and state, with constraints imposed
17215     * by a MeasureSpec.  Will take the desired size, unless a different size
17216     * is imposed by the constraints.  The returned value is a compound integer,
17217     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17218     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17219     * size is smaller than the size the view wants to be.
17220     *
17221     * @param size How big the view wants to be
17222     * @param measureSpec Constraints imposed by the parent
17223     * @return Size information bit mask as defined by
17224     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17225     */
17226    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17227        int result = size;
17228        int specMode = MeasureSpec.getMode(measureSpec);
17229        int specSize =  MeasureSpec.getSize(measureSpec);
17230        switch (specMode) {
17231        case MeasureSpec.UNSPECIFIED:
17232            result = size;
17233            break;
17234        case MeasureSpec.AT_MOST:
17235            if (specSize < size) {
17236                result = specSize | MEASURED_STATE_TOO_SMALL;
17237            } else {
17238                result = size;
17239            }
17240            break;
17241        case MeasureSpec.EXACTLY:
17242            result = specSize;
17243            break;
17244        }
17245        return result | (childMeasuredState&MEASURED_STATE_MASK);
17246    }
17247
17248    /**
17249     * Utility to return a default size. Uses the supplied size if the
17250     * MeasureSpec imposed no constraints. Will get larger if allowed
17251     * by the MeasureSpec.
17252     *
17253     * @param size Default size for this view
17254     * @param measureSpec Constraints imposed by the parent
17255     * @return The size this view should be.
17256     */
17257    public static int getDefaultSize(int size, int measureSpec) {
17258        int result = size;
17259        int specMode = MeasureSpec.getMode(measureSpec);
17260        int specSize = MeasureSpec.getSize(measureSpec);
17261
17262        switch (specMode) {
17263        case MeasureSpec.UNSPECIFIED:
17264            result = size;
17265            break;
17266        case MeasureSpec.AT_MOST:
17267        case MeasureSpec.EXACTLY:
17268            result = specSize;
17269            break;
17270        }
17271        return result;
17272    }
17273
17274    /**
17275     * Returns the suggested minimum height that the view should use. This
17276     * returns the maximum of the view's minimum height
17277     * and the background's minimum height
17278     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17279     * <p>
17280     * When being used in {@link #onMeasure(int, int)}, the caller should still
17281     * ensure the returned height is within the requirements of the parent.
17282     *
17283     * @return The suggested minimum height of the view.
17284     */
17285    protected int getSuggestedMinimumHeight() {
17286        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17287
17288    }
17289
17290    /**
17291     * Returns the suggested minimum width that the view should use. This
17292     * returns the maximum of the view's minimum width)
17293     * and the background's minimum width
17294     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17295     * <p>
17296     * When being used in {@link #onMeasure(int, int)}, the caller should still
17297     * ensure the returned width is within the requirements of the parent.
17298     *
17299     * @return The suggested minimum width of the view.
17300     */
17301    protected int getSuggestedMinimumWidth() {
17302        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17303    }
17304
17305    /**
17306     * Returns the minimum height of the view.
17307     *
17308     * @return the minimum height the view will try to be.
17309     *
17310     * @see #setMinimumHeight(int)
17311     *
17312     * @attr ref android.R.styleable#View_minHeight
17313     */
17314    public int getMinimumHeight() {
17315        return mMinHeight;
17316    }
17317
17318    /**
17319     * Sets the minimum height of the view. It is not guaranteed the view will
17320     * be able to achieve this minimum height (for example, if its parent layout
17321     * constrains it with less available height).
17322     *
17323     * @param minHeight The minimum height the view will try to be.
17324     *
17325     * @see #getMinimumHeight()
17326     *
17327     * @attr ref android.R.styleable#View_minHeight
17328     */
17329    public void setMinimumHeight(int minHeight) {
17330        mMinHeight = minHeight;
17331        requestLayout();
17332    }
17333
17334    /**
17335     * Returns the minimum width of the view.
17336     *
17337     * @return the minimum width the view will try to be.
17338     *
17339     * @see #setMinimumWidth(int)
17340     *
17341     * @attr ref android.R.styleable#View_minWidth
17342     */
17343    public int getMinimumWidth() {
17344        return mMinWidth;
17345    }
17346
17347    /**
17348     * Sets the minimum width of the view. It is not guaranteed the view will
17349     * be able to achieve this minimum width (for example, if its parent layout
17350     * constrains it with less available width).
17351     *
17352     * @param minWidth The minimum width the view will try to be.
17353     *
17354     * @see #getMinimumWidth()
17355     *
17356     * @attr ref android.R.styleable#View_minWidth
17357     */
17358    public void setMinimumWidth(int minWidth) {
17359        mMinWidth = minWidth;
17360        requestLayout();
17361
17362    }
17363
17364    /**
17365     * Get the animation currently associated with this view.
17366     *
17367     * @return The animation that is currently playing or
17368     *         scheduled to play for this view.
17369     */
17370    public Animation getAnimation() {
17371        return mCurrentAnimation;
17372    }
17373
17374    /**
17375     * Start the specified animation now.
17376     *
17377     * @param animation the animation to start now
17378     */
17379    public void startAnimation(Animation animation) {
17380        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17381        setAnimation(animation);
17382        invalidateParentCaches();
17383        invalidate(true);
17384    }
17385
17386    /**
17387     * Cancels any animations for this view.
17388     */
17389    public void clearAnimation() {
17390        if (mCurrentAnimation != null) {
17391            mCurrentAnimation.detach();
17392        }
17393        mCurrentAnimation = null;
17394        invalidateParentIfNeeded();
17395    }
17396
17397    /**
17398     * Sets the next animation to play for this view.
17399     * If you want the animation to play immediately, use
17400     * {@link #startAnimation(android.view.animation.Animation)} instead.
17401     * This method provides allows fine-grained
17402     * control over the start time and invalidation, but you
17403     * must make sure that 1) the animation has a start time set, and
17404     * 2) the view's parent (which controls animations on its children)
17405     * will be invalidated when the animation is supposed to
17406     * start.
17407     *
17408     * @param animation The next animation, or null.
17409     */
17410    public void setAnimation(Animation animation) {
17411        mCurrentAnimation = animation;
17412
17413        if (animation != null) {
17414            // If the screen is off assume the animation start time is now instead of
17415            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17416            // would cause the animation to start when the screen turns back on
17417            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17418                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17419                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17420            }
17421            animation.reset();
17422        }
17423    }
17424
17425    /**
17426     * Invoked by a parent ViewGroup to notify the start of the animation
17427     * currently associated with this view. If you override this method,
17428     * always call super.onAnimationStart();
17429     *
17430     * @see #setAnimation(android.view.animation.Animation)
17431     * @see #getAnimation()
17432     */
17433    protected void onAnimationStart() {
17434        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17435    }
17436
17437    /**
17438     * Invoked by a parent ViewGroup to notify the end of the animation
17439     * currently associated with this view. If you override this method,
17440     * always call super.onAnimationEnd();
17441     *
17442     * @see #setAnimation(android.view.animation.Animation)
17443     * @see #getAnimation()
17444     */
17445    protected void onAnimationEnd() {
17446        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17447    }
17448
17449    /**
17450     * Invoked if there is a Transform that involves alpha. Subclass that can
17451     * draw themselves with the specified alpha should return true, and then
17452     * respect that alpha when their onDraw() is called. If this returns false
17453     * then the view may be redirected to draw into an offscreen buffer to
17454     * fulfill the request, which will look fine, but may be slower than if the
17455     * subclass handles it internally. The default implementation returns false.
17456     *
17457     * @param alpha The alpha (0..255) to apply to the view's drawing
17458     * @return true if the view can draw with the specified alpha.
17459     */
17460    protected boolean onSetAlpha(int alpha) {
17461        return false;
17462    }
17463
17464    /**
17465     * This is used by the RootView to perform an optimization when
17466     * the view hierarchy contains one or several SurfaceView.
17467     * SurfaceView is always considered transparent, but its children are not,
17468     * therefore all View objects remove themselves from the global transparent
17469     * region (passed as a parameter to this function).
17470     *
17471     * @param region The transparent region for this ViewAncestor (window).
17472     *
17473     * @return Returns true if the effective visibility of the view at this
17474     * point is opaque, regardless of the transparent region; returns false
17475     * if it is possible for underlying windows to be seen behind the view.
17476     *
17477     * {@hide}
17478     */
17479    public boolean gatherTransparentRegion(Region region) {
17480        final AttachInfo attachInfo = mAttachInfo;
17481        if (region != null && attachInfo != null) {
17482            final int pflags = mPrivateFlags;
17483            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17484                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17485                // remove it from the transparent region.
17486                final int[] location = attachInfo.mTransparentLocation;
17487                getLocationInWindow(location);
17488                region.op(location[0], location[1], location[0] + mRight - mLeft,
17489                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17490            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17491                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17492                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17493                // exists, so we remove the background drawable's non-transparent
17494                // parts from this transparent region.
17495                applyDrawableToTransparentRegion(mBackground, region);
17496            }
17497        }
17498        return true;
17499    }
17500
17501    /**
17502     * Play a sound effect for this view.
17503     *
17504     * <p>The framework will play sound effects for some built in actions, such as
17505     * clicking, but you may wish to play these effects in your widget,
17506     * for instance, for internal navigation.
17507     *
17508     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17509     * {@link #isSoundEffectsEnabled()} is true.
17510     *
17511     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17512     */
17513    public void playSoundEffect(int soundConstant) {
17514        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17515            return;
17516        }
17517        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17518    }
17519
17520    /**
17521     * BZZZTT!!1!
17522     *
17523     * <p>Provide haptic feedback to the user for this view.
17524     *
17525     * <p>The framework will provide haptic feedback for some built in actions,
17526     * such as long presses, but you may wish to provide feedback for your
17527     * own widget.
17528     *
17529     * <p>The feedback will only be performed if
17530     * {@link #isHapticFeedbackEnabled()} is true.
17531     *
17532     * @param feedbackConstant One of the constants defined in
17533     * {@link HapticFeedbackConstants}
17534     */
17535    public boolean performHapticFeedback(int feedbackConstant) {
17536        return performHapticFeedback(feedbackConstant, 0);
17537    }
17538
17539    /**
17540     * BZZZTT!!1!
17541     *
17542     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17543     *
17544     * @param feedbackConstant One of the constants defined in
17545     * {@link HapticFeedbackConstants}
17546     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17547     */
17548    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17549        if (mAttachInfo == null) {
17550            return false;
17551        }
17552        //noinspection SimplifiableIfStatement
17553        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17554                && !isHapticFeedbackEnabled()) {
17555            return false;
17556        }
17557        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17558                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17559    }
17560
17561    /**
17562     * Request that the visibility of the status bar or other screen/window
17563     * decorations be changed.
17564     *
17565     * <p>This method is used to put the over device UI into temporary modes
17566     * where the user's attention is focused more on the application content,
17567     * by dimming or hiding surrounding system affordances.  This is typically
17568     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17569     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17570     * to be placed behind the action bar (and with these flags other system
17571     * affordances) so that smooth transitions between hiding and showing them
17572     * can be done.
17573     *
17574     * <p>Two representative examples of the use of system UI visibility is
17575     * implementing a content browsing application (like a magazine reader)
17576     * and a video playing application.
17577     *
17578     * <p>The first code shows a typical implementation of a View in a content
17579     * browsing application.  In this implementation, the application goes
17580     * into a content-oriented mode by hiding the status bar and action bar,
17581     * and putting the navigation elements into lights out mode.  The user can
17582     * then interact with content while in this mode.  Such an application should
17583     * provide an easy way for the user to toggle out of the mode (such as to
17584     * check information in the status bar or access notifications).  In the
17585     * implementation here, this is done simply by tapping on the content.
17586     *
17587     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17588     *      content}
17589     *
17590     * <p>This second code sample shows a typical implementation of a View
17591     * in a video playing application.  In this situation, while the video is
17592     * playing the application would like to go into a complete full-screen mode,
17593     * to use as much of the display as possible for the video.  When in this state
17594     * the user can not interact with the application; the system intercepts
17595     * touching on the screen to pop the UI out of full screen mode.  See
17596     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17597     *
17598     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17599     *      content}
17600     *
17601     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17602     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17603     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17604     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17605     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17606     */
17607    public void setSystemUiVisibility(int visibility) {
17608        if (visibility != mSystemUiVisibility) {
17609            mSystemUiVisibility = visibility;
17610            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17611                mParent.recomputeViewAttributes(this);
17612            }
17613        }
17614    }
17615
17616    /**
17617     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17618     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17619     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17620     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17621     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17622     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17623     */
17624    public int getSystemUiVisibility() {
17625        return mSystemUiVisibility;
17626    }
17627
17628    /**
17629     * Returns the current system UI visibility that is currently set for
17630     * the entire window.  This is the combination of the
17631     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17632     * views in the window.
17633     */
17634    public int getWindowSystemUiVisibility() {
17635        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17636    }
17637
17638    /**
17639     * Override to find out when the window's requested system UI visibility
17640     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17641     * This is different from the callbacks received through
17642     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17643     * in that this is only telling you about the local request of the window,
17644     * not the actual values applied by the system.
17645     */
17646    public void onWindowSystemUiVisibilityChanged(int visible) {
17647    }
17648
17649    /**
17650     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17651     * the view hierarchy.
17652     */
17653    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17654        onWindowSystemUiVisibilityChanged(visible);
17655    }
17656
17657    /**
17658     * Set a listener to receive callbacks when the visibility of the system bar changes.
17659     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17660     */
17661    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17662        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17663        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17664            mParent.recomputeViewAttributes(this);
17665        }
17666    }
17667
17668    /**
17669     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17670     * the view hierarchy.
17671     */
17672    public void dispatchSystemUiVisibilityChanged(int visibility) {
17673        ListenerInfo li = mListenerInfo;
17674        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17675            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17676                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17677        }
17678    }
17679
17680    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17681        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17682        if (val != mSystemUiVisibility) {
17683            setSystemUiVisibility(val);
17684            return true;
17685        }
17686        return false;
17687    }
17688
17689    /** @hide */
17690    public void setDisabledSystemUiVisibility(int flags) {
17691        if (mAttachInfo != null) {
17692            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17693                mAttachInfo.mDisabledSystemUiVisibility = flags;
17694                if (mParent != null) {
17695                    mParent.recomputeViewAttributes(this);
17696                }
17697            }
17698        }
17699    }
17700
17701    /**
17702     * Creates an image that the system displays during the drag and drop
17703     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17704     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17705     * appearance as the given View. The default also positions the center of the drag shadow
17706     * directly under the touch point. If no View is provided (the constructor with no parameters
17707     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17708     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17709     * default is an invisible drag shadow.
17710     * <p>
17711     * You are not required to use the View you provide to the constructor as the basis of the
17712     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17713     * anything you want as the drag shadow.
17714     * </p>
17715     * <p>
17716     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17717     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17718     *  size and position of the drag shadow. It uses this data to construct a
17719     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17720     *  so that your application can draw the shadow image in the Canvas.
17721     * </p>
17722     *
17723     * <div class="special reference">
17724     * <h3>Developer Guides</h3>
17725     * <p>For a guide to implementing drag and drop features, read the
17726     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17727     * </div>
17728     */
17729    public static class DragShadowBuilder {
17730        private final WeakReference<View> mView;
17731
17732        /**
17733         * Constructs a shadow image builder based on a View. By default, the resulting drag
17734         * shadow will have the same appearance and dimensions as the View, with the touch point
17735         * over the center of the View.
17736         * @param view A View. Any View in scope can be used.
17737         */
17738        public DragShadowBuilder(View view) {
17739            mView = new WeakReference<View>(view);
17740        }
17741
17742        /**
17743         * Construct a shadow builder object with no associated View.  This
17744         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17745         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17746         * to supply the drag shadow's dimensions and appearance without
17747         * reference to any View object. If they are not overridden, then the result is an
17748         * invisible drag shadow.
17749         */
17750        public DragShadowBuilder() {
17751            mView = new WeakReference<View>(null);
17752        }
17753
17754        /**
17755         * Returns the View object that had been passed to the
17756         * {@link #View.DragShadowBuilder(View)}
17757         * constructor.  If that View parameter was {@code null} or if the
17758         * {@link #View.DragShadowBuilder()}
17759         * constructor was used to instantiate the builder object, this method will return
17760         * null.
17761         *
17762         * @return The View object associate with this builder object.
17763         */
17764        @SuppressWarnings({"JavadocReference"})
17765        final public View getView() {
17766            return mView.get();
17767        }
17768
17769        /**
17770         * Provides the metrics for the shadow image. These include the dimensions of
17771         * the shadow image, and the point within that shadow that should
17772         * be centered under the touch location while dragging.
17773         * <p>
17774         * The default implementation sets the dimensions of the shadow to be the
17775         * same as the dimensions of the View itself and centers the shadow under
17776         * the touch point.
17777         * </p>
17778         *
17779         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17780         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17781         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17782         * image.
17783         *
17784         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17785         * shadow image that should be underneath the touch point during the drag and drop
17786         * operation. Your application must set {@link android.graphics.Point#x} to the
17787         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17788         */
17789        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17790            final View view = mView.get();
17791            if (view != null) {
17792                shadowSize.set(view.getWidth(), view.getHeight());
17793                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17794            } else {
17795                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17796            }
17797        }
17798
17799        /**
17800         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17801         * based on the dimensions it received from the
17802         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17803         *
17804         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17805         */
17806        public void onDrawShadow(Canvas canvas) {
17807            final View view = mView.get();
17808            if (view != null) {
17809                view.draw(canvas);
17810            } else {
17811                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17812            }
17813        }
17814    }
17815
17816    /**
17817     * Starts a drag and drop operation. When your application calls this method, it passes a
17818     * {@link android.view.View.DragShadowBuilder} object to the system. The
17819     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17820     * to get metrics for the drag shadow, and then calls the object's
17821     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17822     * <p>
17823     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17824     *  drag events to all the View objects in your application that are currently visible. It does
17825     *  this either by calling the View object's drag listener (an implementation of
17826     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17827     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17828     *  Both are passed a {@link android.view.DragEvent} object that has a
17829     *  {@link android.view.DragEvent#getAction()} value of
17830     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17831     * </p>
17832     * <p>
17833     * Your application can invoke startDrag() on any attached View object. The View object does not
17834     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17835     * be related to the View the user selected for dragging.
17836     * </p>
17837     * @param data A {@link android.content.ClipData} object pointing to the data to be
17838     * transferred by the drag and drop operation.
17839     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17840     * drag shadow.
17841     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17842     * drop operation. This Object is put into every DragEvent object sent by the system during the
17843     * current drag.
17844     * <p>
17845     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17846     * to the target Views. For example, it can contain flags that differentiate between a
17847     * a copy operation and a move operation.
17848     * </p>
17849     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17850     * so the parameter should be set to 0.
17851     * @return {@code true} if the method completes successfully, or
17852     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17853     * do a drag, and so no drag operation is in progress.
17854     */
17855    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17856            Object myLocalState, int flags) {
17857        if (ViewDebug.DEBUG_DRAG) {
17858            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17859        }
17860        boolean okay = false;
17861
17862        Point shadowSize = new Point();
17863        Point shadowTouchPoint = new Point();
17864        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17865
17866        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17867                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17868            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17869        }
17870
17871        if (ViewDebug.DEBUG_DRAG) {
17872            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17873                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17874        }
17875        Surface surface = new Surface();
17876        try {
17877            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17878                    flags, shadowSize.x, shadowSize.y, surface);
17879            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17880                    + " surface=" + surface);
17881            if (token != null) {
17882                Canvas canvas = surface.lockCanvas(null);
17883                try {
17884                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17885                    shadowBuilder.onDrawShadow(canvas);
17886                } finally {
17887                    surface.unlockCanvasAndPost(canvas);
17888                }
17889
17890                final ViewRootImpl root = getViewRootImpl();
17891
17892                // Cache the local state object for delivery with DragEvents
17893                root.setLocalDragState(myLocalState);
17894
17895                // repurpose 'shadowSize' for the last touch point
17896                root.getLastTouchPoint(shadowSize);
17897
17898                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17899                        shadowSize.x, shadowSize.y,
17900                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17901                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17902
17903                // Off and running!  Release our local surface instance; the drag
17904                // shadow surface is now managed by the system process.
17905                surface.release();
17906            }
17907        } catch (Exception e) {
17908            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17909            surface.destroy();
17910        }
17911
17912        return okay;
17913    }
17914
17915    /**
17916     * Handles drag events sent by the system following a call to
17917     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17918     *<p>
17919     * When the system calls this method, it passes a
17920     * {@link android.view.DragEvent} object. A call to
17921     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17922     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17923     * operation.
17924     * @param event The {@link android.view.DragEvent} sent by the system.
17925     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17926     * in DragEvent, indicating the type of drag event represented by this object.
17927     * @return {@code true} if the method was successful, otherwise {@code false}.
17928     * <p>
17929     *  The method should return {@code true} in response to an action type of
17930     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17931     *  operation.
17932     * </p>
17933     * <p>
17934     *  The method should also return {@code true} in response to an action type of
17935     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17936     *  {@code false} if it didn't.
17937     * </p>
17938     */
17939    public boolean onDragEvent(DragEvent event) {
17940        return false;
17941    }
17942
17943    /**
17944     * Detects if this View is enabled and has a drag event listener.
17945     * If both are true, then it calls the drag event listener with the
17946     * {@link android.view.DragEvent} it received. If the drag event listener returns
17947     * {@code true}, then dispatchDragEvent() returns {@code true}.
17948     * <p>
17949     * For all other cases, the method calls the
17950     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17951     * method and returns its result.
17952     * </p>
17953     * <p>
17954     * This ensures that a drag event is always consumed, even if the View does not have a drag
17955     * event listener. However, if the View has a listener and the listener returns true, then
17956     * onDragEvent() is not called.
17957     * </p>
17958     */
17959    public boolean dispatchDragEvent(DragEvent event) {
17960        ListenerInfo li = mListenerInfo;
17961        //noinspection SimplifiableIfStatement
17962        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17963                && li.mOnDragListener.onDrag(this, event)) {
17964            return true;
17965        }
17966        return onDragEvent(event);
17967    }
17968
17969    boolean canAcceptDrag() {
17970        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17971    }
17972
17973    /**
17974     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17975     * it is ever exposed at all.
17976     * @hide
17977     */
17978    public void onCloseSystemDialogs(String reason) {
17979    }
17980
17981    /**
17982     * Given a Drawable whose bounds have been set to draw into this view,
17983     * update a Region being computed for
17984     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17985     * that any non-transparent parts of the Drawable are removed from the
17986     * given transparent region.
17987     *
17988     * @param dr The Drawable whose transparency is to be applied to the region.
17989     * @param region A Region holding the current transparency information,
17990     * where any parts of the region that are set are considered to be
17991     * transparent.  On return, this region will be modified to have the
17992     * transparency information reduced by the corresponding parts of the
17993     * Drawable that are not transparent.
17994     * {@hide}
17995     */
17996    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17997        if (DBG) {
17998            Log.i("View", "Getting transparent region for: " + this);
17999        }
18000        final Region r = dr.getTransparentRegion();
18001        final Rect db = dr.getBounds();
18002        final AttachInfo attachInfo = mAttachInfo;
18003        if (r != null && attachInfo != null) {
18004            final int w = getRight()-getLeft();
18005            final int h = getBottom()-getTop();
18006            if (db.left > 0) {
18007                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18008                r.op(0, 0, db.left, h, Region.Op.UNION);
18009            }
18010            if (db.right < w) {
18011                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18012                r.op(db.right, 0, w, h, Region.Op.UNION);
18013            }
18014            if (db.top > 0) {
18015                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18016                r.op(0, 0, w, db.top, Region.Op.UNION);
18017            }
18018            if (db.bottom < h) {
18019                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18020                r.op(0, db.bottom, w, h, Region.Op.UNION);
18021            }
18022            final int[] location = attachInfo.mTransparentLocation;
18023            getLocationInWindow(location);
18024            r.translate(location[0], location[1]);
18025            region.op(r, Region.Op.INTERSECT);
18026        } else {
18027            region.op(db, Region.Op.DIFFERENCE);
18028        }
18029    }
18030
18031    private void checkForLongClick(int delayOffset) {
18032        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18033            mHasPerformedLongPress = false;
18034
18035            if (mPendingCheckForLongPress == null) {
18036                mPendingCheckForLongPress = new CheckForLongPress();
18037            }
18038            mPendingCheckForLongPress.rememberWindowAttachCount();
18039            postDelayed(mPendingCheckForLongPress,
18040                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18041        }
18042    }
18043
18044    /**
18045     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18046     * LayoutInflater} class, which provides a full range of options for view inflation.
18047     *
18048     * @param context The Context object for your activity or application.
18049     * @param resource The resource ID to inflate
18050     * @param root A view group that will be the parent.  Used to properly inflate the
18051     * layout_* parameters.
18052     * @see LayoutInflater
18053     */
18054    public static View inflate(Context context, int resource, ViewGroup root) {
18055        LayoutInflater factory = LayoutInflater.from(context);
18056        return factory.inflate(resource, root);
18057    }
18058
18059    /**
18060     * Scroll the view with standard behavior for scrolling beyond the normal
18061     * content boundaries. Views that call this method should override
18062     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18063     * results of an over-scroll operation.
18064     *
18065     * Views can use this method to handle any touch or fling-based scrolling.
18066     *
18067     * @param deltaX Change in X in pixels
18068     * @param deltaY Change in Y in pixels
18069     * @param scrollX Current X scroll value in pixels before applying deltaX
18070     * @param scrollY Current Y scroll value in pixels before applying deltaY
18071     * @param scrollRangeX Maximum content scroll range along the X axis
18072     * @param scrollRangeY Maximum content scroll range along the Y axis
18073     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18074     *          along the X axis.
18075     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18076     *          along the Y axis.
18077     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18078     * @return true if scrolling was clamped to an over-scroll boundary along either
18079     *          axis, false otherwise.
18080     */
18081    @SuppressWarnings({"UnusedParameters"})
18082    protected boolean overScrollBy(int deltaX, int deltaY,
18083            int scrollX, int scrollY,
18084            int scrollRangeX, int scrollRangeY,
18085            int maxOverScrollX, int maxOverScrollY,
18086            boolean isTouchEvent) {
18087        final int overScrollMode = mOverScrollMode;
18088        final boolean canScrollHorizontal =
18089                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18090        final boolean canScrollVertical =
18091                computeVerticalScrollRange() > computeVerticalScrollExtent();
18092        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18093                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18094        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18095                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18096
18097        int newScrollX = scrollX + deltaX;
18098        if (!overScrollHorizontal) {
18099            maxOverScrollX = 0;
18100        }
18101
18102        int newScrollY = scrollY + deltaY;
18103        if (!overScrollVertical) {
18104            maxOverScrollY = 0;
18105        }
18106
18107        // Clamp values if at the limits and record
18108        final int left = -maxOverScrollX;
18109        final int right = maxOverScrollX + scrollRangeX;
18110        final int top = -maxOverScrollY;
18111        final int bottom = maxOverScrollY + scrollRangeY;
18112
18113        boolean clampedX = false;
18114        if (newScrollX > right) {
18115            newScrollX = right;
18116            clampedX = true;
18117        } else if (newScrollX < left) {
18118            newScrollX = left;
18119            clampedX = true;
18120        }
18121
18122        boolean clampedY = false;
18123        if (newScrollY > bottom) {
18124            newScrollY = bottom;
18125            clampedY = true;
18126        } else if (newScrollY < top) {
18127            newScrollY = top;
18128            clampedY = true;
18129        }
18130
18131        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18132
18133        return clampedX || clampedY;
18134    }
18135
18136    /**
18137     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18138     * respond to the results of an over-scroll operation.
18139     *
18140     * @param scrollX New X scroll value in pixels
18141     * @param scrollY New Y scroll value in pixels
18142     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18143     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18144     */
18145    protected void onOverScrolled(int scrollX, int scrollY,
18146            boolean clampedX, boolean clampedY) {
18147        // Intentionally empty.
18148    }
18149
18150    /**
18151     * Returns the over-scroll mode for this view. The result will be
18152     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18153     * (allow over-scrolling only if the view content is larger than the container),
18154     * or {@link #OVER_SCROLL_NEVER}.
18155     *
18156     * @return This view's over-scroll mode.
18157     */
18158    public int getOverScrollMode() {
18159        return mOverScrollMode;
18160    }
18161
18162    /**
18163     * Set the over-scroll mode for this view. Valid over-scroll modes are
18164     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18165     * (allow over-scrolling only if the view content is larger than the container),
18166     * or {@link #OVER_SCROLL_NEVER}.
18167     *
18168     * Setting the over-scroll mode of a view will have an effect only if the
18169     * view is capable of scrolling.
18170     *
18171     * @param overScrollMode The new over-scroll mode for this view.
18172     */
18173    public void setOverScrollMode(int overScrollMode) {
18174        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18175                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18176                overScrollMode != OVER_SCROLL_NEVER) {
18177            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18178        }
18179        mOverScrollMode = overScrollMode;
18180    }
18181
18182    /**
18183     * Enable or disable nested scrolling for this view.
18184     *
18185     * <p>If this property is set to true the view will be permitted to initiate nested
18186     * scrolling operations with a compatible parent view in the current hierarchy. If this
18187     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18188     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18189     * the nested scroll.</p>
18190     *
18191     * @param enabled true to enable nested scrolling, false to disable
18192     *
18193     * @see #isNestedScrollingEnabled()
18194     */
18195    public void setNestedScrollingEnabled(boolean enabled) {
18196        if (enabled) {
18197            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18198        } else {
18199            stopNestedScroll();
18200            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18201        }
18202    }
18203
18204    /**
18205     * Returns true if nested scrolling is enabled for this view.
18206     *
18207     * <p>If nested scrolling is enabled and this View class implementation supports it,
18208     * this view will act as a nested scrolling child view when applicable, forwarding data
18209     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18210     * parent.</p>
18211     *
18212     * @return true if nested scrolling is enabled
18213     *
18214     * @see #setNestedScrollingEnabled(boolean)
18215     */
18216    public boolean isNestedScrollingEnabled() {
18217        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18218                PFLAG3_NESTED_SCROLLING_ENABLED;
18219    }
18220
18221    /**
18222     * Begin a nestable scroll operation along the given axes.
18223     *
18224     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18225     *
18226     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18227     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18228     * In the case of touch scrolling the nested scroll will be terminated automatically in
18229     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18230     * In the event of programmatic scrolling the caller must explicitly call
18231     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18232     *
18233     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18234     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18235     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18236     *
18237     * <p>At each incremental step of the scroll the caller should invoke
18238     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18239     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18240     * parent at least partially consumed the scroll and the caller should adjust the amount it
18241     * scrolls by.</p>
18242     *
18243     * <p>After applying the remainder of the scroll delta the caller should invoke
18244     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18245     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18246     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18247     * </p>
18248     *
18249     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18250     *             {@link #SCROLL_AXIS_VERTICAL}.
18251     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18252     *         the current gesture.
18253     *
18254     * @see #stopNestedScroll()
18255     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18256     * @see #dispatchNestedScroll(int, int, int, int, int[])
18257     */
18258    public boolean startNestedScroll(int axes) {
18259        if (hasNestedScrollingParent()) {
18260            // Already in progress
18261            return true;
18262        }
18263        if (isNestedScrollingEnabled()) {
18264            ViewParent p = getParent();
18265            View child = this;
18266            while (p != null) {
18267                try {
18268                    if (p.onStartNestedScroll(child, this, axes)) {
18269                        mNestedScrollingParent = p;
18270                        p.onNestedScrollAccepted(child, this, axes);
18271                        return true;
18272                    }
18273                } catch (AbstractMethodError e) {
18274                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18275                            "method onStartNestedScroll", e);
18276                    // Allow the search upward to continue
18277                }
18278                if (p instanceof View) {
18279                    child = (View) p;
18280                }
18281                p = p.getParent();
18282            }
18283        }
18284        return false;
18285    }
18286
18287    /**
18288     * Stop a nested scroll in progress.
18289     *
18290     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18291     *
18292     * @see #startNestedScroll(int)
18293     */
18294    public void stopNestedScroll() {
18295        if (mNestedScrollingParent != null) {
18296            mNestedScrollingParent.onStopNestedScroll(this);
18297            mNestedScrollingParent = null;
18298        }
18299    }
18300
18301    /**
18302     * Returns true if this view has a nested scrolling parent.
18303     *
18304     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18305     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18306     *
18307     * @return whether this view has a nested scrolling parent
18308     */
18309    public boolean hasNestedScrollingParent() {
18310        return mNestedScrollingParent != null;
18311    }
18312
18313    /**
18314     * Dispatch one step of a nested scroll in progress.
18315     *
18316     * <p>Implementations of views that support nested scrolling should call this to report
18317     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18318     * is not currently in progress or nested scrolling is not
18319     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18320     *
18321     * <p>Compatible View implementations should also call
18322     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18323     * consuming a component of the scroll event themselves.</p>
18324     *
18325     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18326     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18327     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18328     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18329     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18330     *                       in local view coordinates of this view from before this operation
18331     *                       to after it completes. View implementations may use this to adjust
18332     *                       expected input coordinate tracking.
18333     * @return true if the event was dispatched, false if it could not be dispatched.
18334     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18335     */
18336    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18337            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18338        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18339            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18340                int startX = 0;
18341                int startY = 0;
18342                if (offsetInWindow != null) {
18343                    getLocationInWindow(offsetInWindow);
18344                    startX = offsetInWindow[0];
18345                    startY = offsetInWindow[1];
18346                }
18347
18348                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18349                        dxUnconsumed, dyUnconsumed);
18350
18351                if (offsetInWindow != null) {
18352                    getLocationInWindow(offsetInWindow);
18353                    offsetInWindow[0] -= startX;
18354                    offsetInWindow[1] -= startY;
18355                }
18356                return true;
18357            } else if (offsetInWindow != null) {
18358                // No motion, no dispatch. Keep offsetInWindow up to date.
18359                offsetInWindow[0] = 0;
18360                offsetInWindow[1] = 0;
18361            }
18362        }
18363        return false;
18364    }
18365
18366    /**
18367     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18368     *
18369     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18370     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18371     * scrolling operation to consume some or all of the scroll operation before the child view
18372     * consumes it.</p>
18373     *
18374     * @param dx Horizontal scroll distance in pixels
18375     * @param dy Vertical scroll distance in pixels
18376     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18377     *                 and consumed[1] the consumed dy.
18378     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18379     *                       in local view coordinates of this view from before this operation
18380     *                       to after it completes. View implementations may use this to adjust
18381     *                       expected input coordinate tracking.
18382     * @return true if the parent consumed some or all of the scroll delta
18383     * @see #dispatchNestedScroll(int, int, int, int, int[])
18384     */
18385    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18386        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18387            if (dx != 0 || dy != 0) {
18388                int startX = 0;
18389                int startY = 0;
18390                if (offsetInWindow != null) {
18391                    getLocationInWindow(offsetInWindow);
18392                    startX = offsetInWindow[0];
18393                    startY = offsetInWindow[1];
18394                }
18395
18396                if (consumed == null) {
18397                    if (mTempNestedScrollConsumed == null) {
18398                        mTempNestedScrollConsumed = new int[2];
18399                    }
18400                    consumed = mTempNestedScrollConsumed;
18401                }
18402                consumed[0] = 0;
18403                consumed[1] = 0;
18404                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18405
18406                if (offsetInWindow != null) {
18407                    getLocationInWindow(offsetInWindow);
18408                    offsetInWindow[0] -= startX;
18409                    offsetInWindow[1] -= startY;
18410                }
18411                return consumed[0] != 0 || consumed[1] != 0;
18412            } else if (offsetInWindow != null) {
18413                offsetInWindow[0] = 0;
18414                offsetInWindow[1] = 0;
18415            }
18416        }
18417        return false;
18418    }
18419
18420    /**
18421     * Dispatch a fling to a nested scrolling parent.
18422     *
18423     * <p>This method should be used to indicate that a nested scrolling child has detected
18424     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18425     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18426     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18427     * along a scrollable axis.</p>
18428     *
18429     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18430     * its own content, it can use this method to delegate the fling to its nested scrolling
18431     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18432     *
18433     * @param velocityX Horizontal fling velocity in pixels per second
18434     * @param velocityY Vertical fling velocity in pixels per second
18435     * @param consumed true if the child consumed the fling, false otherwise
18436     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18437     */
18438    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18439        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18440            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18441        }
18442        return false;
18443    }
18444
18445    /**
18446     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18447     *
18448     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18449     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18450     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18451     * before the child view consumes it. If this method returns <code>true</code>, a nested
18452     * parent view consumed the fling and this view should not scroll as a result.</p>
18453     *
18454     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18455     * the fling at a time. If a parent view consumed the fling this method will return false.
18456     * Custom view implementations should account for this in two ways:</p>
18457     *
18458     * <ul>
18459     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18460     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18461     *     position regardless.</li>
18462     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18463     *     even to settle back to a valid idle position.</li>
18464     * </ul>
18465     *
18466     * <p>Views should also not offer fling velocities to nested parent views along an axis
18467     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18468     * should not offer a horizontal fling velocity to its parents since scrolling along that
18469     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18470     *
18471     * @param velocityX Horizontal fling velocity in pixels per second
18472     * @param velocityY Vertical fling velocity in pixels per second
18473     * @return true if a nested scrolling parent consumed the fling
18474     */
18475    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18476        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18477            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18478        }
18479        return false;
18480    }
18481
18482    /**
18483     * Gets a scale factor that determines the distance the view should scroll
18484     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18485     * @return The vertical scroll scale factor.
18486     * @hide
18487     */
18488    protected float getVerticalScrollFactor() {
18489        if (mVerticalScrollFactor == 0) {
18490            TypedValue outValue = new TypedValue();
18491            if (!mContext.getTheme().resolveAttribute(
18492                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18493                throw new IllegalStateException(
18494                        "Expected theme to define listPreferredItemHeight.");
18495            }
18496            mVerticalScrollFactor = outValue.getDimension(
18497                    mContext.getResources().getDisplayMetrics());
18498        }
18499        return mVerticalScrollFactor;
18500    }
18501
18502    /**
18503     * Gets a scale factor that determines the distance the view should scroll
18504     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18505     * @return The horizontal scroll scale factor.
18506     * @hide
18507     */
18508    protected float getHorizontalScrollFactor() {
18509        // TODO: Should use something else.
18510        return getVerticalScrollFactor();
18511    }
18512
18513    /**
18514     * Return the value specifying the text direction or policy that was set with
18515     * {@link #setTextDirection(int)}.
18516     *
18517     * @return the defined text direction. It can be one of:
18518     *
18519     * {@link #TEXT_DIRECTION_INHERIT},
18520     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18521     * {@link #TEXT_DIRECTION_ANY_RTL},
18522     * {@link #TEXT_DIRECTION_LTR},
18523     * {@link #TEXT_DIRECTION_RTL},
18524     * {@link #TEXT_DIRECTION_LOCALE}
18525     *
18526     * @attr ref android.R.styleable#View_textDirection
18527     *
18528     * @hide
18529     */
18530    @ViewDebug.ExportedProperty(category = "text", mapping = {
18531            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18532            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18533            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18534            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18535            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18536            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18537    })
18538    public int getRawTextDirection() {
18539        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18540    }
18541
18542    /**
18543     * Set the text direction.
18544     *
18545     * @param textDirection the direction to set. Should be one of:
18546     *
18547     * {@link #TEXT_DIRECTION_INHERIT},
18548     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18549     * {@link #TEXT_DIRECTION_ANY_RTL},
18550     * {@link #TEXT_DIRECTION_LTR},
18551     * {@link #TEXT_DIRECTION_RTL},
18552     * {@link #TEXT_DIRECTION_LOCALE}
18553     *
18554     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18555     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18556     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18557     *
18558     * @attr ref android.R.styleable#View_textDirection
18559     */
18560    public void setTextDirection(int textDirection) {
18561        if (getRawTextDirection() != textDirection) {
18562            // Reset the current text direction and the resolved one
18563            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18564            resetResolvedTextDirection();
18565            // Set the new text direction
18566            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18567            // Do resolution
18568            resolveTextDirection();
18569            // Notify change
18570            onRtlPropertiesChanged(getLayoutDirection());
18571            // Refresh
18572            requestLayout();
18573            invalidate(true);
18574        }
18575    }
18576
18577    /**
18578     * Return the resolved text direction.
18579     *
18580     * @return the resolved text direction. Returns one of:
18581     *
18582     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18583     * {@link #TEXT_DIRECTION_ANY_RTL},
18584     * {@link #TEXT_DIRECTION_LTR},
18585     * {@link #TEXT_DIRECTION_RTL},
18586     * {@link #TEXT_DIRECTION_LOCALE}
18587     *
18588     * @attr ref android.R.styleable#View_textDirection
18589     */
18590    @ViewDebug.ExportedProperty(category = "text", mapping = {
18591            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18592            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18593            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18594            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18595            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18596            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18597    })
18598    public int getTextDirection() {
18599        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18600    }
18601
18602    /**
18603     * Resolve the text direction.
18604     *
18605     * @return true if resolution has been done, false otherwise.
18606     *
18607     * @hide
18608     */
18609    public boolean resolveTextDirection() {
18610        // Reset any previous text direction resolution
18611        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18612
18613        if (hasRtlSupport()) {
18614            // Set resolved text direction flag depending on text direction flag
18615            final int textDirection = getRawTextDirection();
18616            switch(textDirection) {
18617                case TEXT_DIRECTION_INHERIT:
18618                    if (!canResolveTextDirection()) {
18619                        // We cannot do the resolution if there is no parent, so use the default one
18620                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18621                        // Resolution will need to happen again later
18622                        return false;
18623                    }
18624
18625                    // Parent has not yet resolved, so we still return the default
18626                    try {
18627                        if (!mParent.isTextDirectionResolved()) {
18628                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18629                            // Resolution will need to happen again later
18630                            return false;
18631                        }
18632                    } catch (AbstractMethodError e) {
18633                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18634                                " does not fully implement ViewParent", e);
18635                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18636                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18637                        return true;
18638                    }
18639
18640                    // Set current resolved direction to the same value as the parent's one
18641                    int parentResolvedDirection;
18642                    try {
18643                        parentResolvedDirection = mParent.getTextDirection();
18644                    } catch (AbstractMethodError e) {
18645                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18646                                " does not fully implement ViewParent", e);
18647                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18648                    }
18649                    switch (parentResolvedDirection) {
18650                        case TEXT_DIRECTION_FIRST_STRONG:
18651                        case TEXT_DIRECTION_ANY_RTL:
18652                        case TEXT_DIRECTION_LTR:
18653                        case TEXT_DIRECTION_RTL:
18654                        case TEXT_DIRECTION_LOCALE:
18655                            mPrivateFlags2 |=
18656                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18657                            break;
18658                        default:
18659                            // Default resolved direction is "first strong" heuristic
18660                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18661                    }
18662                    break;
18663                case TEXT_DIRECTION_FIRST_STRONG:
18664                case TEXT_DIRECTION_ANY_RTL:
18665                case TEXT_DIRECTION_LTR:
18666                case TEXT_DIRECTION_RTL:
18667                case TEXT_DIRECTION_LOCALE:
18668                    // Resolved direction is the same as text direction
18669                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18670                    break;
18671                default:
18672                    // Default resolved direction is "first strong" heuristic
18673                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18674            }
18675        } else {
18676            // Default resolved direction is "first strong" heuristic
18677            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18678        }
18679
18680        // Set to resolved
18681        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18682        return true;
18683    }
18684
18685    /**
18686     * Check if text direction resolution can be done.
18687     *
18688     * @return true if text direction resolution can be done otherwise return false.
18689     */
18690    public boolean canResolveTextDirection() {
18691        switch (getRawTextDirection()) {
18692            case TEXT_DIRECTION_INHERIT:
18693                if (mParent != null) {
18694                    try {
18695                        return mParent.canResolveTextDirection();
18696                    } catch (AbstractMethodError e) {
18697                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18698                                " does not fully implement ViewParent", e);
18699                    }
18700                }
18701                return false;
18702
18703            default:
18704                return true;
18705        }
18706    }
18707
18708    /**
18709     * Reset resolved text direction. Text direction will be resolved during a call to
18710     * {@link #onMeasure(int, int)}.
18711     *
18712     * @hide
18713     */
18714    public void resetResolvedTextDirection() {
18715        // Reset any previous text direction resolution
18716        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18717        // Set to default value
18718        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18719    }
18720
18721    /**
18722     * @return true if text direction is inherited.
18723     *
18724     * @hide
18725     */
18726    public boolean isTextDirectionInherited() {
18727        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18728    }
18729
18730    /**
18731     * @return true if text direction is resolved.
18732     */
18733    public boolean isTextDirectionResolved() {
18734        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18735    }
18736
18737    /**
18738     * Return the value specifying the text alignment or policy that was set with
18739     * {@link #setTextAlignment(int)}.
18740     *
18741     * @return the defined text alignment. It can be one of:
18742     *
18743     * {@link #TEXT_ALIGNMENT_INHERIT},
18744     * {@link #TEXT_ALIGNMENT_GRAVITY},
18745     * {@link #TEXT_ALIGNMENT_CENTER},
18746     * {@link #TEXT_ALIGNMENT_TEXT_START},
18747     * {@link #TEXT_ALIGNMENT_TEXT_END},
18748     * {@link #TEXT_ALIGNMENT_VIEW_START},
18749     * {@link #TEXT_ALIGNMENT_VIEW_END}
18750     *
18751     * @attr ref android.R.styleable#View_textAlignment
18752     *
18753     * @hide
18754     */
18755    @ViewDebug.ExportedProperty(category = "text", mapping = {
18756            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18757            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18758            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18759            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18760            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18761            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18762            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18763    })
18764    @TextAlignment
18765    public int getRawTextAlignment() {
18766        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18767    }
18768
18769    /**
18770     * Set the text alignment.
18771     *
18772     * @param textAlignment The text alignment to set. Should be one of
18773     *
18774     * {@link #TEXT_ALIGNMENT_INHERIT},
18775     * {@link #TEXT_ALIGNMENT_GRAVITY},
18776     * {@link #TEXT_ALIGNMENT_CENTER},
18777     * {@link #TEXT_ALIGNMENT_TEXT_START},
18778     * {@link #TEXT_ALIGNMENT_TEXT_END},
18779     * {@link #TEXT_ALIGNMENT_VIEW_START},
18780     * {@link #TEXT_ALIGNMENT_VIEW_END}
18781     *
18782     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18783     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18784     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18785     *
18786     * @attr ref android.R.styleable#View_textAlignment
18787     */
18788    public void setTextAlignment(@TextAlignment int textAlignment) {
18789        if (textAlignment != getRawTextAlignment()) {
18790            // Reset the current and resolved text alignment
18791            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18792            resetResolvedTextAlignment();
18793            // Set the new text alignment
18794            mPrivateFlags2 |=
18795                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18796            // Do resolution
18797            resolveTextAlignment();
18798            // Notify change
18799            onRtlPropertiesChanged(getLayoutDirection());
18800            // Refresh
18801            requestLayout();
18802            invalidate(true);
18803        }
18804    }
18805
18806    /**
18807     * Return the resolved text alignment.
18808     *
18809     * @return the resolved text alignment. Returns one of:
18810     *
18811     * {@link #TEXT_ALIGNMENT_GRAVITY},
18812     * {@link #TEXT_ALIGNMENT_CENTER},
18813     * {@link #TEXT_ALIGNMENT_TEXT_START},
18814     * {@link #TEXT_ALIGNMENT_TEXT_END},
18815     * {@link #TEXT_ALIGNMENT_VIEW_START},
18816     * {@link #TEXT_ALIGNMENT_VIEW_END}
18817     *
18818     * @attr ref android.R.styleable#View_textAlignment
18819     */
18820    @ViewDebug.ExportedProperty(category = "text", mapping = {
18821            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18822            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18823            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18824            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18825            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18826            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18827            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18828    })
18829    @TextAlignment
18830    public int getTextAlignment() {
18831        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18832                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18833    }
18834
18835    /**
18836     * Resolve the text alignment.
18837     *
18838     * @return true if resolution has been done, false otherwise.
18839     *
18840     * @hide
18841     */
18842    public boolean resolveTextAlignment() {
18843        // Reset any previous text alignment resolution
18844        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18845
18846        if (hasRtlSupport()) {
18847            // Set resolved text alignment flag depending on text alignment flag
18848            final int textAlignment = getRawTextAlignment();
18849            switch (textAlignment) {
18850                case TEXT_ALIGNMENT_INHERIT:
18851                    // Check if we can resolve the text alignment
18852                    if (!canResolveTextAlignment()) {
18853                        // We cannot do the resolution if there is no parent so use the default
18854                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18855                        // Resolution will need to happen again later
18856                        return false;
18857                    }
18858
18859                    // Parent has not yet resolved, so we still return the default
18860                    try {
18861                        if (!mParent.isTextAlignmentResolved()) {
18862                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18863                            // Resolution will need to happen again later
18864                            return false;
18865                        }
18866                    } catch (AbstractMethodError e) {
18867                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18868                                " does not fully implement ViewParent", e);
18869                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18870                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18871                        return true;
18872                    }
18873
18874                    int parentResolvedTextAlignment;
18875                    try {
18876                        parentResolvedTextAlignment = mParent.getTextAlignment();
18877                    } catch (AbstractMethodError e) {
18878                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18879                                " does not fully implement ViewParent", e);
18880                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18881                    }
18882                    switch (parentResolvedTextAlignment) {
18883                        case TEXT_ALIGNMENT_GRAVITY:
18884                        case TEXT_ALIGNMENT_TEXT_START:
18885                        case TEXT_ALIGNMENT_TEXT_END:
18886                        case TEXT_ALIGNMENT_CENTER:
18887                        case TEXT_ALIGNMENT_VIEW_START:
18888                        case TEXT_ALIGNMENT_VIEW_END:
18889                            // Resolved text alignment is the same as the parent resolved
18890                            // text alignment
18891                            mPrivateFlags2 |=
18892                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18893                            break;
18894                        default:
18895                            // Use default resolved text alignment
18896                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18897                    }
18898                    break;
18899                case TEXT_ALIGNMENT_GRAVITY:
18900                case TEXT_ALIGNMENT_TEXT_START:
18901                case TEXT_ALIGNMENT_TEXT_END:
18902                case TEXT_ALIGNMENT_CENTER:
18903                case TEXT_ALIGNMENT_VIEW_START:
18904                case TEXT_ALIGNMENT_VIEW_END:
18905                    // Resolved text alignment is the same as text alignment
18906                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18907                    break;
18908                default:
18909                    // Use default resolved text alignment
18910                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18911            }
18912        } else {
18913            // Use default resolved text alignment
18914            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18915        }
18916
18917        // Set the resolved
18918        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18919        return true;
18920    }
18921
18922    /**
18923     * Check if text alignment resolution can be done.
18924     *
18925     * @return true if text alignment resolution can be done otherwise return false.
18926     */
18927    public boolean canResolveTextAlignment() {
18928        switch (getRawTextAlignment()) {
18929            case TEXT_DIRECTION_INHERIT:
18930                if (mParent != null) {
18931                    try {
18932                        return mParent.canResolveTextAlignment();
18933                    } catch (AbstractMethodError e) {
18934                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18935                                " does not fully implement ViewParent", e);
18936                    }
18937                }
18938                return false;
18939
18940            default:
18941                return true;
18942        }
18943    }
18944
18945    /**
18946     * Reset resolved text alignment. Text alignment will be resolved during a call to
18947     * {@link #onMeasure(int, int)}.
18948     *
18949     * @hide
18950     */
18951    public void resetResolvedTextAlignment() {
18952        // Reset any previous text alignment resolution
18953        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18954        // Set to default
18955        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18956    }
18957
18958    /**
18959     * @return true if text alignment is inherited.
18960     *
18961     * @hide
18962     */
18963    public boolean isTextAlignmentInherited() {
18964        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18965    }
18966
18967    /**
18968     * @return true if text alignment is resolved.
18969     */
18970    public boolean isTextAlignmentResolved() {
18971        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18972    }
18973
18974    /**
18975     * Generate a value suitable for use in {@link #setId(int)}.
18976     * This value will not collide with ID values generated at build time by aapt for R.id.
18977     *
18978     * @return a generated ID value
18979     */
18980    public static int generateViewId() {
18981        for (;;) {
18982            final int result = sNextGeneratedId.get();
18983            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18984            int newValue = result + 1;
18985            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18986            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18987                return result;
18988            }
18989        }
18990    }
18991
18992    /**
18993     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18994     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18995     *                           a normal View or a ViewGroup with
18996     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18997     * @hide
18998     */
18999    public void captureTransitioningViews(List<View> transitioningViews) {
19000        if (getVisibility() == View.VISIBLE) {
19001            transitioningViews.add(this);
19002        }
19003    }
19004
19005    /**
19006     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19007     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19008     * @hide
19009     */
19010    public void findNamedViews(Map<String, View> namedElements) {
19011        if (getVisibility() == VISIBLE || mGhostView != null) {
19012            String transitionName = getTransitionName();
19013            if (transitionName != null) {
19014                namedElements.put(transitionName, this);
19015            }
19016        }
19017    }
19018
19019    //
19020    // Properties
19021    //
19022    /**
19023     * A Property wrapper around the <code>alpha</code> functionality handled by the
19024     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19025     */
19026    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19027        @Override
19028        public void setValue(View object, float value) {
19029            object.setAlpha(value);
19030        }
19031
19032        @Override
19033        public Float get(View object) {
19034            return object.getAlpha();
19035        }
19036    };
19037
19038    /**
19039     * A Property wrapper around the <code>translationX</code> functionality handled by the
19040     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19041     */
19042    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19043        @Override
19044        public void setValue(View object, float value) {
19045            object.setTranslationX(value);
19046        }
19047
19048                @Override
19049        public Float get(View object) {
19050            return object.getTranslationX();
19051        }
19052    };
19053
19054    /**
19055     * A Property wrapper around the <code>translationY</code> functionality handled by the
19056     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19057     */
19058    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19059        @Override
19060        public void setValue(View object, float value) {
19061            object.setTranslationY(value);
19062        }
19063
19064        @Override
19065        public Float get(View object) {
19066            return object.getTranslationY();
19067        }
19068    };
19069
19070    /**
19071     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19072     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19073     */
19074    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19075        @Override
19076        public void setValue(View object, float value) {
19077            object.setTranslationZ(value);
19078        }
19079
19080        @Override
19081        public Float get(View object) {
19082            return object.getTranslationZ();
19083        }
19084    };
19085
19086    /**
19087     * A Property wrapper around the <code>x</code> functionality handled by the
19088     * {@link View#setX(float)} and {@link View#getX()} methods.
19089     */
19090    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19091        @Override
19092        public void setValue(View object, float value) {
19093            object.setX(value);
19094        }
19095
19096        @Override
19097        public Float get(View object) {
19098            return object.getX();
19099        }
19100    };
19101
19102    /**
19103     * A Property wrapper around the <code>y</code> functionality handled by the
19104     * {@link View#setY(float)} and {@link View#getY()} methods.
19105     */
19106    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19107        @Override
19108        public void setValue(View object, float value) {
19109            object.setY(value);
19110        }
19111
19112        @Override
19113        public Float get(View object) {
19114            return object.getY();
19115        }
19116    };
19117
19118    /**
19119     * A Property wrapper around the <code>z</code> functionality handled by the
19120     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19121     */
19122    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19123        @Override
19124        public void setValue(View object, float value) {
19125            object.setZ(value);
19126        }
19127
19128        @Override
19129        public Float get(View object) {
19130            return object.getZ();
19131        }
19132    };
19133
19134    /**
19135     * A Property wrapper around the <code>rotation</code> functionality handled by the
19136     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19137     */
19138    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19139        @Override
19140        public void setValue(View object, float value) {
19141            object.setRotation(value);
19142        }
19143
19144        @Override
19145        public Float get(View object) {
19146            return object.getRotation();
19147        }
19148    };
19149
19150    /**
19151     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19152     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19153     */
19154    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19155        @Override
19156        public void setValue(View object, float value) {
19157            object.setRotationX(value);
19158        }
19159
19160        @Override
19161        public Float get(View object) {
19162            return object.getRotationX();
19163        }
19164    };
19165
19166    /**
19167     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19168     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19169     */
19170    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19171        @Override
19172        public void setValue(View object, float value) {
19173            object.setRotationY(value);
19174        }
19175
19176        @Override
19177        public Float get(View object) {
19178            return object.getRotationY();
19179        }
19180    };
19181
19182    /**
19183     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19184     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19185     */
19186    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19187        @Override
19188        public void setValue(View object, float value) {
19189            object.setScaleX(value);
19190        }
19191
19192        @Override
19193        public Float get(View object) {
19194            return object.getScaleX();
19195        }
19196    };
19197
19198    /**
19199     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19200     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19201     */
19202    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19203        @Override
19204        public void setValue(View object, float value) {
19205            object.setScaleY(value);
19206        }
19207
19208        @Override
19209        public Float get(View object) {
19210            return object.getScaleY();
19211        }
19212    };
19213
19214    /**
19215     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19216     * Each MeasureSpec represents a requirement for either the width or the height.
19217     * A MeasureSpec is comprised of a size and a mode. There are three possible
19218     * modes:
19219     * <dl>
19220     * <dt>UNSPECIFIED</dt>
19221     * <dd>
19222     * The parent has not imposed any constraint on the child. It can be whatever size
19223     * it wants.
19224     * </dd>
19225     *
19226     * <dt>EXACTLY</dt>
19227     * <dd>
19228     * The parent has determined an exact size for the child. The child is going to be
19229     * given those bounds regardless of how big it wants to be.
19230     * </dd>
19231     *
19232     * <dt>AT_MOST</dt>
19233     * <dd>
19234     * The child can be as large as it wants up to the specified size.
19235     * </dd>
19236     * </dl>
19237     *
19238     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19239     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19240     */
19241    public static class MeasureSpec {
19242        private static final int MODE_SHIFT = 30;
19243        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19244
19245        /**
19246         * Measure specification mode: The parent has not imposed any constraint
19247         * on the child. It can be whatever size it wants.
19248         */
19249        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19250
19251        /**
19252         * Measure specification mode: The parent has determined an exact size
19253         * for the child. The child is going to be given those bounds regardless
19254         * of how big it wants to be.
19255         */
19256        public static final int EXACTLY     = 1 << MODE_SHIFT;
19257
19258        /**
19259         * Measure specification mode: The child can be as large as it wants up
19260         * to the specified size.
19261         */
19262        public static final int AT_MOST     = 2 << MODE_SHIFT;
19263
19264        /**
19265         * Creates a measure specification based on the supplied size and mode.
19266         *
19267         * The mode must always be one of the following:
19268         * <ul>
19269         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19270         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19271         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19272         * </ul>
19273         *
19274         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19275         * implementation was such that the order of arguments did not matter
19276         * and overflow in either value could impact the resulting MeasureSpec.
19277         * {@link android.widget.RelativeLayout} was affected by this bug.
19278         * Apps targeting API levels greater than 17 will get the fixed, more strict
19279         * behavior.</p>
19280         *
19281         * @param size the size of the measure specification
19282         * @param mode the mode of the measure specification
19283         * @return the measure specification based on size and mode
19284         */
19285        public static int makeMeasureSpec(int size, int mode) {
19286            if (sUseBrokenMakeMeasureSpec) {
19287                return size + mode;
19288            } else {
19289                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19290            }
19291        }
19292
19293        /**
19294         * Extracts the mode from the supplied measure specification.
19295         *
19296         * @param measureSpec the measure specification to extract the mode from
19297         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19298         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19299         *         {@link android.view.View.MeasureSpec#EXACTLY}
19300         */
19301        public static int getMode(int measureSpec) {
19302            return (measureSpec & MODE_MASK);
19303        }
19304
19305        /**
19306         * Extracts the size from the supplied measure specification.
19307         *
19308         * @param measureSpec the measure specification to extract the size from
19309         * @return the size in pixels defined in the supplied measure specification
19310         */
19311        public static int getSize(int measureSpec) {
19312            return (measureSpec & ~MODE_MASK);
19313        }
19314
19315        static int adjust(int measureSpec, int delta) {
19316            final int mode = getMode(measureSpec);
19317            if (mode == UNSPECIFIED) {
19318                // No need to adjust size for UNSPECIFIED mode.
19319                return makeMeasureSpec(0, UNSPECIFIED);
19320            }
19321            int size = getSize(measureSpec) + delta;
19322            if (size < 0) {
19323                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19324                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19325                size = 0;
19326            }
19327            return makeMeasureSpec(size, mode);
19328        }
19329
19330        /**
19331         * Returns a String representation of the specified measure
19332         * specification.
19333         *
19334         * @param measureSpec the measure specification to convert to a String
19335         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19336         */
19337        public static String toString(int measureSpec) {
19338            int mode = getMode(measureSpec);
19339            int size = getSize(measureSpec);
19340
19341            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19342
19343            if (mode == UNSPECIFIED)
19344                sb.append("UNSPECIFIED ");
19345            else if (mode == EXACTLY)
19346                sb.append("EXACTLY ");
19347            else if (mode == AT_MOST)
19348                sb.append("AT_MOST ");
19349            else
19350                sb.append(mode).append(" ");
19351
19352            sb.append(size);
19353            return sb.toString();
19354        }
19355    }
19356
19357    private final class CheckForLongPress implements Runnable {
19358        private int mOriginalWindowAttachCount;
19359
19360        @Override
19361        public void run() {
19362            if (isPressed() && (mParent != null)
19363                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19364                if (performLongClick()) {
19365                    mHasPerformedLongPress = true;
19366                }
19367            }
19368        }
19369
19370        public void rememberWindowAttachCount() {
19371            mOriginalWindowAttachCount = mWindowAttachCount;
19372        }
19373    }
19374
19375    private final class CheckForTap implements Runnable {
19376        public float x;
19377        public float y;
19378
19379        @Override
19380        public void run() {
19381            mPrivateFlags &= ~PFLAG_PREPRESSED;
19382            setPressed(true, x, y);
19383            checkForLongClick(ViewConfiguration.getTapTimeout());
19384        }
19385    }
19386
19387    private final class PerformClick implements Runnable {
19388        @Override
19389        public void run() {
19390            performClick();
19391        }
19392    }
19393
19394    /** @hide */
19395    public void hackTurnOffWindowResizeAnim(boolean off) {
19396        mAttachInfo.mTurnOffWindowResizeAnim = off;
19397    }
19398
19399    /**
19400     * This method returns a ViewPropertyAnimator object, which can be used to animate
19401     * specific properties on this View.
19402     *
19403     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19404     */
19405    public ViewPropertyAnimator animate() {
19406        if (mAnimator == null) {
19407            mAnimator = new ViewPropertyAnimator(this);
19408        }
19409        return mAnimator;
19410    }
19411
19412    /**
19413     * Sets the name of the View to be used to identify Views in Transitions.
19414     * Names should be unique in the View hierarchy.
19415     *
19416     * @param transitionName The name of the View to uniquely identify it for Transitions.
19417     */
19418    public final void setTransitionName(String transitionName) {
19419        mTransitionName = transitionName;
19420    }
19421
19422    /**
19423     * Returns the name of the View to be used to identify Views in Transitions.
19424     * Names should be unique in the View hierarchy.
19425     *
19426     * <p>This returns null if the View has not been given a name.</p>
19427     *
19428     * @return The name used of the View to be used to identify Views in Transitions or null
19429     * if no name has been given.
19430     */
19431    @ViewDebug.ExportedProperty
19432    public String getTransitionName() {
19433        return mTransitionName;
19434    }
19435
19436    /**
19437     * Interface definition for a callback to be invoked when a hardware key event is
19438     * dispatched to this view. The callback will be invoked before the key event is
19439     * given to the view. This is only useful for hardware keyboards; a software input
19440     * method has no obligation to trigger this listener.
19441     */
19442    public interface OnKeyListener {
19443        /**
19444         * Called when a hardware key is dispatched to a view. This allows listeners to
19445         * get a chance to respond before the target view.
19446         * <p>Key presses in software keyboards will generally NOT trigger this method,
19447         * although some may elect to do so in some situations. Do not assume a
19448         * software input method has to be key-based; even if it is, it may use key presses
19449         * in a different way than you expect, so there is no way to reliably catch soft
19450         * input key presses.
19451         *
19452         * @param v The view the key has been dispatched to.
19453         * @param keyCode The code for the physical key that was pressed
19454         * @param event The KeyEvent object containing full information about
19455         *        the event.
19456         * @return True if the listener has consumed the event, false otherwise.
19457         */
19458        boolean onKey(View v, int keyCode, KeyEvent event);
19459    }
19460
19461    /**
19462     * Interface definition for a callback to be invoked when a touch event is
19463     * dispatched to this view. The callback will be invoked before the touch
19464     * event is given to the view.
19465     */
19466    public interface OnTouchListener {
19467        /**
19468         * Called when a touch event is dispatched to a view. This allows listeners to
19469         * get a chance to respond before the target view.
19470         *
19471         * @param v The view the touch event has been dispatched to.
19472         * @param event The MotionEvent object containing full information about
19473         *        the event.
19474         * @return True if the listener has consumed the event, false otherwise.
19475         */
19476        boolean onTouch(View v, MotionEvent event);
19477    }
19478
19479    /**
19480     * Interface definition for a callback to be invoked when a hover event is
19481     * dispatched to this view. The callback will be invoked before the hover
19482     * event is given to the view.
19483     */
19484    public interface OnHoverListener {
19485        /**
19486         * Called when a hover event is dispatched to a view. This allows listeners to
19487         * get a chance to respond before the target view.
19488         *
19489         * @param v The view the hover event has been dispatched to.
19490         * @param event The MotionEvent object containing full information about
19491         *        the event.
19492         * @return True if the listener has consumed the event, false otherwise.
19493         */
19494        boolean onHover(View v, MotionEvent event);
19495    }
19496
19497    /**
19498     * Interface definition for a callback to be invoked when a generic motion event is
19499     * dispatched to this view. The callback will be invoked before the generic motion
19500     * event is given to the view.
19501     */
19502    public interface OnGenericMotionListener {
19503        /**
19504         * Called when a generic motion event is dispatched to a view. This allows listeners to
19505         * get a chance to respond before the target view.
19506         *
19507         * @param v The view the generic motion event has been dispatched to.
19508         * @param event The MotionEvent object containing full information about
19509         *        the event.
19510         * @return True if the listener has consumed the event, false otherwise.
19511         */
19512        boolean onGenericMotion(View v, MotionEvent event);
19513    }
19514
19515    /**
19516     * Interface definition for a callback to be invoked when a view has been clicked and held.
19517     */
19518    public interface OnLongClickListener {
19519        /**
19520         * Called when a view has been clicked and held.
19521         *
19522         * @param v The view that was clicked and held.
19523         *
19524         * @return true if the callback consumed the long click, false otherwise.
19525         */
19526        boolean onLongClick(View v);
19527    }
19528
19529    /**
19530     * Interface definition for a callback to be invoked when a drag is being dispatched
19531     * to this view.  The callback will be invoked before the hosting view's own
19532     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19533     * onDrag(event) behavior, it should return 'false' from this callback.
19534     *
19535     * <div class="special reference">
19536     * <h3>Developer Guides</h3>
19537     * <p>For a guide to implementing drag and drop features, read the
19538     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19539     * </div>
19540     */
19541    public interface OnDragListener {
19542        /**
19543         * Called when a drag event is dispatched to a view. This allows listeners
19544         * to get a chance to override base View behavior.
19545         *
19546         * @param v The View that received the drag event.
19547         * @param event The {@link android.view.DragEvent} object for the drag event.
19548         * @return {@code true} if the drag event was handled successfully, or {@code false}
19549         * if the drag event was not handled. Note that {@code false} will trigger the View
19550         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19551         */
19552        boolean onDrag(View v, DragEvent event);
19553    }
19554
19555    /**
19556     * Interface definition for a callback to be invoked when the focus state of
19557     * a view changed.
19558     */
19559    public interface OnFocusChangeListener {
19560        /**
19561         * Called when the focus state of a view has changed.
19562         *
19563         * @param v The view whose state has changed.
19564         * @param hasFocus The new focus state of v.
19565         */
19566        void onFocusChange(View v, boolean hasFocus);
19567    }
19568
19569    /**
19570     * Interface definition for a callback to be invoked when a view is clicked.
19571     */
19572    public interface OnClickListener {
19573        /**
19574         * Called when a view has been clicked.
19575         *
19576         * @param v The view that was clicked.
19577         */
19578        void onClick(View v);
19579    }
19580
19581    /**
19582     * Interface definition for a callback to be invoked when the context menu
19583     * for this view is being built.
19584     */
19585    public interface OnCreateContextMenuListener {
19586        /**
19587         * Called when the context menu for this view is being built. It is not
19588         * safe to hold onto the menu after this method returns.
19589         *
19590         * @param menu The context menu that is being built
19591         * @param v The view for which the context menu is being built
19592         * @param menuInfo Extra information about the item for which the
19593         *            context menu should be shown. This information will vary
19594         *            depending on the class of v.
19595         */
19596        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19597    }
19598
19599    /**
19600     * Interface definition for a callback to be invoked when the status bar changes
19601     * visibility.  This reports <strong>global</strong> changes to the system UI
19602     * state, not what the application is requesting.
19603     *
19604     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19605     */
19606    public interface OnSystemUiVisibilityChangeListener {
19607        /**
19608         * Called when the status bar changes visibility because of a call to
19609         * {@link View#setSystemUiVisibility(int)}.
19610         *
19611         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19612         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19613         * This tells you the <strong>global</strong> state of these UI visibility
19614         * flags, not what your app is currently applying.
19615         */
19616        public void onSystemUiVisibilityChange(int visibility);
19617    }
19618
19619    /**
19620     * Interface definition for a callback to be invoked when this view is attached
19621     * or detached from its window.
19622     */
19623    public interface OnAttachStateChangeListener {
19624        /**
19625         * Called when the view is attached to a window.
19626         * @param v The view that was attached
19627         */
19628        public void onViewAttachedToWindow(View v);
19629        /**
19630         * Called when the view is detached from a window.
19631         * @param v The view that was detached
19632         */
19633        public void onViewDetachedFromWindow(View v);
19634    }
19635
19636    /**
19637     * Listener for applying window insets on a view in a custom way.
19638     *
19639     * <p>Apps may choose to implement this interface if they want to apply custom policy
19640     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19641     * is set, its
19642     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19643     * method will be called instead of the View's own
19644     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19645     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19646     * the View's normal behavior as part of its own.</p>
19647     */
19648    public interface OnApplyWindowInsetsListener {
19649        /**
19650         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19651         * on a View, this listener method will be called instead of the view's own
19652         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19653         *
19654         * @param v The view applying window insets
19655         * @param insets The insets to apply
19656         * @return The insets supplied, minus any insets that were consumed
19657         */
19658        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19659    }
19660
19661    private final class UnsetPressedState implements Runnable {
19662        @Override
19663        public void run() {
19664            setPressed(false);
19665        }
19666    }
19667
19668    /**
19669     * Base class for derived classes that want to save and restore their own
19670     * state in {@link android.view.View#onSaveInstanceState()}.
19671     */
19672    public static class BaseSavedState extends AbsSavedState {
19673        /**
19674         * Constructor used when reading from a parcel. Reads the state of the superclass.
19675         *
19676         * @param source
19677         */
19678        public BaseSavedState(Parcel source) {
19679            super(source);
19680        }
19681
19682        /**
19683         * Constructor called by derived classes when creating their SavedState objects
19684         *
19685         * @param superState The state of the superclass of this view
19686         */
19687        public BaseSavedState(Parcelable superState) {
19688            super(superState);
19689        }
19690
19691        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19692                new Parcelable.Creator<BaseSavedState>() {
19693            public BaseSavedState createFromParcel(Parcel in) {
19694                return new BaseSavedState(in);
19695            }
19696
19697            public BaseSavedState[] newArray(int size) {
19698                return new BaseSavedState[size];
19699            }
19700        };
19701    }
19702
19703    /**
19704     * A set of information given to a view when it is attached to its parent
19705     * window.
19706     */
19707    final static class AttachInfo {
19708        interface Callbacks {
19709            void playSoundEffect(int effectId);
19710            boolean performHapticFeedback(int effectId, boolean always);
19711        }
19712
19713        /**
19714         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19715         * to a Handler. This class contains the target (View) to invalidate and
19716         * the coordinates of the dirty rectangle.
19717         *
19718         * For performance purposes, this class also implements a pool of up to
19719         * POOL_LIMIT objects that get reused. This reduces memory allocations
19720         * whenever possible.
19721         */
19722        static class InvalidateInfo {
19723            private static final int POOL_LIMIT = 10;
19724
19725            private static final SynchronizedPool<InvalidateInfo> sPool =
19726                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19727
19728            View target;
19729
19730            int left;
19731            int top;
19732            int right;
19733            int bottom;
19734
19735            public static InvalidateInfo obtain() {
19736                InvalidateInfo instance = sPool.acquire();
19737                return (instance != null) ? instance : new InvalidateInfo();
19738            }
19739
19740            public void recycle() {
19741                target = null;
19742                sPool.release(this);
19743            }
19744        }
19745
19746        final IWindowSession mSession;
19747
19748        final IWindow mWindow;
19749
19750        final IBinder mWindowToken;
19751
19752        final Display mDisplay;
19753
19754        final Callbacks mRootCallbacks;
19755
19756        IWindowId mIWindowId;
19757        WindowId mWindowId;
19758
19759        /**
19760         * The top view of the hierarchy.
19761         */
19762        View mRootView;
19763
19764        IBinder mPanelParentWindowToken;
19765
19766        boolean mHardwareAccelerated;
19767        boolean mHardwareAccelerationRequested;
19768        HardwareRenderer mHardwareRenderer;
19769
19770        /**
19771         * The state of the display to which the window is attached, as reported
19772         * by {@link Display#getState()}.  Note that the display state constants
19773         * declared by {@link Display} do not exactly line up with the screen state
19774         * constants declared by {@link View} (there are more display states than
19775         * screen states).
19776         */
19777        int mDisplayState = Display.STATE_UNKNOWN;
19778
19779        /**
19780         * Scale factor used by the compatibility mode
19781         */
19782        float mApplicationScale;
19783
19784        /**
19785         * Indicates whether the application is in compatibility mode
19786         */
19787        boolean mScalingRequired;
19788
19789        /**
19790         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19791         */
19792        boolean mTurnOffWindowResizeAnim;
19793
19794        /**
19795         * Left position of this view's window
19796         */
19797        int mWindowLeft;
19798
19799        /**
19800         * Top position of this view's window
19801         */
19802        int mWindowTop;
19803
19804        /**
19805         * Indicates whether views need to use 32-bit drawing caches
19806         */
19807        boolean mUse32BitDrawingCache;
19808
19809        /**
19810         * For windows that are full-screen but using insets to layout inside
19811         * of the screen areas, these are the current insets to appear inside
19812         * the overscan area of the display.
19813         */
19814        final Rect mOverscanInsets = new Rect();
19815
19816        /**
19817         * For windows that are full-screen but using insets to layout inside
19818         * of the screen decorations, these are the current insets for the
19819         * content of the window.
19820         */
19821        final Rect mContentInsets = new Rect();
19822
19823        /**
19824         * For windows that are full-screen but using insets to layout inside
19825         * of the screen decorations, these are the current insets for the
19826         * actual visible parts of the window.
19827         */
19828        final Rect mVisibleInsets = new Rect();
19829
19830        /**
19831         * For windows that are full-screen but using insets to layout inside
19832         * of the screen decorations, these are the current insets for the
19833         * stable system windows.
19834         */
19835        final Rect mStableInsets = new Rect();
19836
19837        /**
19838         * The internal insets given by this window.  This value is
19839         * supplied by the client (through
19840         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19841         * be given to the window manager when changed to be used in laying
19842         * out windows behind it.
19843         */
19844        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19845                = new ViewTreeObserver.InternalInsetsInfo();
19846
19847        /**
19848         * Set to true when mGivenInternalInsets is non-empty.
19849         */
19850        boolean mHasNonEmptyGivenInternalInsets;
19851
19852        /**
19853         * All views in the window's hierarchy that serve as scroll containers,
19854         * used to determine if the window can be resized or must be panned
19855         * to adjust for a soft input area.
19856         */
19857        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19858
19859        final KeyEvent.DispatcherState mKeyDispatchState
19860                = new KeyEvent.DispatcherState();
19861
19862        /**
19863         * Indicates whether the view's window currently has the focus.
19864         */
19865        boolean mHasWindowFocus;
19866
19867        /**
19868         * The current visibility of the window.
19869         */
19870        int mWindowVisibility;
19871
19872        /**
19873         * Indicates the time at which drawing started to occur.
19874         */
19875        long mDrawingTime;
19876
19877        /**
19878         * Indicates whether or not ignoring the DIRTY_MASK flags.
19879         */
19880        boolean mIgnoreDirtyState;
19881
19882        /**
19883         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19884         * to avoid clearing that flag prematurely.
19885         */
19886        boolean mSetIgnoreDirtyState = false;
19887
19888        /**
19889         * Indicates whether the view's window is currently in touch mode.
19890         */
19891        boolean mInTouchMode;
19892
19893        /**
19894         * Indicates whether the view has requested unbuffered input dispatching for the current
19895         * event stream.
19896         */
19897        boolean mUnbufferedDispatchRequested;
19898
19899        /**
19900         * Indicates that ViewAncestor should trigger a global layout change
19901         * the next time it performs a traversal
19902         */
19903        boolean mRecomputeGlobalAttributes;
19904
19905        /**
19906         * Always report new attributes at next traversal.
19907         */
19908        boolean mForceReportNewAttributes;
19909
19910        /**
19911         * Set during a traveral if any views want to keep the screen on.
19912         */
19913        boolean mKeepScreenOn;
19914
19915        /**
19916         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19917         */
19918        int mSystemUiVisibility;
19919
19920        /**
19921         * Hack to force certain system UI visibility flags to be cleared.
19922         */
19923        int mDisabledSystemUiVisibility;
19924
19925        /**
19926         * Last global system UI visibility reported by the window manager.
19927         */
19928        int mGlobalSystemUiVisibility;
19929
19930        /**
19931         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19932         * attached.
19933         */
19934        boolean mHasSystemUiListeners;
19935
19936        /**
19937         * Set if the window has requested to extend into the overscan region
19938         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19939         */
19940        boolean mOverscanRequested;
19941
19942        /**
19943         * Set if the visibility of any views has changed.
19944         */
19945        boolean mViewVisibilityChanged;
19946
19947        /**
19948         * Set to true if a view has been scrolled.
19949         */
19950        boolean mViewScrollChanged;
19951
19952        /**
19953         * Set to true if high contrast mode enabled
19954         */
19955        boolean mHighContrastText;
19956
19957        /**
19958         * Global to the view hierarchy used as a temporary for dealing with
19959         * x/y points in the transparent region computations.
19960         */
19961        final int[] mTransparentLocation = new int[2];
19962
19963        /**
19964         * Global to the view hierarchy used as a temporary for dealing with
19965         * x/y points in the ViewGroup.invalidateChild implementation.
19966         */
19967        final int[] mInvalidateChildLocation = new int[2];
19968
19969        /**
19970         * Global to the view hierarchy used as a temporary for dealng with
19971         * computing absolute on-screen location.
19972         */
19973        final int[] mTmpLocation = new int[2];
19974
19975        /**
19976         * Global to the view hierarchy used as a temporary for dealing with
19977         * x/y location when view is transformed.
19978         */
19979        final float[] mTmpTransformLocation = new float[2];
19980
19981        /**
19982         * The view tree observer used to dispatch global events like
19983         * layout, pre-draw, touch mode change, etc.
19984         */
19985        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19986
19987        /**
19988         * A Canvas used by the view hierarchy to perform bitmap caching.
19989         */
19990        Canvas mCanvas;
19991
19992        /**
19993         * The view root impl.
19994         */
19995        final ViewRootImpl mViewRootImpl;
19996
19997        /**
19998         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19999         * handler can be used to pump events in the UI events queue.
20000         */
20001        final Handler mHandler;
20002
20003        /**
20004         * Temporary for use in computing invalidate rectangles while
20005         * calling up the hierarchy.
20006         */
20007        final Rect mTmpInvalRect = new Rect();
20008
20009        /**
20010         * Temporary for use in computing hit areas with transformed views
20011         */
20012        final RectF mTmpTransformRect = new RectF();
20013
20014        /**
20015         * Temporary for use in transforming invalidation rect
20016         */
20017        final Matrix mTmpMatrix = new Matrix();
20018
20019        /**
20020         * Temporary for use in transforming invalidation rect
20021         */
20022        final Transformation mTmpTransformation = new Transformation();
20023
20024        /**
20025         * Temporary for use in querying outlines from OutlineProviders
20026         */
20027        final Outline mTmpOutline = new Outline();
20028
20029        /**
20030         * Temporary list for use in collecting focusable descendents of a view.
20031         */
20032        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20033
20034        /**
20035         * The id of the window for accessibility purposes.
20036         */
20037        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20038
20039        /**
20040         * Flags related to accessibility processing.
20041         *
20042         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20043         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20044         */
20045        int mAccessibilityFetchFlags;
20046
20047        /**
20048         * The drawable for highlighting accessibility focus.
20049         */
20050        Drawable mAccessibilityFocusDrawable;
20051
20052        /**
20053         * Show where the margins, bounds and layout bounds are for each view.
20054         */
20055        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20056
20057        /**
20058         * Point used to compute visible regions.
20059         */
20060        final Point mPoint = new Point();
20061
20062        /**
20063         * Used to track which View originated a requestLayout() call, used when
20064         * requestLayout() is called during layout.
20065         */
20066        View mViewRequestingLayout;
20067
20068        /**
20069         * Creates a new set of attachment information with the specified
20070         * events handler and thread.
20071         *
20072         * @param handler the events handler the view must use
20073         */
20074        AttachInfo(IWindowSession session, IWindow window, Display display,
20075                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20076            mSession = session;
20077            mWindow = window;
20078            mWindowToken = window.asBinder();
20079            mDisplay = display;
20080            mViewRootImpl = viewRootImpl;
20081            mHandler = handler;
20082            mRootCallbacks = effectPlayer;
20083        }
20084    }
20085
20086    /**
20087     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20088     * is supported. This avoids keeping too many unused fields in most
20089     * instances of View.</p>
20090     */
20091    private static class ScrollabilityCache implements Runnable {
20092
20093        /**
20094         * Scrollbars are not visible
20095         */
20096        public static final int OFF = 0;
20097
20098        /**
20099         * Scrollbars are visible
20100         */
20101        public static final int ON = 1;
20102
20103        /**
20104         * Scrollbars are fading away
20105         */
20106        public static final int FADING = 2;
20107
20108        public boolean fadeScrollBars;
20109
20110        public int fadingEdgeLength;
20111        public int scrollBarDefaultDelayBeforeFade;
20112        public int scrollBarFadeDuration;
20113
20114        public int scrollBarSize;
20115        public ScrollBarDrawable scrollBar;
20116        public float[] interpolatorValues;
20117        public View host;
20118
20119        public final Paint paint;
20120        public final Matrix matrix;
20121        public Shader shader;
20122
20123        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20124
20125        private static final float[] OPAQUE = { 255 };
20126        private static final float[] TRANSPARENT = { 0.0f };
20127
20128        /**
20129         * When fading should start. This time moves into the future every time
20130         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20131         */
20132        public long fadeStartTime;
20133
20134
20135        /**
20136         * The current state of the scrollbars: ON, OFF, or FADING
20137         */
20138        public int state = OFF;
20139
20140        private int mLastColor;
20141
20142        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20143            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20144            scrollBarSize = configuration.getScaledScrollBarSize();
20145            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20146            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20147
20148            paint = new Paint();
20149            matrix = new Matrix();
20150            // use use a height of 1, and then wack the matrix each time we
20151            // actually use it.
20152            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20153            paint.setShader(shader);
20154            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20155
20156            this.host = host;
20157        }
20158
20159        public void setFadeColor(int color) {
20160            if (color != mLastColor) {
20161                mLastColor = color;
20162
20163                if (color != 0) {
20164                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20165                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20166                    paint.setShader(shader);
20167                    // Restore the default transfer mode (src_over)
20168                    paint.setXfermode(null);
20169                } else {
20170                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20171                    paint.setShader(shader);
20172                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20173                }
20174            }
20175        }
20176
20177        public void run() {
20178            long now = AnimationUtils.currentAnimationTimeMillis();
20179            if (now >= fadeStartTime) {
20180
20181                // the animation fades the scrollbars out by changing
20182                // the opacity (alpha) from fully opaque to fully
20183                // transparent
20184                int nextFrame = (int) now;
20185                int framesCount = 0;
20186
20187                Interpolator interpolator = scrollBarInterpolator;
20188
20189                // Start opaque
20190                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20191
20192                // End transparent
20193                nextFrame += scrollBarFadeDuration;
20194                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20195
20196                state = FADING;
20197
20198                // Kick off the fade animation
20199                host.invalidate(true);
20200            }
20201        }
20202    }
20203
20204    /**
20205     * Resuable callback for sending
20206     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20207     */
20208    private class SendViewScrolledAccessibilityEvent implements Runnable {
20209        public volatile boolean mIsPending;
20210
20211        public void run() {
20212            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20213            mIsPending = false;
20214        }
20215    }
20216
20217    /**
20218     * <p>
20219     * This class represents a delegate that can be registered in a {@link View}
20220     * to enhance accessibility support via composition rather via inheritance.
20221     * It is specifically targeted to widget developers that extend basic View
20222     * classes i.e. classes in package android.view, that would like their
20223     * applications to be backwards compatible.
20224     * </p>
20225     * <div class="special reference">
20226     * <h3>Developer Guides</h3>
20227     * <p>For more information about making applications accessible, read the
20228     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20229     * developer guide.</p>
20230     * </div>
20231     * <p>
20232     * A scenario in which a developer would like to use an accessibility delegate
20233     * is overriding a method introduced in a later API version then the minimal API
20234     * version supported by the application. For example, the method
20235     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20236     * in API version 4 when the accessibility APIs were first introduced. If a
20237     * developer would like his application to run on API version 4 devices (assuming
20238     * all other APIs used by the application are version 4 or lower) and take advantage
20239     * of this method, instead of overriding the method which would break the application's
20240     * backwards compatibility, he can override the corresponding method in this
20241     * delegate and register the delegate in the target View if the API version of
20242     * the system is high enough i.e. the API version is same or higher to the API
20243     * version that introduced
20244     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20245     * </p>
20246     * <p>
20247     * Here is an example implementation:
20248     * </p>
20249     * <code><pre><p>
20250     * if (Build.VERSION.SDK_INT >= 14) {
20251     *     // If the API version is equal of higher than the version in
20252     *     // which onInitializeAccessibilityNodeInfo was introduced we
20253     *     // register a delegate with a customized implementation.
20254     *     View view = findViewById(R.id.view_id);
20255     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20256     *         public void onInitializeAccessibilityNodeInfo(View host,
20257     *                 AccessibilityNodeInfo info) {
20258     *             // Let the default implementation populate the info.
20259     *             super.onInitializeAccessibilityNodeInfo(host, info);
20260     *             // Set some other information.
20261     *             info.setEnabled(host.isEnabled());
20262     *         }
20263     *     });
20264     * }
20265     * </code></pre></p>
20266     * <p>
20267     * This delegate contains methods that correspond to the accessibility methods
20268     * in View. If a delegate has been specified the implementation in View hands
20269     * off handling to the corresponding method in this delegate. The default
20270     * implementation the delegate methods behaves exactly as the corresponding
20271     * method in View for the case of no accessibility delegate been set. Hence,
20272     * to customize the behavior of a View method, clients can override only the
20273     * corresponding delegate method without altering the behavior of the rest
20274     * accessibility related methods of the host view.
20275     * </p>
20276     */
20277    public static class AccessibilityDelegate {
20278
20279        /**
20280         * Sends an accessibility event of the given type. If accessibility is not
20281         * enabled this method has no effect.
20282         * <p>
20283         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20284         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20285         * been set.
20286         * </p>
20287         *
20288         * @param host The View hosting the delegate.
20289         * @param eventType The type of the event to send.
20290         *
20291         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20292         */
20293        public void sendAccessibilityEvent(View host, int eventType) {
20294            host.sendAccessibilityEventInternal(eventType);
20295        }
20296
20297        /**
20298         * Performs the specified accessibility action on the view. For
20299         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20300         * <p>
20301         * The default implementation behaves as
20302         * {@link View#performAccessibilityAction(int, Bundle)
20303         *  View#performAccessibilityAction(int, Bundle)} for the case of
20304         *  no accessibility delegate been set.
20305         * </p>
20306         *
20307         * @param action The action to perform.
20308         * @return Whether the action was performed.
20309         *
20310         * @see View#performAccessibilityAction(int, Bundle)
20311         *      View#performAccessibilityAction(int, Bundle)
20312         */
20313        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20314            return host.performAccessibilityActionInternal(action, args);
20315        }
20316
20317        /**
20318         * Sends an accessibility event. This method behaves exactly as
20319         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20320         * empty {@link AccessibilityEvent} and does not perform a check whether
20321         * accessibility is enabled.
20322         * <p>
20323         * The default implementation behaves as
20324         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20325         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20326         * the case of no accessibility delegate been set.
20327         * </p>
20328         *
20329         * @param host The View hosting the delegate.
20330         * @param event The event to send.
20331         *
20332         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20333         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20334         */
20335        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20336            host.sendAccessibilityEventUncheckedInternal(event);
20337        }
20338
20339        /**
20340         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20341         * to its children for adding their text content to the event.
20342         * <p>
20343         * The default implementation behaves as
20344         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20345         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20346         * the case of no accessibility delegate been set.
20347         * </p>
20348         *
20349         * @param host The View hosting the delegate.
20350         * @param event The event.
20351         * @return True if the event population was completed.
20352         *
20353         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20354         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20355         */
20356        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20357            return host.dispatchPopulateAccessibilityEventInternal(event);
20358        }
20359
20360        /**
20361         * Gives a chance to the host View to populate the accessibility event with its
20362         * text content.
20363         * <p>
20364         * The default implementation behaves as
20365         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20366         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20367         * the case of no accessibility delegate been set.
20368         * </p>
20369         *
20370         * @param host The View hosting the delegate.
20371         * @param event The accessibility event which to populate.
20372         *
20373         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20374         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20375         */
20376        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20377            host.onPopulateAccessibilityEventInternal(event);
20378        }
20379
20380        /**
20381         * Initializes an {@link AccessibilityEvent} with information about the
20382         * the host View which is the event source.
20383         * <p>
20384         * The default implementation behaves as
20385         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20386         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20387         * the case of no accessibility delegate been set.
20388         * </p>
20389         *
20390         * @param host The View hosting the delegate.
20391         * @param event The event to initialize.
20392         *
20393         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20394         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20395         */
20396        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20397            host.onInitializeAccessibilityEventInternal(event);
20398        }
20399
20400        /**
20401         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20402         * <p>
20403         * The default implementation behaves as
20404         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20405         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20406         * the case of no accessibility delegate been set.
20407         * </p>
20408         *
20409         * @param host The View hosting the delegate.
20410         * @param info The instance to initialize.
20411         *
20412         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20413         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20414         */
20415        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20416            host.onInitializeAccessibilityNodeInfoInternal(info);
20417        }
20418
20419        /**
20420         * Called when a child of the host View has requested sending an
20421         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20422         * to augment the event.
20423         * <p>
20424         * The default implementation behaves as
20425         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20426         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20427         * the case of no accessibility delegate been set.
20428         * </p>
20429         *
20430         * @param host The View hosting the delegate.
20431         * @param child The child which requests sending the event.
20432         * @param event The event to be sent.
20433         * @return True if the event should be sent
20434         *
20435         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20436         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20437         */
20438        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20439                AccessibilityEvent event) {
20440            return host.onRequestSendAccessibilityEventInternal(child, event);
20441        }
20442
20443        /**
20444         * Gets the provider for managing a virtual view hierarchy rooted at this View
20445         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20446         * that explore the window content.
20447         * <p>
20448         * The default implementation behaves as
20449         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20450         * the case of no accessibility delegate been set.
20451         * </p>
20452         *
20453         * @return The provider.
20454         *
20455         * @see AccessibilityNodeProvider
20456         */
20457        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20458            return null;
20459        }
20460
20461        /**
20462         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20463         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20464         * This method is responsible for obtaining an accessibility node info from a
20465         * pool of reusable instances and calling
20466         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20467         * view to initialize the former.
20468         * <p>
20469         * <strong>Note:</strong> The client is responsible for recycling the obtained
20470         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20471         * creation.
20472         * </p>
20473         * <p>
20474         * The default implementation behaves as
20475         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20476         * the case of no accessibility delegate been set.
20477         * </p>
20478         * @return A populated {@link AccessibilityNodeInfo}.
20479         *
20480         * @see AccessibilityNodeInfo
20481         *
20482         * @hide
20483         */
20484        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20485            return host.createAccessibilityNodeInfoInternal();
20486        }
20487    }
20488
20489    private class MatchIdPredicate implements Predicate<View> {
20490        public int mId;
20491
20492        @Override
20493        public boolean apply(View view) {
20494            return (view.mID == mId);
20495        }
20496    }
20497
20498    private class MatchLabelForPredicate implements Predicate<View> {
20499        private int mLabeledId;
20500
20501        @Override
20502        public boolean apply(View view) {
20503            return (view.mLabelForId == mLabeledId);
20504        }
20505    }
20506
20507    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20508        private int mChangeTypes = 0;
20509        private boolean mPosted;
20510        private boolean mPostedWithDelay;
20511        private long mLastEventTimeMillis;
20512
20513        @Override
20514        public void run() {
20515            mPosted = false;
20516            mPostedWithDelay = false;
20517            mLastEventTimeMillis = SystemClock.uptimeMillis();
20518            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20519                final AccessibilityEvent event = AccessibilityEvent.obtain();
20520                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20521                event.setContentChangeTypes(mChangeTypes);
20522                sendAccessibilityEventUnchecked(event);
20523            }
20524            mChangeTypes = 0;
20525        }
20526
20527        public void runOrPost(int changeType) {
20528            mChangeTypes |= changeType;
20529
20530            // If this is a live region or the child of a live region, collect
20531            // all events from this frame and send them on the next frame.
20532            if (inLiveRegion()) {
20533                // If we're already posted with a delay, remove that.
20534                if (mPostedWithDelay) {
20535                    removeCallbacks(this);
20536                    mPostedWithDelay = false;
20537                }
20538                // Only post if we're not already posted.
20539                if (!mPosted) {
20540                    post(this);
20541                    mPosted = true;
20542                }
20543                return;
20544            }
20545
20546            if (mPosted) {
20547                return;
20548            }
20549            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20550            final long minEventIntevalMillis =
20551                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20552            if (timeSinceLastMillis >= minEventIntevalMillis) {
20553                removeCallbacks(this);
20554                run();
20555            } else {
20556                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20557                mPosted = true;
20558                mPostedWithDelay = true;
20559            }
20560        }
20561    }
20562
20563    private boolean inLiveRegion() {
20564        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20565            return true;
20566        }
20567
20568        ViewParent parent = getParent();
20569        while (parent instanceof View) {
20570            if (((View) parent).getAccessibilityLiveRegion()
20571                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20572                return true;
20573            }
20574            parent = parent.getParent();
20575        }
20576
20577        return false;
20578    }
20579
20580    /**
20581     * Dump all private flags in readable format, useful for documentation and
20582     * sanity checking.
20583     */
20584    private static void dumpFlags() {
20585        final HashMap<String, String> found = Maps.newHashMap();
20586        try {
20587            for (Field field : View.class.getDeclaredFields()) {
20588                final int modifiers = field.getModifiers();
20589                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20590                    if (field.getType().equals(int.class)) {
20591                        final int value = field.getInt(null);
20592                        dumpFlag(found, field.getName(), value);
20593                    } else if (field.getType().equals(int[].class)) {
20594                        final int[] values = (int[]) field.get(null);
20595                        for (int i = 0; i < values.length; i++) {
20596                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20597                        }
20598                    }
20599                }
20600            }
20601        } catch (IllegalAccessException e) {
20602            throw new RuntimeException(e);
20603        }
20604
20605        final ArrayList<String> keys = Lists.newArrayList();
20606        keys.addAll(found.keySet());
20607        Collections.sort(keys);
20608        for (String key : keys) {
20609            Log.d(VIEW_LOG_TAG, found.get(key));
20610        }
20611    }
20612
20613    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20614        // Sort flags by prefix, then by bits, always keeping unique keys
20615        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20616        final int prefix = name.indexOf('_');
20617        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20618        final String output = bits + " " + name;
20619        found.put(key, output);
20620    }
20621}
20622