View.java revision 0615026ba15d7d7a68d0a191d449da47a1ceabea
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 mBackgroundTint = 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                    mBackgroundTint = 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        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4653
4654        ListenerInfo li = mListenerInfo;
4655        if (li != null && li.mOnClickListener != null) {
4656            playSoundEffect(SoundEffectConstants.CLICK);
4657            li.mOnClickListener.onClick(this);
4658            return true;
4659        }
4660
4661        return false;
4662    }
4663
4664    /**
4665     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4666     * this only calls the listener, and does not do any associated clicking
4667     * actions like reporting an accessibility event.
4668     *
4669     * @return True there was an assigned OnClickListener that was called, false
4670     *         otherwise is returned.
4671     */
4672    public boolean callOnClick() {
4673        ListenerInfo li = mListenerInfo;
4674        if (li != null && li.mOnClickListener != null) {
4675            li.mOnClickListener.onClick(this);
4676            return true;
4677        }
4678        return false;
4679    }
4680
4681    /**
4682     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4683     * OnLongClickListener did not consume the event.
4684     *
4685     * @return True if one of the above receivers consumed the event, false otherwise.
4686     */
4687    public boolean performLongClick() {
4688        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4689
4690        boolean handled = false;
4691        ListenerInfo li = mListenerInfo;
4692        if (li != null && li.mOnLongClickListener != null) {
4693            handled = li.mOnLongClickListener.onLongClick(View.this);
4694        }
4695        if (!handled) {
4696            handled = showContextMenu();
4697        }
4698        if (handled) {
4699            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4700        }
4701        return handled;
4702    }
4703
4704    /**
4705     * Performs button-related actions during a touch down event.
4706     *
4707     * @param event The event.
4708     * @return True if the down was consumed.
4709     *
4710     * @hide
4711     */
4712    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4713        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4714            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4715                return true;
4716            }
4717        }
4718        return false;
4719    }
4720
4721    /**
4722     * Bring up the context menu for this view.
4723     *
4724     * @return Whether a context menu was displayed.
4725     */
4726    public boolean showContextMenu() {
4727        return getParent().showContextMenuForChild(this);
4728    }
4729
4730    /**
4731     * Bring up the context menu for this view, referring to the item under the specified point.
4732     *
4733     * @param x The referenced x coordinate.
4734     * @param y The referenced y coordinate.
4735     * @param metaState The keyboard modifiers that were pressed.
4736     * @return Whether a context menu was displayed.
4737     *
4738     * @hide
4739     */
4740    public boolean showContextMenu(float x, float y, int metaState) {
4741        return showContextMenu();
4742    }
4743
4744    /**
4745     * Start an action mode.
4746     *
4747     * @param callback Callback that will control the lifecycle of the action mode
4748     * @return The new action mode if it is started, null otherwise
4749     *
4750     * @see ActionMode
4751     */
4752    public ActionMode startActionMode(ActionMode.Callback callback) {
4753        ViewParent parent = getParent();
4754        if (parent == null) return null;
4755        return parent.startActionModeForChild(this, callback);
4756    }
4757
4758    /**
4759     * Register a callback to be invoked when a hardware key is pressed in this view.
4760     * Key presses in software input methods will generally not trigger the methods of
4761     * this listener.
4762     * @param l the key listener to attach to this view
4763     */
4764    public void setOnKeyListener(OnKeyListener l) {
4765        getListenerInfo().mOnKeyListener = l;
4766    }
4767
4768    /**
4769     * Register a callback to be invoked when a touch event is sent to this view.
4770     * @param l the touch listener to attach to this view
4771     */
4772    public void setOnTouchListener(OnTouchListener l) {
4773        getListenerInfo().mOnTouchListener = l;
4774    }
4775
4776    /**
4777     * Register a callback to be invoked when a generic motion event is sent to this view.
4778     * @param l the generic motion listener to attach to this view
4779     */
4780    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4781        getListenerInfo().mOnGenericMotionListener = l;
4782    }
4783
4784    /**
4785     * Register a callback to be invoked when a hover event is sent to this view.
4786     * @param l the hover listener to attach to this view
4787     */
4788    public void setOnHoverListener(OnHoverListener l) {
4789        getListenerInfo().mOnHoverListener = l;
4790    }
4791
4792    /**
4793     * Register a drag event listener callback object for this View. The parameter is
4794     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4795     * View, the system calls the
4796     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4797     * @param l An implementation of {@link android.view.View.OnDragListener}.
4798     */
4799    public void setOnDragListener(OnDragListener l) {
4800        getListenerInfo().mOnDragListener = l;
4801    }
4802
4803    /**
4804     * Give this view focus. This will cause
4805     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4806     *
4807     * Note: this does not check whether this {@link View} should get focus, it just
4808     * gives it focus no matter what.  It should only be called internally by framework
4809     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4810     *
4811     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4812     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4813     *        focus moved when requestFocus() is called. It may not always
4814     *        apply, in which case use the default View.FOCUS_DOWN.
4815     * @param previouslyFocusedRect The rectangle of the view that had focus
4816     *        prior in this View's coordinate system.
4817     */
4818    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4819        if (DBG) {
4820            System.out.println(this + " requestFocus()");
4821        }
4822
4823        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4824            mPrivateFlags |= PFLAG_FOCUSED;
4825
4826            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4827
4828            if (mParent != null) {
4829                mParent.requestChildFocus(this, this);
4830            }
4831
4832            if (mAttachInfo != null) {
4833                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4834            }
4835
4836            onFocusChanged(true, direction, previouslyFocusedRect);
4837            manageFocusHotspot(true, oldFocus);
4838            refreshDrawableState();
4839        }
4840    }
4841
4842    /**
4843     * Forwards focus information to the background drawable, if necessary. When
4844     * the view is gaining focus, <code>v</code> is the previous focus holder.
4845     * When the view is losing focus, <code>v</code> is the next focus holder.
4846     *
4847     * @param focused whether this view is focused
4848     * @param v previous or the next focus holder, or null if none
4849     */
4850    private void manageFocusHotspot(boolean focused, View v) {
4851        final Rect r = new Rect();
4852        if (v != null && mAttachInfo != null) {
4853            v.getHotspotBounds(r);
4854            final int[] location = mAttachInfo.mTmpLocation;
4855            getLocationOnScreen(location);
4856            r.offset(-location[0], -location[1]);
4857        } else {
4858            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4859        }
4860
4861        final float x = r.exactCenterX();
4862        final float y = r.exactCenterY();
4863        drawableHotspotChanged(x, y);
4864    }
4865
4866    /**
4867     * Populates <code>outRect</code> with the hotspot bounds. By default,
4868     * the hotspot bounds are identical to the screen bounds.
4869     *
4870     * @param outRect rect to populate with hotspot bounds
4871     * @hide Only for internal use by views and widgets.
4872     */
4873    public void getHotspotBounds(Rect outRect) {
4874        final Drawable background = getBackground();
4875        if (background != null) {
4876            background.getHotspotBounds(outRect);
4877        } else {
4878            getBoundsOnScreen(outRect);
4879        }
4880    }
4881
4882    /**
4883     * Request that a rectangle of this view be visible on the screen,
4884     * scrolling if necessary just enough.
4885     *
4886     * <p>A View should call this if it maintains some notion of which part
4887     * of its content is interesting.  For example, a text editing view
4888     * should call this when its cursor moves.
4889     *
4890     * @param rectangle The rectangle.
4891     * @return Whether any parent scrolled.
4892     */
4893    public boolean requestRectangleOnScreen(Rect rectangle) {
4894        return requestRectangleOnScreen(rectangle, false);
4895    }
4896
4897    /**
4898     * Request that a rectangle of this view be visible on the screen,
4899     * scrolling if necessary just enough.
4900     *
4901     * <p>A View should call this if it maintains some notion of which part
4902     * of its content is interesting.  For example, a text editing view
4903     * should call this when its cursor moves.
4904     *
4905     * <p>When <code>immediate</code> is set to true, scrolling will not be
4906     * animated.
4907     *
4908     * @param rectangle The rectangle.
4909     * @param immediate True to forbid animated scrolling, false otherwise
4910     * @return Whether any parent scrolled.
4911     */
4912    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4913        if (mParent == null) {
4914            return false;
4915        }
4916
4917        View child = this;
4918
4919        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4920        position.set(rectangle);
4921
4922        ViewParent parent = mParent;
4923        boolean scrolled = false;
4924        while (parent != null) {
4925            rectangle.set((int) position.left, (int) position.top,
4926                    (int) position.right, (int) position.bottom);
4927
4928            scrolled |= parent.requestChildRectangleOnScreen(child,
4929                    rectangle, immediate);
4930
4931            if (!child.hasIdentityMatrix()) {
4932                child.getMatrix().mapRect(position);
4933            }
4934
4935            position.offset(child.mLeft, child.mTop);
4936
4937            if (!(parent instanceof View)) {
4938                break;
4939            }
4940
4941            View parentView = (View) parent;
4942
4943            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4944
4945            child = parentView;
4946            parent = child.getParent();
4947        }
4948
4949        return scrolled;
4950    }
4951
4952    /**
4953     * Called when this view wants to give up focus. If focus is cleared
4954     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4955     * <p>
4956     * <strong>Note:</strong> When a View clears focus the framework is trying
4957     * to give focus to the first focusable View from the top. Hence, if this
4958     * View is the first from the top that can take focus, then all callbacks
4959     * related to clearing focus will be invoked after wich the framework will
4960     * give focus to this view.
4961     * </p>
4962     */
4963    public void clearFocus() {
4964        if (DBG) {
4965            System.out.println(this + " clearFocus()");
4966        }
4967
4968        clearFocusInternal(null, true, true);
4969    }
4970
4971    /**
4972     * Clears focus from the view, optionally propagating the change up through
4973     * the parent hierarchy and requesting that the root view place new focus.
4974     *
4975     * @param propagate whether to propagate the change up through the parent
4976     *            hierarchy
4977     * @param refocus when propagate is true, specifies whether to request the
4978     *            root view place new focus
4979     */
4980    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4981        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4982            mPrivateFlags &= ~PFLAG_FOCUSED;
4983
4984            if (propagate && mParent != null) {
4985                mParent.clearChildFocus(this);
4986            }
4987
4988            onFocusChanged(false, 0, null);
4989
4990            manageFocusHotspot(false, focused);
4991            refreshDrawableState();
4992
4993            if (propagate && (!refocus || !rootViewRequestFocus())) {
4994                notifyGlobalFocusCleared(this);
4995            }
4996        }
4997    }
4998
4999    void notifyGlobalFocusCleared(View oldFocus) {
5000        if (oldFocus != null && mAttachInfo != null) {
5001            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5002        }
5003    }
5004
5005    boolean rootViewRequestFocus() {
5006        final View root = getRootView();
5007        return root != null && root.requestFocus();
5008    }
5009
5010    /**
5011     * Called internally by the view system when a new view is getting focus.
5012     * This is what clears the old focus.
5013     * <p>
5014     * <b>NOTE:</b> The parent view's focused child must be updated manually
5015     * after calling this method. Otherwise, the view hierarchy may be left in
5016     * an inconstent state.
5017     */
5018    void unFocus(View focused) {
5019        if (DBG) {
5020            System.out.println(this + " unFocus()");
5021        }
5022
5023        clearFocusInternal(focused, false, false);
5024    }
5025
5026    /**
5027     * Returns true if this view has focus iteself, or is the ancestor of the
5028     * view that has focus.
5029     *
5030     * @return True if this view has or contains focus, false otherwise.
5031     */
5032    @ViewDebug.ExportedProperty(category = "focus")
5033    public boolean hasFocus() {
5034        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5035    }
5036
5037    /**
5038     * Returns true if this view is focusable or if it contains a reachable View
5039     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5040     * is a View whose parents do not block descendants focus.
5041     *
5042     * Only {@link #VISIBLE} views are considered focusable.
5043     *
5044     * @return True if the view is focusable or if the view contains a focusable
5045     *         View, false otherwise.
5046     *
5047     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5048     * @see ViewGroup#getTouchscreenBlocksFocus()
5049     */
5050    public boolean hasFocusable() {
5051        if (!isFocusableInTouchMode()) {
5052            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5053                final ViewGroup g = (ViewGroup) p;
5054                if (g.shouldBlockFocusForTouchscreen()) {
5055                    return false;
5056                }
5057            }
5058        }
5059        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5060    }
5061
5062    /**
5063     * Called by the view system when the focus state of this view changes.
5064     * When the focus change event is caused by directional navigation, direction
5065     * and previouslyFocusedRect provide insight into where the focus is coming from.
5066     * When overriding, be sure to call up through to the super class so that
5067     * the standard focus handling will occur.
5068     *
5069     * @param gainFocus True if the View has focus; false otherwise.
5070     * @param direction The direction focus has moved when requestFocus()
5071     *                  is called to give this view focus. Values are
5072     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5073     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5074     *                  It may not always apply, in which case use the default.
5075     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5076     *        system, of the previously focused view.  If applicable, this will be
5077     *        passed in as finer grained information about where the focus is coming
5078     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5079     */
5080    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5081            @Nullable Rect previouslyFocusedRect) {
5082        if (gainFocus) {
5083            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5084        } else {
5085            notifyViewAccessibilityStateChangedIfNeeded(
5086                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5087        }
5088
5089        InputMethodManager imm = InputMethodManager.peekInstance();
5090        if (!gainFocus) {
5091            if (isPressed()) {
5092                setPressed(false);
5093            }
5094            if (imm != null && mAttachInfo != null
5095                    && mAttachInfo.mHasWindowFocus) {
5096                imm.focusOut(this);
5097            }
5098            onFocusLost();
5099        } else if (imm != null && mAttachInfo != null
5100                && mAttachInfo.mHasWindowFocus) {
5101            imm.focusIn(this);
5102        }
5103
5104        invalidate(true);
5105        ListenerInfo li = mListenerInfo;
5106        if (li != null && li.mOnFocusChangeListener != null) {
5107            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5108        }
5109
5110        if (mAttachInfo != null) {
5111            mAttachInfo.mKeyDispatchState.reset(this);
5112        }
5113    }
5114
5115    /**
5116     * Sends an accessibility event of the given type. If accessibility is
5117     * not enabled this method has no effect. The default implementation calls
5118     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5119     * to populate information about the event source (this View), then calls
5120     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5121     * populate the text content of the event source including its descendants,
5122     * and last calls
5123     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5124     * on its parent to resuest sending of the event to interested parties.
5125     * <p>
5126     * If an {@link AccessibilityDelegate} has been specified via calling
5127     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5128     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5129     * responsible for handling this call.
5130     * </p>
5131     *
5132     * @param eventType The type of the event to send, as defined by several types from
5133     * {@link android.view.accessibility.AccessibilityEvent}, such as
5134     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5135     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5136     *
5137     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5138     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5139     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5140     * @see AccessibilityDelegate
5141     */
5142    public void sendAccessibilityEvent(int eventType) {
5143        if (mAccessibilityDelegate != null) {
5144            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5145        } else {
5146            sendAccessibilityEventInternal(eventType);
5147        }
5148    }
5149
5150    /**
5151     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5152     * {@link AccessibilityEvent} to make an announcement which is related to some
5153     * sort of a context change for which none of the events representing UI transitions
5154     * is a good fit. For example, announcing a new page in a book. If accessibility
5155     * is not enabled this method does nothing.
5156     *
5157     * @param text The announcement text.
5158     */
5159    public void announceForAccessibility(CharSequence text) {
5160        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5161            AccessibilityEvent event = AccessibilityEvent.obtain(
5162                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5163            onInitializeAccessibilityEvent(event);
5164            event.getText().add(text);
5165            event.setContentDescription(null);
5166            mParent.requestSendAccessibilityEvent(this, event);
5167        }
5168    }
5169
5170    /**
5171     * @see #sendAccessibilityEvent(int)
5172     *
5173     * Note: Called from the default {@link AccessibilityDelegate}.
5174     */
5175    void sendAccessibilityEventInternal(int eventType) {
5176        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5177            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5178        }
5179    }
5180
5181    /**
5182     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5183     * takes as an argument an empty {@link AccessibilityEvent} and does not
5184     * perform a check whether accessibility is enabled.
5185     * <p>
5186     * If an {@link AccessibilityDelegate} has been specified via calling
5187     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5188     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5189     * is responsible for handling this call.
5190     * </p>
5191     *
5192     * @param event The event to send.
5193     *
5194     * @see #sendAccessibilityEvent(int)
5195     */
5196    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5197        if (mAccessibilityDelegate != null) {
5198            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5199        } else {
5200            sendAccessibilityEventUncheckedInternal(event);
5201        }
5202    }
5203
5204    /**
5205     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5206     *
5207     * Note: Called from the default {@link AccessibilityDelegate}.
5208     */
5209    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5210        if (!isShown()) {
5211            return;
5212        }
5213        onInitializeAccessibilityEvent(event);
5214        // Only a subset of accessibility events populates text content.
5215        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5216            dispatchPopulateAccessibilityEvent(event);
5217        }
5218        // In the beginning we called #isShown(), so we know that getParent() is not null.
5219        getParent().requestSendAccessibilityEvent(this, event);
5220    }
5221
5222    /**
5223     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5224     * to its children for adding their text content to the event. Note that the
5225     * event text is populated in a separate dispatch path since we add to the
5226     * event not only the text of the source but also the text of all its descendants.
5227     * A typical implementation will call
5228     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5229     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5230     * on each child. Override this method if custom population of the event text
5231     * content is required.
5232     * <p>
5233     * If an {@link AccessibilityDelegate} has been specified via calling
5234     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5235     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5236     * is responsible for handling this call.
5237     * </p>
5238     * <p>
5239     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5240     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5241     * </p>
5242     *
5243     * @param event The event.
5244     *
5245     * @return True if the event population was completed.
5246     */
5247    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5248        if (mAccessibilityDelegate != null) {
5249            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5250        } else {
5251            return dispatchPopulateAccessibilityEventInternal(event);
5252        }
5253    }
5254
5255    /**
5256     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5257     *
5258     * Note: Called from the default {@link AccessibilityDelegate}.
5259     */
5260    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5261        onPopulateAccessibilityEvent(event);
5262        return false;
5263    }
5264
5265    /**
5266     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5267     * giving a chance to this View to populate the accessibility event with its
5268     * text content. While this method is free to modify event
5269     * attributes other than text content, doing so should normally be performed in
5270     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5271     * <p>
5272     * Example: Adding formatted date string to an accessibility event in addition
5273     *          to the text added by the super implementation:
5274     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5275     *     super.onPopulateAccessibilityEvent(event);
5276     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5277     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5278     *         mCurrentDate.getTimeInMillis(), flags);
5279     *     event.getText().add(selectedDateUtterance);
5280     * }</pre>
5281     * <p>
5282     * If an {@link AccessibilityDelegate} has been specified via calling
5283     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5284     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5285     * is responsible for handling this call.
5286     * </p>
5287     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5288     * information to the event, in case the default implementation has basic information to add.
5289     * </p>
5290     *
5291     * @param event The accessibility event which to populate.
5292     *
5293     * @see #sendAccessibilityEvent(int)
5294     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5295     */
5296    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5297        if (mAccessibilityDelegate != null) {
5298            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5299        } else {
5300            onPopulateAccessibilityEventInternal(event);
5301        }
5302    }
5303
5304    /**
5305     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5306     *
5307     * Note: Called from the default {@link AccessibilityDelegate}.
5308     */
5309    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5310    }
5311
5312    /**
5313     * Initializes an {@link AccessibilityEvent} with information about
5314     * this View which is the event source. In other words, the source of
5315     * an accessibility event is the view whose state change triggered firing
5316     * the event.
5317     * <p>
5318     * Example: Setting the password property of an event in addition
5319     *          to properties set by the super implementation:
5320     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5321     *     super.onInitializeAccessibilityEvent(event);
5322     *     event.setPassword(true);
5323     * }</pre>
5324     * <p>
5325     * If an {@link AccessibilityDelegate} has been specified via calling
5326     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5327     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5328     * is responsible for handling this call.
5329     * </p>
5330     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5331     * information to the event, in case the default implementation has basic information to add.
5332     * </p>
5333     * @param event The event to initialize.
5334     *
5335     * @see #sendAccessibilityEvent(int)
5336     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5337     */
5338    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5339        if (mAccessibilityDelegate != null) {
5340            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5341        } else {
5342            onInitializeAccessibilityEventInternal(event);
5343        }
5344    }
5345
5346    /**
5347     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5348     *
5349     * Note: Called from the default {@link AccessibilityDelegate}.
5350     */
5351    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5352        event.setSource(this);
5353        event.setClassName(View.class.getName());
5354        event.setPackageName(getContext().getPackageName());
5355        event.setEnabled(isEnabled());
5356        event.setContentDescription(mContentDescription);
5357
5358        switch (event.getEventType()) {
5359            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5360                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5361                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5362                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5363                event.setItemCount(focusablesTempList.size());
5364                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5365                if (mAttachInfo != null) {
5366                    focusablesTempList.clear();
5367                }
5368            } break;
5369            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5370                CharSequence text = getIterableTextForAccessibility();
5371                if (text != null && text.length() > 0) {
5372                    event.setFromIndex(getAccessibilitySelectionStart());
5373                    event.setToIndex(getAccessibilitySelectionEnd());
5374                    event.setItemCount(text.length());
5375                }
5376            } break;
5377        }
5378    }
5379
5380    /**
5381     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5382     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5383     * This method is responsible for obtaining an accessibility node info from a
5384     * pool of reusable instances and calling
5385     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5386     * initialize the former.
5387     * <p>
5388     * Note: The client is responsible for recycling the obtained instance by calling
5389     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5390     * </p>
5391     *
5392     * @return A populated {@link AccessibilityNodeInfo}.
5393     *
5394     * @see AccessibilityNodeInfo
5395     */
5396    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5397        if (mAccessibilityDelegate != null) {
5398            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5399        } else {
5400            return createAccessibilityNodeInfoInternal();
5401        }
5402    }
5403
5404    /**
5405     * @see #createAccessibilityNodeInfo()
5406     */
5407    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5408        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5409        if (provider != null) {
5410            return provider.createAccessibilityNodeInfo(View.NO_ID);
5411        } else {
5412            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5413            onInitializeAccessibilityNodeInfo(info);
5414            return info;
5415        }
5416    }
5417
5418    /**
5419     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5420     * The base implementation sets:
5421     * <ul>
5422     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5423     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5424     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5425     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5426     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5427     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5428     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5429     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5430     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5431     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5432     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5433     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5434     * </ul>
5435     * <p>
5436     * Subclasses should override this method, call the super implementation,
5437     * and set additional attributes.
5438     * </p>
5439     * <p>
5440     * If an {@link AccessibilityDelegate} has been specified via calling
5441     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5442     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5443     * is responsible for handling this call.
5444     * </p>
5445     *
5446     * @param info The instance to initialize.
5447     */
5448    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5449        if (mAccessibilityDelegate != null) {
5450            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5451        } else {
5452            onInitializeAccessibilityNodeInfoInternal(info);
5453        }
5454    }
5455
5456    /**
5457     * Gets the location of this view in screen coordintates.
5458     *
5459     * @param outRect The output location
5460     * @hide
5461     */
5462    public void getBoundsOnScreen(Rect outRect) {
5463        if (mAttachInfo == null) {
5464            return;
5465        }
5466
5467        RectF position = mAttachInfo.mTmpTransformRect;
5468        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5469
5470        if (!hasIdentityMatrix()) {
5471            getMatrix().mapRect(position);
5472        }
5473
5474        position.offset(mLeft, mTop);
5475
5476        ViewParent parent = mParent;
5477        while (parent instanceof View) {
5478            View parentView = (View) parent;
5479
5480            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5481
5482            if (!parentView.hasIdentityMatrix()) {
5483                parentView.getMatrix().mapRect(position);
5484            }
5485
5486            position.offset(parentView.mLeft, parentView.mTop);
5487
5488            parent = parentView.mParent;
5489        }
5490
5491        if (parent instanceof ViewRootImpl) {
5492            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5493            position.offset(0, -viewRootImpl.mCurScrollY);
5494        }
5495
5496        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5497
5498        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5499                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5500    }
5501
5502    /**
5503     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5504     *
5505     * Note: Called from the default {@link AccessibilityDelegate}.
5506     */
5507    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5508        Rect bounds = mAttachInfo.mTmpInvalRect;
5509
5510        getDrawingRect(bounds);
5511        info.setBoundsInParent(bounds);
5512
5513        getBoundsOnScreen(bounds);
5514        info.setBoundsInScreen(bounds);
5515
5516        ViewParent parent = getParentForAccessibility();
5517        if (parent instanceof View) {
5518            info.setParent((View) parent);
5519        }
5520
5521        if (mID != View.NO_ID) {
5522            View rootView = getRootView();
5523            if (rootView == null) {
5524                rootView = this;
5525            }
5526            View label = rootView.findLabelForView(this, mID);
5527            if (label != null) {
5528                info.setLabeledBy(label);
5529            }
5530
5531            if ((mAttachInfo.mAccessibilityFetchFlags
5532                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5533                    && Resources.resourceHasPackage(mID)) {
5534                try {
5535                    String viewId = getResources().getResourceName(mID);
5536                    info.setViewIdResourceName(viewId);
5537                } catch (Resources.NotFoundException nfe) {
5538                    /* ignore */
5539                }
5540            }
5541        }
5542
5543        if (mLabelForId != View.NO_ID) {
5544            View rootView = getRootView();
5545            if (rootView == null) {
5546                rootView = this;
5547            }
5548            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5549            if (labeled != null) {
5550                info.setLabelFor(labeled);
5551            }
5552        }
5553
5554        info.setVisibleToUser(isVisibleToUser());
5555
5556        info.setPackageName(mContext.getPackageName());
5557        info.setClassName(View.class.getName());
5558        info.setContentDescription(getContentDescription());
5559
5560        info.setEnabled(isEnabled());
5561        info.setClickable(isClickable());
5562        info.setFocusable(isFocusable());
5563        info.setFocused(isFocused());
5564        info.setAccessibilityFocused(isAccessibilityFocused());
5565        info.setSelected(isSelected());
5566        info.setLongClickable(isLongClickable());
5567        info.setLiveRegion(getAccessibilityLiveRegion());
5568
5569        // TODO: These make sense only if we are in an AdapterView but all
5570        // views can be selected. Maybe from accessibility perspective
5571        // we should report as selectable view in an AdapterView.
5572        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5573        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5574
5575        if (isFocusable()) {
5576            if (isFocused()) {
5577                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5578            } else {
5579                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5580            }
5581        }
5582
5583        if (!isAccessibilityFocused()) {
5584            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5585        } else {
5586            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5587        }
5588
5589        if (isClickable() && isEnabled()) {
5590            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5591        }
5592
5593        if (isLongClickable() && isEnabled()) {
5594            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5595        }
5596
5597        CharSequence text = getIterableTextForAccessibility();
5598        if (text != null && text.length() > 0) {
5599            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5600
5601            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5602            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5603            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5604            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5605                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5606                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5607        }
5608    }
5609
5610    private View findLabelForView(View view, int labeledId) {
5611        if (mMatchLabelForPredicate == null) {
5612            mMatchLabelForPredicate = new MatchLabelForPredicate();
5613        }
5614        mMatchLabelForPredicate.mLabeledId = labeledId;
5615        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5616    }
5617
5618    /**
5619     * Computes whether this view is visible to the user. Such a view is
5620     * attached, visible, all its predecessors are visible, it is not clipped
5621     * entirely by its predecessors, and has an alpha greater than zero.
5622     *
5623     * @return Whether the view is visible on the screen.
5624     *
5625     * @hide
5626     */
5627    protected boolean isVisibleToUser() {
5628        return isVisibleToUser(null);
5629    }
5630
5631    /**
5632     * Computes whether the given portion of this view is visible to the user.
5633     * Such a view is attached, visible, all its predecessors are visible,
5634     * has an alpha greater than zero, and the specified portion is not
5635     * clipped entirely by its predecessors.
5636     *
5637     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5638     *                    <code>null</code>, and the entire view will be tested in this case.
5639     *                    When <code>true</code> is returned by the function, the actual visible
5640     *                    region will be stored in this parameter; that is, if boundInView is fully
5641     *                    contained within the view, no modification will be made, otherwise regions
5642     *                    outside of the visible area of the view will be clipped.
5643     *
5644     * @return Whether the specified portion of the view is visible on the screen.
5645     *
5646     * @hide
5647     */
5648    protected boolean isVisibleToUser(Rect boundInView) {
5649        if (mAttachInfo != null) {
5650            // Attached to invisible window means this view is not visible.
5651            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5652                return false;
5653            }
5654            // An invisible predecessor or one with alpha zero means
5655            // that this view is not visible to the user.
5656            Object current = this;
5657            while (current instanceof View) {
5658                View view = (View) current;
5659                // We have attach info so this view is attached and there is no
5660                // need to check whether we reach to ViewRootImpl on the way up.
5661                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5662                        view.getVisibility() != VISIBLE) {
5663                    return false;
5664                }
5665                current = view.mParent;
5666            }
5667            // Check if the view is entirely covered by its predecessors.
5668            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5669            Point offset = mAttachInfo.mPoint;
5670            if (!getGlobalVisibleRect(visibleRect, offset)) {
5671                return false;
5672            }
5673            // Check if the visible portion intersects the rectangle of interest.
5674            if (boundInView != null) {
5675                visibleRect.offset(-offset.x, -offset.y);
5676                return boundInView.intersect(visibleRect);
5677            }
5678            return true;
5679        }
5680        return false;
5681    }
5682
5683    /**
5684     * Returns the delegate for implementing accessibility support via
5685     * composition. For more details see {@link AccessibilityDelegate}.
5686     *
5687     * @return The delegate, or null if none set.
5688     *
5689     * @hide
5690     */
5691    public AccessibilityDelegate getAccessibilityDelegate() {
5692        return mAccessibilityDelegate;
5693    }
5694
5695    /**
5696     * Sets a delegate for implementing accessibility support via composition as
5697     * opposed to inheritance. The delegate's primary use is for implementing
5698     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5699     *
5700     * @param delegate The delegate instance.
5701     *
5702     * @see AccessibilityDelegate
5703     */
5704    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5705        mAccessibilityDelegate = delegate;
5706    }
5707
5708    /**
5709     * Gets the provider for managing a virtual view hierarchy rooted at this View
5710     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5711     * that explore the window content.
5712     * <p>
5713     * If this method returns an instance, this instance is responsible for managing
5714     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5715     * View including the one representing the View itself. Similarly the returned
5716     * instance is responsible for performing accessibility actions on any virtual
5717     * view or the root view itself.
5718     * </p>
5719     * <p>
5720     * If an {@link AccessibilityDelegate} has been specified via calling
5721     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5722     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5723     * is responsible for handling this call.
5724     * </p>
5725     *
5726     * @return The provider.
5727     *
5728     * @see AccessibilityNodeProvider
5729     */
5730    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5731        if (mAccessibilityDelegate != null) {
5732            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5733        } else {
5734            return null;
5735        }
5736    }
5737
5738    /**
5739     * Gets the unique identifier of this view on the screen for accessibility purposes.
5740     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5741     *
5742     * @return The view accessibility id.
5743     *
5744     * @hide
5745     */
5746    public int getAccessibilityViewId() {
5747        if (mAccessibilityViewId == NO_ID) {
5748            mAccessibilityViewId = sNextAccessibilityViewId++;
5749        }
5750        return mAccessibilityViewId;
5751    }
5752
5753    /**
5754     * Gets the unique identifier of the window in which this View reseides.
5755     *
5756     * @return The window accessibility id.
5757     *
5758     * @hide
5759     */
5760    public int getAccessibilityWindowId() {
5761        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5762                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5763    }
5764
5765    /**
5766     * Gets the {@link View} description. It briefly describes the view and is
5767     * primarily used for accessibility support. Set this property to enable
5768     * better accessibility support for your application. This is especially
5769     * true for views that do not have textual representation (For example,
5770     * ImageButton).
5771     *
5772     * @return The content description.
5773     *
5774     * @attr ref android.R.styleable#View_contentDescription
5775     */
5776    @ViewDebug.ExportedProperty(category = "accessibility")
5777    public CharSequence getContentDescription() {
5778        return mContentDescription;
5779    }
5780
5781    /**
5782     * Sets the {@link View} description. It briefly describes the view and is
5783     * primarily used for accessibility support. Set this property to enable
5784     * better accessibility support for your application. This is especially
5785     * true for views that do not have textual representation (For example,
5786     * ImageButton).
5787     *
5788     * @param contentDescription The content description.
5789     *
5790     * @attr ref android.R.styleable#View_contentDescription
5791     */
5792    @RemotableViewMethod
5793    public void setContentDescription(CharSequence contentDescription) {
5794        if (mContentDescription == null) {
5795            if (contentDescription == null) {
5796                return;
5797            }
5798        } else if (mContentDescription.equals(contentDescription)) {
5799            return;
5800        }
5801        mContentDescription = contentDescription;
5802        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5803        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5804            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5805            notifySubtreeAccessibilityStateChangedIfNeeded();
5806        } else {
5807            notifyViewAccessibilityStateChangedIfNeeded(
5808                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5809        }
5810    }
5811
5812    /**
5813     * Gets the id of a view for which this view serves as a label for
5814     * accessibility purposes.
5815     *
5816     * @return The labeled view id.
5817     */
5818    @ViewDebug.ExportedProperty(category = "accessibility")
5819    public int getLabelFor() {
5820        return mLabelForId;
5821    }
5822
5823    /**
5824     * Sets the id of a view for which this view serves as a label for
5825     * accessibility purposes.
5826     *
5827     * @param id The labeled view id.
5828     */
5829    @RemotableViewMethod
5830    public void setLabelFor(int id) {
5831        mLabelForId = id;
5832        if (mLabelForId != View.NO_ID
5833                && mID == View.NO_ID) {
5834            mID = generateViewId();
5835        }
5836    }
5837
5838    /**
5839     * Invoked whenever this view loses focus, either by losing window focus or by losing
5840     * focus within its window. This method can be used to clear any state tied to the
5841     * focus. For instance, if a button is held pressed with the trackball and the window
5842     * loses focus, this method can be used to cancel the press.
5843     *
5844     * Subclasses of View overriding this method should always call super.onFocusLost().
5845     *
5846     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5847     * @see #onWindowFocusChanged(boolean)
5848     *
5849     * @hide pending API council approval
5850     */
5851    protected void onFocusLost() {
5852        resetPressedState();
5853    }
5854
5855    private void resetPressedState() {
5856        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5857            return;
5858        }
5859
5860        if (isPressed()) {
5861            setPressed(false);
5862
5863            if (!mHasPerformedLongPress) {
5864                removeLongPressCallback();
5865            }
5866        }
5867    }
5868
5869    /**
5870     * Returns true if this view has focus
5871     *
5872     * @return True if this view has focus, false otherwise.
5873     */
5874    @ViewDebug.ExportedProperty(category = "focus")
5875    public boolean isFocused() {
5876        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5877    }
5878
5879    /**
5880     * Find the view in the hierarchy rooted at this view that currently has
5881     * focus.
5882     *
5883     * @return The view that currently has focus, or null if no focused view can
5884     *         be found.
5885     */
5886    public View findFocus() {
5887        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5888    }
5889
5890    /**
5891     * Indicates whether this view is one of the set of scrollable containers in
5892     * its window.
5893     *
5894     * @return whether this view is one of the set of scrollable containers in
5895     * its window
5896     *
5897     * @attr ref android.R.styleable#View_isScrollContainer
5898     */
5899    public boolean isScrollContainer() {
5900        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5901    }
5902
5903    /**
5904     * Change whether this view is one of the set of scrollable containers in
5905     * its window.  This will be used to determine whether the window can
5906     * resize or must pan when a soft input area is open -- scrollable
5907     * containers allow the window to use resize mode since the container
5908     * will appropriately shrink.
5909     *
5910     * @attr ref android.R.styleable#View_isScrollContainer
5911     */
5912    public void setScrollContainer(boolean isScrollContainer) {
5913        if (isScrollContainer) {
5914            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5915                mAttachInfo.mScrollContainers.add(this);
5916                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5917            }
5918            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5919        } else {
5920            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5921                mAttachInfo.mScrollContainers.remove(this);
5922            }
5923            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5924        }
5925    }
5926
5927    /**
5928     * Returns the quality of the drawing cache.
5929     *
5930     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5931     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5932     *
5933     * @see #setDrawingCacheQuality(int)
5934     * @see #setDrawingCacheEnabled(boolean)
5935     * @see #isDrawingCacheEnabled()
5936     *
5937     * @attr ref android.R.styleable#View_drawingCacheQuality
5938     */
5939    @DrawingCacheQuality
5940    public int getDrawingCacheQuality() {
5941        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5942    }
5943
5944    /**
5945     * Set the drawing cache quality of this view. This value is used only when the
5946     * drawing cache is enabled
5947     *
5948     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5949     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5950     *
5951     * @see #getDrawingCacheQuality()
5952     * @see #setDrawingCacheEnabled(boolean)
5953     * @see #isDrawingCacheEnabled()
5954     *
5955     * @attr ref android.R.styleable#View_drawingCacheQuality
5956     */
5957    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5958        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5959    }
5960
5961    /**
5962     * Returns whether the screen should remain on, corresponding to the current
5963     * value of {@link #KEEP_SCREEN_ON}.
5964     *
5965     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5966     *
5967     * @see #setKeepScreenOn(boolean)
5968     *
5969     * @attr ref android.R.styleable#View_keepScreenOn
5970     */
5971    public boolean getKeepScreenOn() {
5972        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5973    }
5974
5975    /**
5976     * Controls whether the screen should remain on, modifying the
5977     * value of {@link #KEEP_SCREEN_ON}.
5978     *
5979     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5980     *
5981     * @see #getKeepScreenOn()
5982     *
5983     * @attr ref android.R.styleable#View_keepScreenOn
5984     */
5985    public void setKeepScreenOn(boolean keepScreenOn) {
5986        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5987    }
5988
5989    /**
5990     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5991     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5992     *
5993     * @attr ref android.R.styleable#View_nextFocusLeft
5994     */
5995    public int getNextFocusLeftId() {
5996        return mNextFocusLeftId;
5997    }
5998
5999    /**
6000     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6001     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6002     * decide automatically.
6003     *
6004     * @attr ref android.R.styleable#View_nextFocusLeft
6005     */
6006    public void setNextFocusLeftId(int nextFocusLeftId) {
6007        mNextFocusLeftId = nextFocusLeftId;
6008    }
6009
6010    /**
6011     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6012     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6013     *
6014     * @attr ref android.R.styleable#View_nextFocusRight
6015     */
6016    public int getNextFocusRightId() {
6017        return mNextFocusRightId;
6018    }
6019
6020    /**
6021     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6022     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6023     * decide automatically.
6024     *
6025     * @attr ref android.R.styleable#View_nextFocusRight
6026     */
6027    public void setNextFocusRightId(int nextFocusRightId) {
6028        mNextFocusRightId = nextFocusRightId;
6029    }
6030
6031    /**
6032     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6033     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6034     *
6035     * @attr ref android.R.styleable#View_nextFocusUp
6036     */
6037    public int getNextFocusUpId() {
6038        return mNextFocusUpId;
6039    }
6040
6041    /**
6042     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6043     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6044     * decide automatically.
6045     *
6046     * @attr ref android.R.styleable#View_nextFocusUp
6047     */
6048    public void setNextFocusUpId(int nextFocusUpId) {
6049        mNextFocusUpId = nextFocusUpId;
6050    }
6051
6052    /**
6053     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6054     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6055     *
6056     * @attr ref android.R.styleable#View_nextFocusDown
6057     */
6058    public int getNextFocusDownId() {
6059        return mNextFocusDownId;
6060    }
6061
6062    /**
6063     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6064     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6065     * decide automatically.
6066     *
6067     * @attr ref android.R.styleable#View_nextFocusDown
6068     */
6069    public void setNextFocusDownId(int nextFocusDownId) {
6070        mNextFocusDownId = nextFocusDownId;
6071    }
6072
6073    /**
6074     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6075     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6076     *
6077     * @attr ref android.R.styleable#View_nextFocusForward
6078     */
6079    public int getNextFocusForwardId() {
6080        return mNextFocusForwardId;
6081    }
6082
6083    /**
6084     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6085     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6086     * decide automatically.
6087     *
6088     * @attr ref android.R.styleable#View_nextFocusForward
6089     */
6090    public void setNextFocusForwardId(int nextFocusForwardId) {
6091        mNextFocusForwardId = nextFocusForwardId;
6092    }
6093
6094    /**
6095     * Returns the visibility of this view and all of its ancestors
6096     *
6097     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6098     */
6099    public boolean isShown() {
6100        View current = this;
6101        //noinspection ConstantConditions
6102        do {
6103            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6104                return false;
6105            }
6106            ViewParent parent = current.mParent;
6107            if (parent == null) {
6108                return false; // We are not attached to the view root
6109            }
6110            if (!(parent instanceof View)) {
6111                return true;
6112            }
6113            current = (View) parent;
6114        } while (current != null);
6115
6116        return false;
6117    }
6118
6119    /**
6120     * Called by the view hierarchy when the content insets for a window have
6121     * changed, to allow it to adjust its content to fit within those windows.
6122     * The content insets tell you the space that the status bar, input method,
6123     * and other system windows infringe on the application's window.
6124     *
6125     * <p>You do not normally need to deal with this function, since the default
6126     * window decoration given to applications takes care of applying it to the
6127     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6128     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6129     * and your content can be placed under those system elements.  You can then
6130     * use this method within your view hierarchy if you have parts of your UI
6131     * which you would like to ensure are not being covered.
6132     *
6133     * <p>The default implementation of this method simply applies the content
6134     * insets to the view's padding, consuming that content (modifying the
6135     * insets to be 0), and returning true.  This behavior is off by default, but can
6136     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6137     *
6138     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6139     * insets object is propagated down the hierarchy, so any changes made to it will
6140     * be seen by all following views (including potentially ones above in
6141     * the hierarchy since this is a depth-first traversal).  The first view
6142     * that returns true will abort the entire traversal.
6143     *
6144     * <p>The default implementation works well for a situation where it is
6145     * used with a container that covers the entire window, allowing it to
6146     * apply the appropriate insets to its content on all edges.  If you need
6147     * a more complicated layout (such as two different views fitting system
6148     * windows, one on the top of the window, and one on the bottom),
6149     * you can override the method and handle the insets however you would like.
6150     * Note that the insets provided by the framework are always relative to the
6151     * far edges of the window, not accounting for the location of the called view
6152     * within that window.  (In fact when this method is called you do not yet know
6153     * where the layout will place the view, as it is done before layout happens.)
6154     *
6155     * <p>Note: unlike many View methods, there is no dispatch phase to this
6156     * call.  If you are overriding it in a ViewGroup and want to allow the
6157     * call to continue to your children, you must be sure to call the super
6158     * implementation.
6159     *
6160     * <p>Here is a sample layout that makes use of fitting system windows
6161     * to have controls for a video view placed inside of the window decorations
6162     * that it hides and shows.  This can be used with code like the second
6163     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6164     *
6165     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6166     *
6167     * @param insets Current content insets of the window.  Prior to
6168     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6169     * the insets or else you and Android will be unhappy.
6170     *
6171     * @return {@code true} if this view applied the insets and it should not
6172     * continue propagating further down the hierarchy, {@code false} otherwise.
6173     * @see #getFitsSystemWindows()
6174     * @see #setFitsSystemWindows(boolean)
6175     * @see #setSystemUiVisibility(int)
6176     *
6177     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6178     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6179     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6180     * to implement handling their own insets.
6181     */
6182    protected boolean fitSystemWindows(Rect insets) {
6183        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6184            if (insets == null) {
6185                // Null insets by definition have already been consumed.
6186                // This call cannot apply insets since there are none to apply,
6187                // so return false.
6188                return false;
6189            }
6190            // If we're not in the process of dispatching the newer apply insets call,
6191            // that means we're not in the compatibility path. Dispatch into the newer
6192            // apply insets path and take things from there.
6193            try {
6194                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6195                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6196            } finally {
6197                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6198            }
6199        } else {
6200            // We're being called from the newer apply insets path.
6201            // Perform the standard fallback behavior.
6202            return fitSystemWindowsInt(insets);
6203        }
6204    }
6205
6206    private boolean fitSystemWindowsInt(Rect insets) {
6207        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6208            mUserPaddingStart = UNDEFINED_PADDING;
6209            mUserPaddingEnd = UNDEFINED_PADDING;
6210            Rect localInsets = sThreadLocal.get();
6211            if (localInsets == null) {
6212                localInsets = new Rect();
6213                sThreadLocal.set(localInsets);
6214            }
6215            boolean res = computeFitSystemWindows(insets, localInsets);
6216            mUserPaddingLeftInitial = localInsets.left;
6217            mUserPaddingRightInitial = localInsets.right;
6218            internalSetPadding(localInsets.left, localInsets.top,
6219                    localInsets.right, localInsets.bottom);
6220            return res;
6221        }
6222        return false;
6223    }
6224
6225    /**
6226     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6227     *
6228     * <p>This method should be overridden by views that wish to apply a policy different from or
6229     * in addition to the default behavior. Clients that wish to force a view subtree
6230     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6231     *
6232     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6233     * it will be called during dispatch instead of this method. The listener may optionally
6234     * call this method from its own implementation if it wishes to apply the view's default
6235     * insets policy in addition to its own.</p>
6236     *
6237     * <p>Implementations of this method should either return the insets parameter unchanged
6238     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6239     * that this view applied itself. This allows new inset types added in future platform
6240     * versions to pass through existing implementations unchanged without being erroneously
6241     * consumed.</p>
6242     *
6243     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6244     * property is set then the view will consume the system window insets and apply them
6245     * as padding for the view.</p>
6246     *
6247     * @param insets Insets to apply
6248     * @return The supplied insets with any applied insets consumed
6249     */
6250    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6251        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6252            // We weren't called from within a direct call to fitSystemWindows,
6253            // call into it as a fallback in case we're in a class that overrides it
6254            // and has logic to perform.
6255            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6256                return insets.consumeSystemWindowInsets();
6257            }
6258        } else {
6259            // We were called from within a direct call to fitSystemWindows.
6260            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6261                return insets.consumeSystemWindowInsets();
6262            }
6263        }
6264        return insets;
6265    }
6266
6267    /**
6268     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6269     * window insets to this view. The listener's
6270     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6271     * method will be called instead of the view's
6272     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6273     *
6274     * @param listener Listener to set
6275     *
6276     * @see #onApplyWindowInsets(WindowInsets)
6277     */
6278    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6279        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6280    }
6281
6282    /**
6283     * Request to apply the given window insets to this view or another view in its subtree.
6284     *
6285     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6286     * obscured by window decorations or overlays. This can include the status and navigation bars,
6287     * action bars, input methods and more. New inset categories may be added in the future.
6288     * The method returns the insets provided minus any that were applied by this view or its
6289     * children.</p>
6290     *
6291     * <p>Clients wishing to provide custom behavior should override the
6292     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6293     * {@link OnApplyWindowInsetsListener} via the
6294     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6295     * method.</p>
6296     *
6297     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6298     * </p>
6299     *
6300     * @param insets Insets to apply
6301     * @return The provided insets minus the insets that were consumed
6302     */
6303    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6304        try {
6305            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6306            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6307                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6308            } else {
6309                return onApplyWindowInsets(insets);
6310            }
6311        } finally {
6312            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6313        }
6314    }
6315
6316    /**
6317     * @hide Compute the insets that should be consumed by this view and the ones
6318     * that should propagate to those under it.
6319     */
6320    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6321        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6322                || mAttachInfo == null
6323                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6324                        && !mAttachInfo.mOverscanRequested)) {
6325            outLocalInsets.set(inoutInsets);
6326            inoutInsets.set(0, 0, 0, 0);
6327            return true;
6328        } else {
6329            // The application wants to take care of fitting system window for
6330            // the content...  however we still need to take care of any overscan here.
6331            final Rect overscan = mAttachInfo.mOverscanInsets;
6332            outLocalInsets.set(overscan);
6333            inoutInsets.left -= overscan.left;
6334            inoutInsets.top -= overscan.top;
6335            inoutInsets.right -= overscan.right;
6336            inoutInsets.bottom -= overscan.bottom;
6337            return false;
6338        }
6339    }
6340
6341    /**
6342     * Sets whether or not this view should account for system screen decorations
6343     * such as the status bar and inset its content; that is, controlling whether
6344     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6345     * executed.  See that method for more details.
6346     *
6347     * <p>Note that if you are providing your own implementation of
6348     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6349     * flag to true -- your implementation will be overriding the default
6350     * implementation that checks this flag.
6351     *
6352     * @param fitSystemWindows If true, then the default implementation of
6353     * {@link #fitSystemWindows(Rect)} will be executed.
6354     *
6355     * @attr ref android.R.styleable#View_fitsSystemWindows
6356     * @see #getFitsSystemWindows()
6357     * @see #fitSystemWindows(Rect)
6358     * @see #setSystemUiVisibility(int)
6359     */
6360    public void setFitsSystemWindows(boolean fitSystemWindows) {
6361        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6362    }
6363
6364    /**
6365     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6366     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6367     * will be executed.
6368     *
6369     * @return {@code true} if the default implementation of
6370     * {@link #fitSystemWindows(Rect)} will be executed.
6371     *
6372     * @attr ref android.R.styleable#View_fitsSystemWindows
6373     * @see #setFitsSystemWindows(boolean)
6374     * @see #fitSystemWindows(Rect)
6375     * @see #setSystemUiVisibility(int)
6376     */
6377    public boolean getFitsSystemWindows() {
6378        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6379    }
6380
6381    /** @hide */
6382    public boolean fitsSystemWindows() {
6383        return getFitsSystemWindows();
6384    }
6385
6386    /**
6387     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6388     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6389     */
6390    public void requestFitSystemWindows() {
6391        if (mParent != null) {
6392            mParent.requestFitSystemWindows();
6393        }
6394    }
6395
6396    /**
6397     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6398     */
6399    public void requestApplyInsets() {
6400        requestFitSystemWindows();
6401    }
6402
6403    /**
6404     * For use by PhoneWindow to make its own system window fitting optional.
6405     * @hide
6406     */
6407    public void makeOptionalFitsSystemWindows() {
6408        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6409    }
6410
6411    /**
6412     * Returns the visibility status for this view.
6413     *
6414     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6415     * @attr ref android.R.styleable#View_visibility
6416     */
6417    @ViewDebug.ExportedProperty(mapping = {
6418        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6419        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6420        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6421    })
6422    @Visibility
6423    public int getVisibility() {
6424        return mViewFlags & VISIBILITY_MASK;
6425    }
6426
6427    /**
6428     * Set the enabled state of this view.
6429     *
6430     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6431     * @attr ref android.R.styleable#View_visibility
6432     */
6433    @RemotableViewMethod
6434    public void setVisibility(@Visibility int visibility) {
6435        setFlags(visibility, VISIBILITY_MASK);
6436        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6437    }
6438
6439    /**
6440     * Returns the enabled status for this view. The interpretation of the
6441     * enabled state varies by subclass.
6442     *
6443     * @return True if this view is enabled, false otherwise.
6444     */
6445    @ViewDebug.ExportedProperty
6446    public boolean isEnabled() {
6447        return (mViewFlags & ENABLED_MASK) == ENABLED;
6448    }
6449
6450    /**
6451     * Set the enabled state of this view. The interpretation of the enabled
6452     * state varies by subclass.
6453     *
6454     * @param enabled True if this view is enabled, false otherwise.
6455     */
6456    @RemotableViewMethod
6457    public void setEnabled(boolean enabled) {
6458        if (enabled == isEnabled()) return;
6459
6460        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6461
6462        /*
6463         * The View most likely has to change its appearance, so refresh
6464         * the drawable state.
6465         */
6466        refreshDrawableState();
6467
6468        // Invalidate too, since the default behavior for views is to be
6469        // be drawn at 50% alpha rather than to change the drawable.
6470        invalidate(true);
6471
6472        if (!enabled) {
6473            cancelPendingInputEvents();
6474        }
6475    }
6476
6477    /**
6478     * Set whether this view can receive the focus.
6479     *
6480     * Setting this to false will also ensure that this view is not focusable
6481     * in touch mode.
6482     *
6483     * @param focusable If true, this view can receive the focus.
6484     *
6485     * @see #setFocusableInTouchMode(boolean)
6486     * @attr ref android.R.styleable#View_focusable
6487     */
6488    public void setFocusable(boolean focusable) {
6489        if (!focusable) {
6490            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6491        }
6492        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6493    }
6494
6495    /**
6496     * Set whether this view can receive focus while in touch mode.
6497     *
6498     * Setting this to true will also ensure that this view is focusable.
6499     *
6500     * @param focusableInTouchMode If true, this view can receive the focus while
6501     *   in touch mode.
6502     *
6503     * @see #setFocusable(boolean)
6504     * @attr ref android.R.styleable#View_focusableInTouchMode
6505     */
6506    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6507        // Focusable in touch mode should always be set before the focusable flag
6508        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6509        // which, in touch mode, will not successfully request focus on this view
6510        // because the focusable in touch mode flag is not set
6511        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6512        if (focusableInTouchMode) {
6513            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6514        }
6515    }
6516
6517    /**
6518     * Set whether this view should have sound effects enabled for events such as
6519     * clicking and touching.
6520     *
6521     * <p>You may wish to disable sound effects for a view if you already play sounds,
6522     * for instance, a dial key that plays dtmf tones.
6523     *
6524     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6525     * @see #isSoundEffectsEnabled()
6526     * @see #playSoundEffect(int)
6527     * @attr ref android.R.styleable#View_soundEffectsEnabled
6528     */
6529    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6530        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6531    }
6532
6533    /**
6534     * @return whether this view should have sound effects enabled for events such as
6535     *     clicking and touching.
6536     *
6537     * @see #setSoundEffectsEnabled(boolean)
6538     * @see #playSoundEffect(int)
6539     * @attr ref android.R.styleable#View_soundEffectsEnabled
6540     */
6541    @ViewDebug.ExportedProperty
6542    public boolean isSoundEffectsEnabled() {
6543        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6544    }
6545
6546    /**
6547     * Set whether this view should have haptic feedback for events such as
6548     * long presses.
6549     *
6550     * <p>You may wish to disable haptic feedback if your view already controls
6551     * its own haptic feedback.
6552     *
6553     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6554     * @see #isHapticFeedbackEnabled()
6555     * @see #performHapticFeedback(int)
6556     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6557     */
6558    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6559        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6560    }
6561
6562    /**
6563     * @return whether this view should have haptic feedback enabled for events
6564     * long presses.
6565     *
6566     * @see #setHapticFeedbackEnabled(boolean)
6567     * @see #performHapticFeedback(int)
6568     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6569     */
6570    @ViewDebug.ExportedProperty
6571    public boolean isHapticFeedbackEnabled() {
6572        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6573    }
6574
6575    /**
6576     * Returns the layout direction for this view.
6577     *
6578     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6579     *   {@link #LAYOUT_DIRECTION_RTL},
6580     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6581     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6582     *
6583     * @attr ref android.R.styleable#View_layoutDirection
6584     *
6585     * @hide
6586     */
6587    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6588        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6589        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6590        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6591        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6592    })
6593    @LayoutDir
6594    public int getRawLayoutDirection() {
6595        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6596    }
6597
6598    /**
6599     * Set the layout direction for this view. This will propagate a reset of layout direction
6600     * resolution to the view's children and resolve layout direction for this view.
6601     *
6602     * @param layoutDirection the layout direction to set. Should be one of:
6603     *
6604     * {@link #LAYOUT_DIRECTION_LTR},
6605     * {@link #LAYOUT_DIRECTION_RTL},
6606     * {@link #LAYOUT_DIRECTION_INHERIT},
6607     * {@link #LAYOUT_DIRECTION_LOCALE}.
6608     *
6609     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6610     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6611     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6612     *
6613     * @attr ref android.R.styleable#View_layoutDirection
6614     */
6615    @RemotableViewMethod
6616    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6617        if (getRawLayoutDirection() != layoutDirection) {
6618            // Reset the current layout direction and the resolved one
6619            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6620            resetRtlProperties();
6621            // Set the new layout direction (filtered)
6622            mPrivateFlags2 |=
6623                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6624            // We need to resolve all RTL properties as they all depend on layout direction
6625            resolveRtlPropertiesIfNeeded();
6626            requestLayout();
6627            invalidate(true);
6628        }
6629    }
6630
6631    /**
6632     * Returns the resolved layout direction for this view.
6633     *
6634     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6635     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6636     *
6637     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6638     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6639     *
6640     * @attr ref android.R.styleable#View_layoutDirection
6641     */
6642    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6643        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6644        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6645    })
6646    @ResolvedLayoutDir
6647    public int getLayoutDirection() {
6648        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6649        if (targetSdkVersion < JELLY_BEAN_MR1) {
6650            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6651            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6652        }
6653        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6654                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6655    }
6656
6657    /**
6658     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6659     * layout attribute and/or the inherited value from the parent
6660     *
6661     * @return true if the layout is right-to-left.
6662     *
6663     * @hide
6664     */
6665    @ViewDebug.ExportedProperty(category = "layout")
6666    public boolean isLayoutRtl() {
6667        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6668    }
6669
6670    /**
6671     * Indicates whether the view is currently tracking transient state that the
6672     * app should not need to concern itself with saving and restoring, but that
6673     * the framework should take special note to preserve when possible.
6674     *
6675     * <p>A view with transient state cannot be trivially rebound from an external
6676     * data source, such as an adapter binding item views in a list. This may be
6677     * because the view is performing an animation, tracking user selection
6678     * of content, or similar.</p>
6679     *
6680     * @return true if the view has transient state
6681     */
6682    @ViewDebug.ExportedProperty(category = "layout")
6683    public boolean hasTransientState() {
6684        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6685    }
6686
6687    /**
6688     * Set whether this view is currently tracking transient state that the
6689     * framework should attempt to preserve when possible. This flag is reference counted,
6690     * so every call to setHasTransientState(true) should be paired with a later call
6691     * to setHasTransientState(false).
6692     *
6693     * <p>A view with transient state cannot be trivially rebound from an external
6694     * data source, such as an adapter binding item views in a list. This may be
6695     * because the view is performing an animation, tracking user selection
6696     * of content, or similar.</p>
6697     *
6698     * @param hasTransientState true if this view has transient state
6699     */
6700    public void setHasTransientState(boolean hasTransientState) {
6701        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6702                mTransientStateCount - 1;
6703        if (mTransientStateCount < 0) {
6704            mTransientStateCount = 0;
6705            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6706                    "unmatched pair of setHasTransientState calls");
6707        } else if ((hasTransientState && mTransientStateCount == 1) ||
6708                (!hasTransientState && mTransientStateCount == 0)) {
6709            // update flag if we've just incremented up from 0 or decremented down to 0
6710            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6711                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6712            if (mParent != null) {
6713                try {
6714                    mParent.childHasTransientStateChanged(this, hasTransientState);
6715                } catch (AbstractMethodError e) {
6716                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6717                            " does not fully implement ViewParent", e);
6718                }
6719            }
6720        }
6721    }
6722
6723    /**
6724     * Returns true if this view is currently attached to a window.
6725     */
6726    public boolean isAttachedToWindow() {
6727        return mAttachInfo != null;
6728    }
6729
6730    /**
6731     * Returns true if this view has been through at least one layout since it
6732     * was last attached to or detached from a window.
6733     */
6734    public boolean isLaidOut() {
6735        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6736    }
6737
6738    /**
6739     * If this view doesn't do any drawing on its own, set this flag to
6740     * allow further optimizations. By default, this flag is not set on
6741     * View, but could be set on some View subclasses such as ViewGroup.
6742     *
6743     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6744     * you should clear this flag.
6745     *
6746     * @param willNotDraw whether or not this View draw on its own
6747     */
6748    public void setWillNotDraw(boolean willNotDraw) {
6749        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6750    }
6751
6752    /**
6753     * Returns whether or not this View draws on its own.
6754     *
6755     * @return true if this view has nothing to draw, false otherwise
6756     */
6757    @ViewDebug.ExportedProperty(category = "drawing")
6758    public boolean willNotDraw() {
6759        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6760    }
6761
6762    /**
6763     * When a View's drawing cache is enabled, drawing is redirected to an
6764     * offscreen bitmap. Some views, like an ImageView, must be able to
6765     * bypass this mechanism if they already draw a single bitmap, to avoid
6766     * unnecessary usage of the memory.
6767     *
6768     * @param willNotCacheDrawing true if this view does not cache its
6769     *        drawing, false otherwise
6770     */
6771    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6772        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6773    }
6774
6775    /**
6776     * Returns whether or not this View can cache its drawing or not.
6777     *
6778     * @return true if this view does not cache its drawing, false otherwise
6779     */
6780    @ViewDebug.ExportedProperty(category = "drawing")
6781    public boolean willNotCacheDrawing() {
6782        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6783    }
6784
6785    /**
6786     * Indicates whether this view reacts to click events or not.
6787     *
6788     * @return true if the view is clickable, false otherwise
6789     *
6790     * @see #setClickable(boolean)
6791     * @attr ref android.R.styleable#View_clickable
6792     */
6793    @ViewDebug.ExportedProperty
6794    public boolean isClickable() {
6795        return (mViewFlags & CLICKABLE) == CLICKABLE;
6796    }
6797
6798    /**
6799     * Enables or disables click events for this view. When a view
6800     * is clickable it will change its state to "pressed" on every click.
6801     * Subclasses should set the view clickable to visually react to
6802     * user's clicks.
6803     *
6804     * @param clickable true to make the view clickable, false otherwise
6805     *
6806     * @see #isClickable()
6807     * @attr ref android.R.styleable#View_clickable
6808     */
6809    public void setClickable(boolean clickable) {
6810        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6811    }
6812
6813    /**
6814     * Indicates whether this view reacts to long click events or not.
6815     *
6816     * @return true if the view is long clickable, false otherwise
6817     *
6818     * @see #setLongClickable(boolean)
6819     * @attr ref android.R.styleable#View_longClickable
6820     */
6821    public boolean isLongClickable() {
6822        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6823    }
6824
6825    /**
6826     * Enables or disables long click events for this view. When a view is long
6827     * clickable it reacts to the user holding down the button for a longer
6828     * duration than a tap. This event can either launch the listener or a
6829     * context menu.
6830     *
6831     * @param longClickable true to make the view long clickable, false otherwise
6832     * @see #isLongClickable()
6833     * @attr ref android.R.styleable#View_longClickable
6834     */
6835    public void setLongClickable(boolean longClickable) {
6836        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6837    }
6838
6839    /**
6840     * Sets the pressed state for this view and provides a touch coordinate for
6841     * animation hinting.
6842     *
6843     * @param pressed Pass true to set the View's internal state to "pressed",
6844     *            or false to reverts the View's internal state from a
6845     *            previously set "pressed" state.
6846     * @param x The x coordinate of the touch that caused the press
6847     * @param y The y coordinate of the touch that caused the press
6848     */
6849    private void setPressed(boolean pressed, float x, float y) {
6850        if (pressed) {
6851            drawableHotspotChanged(x, y);
6852        }
6853
6854        setPressed(pressed);
6855    }
6856
6857    /**
6858     * Sets the pressed state for this view.
6859     *
6860     * @see #isClickable()
6861     * @see #setClickable(boolean)
6862     *
6863     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6864     *        the View's internal state from a previously set "pressed" state.
6865     */
6866    public void setPressed(boolean pressed) {
6867        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6868
6869        if (pressed) {
6870            mPrivateFlags |= PFLAG_PRESSED;
6871        } else {
6872            mPrivateFlags &= ~PFLAG_PRESSED;
6873        }
6874
6875        if (needsRefresh) {
6876            refreshDrawableState();
6877        }
6878        dispatchSetPressed(pressed);
6879    }
6880
6881    /**
6882     * Dispatch setPressed to all of this View's children.
6883     *
6884     * @see #setPressed(boolean)
6885     *
6886     * @param pressed The new pressed state
6887     */
6888    protected void dispatchSetPressed(boolean pressed) {
6889    }
6890
6891    /**
6892     * Indicates whether the view is currently in pressed state. Unless
6893     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6894     * the pressed state.
6895     *
6896     * @see #setPressed(boolean)
6897     * @see #isClickable()
6898     * @see #setClickable(boolean)
6899     *
6900     * @return true if the view is currently pressed, false otherwise
6901     */
6902    public boolean isPressed() {
6903        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6904    }
6905
6906    /**
6907     * Indicates whether this view will save its state (that is,
6908     * whether its {@link #onSaveInstanceState} method will be called).
6909     *
6910     * @return Returns true if the view state saving is enabled, else false.
6911     *
6912     * @see #setSaveEnabled(boolean)
6913     * @attr ref android.R.styleable#View_saveEnabled
6914     */
6915    public boolean isSaveEnabled() {
6916        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6917    }
6918
6919    /**
6920     * Controls whether the saving of this view's state is
6921     * enabled (that is, whether its {@link #onSaveInstanceState} method
6922     * will be called).  Note that even if freezing is enabled, the
6923     * view still must have an id assigned to it (via {@link #setId(int)})
6924     * for its state to be saved.  This flag can only disable the
6925     * saving of this view; any child views may still have their state saved.
6926     *
6927     * @param enabled Set to false to <em>disable</em> state saving, or true
6928     * (the default) to allow it.
6929     *
6930     * @see #isSaveEnabled()
6931     * @see #setId(int)
6932     * @see #onSaveInstanceState()
6933     * @attr ref android.R.styleable#View_saveEnabled
6934     */
6935    public void setSaveEnabled(boolean enabled) {
6936        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6937    }
6938
6939    /**
6940     * Gets whether the framework should discard touches when the view's
6941     * window is obscured by another visible window.
6942     * Refer to the {@link View} security documentation for more details.
6943     *
6944     * @return True if touch filtering is enabled.
6945     *
6946     * @see #setFilterTouchesWhenObscured(boolean)
6947     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6948     */
6949    @ViewDebug.ExportedProperty
6950    public boolean getFilterTouchesWhenObscured() {
6951        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6952    }
6953
6954    /**
6955     * Sets whether the framework should discard touches when the view's
6956     * window is obscured by another visible window.
6957     * Refer to the {@link View} security documentation for more details.
6958     *
6959     * @param enabled True if touch filtering should be enabled.
6960     *
6961     * @see #getFilterTouchesWhenObscured
6962     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6963     */
6964    public void setFilterTouchesWhenObscured(boolean enabled) {
6965        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6966                FILTER_TOUCHES_WHEN_OBSCURED);
6967    }
6968
6969    /**
6970     * Indicates whether the entire hierarchy under this view will save its
6971     * state when a state saving traversal occurs from its parent.  The default
6972     * is true; if false, these views will not be saved unless
6973     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6974     *
6975     * @return Returns true if the view state saving from parent is enabled, else false.
6976     *
6977     * @see #setSaveFromParentEnabled(boolean)
6978     */
6979    public boolean isSaveFromParentEnabled() {
6980        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6981    }
6982
6983    /**
6984     * Controls whether the entire hierarchy under this view will save its
6985     * state when a state saving traversal occurs from its parent.  The default
6986     * is true; if false, these views will not be saved unless
6987     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6988     *
6989     * @param enabled Set to false to <em>disable</em> state saving, or true
6990     * (the default) to allow it.
6991     *
6992     * @see #isSaveFromParentEnabled()
6993     * @see #setId(int)
6994     * @see #onSaveInstanceState()
6995     */
6996    public void setSaveFromParentEnabled(boolean enabled) {
6997        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6998    }
6999
7000
7001    /**
7002     * Returns whether this View is able to take focus.
7003     *
7004     * @return True if this view can take focus, or false otherwise.
7005     * @attr ref android.R.styleable#View_focusable
7006     */
7007    @ViewDebug.ExportedProperty(category = "focus")
7008    public final boolean isFocusable() {
7009        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7010    }
7011
7012    /**
7013     * When a view is focusable, it may not want to take focus when in touch mode.
7014     * For example, a button would like focus when the user is navigating via a D-pad
7015     * so that the user can click on it, but once the user starts touching the screen,
7016     * the button shouldn't take focus
7017     * @return Whether the view is focusable in touch mode.
7018     * @attr ref android.R.styleable#View_focusableInTouchMode
7019     */
7020    @ViewDebug.ExportedProperty
7021    public final boolean isFocusableInTouchMode() {
7022        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7023    }
7024
7025    /**
7026     * Find the nearest view in the specified direction that can take focus.
7027     * This does not actually give focus to that view.
7028     *
7029     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7030     *
7031     * @return The nearest focusable in the specified direction, or null if none
7032     *         can be found.
7033     */
7034    public View focusSearch(@FocusRealDirection int direction) {
7035        if (mParent != null) {
7036            return mParent.focusSearch(this, direction);
7037        } else {
7038            return null;
7039        }
7040    }
7041
7042    /**
7043     * This method is the last chance for the focused view and its ancestors to
7044     * respond to an arrow key. This is called when the focused view did not
7045     * consume the key internally, nor could the view system find a new view in
7046     * the requested direction to give focus to.
7047     *
7048     * @param focused The currently focused view.
7049     * @param direction The direction focus wants to move. One of FOCUS_UP,
7050     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7051     * @return True if the this view consumed this unhandled move.
7052     */
7053    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7054        return false;
7055    }
7056
7057    /**
7058     * If a user manually specified the next view id for a particular direction,
7059     * use the root to look up the view.
7060     * @param root The root view of the hierarchy containing this view.
7061     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7062     * or FOCUS_BACKWARD.
7063     * @return The user specified next view, or null if there is none.
7064     */
7065    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7066        switch (direction) {
7067            case FOCUS_LEFT:
7068                if (mNextFocusLeftId == View.NO_ID) return null;
7069                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7070            case FOCUS_RIGHT:
7071                if (mNextFocusRightId == View.NO_ID) return null;
7072                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7073            case FOCUS_UP:
7074                if (mNextFocusUpId == View.NO_ID) return null;
7075                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7076            case FOCUS_DOWN:
7077                if (mNextFocusDownId == View.NO_ID) return null;
7078                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7079            case FOCUS_FORWARD:
7080                if (mNextFocusForwardId == View.NO_ID) return null;
7081                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7082            case FOCUS_BACKWARD: {
7083                if (mID == View.NO_ID) return null;
7084                final int id = mID;
7085                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7086                    @Override
7087                    public boolean apply(View t) {
7088                        return t.mNextFocusForwardId == id;
7089                    }
7090                });
7091            }
7092        }
7093        return null;
7094    }
7095
7096    private View findViewInsideOutShouldExist(View root, int id) {
7097        if (mMatchIdPredicate == null) {
7098            mMatchIdPredicate = new MatchIdPredicate();
7099        }
7100        mMatchIdPredicate.mId = id;
7101        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7102        if (result == null) {
7103            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7104        }
7105        return result;
7106    }
7107
7108    /**
7109     * Find and return all focusable views that are descendants of this view,
7110     * possibly including this view if it is focusable itself.
7111     *
7112     * @param direction The direction of the focus
7113     * @return A list of focusable views
7114     */
7115    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7116        ArrayList<View> result = new ArrayList<View>(24);
7117        addFocusables(result, direction);
7118        return result;
7119    }
7120
7121    /**
7122     * Add any focusable views that are descendants of this view (possibly
7123     * including this view if it is focusable itself) to views.  If we are in touch mode,
7124     * only add views that are also focusable in touch mode.
7125     *
7126     * @param views Focusable views found so far
7127     * @param direction The direction of the focus
7128     */
7129    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7130        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7131    }
7132
7133    /**
7134     * Adds any focusable views that are descendants of this view (possibly
7135     * including this view if it is focusable itself) to views. This method
7136     * adds all focusable views regardless if we are in touch mode or
7137     * only views focusable in touch mode if we are in touch mode or
7138     * only views that can take accessibility focus if accessibility is enabeld
7139     * depending on the focusable mode paramater.
7140     *
7141     * @param views Focusable views found so far or null if all we are interested is
7142     *        the number of focusables.
7143     * @param direction The direction of the focus.
7144     * @param focusableMode The type of focusables to be added.
7145     *
7146     * @see #FOCUSABLES_ALL
7147     * @see #FOCUSABLES_TOUCH_MODE
7148     */
7149    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7150            @FocusableMode int focusableMode) {
7151        if (views == null) {
7152            return;
7153        }
7154        if (!isFocusable()) {
7155            return;
7156        }
7157        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7158                && isInTouchMode() && !isFocusableInTouchMode()) {
7159            return;
7160        }
7161        views.add(this);
7162    }
7163
7164    /**
7165     * Finds the Views that contain given text. The containment is case insensitive.
7166     * The search is performed by either the text that the View renders or the content
7167     * description that describes the view for accessibility purposes and the view does
7168     * not render or both. Clients can specify how the search is to be performed via
7169     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7170     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7171     *
7172     * @param outViews The output list of matching Views.
7173     * @param searched The text to match against.
7174     *
7175     * @see #FIND_VIEWS_WITH_TEXT
7176     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7177     * @see #setContentDescription(CharSequence)
7178     */
7179    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7180            @FindViewFlags int flags) {
7181        if (getAccessibilityNodeProvider() != null) {
7182            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7183                outViews.add(this);
7184            }
7185        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7186                && (searched != null && searched.length() > 0)
7187                && (mContentDescription != null && mContentDescription.length() > 0)) {
7188            String searchedLowerCase = searched.toString().toLowerCase();
7189            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7190            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7191                outViews.add(this);
7192            }
7193        }
7194    }
7195
7196    /**
7197     * Find and return all touchable views that are descendants of this view,
7198     * possibly including this view if it is touchable itself.
7199     *
7200     * @return A list of touchable views
7201     */
7202    public ArrayList<View> getTouchables() {
7203        ArrayList<View> result = new ArrayList<View>();
7204        addTouchables(result);
7205        return result;
7206    }
7207
7208    /**
7209     * Add any touchable views that are descendants of this view (possibly
7210     * including this view if it is touchable itself) to views.
7211     *
7212     * @param views Touchable views found so far
7213     */
7214    public void addTouchables(ArrayList<View> views) {
7215        final int viewFlags = mViewFlags;
7216
7217        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7218                && (viewFlags & ENABLED_MASK) == ENABLED) {
7219            views.add(this);
7220        }
7221    }
7222
7223    /**
7224     * Returns whether this View is accessibility focused.
7225     *
7226     * @return True if this View is accessibility focused.
7227     */
7228    public boolean isAccessibilityFocused() {
7229        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7230    }
7231
7232    /**
7233     * Call this to try to give accessibility focus to this view.
7234     *
7235     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7236     * returns false or the view is no visible or the view already has accessibility
7237     * focus.
7238     *
7239     * See also {@link #focusSearch(int)}, which is what you call to say that you
7240     * have focus, and you want your parent to look for the next one.
7241     *
7242     * @return Whether this view actually took accessibility focus.
7243     *
7244     * @hide
7245     */
7246    public boolean requestAccessibilityFocus() {
7247        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7248        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7249            return false;
7250        }
7251        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7252            return false;
7253        }
7254        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7255            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7256            ViewRootImpl viewRootImpl = getViewRootImpl();
7257            if (viewRootImpl != null) {
7258                viewRootImpl.setAccessibilityFocus(this, null);
7259            }
7260            invalidate();
7261            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7262            return true;
7263        }
7264        return false;
7265    }
7266
7267    /**
7268     * Call this to try to clear accessibility focus of this view.
7269     *
7270     * See also {@link #focusSearch(int)}, which is what you call to say that you
7271     * have focus, and you want your parent to look for the next one.
7272     *
7273     * @hide
7274     */
7275    public void clearAccessibilityFocus() {
7276        clearAccessibilityFocusNoCallbacks();
7277        // Clear the global reference of accessibility focus if this
7278        // view or any of its descendants had accessibility focus.
7279        ViewRootImpl viewRootImpl = getViewRootImpl();
7280        if (viewRootImpl != null) {
7281            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7282            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7283                viewRootImpl.setAccessibilityFocus(null, null);
7284            }
7285        }
7286    }
7287
7288    private void sendAccessibilityHoverEvent(int eventType) {
7289        // Since we are not delivering to a client accessibility events from not
7290        // important views (unless the clinet request that) we need to fire the
7291        // event from the deepest view exposed to the client. As a consequence if
7292        // the user crosses a not exposed view the client will see enter and exit
7293        // of the exposed predecessor followed by and enter and exit of that same
7294        // predecessor when entering and exiting the not exposed descendant. This
7295        // is fine since the client has a clear idea which view is hovered at the
7296        // price of a couple more events being sent. This is a simple and
7297        // working solution.
7298        View source = this;
7299        while (true) {
7300            if (source.includeForAccessibility()) {
7301                source.sendAccessibilityEvent(eventType);
7302                return;
7303            }
7304            ViewParent parent = source.getParent();
7305            if (parent instanceof View) {
7306                source = (View) parent;
7307            } else {
7308                return;
7309            }
7310        }
7311    }
7312
7313    /**
7314     * Clears accessibility focus without calling any callback methods
7315     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7316     * is used for clearing accessibility focus when giving this focus to
7317     * another view.
7318     */
7319    void clearAccessibilityFocusNoCallbacks() {
7320        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7321            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7322            invalidate();
7323            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7324        }
7325    }
7326
7327    /**
7328     * Call this to try to give focus to a specific view or to one of its
7329     * descendants.
7330     *
7331     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7332     * false), or if it is focusable and it is not focusable in touch mode
7333     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7334     *
7335     * See also {@link #focusSearch(int)}, which is what you call to say that you
7336     * have focus, and you want your parent to look for the next one.
7337     *
7338     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7339     * {@link #FOCUS_DOWN} and <code>null</code>.
7340     *
7341     * @return Whether this view or one of its descendants actually took focus.
7342     */
7343    public final boolean requestFocus() {
7344        return requestFocus(View.FOCUS_DOWN);
7345    }
7346
7347    /**
7348     * Call this to try to give focus to a specific view or to one of its
7349     * descendants and give it a hint about what direction focus is heading.
7350     *
7351     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7352     * false), or if it is focusable and it is not focusable in touch mode
7353     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7354     *
7355     * See also {@link #focusSearch(int)}, which is what you call to say that you
7356     * have focus, and you want your parent to look for the next one.
7357     *
7358     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7359     * <code>null</code> set for the previously focused rectangle.
7360     *
7361     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7362     * @return Whether this view or one of its descendants actually took focus.
7363     */
7364    public final boolean requestFocus(int direction) {
7365        return requestFocus(direction, null);
7366    }
7367
7368    /**
7369     * Call this to try to give focus to a specific view or to one of its descendants
7370     * and give it hints about the direction and a specific rectangle that the focus
7371     * is coming from.  The rectangle can help give larger views a finer grained hint
7372     * about where focus is coming from, and therefore, where to show selection, or
7373     * forward focus change internally.
7374     *
7375     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7376     * false), or if it is focusable and it is not focusable in touch mode
7377     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7378     *
7379     * A View will not take focus if it is not visible.
7380     *
7381     * A View will not take focus if one of its parents has
7382     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7383     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7384     *
7385     * See also {@link #focusSearch(int)}, which is what you call to say that you
7386     * have focus, and you want your parent to look for the next one.
7387     *
7388     * You may wish to override this method if your custom {@link View} has an internal
7389     * {@link View} that it wishes to forward the request to.
7390     *
7391     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7392     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7393     *        to give a finer grained hint about where focus is coming from.  May be null
7394     *        if there is no hint.
7395     * @return Whether this view or one of its descendants actually took focus.
7396     */
7397    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7398        return requestFocusNoSearch(direction, previouslyFocusedRect);
7399    }
7400
7401    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7402        // need to be focusable
7403        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7404                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7405            return false;
7406        }
7407
7408        // need to be focusable in touch mode if in touch mode
7409        if (isInTouchMode() &&
7410            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7411               return false;
7412        }
7413
7414        // need to not have any parents blocking us
7415        if (hasAncestorThatBlocksDescendantFocus()) {
7416            return false;
7417        }
7418
7419        handleFocusGainInternal(direction, previouslyFocusedRect);
7420        return true;
7421    }
7422
7423    /**
7424     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7425     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7426     * touch mode to request focus when they are touched.
7427     *
7428     * @return Whether this view or one of its descendants actually took focus.
7429     *
7430     * @see #isInTouchMode()
7431     *
7432     */
7433    public final boolean requestFocusFromTouch() {
7434        // Leave touch mode if we need to
7435        if (isInTouchMode()) {
7436            ViewRootImpl viewRoot = getViewRootImpl();
7437            if (viewRoot != null) {
7438                viewRoot.ensureTouchMode(false);
7439            }
7440        }
7441        return requestFocus(View.FOCUS_DOWN);
7442    }
7443
7444    /**
7445     * @return Whether any ancestor of this view blocks descendant focus.
7446     */
7447    private boolean hasAncestorThatBlocksDescendantFocus() {
7448        final boolean focusableInTouchMode = isFocusableInTouchMode();
7449        ViewParent ancestor = mParent;
7450        while (ancestor instanceof ViewGroup) {
7451            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7452            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7453                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7454                return true;
7455            } else {
7456                ancestor = vgAncestor.getParent();
7457            }
7458        }
7459        return false;
7460    }
7461
7462    /**
7463     * Gets the mode for determining whether this View is important for accessibility
7464     * which is if it fires accessibility events and if it is reported to
7465     * accessibility services that query the screen.
7466     *
7467     * @return The mode for determining whether a View is important for accessibility.
7468     *
7469     * @attr ref android.R.styleable#View_importantForAccessibility
7470     *
7471     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7472     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7473     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7474     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7475     */
7476    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7477            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7478            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7479            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7480            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7481                    to = "noHideDescendants")
7482        })
7483    public int getImportantForAccessibility() {
7484        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7485                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7486    }
7487
7488    /**
7489     * Sets the live region mode for this view. This indicates to accessibility
7490     * services whether they should automatically notify the user about changes
7491     * to the view's content description or text, or to the content descriptions
7492     * or text of the view's children (where applicable).
7493     * <p>
7494     * For example, in a login screen with a TextView that displays an "incorrect
7495     * password" notification, that view should be marked as a live region with
7496     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7497     * <p>
7498     * To disable change notifications for this view, use
7499     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7500     * mode for most views.
7501     * <p>
7502     * To indicate that the user should be notified of changes, use
7503     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7504     * <p>
7505     * If the view's changes should interrupt ongoing speech and notify the user
7506     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7507     *
7508     * @param mode The live region mode for this view, one of:
7509     *        <ul>
7510     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7511     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7512     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7513     *        </ul>
7514     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7515     */
7516    public void setAccessibilityLiveRegion(int mode) {
7517        if (mode != getAccessibilityLiveRegion()) {
7518            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7519            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7520                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7521            notifyViewAccessibilityStateChangedIfNeeded(
7522                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7523        }
7524    }
7525
7526    /**
7527     * Gets the live region mode for this View.
7528     *
7529     * @return The live region mode for the view.
7530     *
7531     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7532     *
7533     * @see #setAccessibilityLiveRegion(int)
7534     */
7535    public int getAccessibilityLiveRegion() {
7536        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7537                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7538    }
7539
7540    /**
7541     * Sets how to determine whether this view is important for accessibility
7542     * which is if it fires accessibility events and if it is reported to
7543     * accessibility services that query the screen.
7544     *
7545     * @param mode How to determine whether this view is important for accessibility.
7546     *
7547     * @attr ref android.R.styleable#View_importantForAccessibility
7548     *
7549     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7550     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7551     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7552     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7553     */
7554    public void setImportantForAccessibility(int mode) {
7555        final int oldMode = getImportantForAccessibility();
7556        if (mode != oldMode) {
7557            // If we're moving between AUTO and another state, we might not need
7558            // to send a subtree changed notification. We'll store the computed
7559            // importance, since we'll need to check it later to make sure.
7560            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7561                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7562            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7563            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7564            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7565                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7566            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7567                notifySubtreeAccessibilityStateChangedIfNeeded();
7568            } else {
7569                notifyViewAccessibilityStateChangedIfNeeded(
7570                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7571            }
7572        }
7573    }
7574
7575    /**
7576     * Computes whether this view should be exposed for accessibility. In
7577     * general, views that are interactive or provide information are exposed
7578     * while views that serve only as containers are hidden.
7579     * <p>
7580     * If an ancestor of this view has importance
7581     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7582     * returns <code>false</code>.
7583     * <p>
7584     * Otherwise, the value is computed according to the view's
7585     * {@link #getImportantForAccessibility()} value:
7586     * <ol>
7587     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7588     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7589     * </code>
7590     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7591     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7592     * view satisfies any of the following:
7593     * <ul>
7594     * <li>Is actionable, e.g. {@link #isClickable()},
7595     * {@link #isLongClickable()}, or {@link #isFocusable()}
7596     * <li>Has an {@link AccessibilityDelegate}
7597     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7598     * {@link OnKeyListener}, etc.
7599     * <li>Is an accessibility live region, e.g.
7600     * {@link #getAccessibilityLiveRegion()} is not
7601     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7602     * </ul>
7603     * </ol>
7604     *
7605     * @return Whether the view is exposed for accessibility.
7606     * @see #setImportantForAccessibility(int)
7607     * @see #getImportantForAccessibility()
7608     */
7609    public boolean isImportantForAccessibility() {
7610        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7611                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7612        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7613                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7614            return false;
7615        }
7616
7617        // Check parent mode to ensure we're not hidden.
7618        ViewParent parent = mParent;
7619        while (parent instanceof View) {
7620            if (((View) parent).getImportantForAccessibility()
7621                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7622                return false;
7623            }
7624            parent = parent.getParent();
7625        }
7626
7627        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7628                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7629                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7630    }
7631
7632    /**
7633     * Gets the parent for accessibility purposes. Note that the parent for
7634     * accessibility is not necessary the immediate parent. It is the first
7635     * predecessor that is important for accessibility.
7636     *
7637     * @return The parent for accessibility purposes.
7638     */
7639    public ViewParent getParentForAccessibility() {
7640        if (mParent instanceof View) {
7641            View parentView = (View) mParent;
7642            if (parentView.includeForAccessibility()) {
7643                return mParent;
7644            } else {
7645                return mParent.getParentForAccessibility();
7646            }
7647        }
7648        return null;
7649    }
7650
7651    /**
7652     * Adds the children of a given View for accessibility. Since some Views are
7653     * not important for accessibility the children for accessibility are not
7654     * necessarily direct children of the view, rather they are the first level of
7655     * descendants important for accessibility.
7656     *
7657     * @param children The list of children for accessibility.
7658     */
7659    public void addChildrenForAccessibility(ArrayList<View> children) {
7660
7661    }
7662
7663    /**
7664     * Whether to regard this view for accessibility. A view is regarded for
7665     * accessibility if it is important for accessibility or the querying
7666     * accessibility service has explicitly requested that view not
7667     * important for accessibility are regarded.
7668     *
7669     * @return Whether to regard the view for accessibility.
7670     *
7671     * @hide
7672     */
7673    public boolean includeForAccessibility() {
7674        if (mAttachInfo != null) {
7675            return (mAttachInfo.mAccessibilityFetchFlags
7676                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7677                    || isImportantForAccessibility();
7678        }
7679        return false;
7680    }
7681
7682    /**
7683     * Returns whether the View is considered actionable from
7684     * accessibility perspective. Such view are important for
7685     * accessibility.
7686     *
7687     * @return True if the view is actionable for accessibility.
7688     *
7689     * @hide
7690     */
7691    public boolean isActionableForAccessibility() {
7692        return (isClickable() || isLongClickable() || isFocusable());
7693    }
7694
7695    /**
7696     * Returns whether the View has registered callbacks which makes it
7697     * important for accessibility.
7698     *
7699     * @return True if the view is actionable for accessibility.
7700     */
7701    private boolean hasListenersForAccessibility() {
7702        ListenerInfo info = getListenerInfo();
7703        return mTouchDelegate != null || info.mOnKeyListener != null
7704                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7705                || info.mOnHoverListener != null || info.mOnDragListener != null;
7706    }
7707
7708    /**
7709     * Notifies that the accessibility state of this view changed. The change
7710     * is local to this view and does not represent structural changes such
7711     * as children and parent. For example, the view became focusable. The
7712     * notification is at at most once every
7713     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7714     * to avoid unnecessary load to the system. Also once a view has a pending
7715     * notification this method is a NOP until the notification has been sent.
7716     *
7717     * @hide
7718     */
7719    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7720        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7721            return;
7722        }
7723        if (mSendViewStateChangedAccessibilityEvent == null) {
7724            mSendViewStateChangedAccessibilityEvent =
7725                    new SendViewStateChangedAccessibilityEvent();
7726        }
7727        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7728    }
7729
7730    /**
7731     * Notifies that the accessibility state of this view changed. The change
7732     * is *not* local to this view and does represent structural changes such
7733     * as children and parent. For example, the view size changed. The
7734     * notification is at at most once every
7735     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7736     * to avoid unnecessary load to the system. Also once a view has a pending
7737     * notification this method is a NOP until the notification has been sent.
7738     *
7739     * @hide
7740     */
7741    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7742        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7743            return;
7744        }
7745        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7746            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7747            if (mParent != null) {
7748                try {
7749                    mParent.notifySubtreeAccessibilityStateChanged(
7750                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7751                } catch (AbstractMethodError e) {
7752                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7753                            " does not fully implement ViewParent", e);
7754                }
7755            }
7756        }
7757    }
7758
7759    /**
7760     * Reset the flag indicating the accessibility state of the subtree rooted
7761     * at this view changed.
7762     */
7763    void resetSubtreeAccessibilityStateChanged() {
7764        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7765    }
7766
7767    /**
7768     * Performs the specified accessibility action on the view. For
7769     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7770     * <p>
7771     * If an {@link AccessibilityDelegate} has been specified via calling
7772     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7773     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7774     * is responsible for handling this call.
7775     * </p>
7776     *
7777     * @param action The action to perform.
7778     * @param arguments Optional action arguments.
7779     * @return Whether the action was performed.
7780     */
7781    public boolean performAccessibilityAction(int action, Bundle arguments) {
7782      if (mAccessibilityDelegate != null) {
7783          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7784      } else {
7785          return performAccessibilityActionInternal(action, arguments);
7786      }
7787    }
7788
7789   /**
7790    * @see #performAccessibilityAction(int, Bundle)
7791    *
7792    * Note: Called from the default {@link AccessibilityDelegate}.
7793    */
7794    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7795        switch (action) {
7796            case AccessibilityNodeInfo.ACTION_CLICK: {
7797                if (isClickable()) {
7798                    performClick();
7799                    return true;
7800                }
7801            } break;
7802            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7803                if (isLongClickable()) {
7804                    performLongClick();
7805                    return true;
7806                }
7807            } break;
7808            case AccessibilityNodeInfo.ACTION_FOCUS: {
7809                if (!hasFocus()) {
7810                    // Get out of touch mode since accessibility
7811                    // wants to move focus around.
7812                    getViewRootImpl().ensureTouchMode(false);
7813                    return requestFocus();
7814                }
7815            } break;
7816            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7817                if (hasFocus()) {
7818                    clearFocus();
7819                    return !isFocused();
7820                }
7821            } break;
7822            case AccessibilityNodeInfo.ACTION_SELECT: {
7823                if (!isSelected()) {
7824                    setSelected(true);
7825                    return isSelected();
7826                }
7827            } break;
7828            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7829                if (isSelected()) {
7830                    setSelected(false);
7831                    return !isSelected();
7832                }
7833            } break;
7834            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7835                if (!isAccessibilityFocused()) {
7836                    return requestAccessibilityFocus();
7837                }
7838            } break;
7839            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7840                if (isAccessibilityFocused()) {
7841                    clearAccessibilityFocus();
7842                    return true;
7843                }
7844            } break;
7845            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7846                if (arguments != null) {
7847                    final int granularity = arguments.getInt(
7848                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7849                    final boolean extendSelection = arguments.getBoolean(
7850                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7851                    return traverseAtGranularity(granularity, true, extendSelection);
7852                }
7853            } break;
7854            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7855                if (arguments != null) {
7856                    final int granularity = arguments.getInt(
7857                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7858                    final boolean extendSelection = arguments.getBoolean(
7859                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7860                    return traverseAtGranularity(granularity, false, extendSelection);
7861                }
7862            } break;
7863            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7864                CharSequence text = getIterableTextForAccessibility();
7865                if (text == null) {
7866                    return false;
7867                }
7868                final int start = (arguments != null) ? arguments.getInt(
7869                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7870                final int end = (arguments != null) ? arguments.getInt(
7871                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7872                // Only cursor position can be specified (selection length == 0)
7873                if ((getAccessibilitySelectionStart() != start
7874                        || getAccessibilitySelectionEnd() != end)
7875                        && (start == end)) {
7876                    setAccessibilitySelection(start, end);
7877                    notifyViewAccessibilityStateChangedIfNeeded(
7878                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7879                    return true;
7880                }
7881            } break;
7882        }
7883        return false;
7884    }
7885
7886    private boolean traverseAtGranularity(int granularity, boolean forward,
7887            boolean extendSelection) {
7888        CharSequence text = getIterableTextForAccessibility();
7889        if (text == null || text.length() == 0) {
7890            return false;
7891        }
7892        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7893        if (iterator == null) {
7894            return false;
7895        }
7896        int current = getAccessibilitySelectionEnd();
7897        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7898            current = forward ? 0 : text.length();
7899        }
7900        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7901        if (range == null) {
7902            return false;
7903        }
7904        final int segmentStart = range[0];
7905        final int segmentEnd = range[1];
7906        int selectionStart;
7907        int selectionEnd;
7908        if (extendSelection && isAccessibilitySelectionExtendable()) {
7909            selectionStart = getAccessibilitySelectionStart();
7910            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7911                selectionStart = forward ? segmentStart : segmentEnd;
7912            }
7913            selectionEnd = forward ? segmentEnd : segmentStart;
7914        } else {
7915            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7916        }
7917        setAccessibilitySelection(selectionStart, selectionEnd);
7918        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7919                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7920        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7921        return true;
7922    }
7923
7924    /**
7925     * Gets the text reported for accessibility purposes.
7926     *
7927     * @return The accessibility text.
7928     *
7929     * @hide
7930     */
7931    public CharSequence getIterableTextForAccessibility() {
7932        return getContentDescription();
7933    }
7934
7935    /**
7936     * Gets whether accessibility selection can be extended.
7937     *
7938     * @return If selection is extensible.
7939     *
7940     * @hide
7941     */
7942    public boolean isAccessibilitySelectionExtendable() {
7943        return false;
7944    }
7945
7946    /**
7947     * @hide
7948     */
7949    public int getAccessibilitySelectionStart() {
7950        return mAccessibilityCursorPosition;
7951    }
7952
7953    /**
7954     * @hide
7955     */
7956    public int getAccessibilitySelectionEnd() {
7957        return getAccessibilitySelectionStart();
7958    }
7959
7960    /**
7961     * @hide
7962     */
7963    public void setAccessibilitySelection(int start, int end) {
7964        if (start ==  end && end == mAccessibilityCursorPosition) {
7965            return;
7966        }
7967        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7968            mAccessibilityCursorPosition = start;
7969        } else {
7970            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7971        }
7972        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7973    }
7974
7975    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7976            int fromIndex, int toIndex) {
7977        if (mParent == null) {
7978            return;
7979        }
7980        AccessibilityEvent event = AccessibilityEvent.obtain(
7981                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7982        onInitializeAccessibilityEvent(event);
7983        onPopulateAccessibilityEvent(event);
7984        event.setFromIndex(fromIndex);
7985        event.setToIndex(toIndex);
7986        event.setAction(action);
7987        event.setMovementGranularity(granularity);
7988        mParent.requestSendAccessibilityEvent(this, event);
7989    }
7990
7991    /**
7992     * @hide
7993     */
7994    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7995        switch (granularity) {
7996            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7997                CharSequence text = getIterableTextForAccessibility();
7998                if (text != null && text.length() > 0) {
7999                    CharacterTextSegmentIterator iterator =
8000                        CharacterTextSegmentIterator.getInstance(
8001                                mContext.getResources().getConfiguration().locale);
8002                    iterator.initialize(text.toString());
8003                    return iterator;
8004                }
8005            } break;
8006            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8007                CharSequence text = getIterableTextForAccessibility();
8008                if (text != null && text.length() > 0) {
8009                    WordTextSegmentIterator iterator =
8010                        WordTextSegmentIterator.getInstance(
8011                                mContext.getResources().getConfiguration().locale);
8012                    iterator.initialize(text.toString());
8013                    return iterator;
8014                }
8015            } break;
8016            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8017                CharSequence text = getIterableTextForAccessibility();
8018                if (text != null && text.length() > 0) {
8019                    ParagraphTextSegmentIterator iterator =
8020                        ParagraphTextSegmentIterator.getInstance();
8021                    iterator.initialize(text.toString());
8022                    return iterator;
8023                }
8024            } break;
8025        }
8026        return null;
8027    }
8028
8029    /**
8030     * @hide
8031     */
8032    public void dispatchStartTemporaryDetach() {
8033        onStartTemporaryDetach();
8034    }
8035
8036    /**
8037     * This is called when a container is going to temporarily detach a child, with
8038     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8039     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8040     * {@link #onDetachedFromWindow()} when the container is done.
8041     */
8042    public void onStartTemporaryDetach() {
8043        removeUnsetPressCallback();
8044        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8045    }
8046
8047    /**
8048     * @hide
8049     */
8050    public void dispatchFinishTemporaryDetach() {
8051        onFinishTemporaryDetach();
8052    }
8053
8054    /**
8055     * Called after {@link #onStartTemporaryDetach} when the container is done
8056     * changing the view.
8057     */
8058    public void onFinishTemporaryDetach() {
8059    }
8060
8061    /**
8062     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8063     * for this view's window.  Returns null if the view is not currently attached
8064     * to the window.  Normally you will not need to use this directly, but
8065     * just use the standard high-level event callbacks like
8066     * {@link #onKeyDown(int, KeyEvent)}.
8067     */
8068    public KeyEvent.DispatcherState getKeyDispatcherState() {
8069        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8070    }
8071
8072    /**
8073     * Dispatch a key event before it is processed by any input method
8074     * associated with the view hierarchy.  This can be used to intercept
8075     * key events in special situations before the IME consumes them; a
8076     * typical example would be handling the BACK key to update the application's
8077     * UI instead of allowing the IME to see it and close itself.
8078     *
8079     * @param event The key event to be dispatched.
8080     * @return True if the event was handled, false otherwise.
8081     */
8082    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8083        return onKeyPreIme(event.getKeyCode(), event);
8084    }
8085
8086    /**
8087     * Dispatch a key event to the next view on the focus path. This path runs
8088     * from the top of the view tree down to the currently focused view. If this
8089     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8090     * the next node down the focus path. This method also fires any key
8091     * listeners.
8092     *
8093     * @param event The key event to be dispatched.
8094     * @return True if the event was handled, false otherwise.
8095     */
8096    public boolean dispatchKeyEvent(KeyEvent event) {
8097        if (mInputEventConsistencyVerifier != null) {
8098            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8099        }
8100
8101        // Give any attached key listener a first crack at the event.
8102        //noinspection SimplifiableIfStatement
8103        ListenerInfo li = mListenerInfo;
8104        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8105                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8106            return true;
8107        }
8108
8109        if (event.dispatch(this, mAttachInfo != null
8110                ? mAttachInfo.mKeyDispatchState : null, this)) {
8111            return true;
8112        }
8113
8114        if (mInputEventConsistencyVerifier != null) {
8115            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8116        }
8117        return false;
8118    }
8119
8120    /**
8121     * Dispatches a key shortcut event.
8122     *
8123     * @param event The key event to be dispatched.
8124     * @return True if the event was handled by the view, false otherwise.
8125     */
8126    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8127        return onKeyShortcut(event.getKeyCode(), event);
8128    }
8129
8130    /**
8131     * Pass the touch screen motion event down to the target view, or this
8132     * view if it is the target.
8133     *
8134     * @param event The motion event to be dispatched.
8135     * @return True if the event was handled by the view, false otherwise.
8136     */
8137    public boolean dispatchTouchEvent(MotionEvent event) {
8138        boolean result = false;
8139
8140        if (mInputEventConsistencyVerifier != null) {
8141            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8142        }
8143
8144        final int actionMasked = event.getActionMasked();
8145        if (actionMasked == MotionEvent.ACTION_DOWN) {
8146            // Defensive cleanup for new gesture
8147            stopNestedScroll();
8148        }
8149
8150        if (onFilterTouchEventForSecurity(event)) {
8151            //noinspection SimplifiableIfStatement
8152            ListenerInfo li = mListenerInfo;
8153            if (li != null && li.mOnTouchListener != null
8154                    && (mViewFlags & ENABLED_MASK) == ENABLED
8155                    && li.mOnTouchListener.onTouch(this, event)) {
8156                result = true;
8157            }
8158
8159            if (!result && onTouchEvent(event)) {
8160                result = true;
8161            }
8162        }
8163
8164        if (!result && mInputEventConsistencyVerifier != null) {
8165            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8166        }
8167
8168        // Clean up after nested scrolls if this is the end of a gesture;
8169        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8170        // of the gesture.
8171        if (actionMasked == MotionEvent.ACTION_UP ||
8172                actionMasked == MotionEvent.ACTION_CANCEL ||
8173                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8174            stopNestedScroll();
8175        }
8176
8177        return result;
8178    }
8179
8180    /**
8181     * Filter the touch event to apply security policies.
8182     *
8183     * @param event The motion event to be filtered.
8184     * @return True if the event should be dispatched, false if the event should be dropped.
8185     *
8186     * @see #getFilterTouchesWhenObscured
8187     */
8188    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8189        //noinspection RedundantIfStatement
8190        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8191                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8192            // Window is obscured, drop this touch.
8193            return false;
8194        }
8195        return true;
8196    }
8197
8198    /**
8199     * Pass a trackball motion event down to the focused view.
8200     *
8201     * @param event The motion event to be dispatched.
8202     * @return True if the event was handled by the view, false otherwise.
8203     */
8204    public boolean dispatchTrackballEvent(MotionEvent event) {
8205        if (mInputEventConsistencyVerifier != null) {
8206            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8207        }
8208
8209        return onTrackballEvent(event);
8210    }
8211
8212    /**
8213     * Dispatch a generic motion event.
8214     * <p>
8215     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8216     * are delivered to the view under the pointer.  All other generic motion events are
8217     * delivered to the focused view.  Hover events are handled specially and are delivered
8218     * to {@link #onHoverEvent(MotionEvent)}.
8219     * </p>
8220     *
8221     * @param event The motion event to be dispatched.
8222     * @return True if the event was handled by the view, false otherwise.
8223     */
8224    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8225        if (mInputEventConsistencyVerifier != null) {
8226            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8227        }
8228
8229        final int source = event.getSource();
8230        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8231            final int action = event.getAction();
8232            if (action == MotionEvent.ACTION_HOVER_ENTER
8233                    || action == MotionEvent.ACTION_HOVER_MOVE
8234                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8235                if (dispatchHoverEvent(event)) {
8236                    return true;
8237                }
8238            } else if (dispatchGenericPointerEvent(event)) {
8239                return true;
8240            }
8241        } else if (dispatchGenericFocusedEvent(event)) {
8242            return true;
8243        }
8244
8245        if (dispatchGenericMotionEventInternal(event)) {
8246            return true;
8247        }
8248
8249        if (mInputEventConsistencyVerifier != null) {
8250            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8251        }
8252        return false;
8253    }
8254
8255    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8256        //noinspection SimplifiableIfStatement
8257        ListenerInfo li = mListenerInfo;
8258        if (li != null && li.mOnGenericMotionListener != null
8259                && (mViewFlags & ENABLED_MASK) == ENABLED
8260                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8261            return true;
8262        }
8263
8264        if (onGenericMotionEvent(event)) {
8265            return true;
8266        }
8267
8268        if (mInputEventConsistencyVerifier != null) {
8269            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8270        }
8271        return false;
8272    }
8273
8274    /**
8275     * Dispatch a hover event.
8276     * <p>
8277     * Do not call this method directly.
8278     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8279     * </p>
8280     *
8281     * @param event The motion event to be dispatched.
8282     * @return True if the event was handled by the view, false otherwise.
8283     */
8284    protected boolean dispatchHoverEvent(MotionEvent event) {
8285        ListenerInfo li = mListenerInfo;
8286        //noinspection SimplifiableIfStatement
8287        if (li != null && li.mOnHoverListener != null
8288                && (mViewFlags & ENABLED_MASK) == ENABLED
8289                && li.mOnHoverListener.onHover(this, event)) {
8290            return true;
8291        }
8292
8293        return onHoverEvent(event);
8294    }
8295
8296    /**
8297     * Returns true if the view has a child to which it has recently sent
8298     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8299     * it does not have a hovered child, then it must be the innermost hovered view.
8300     * @hide
8301     */
8302    protected boolean hasHoveredChild() {
8303        return false;
8304    }
8305
8306    /**
8307     * Dispatch a generic motion event to the view under the first pointer.
8308     * <p>
8309     * Do not call this method directly.
8310     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8311     * </p>
8312     *
8313     * @param event The motion event to be dispatched.
8314     * @return True if the event was handled by the view, false otherwise.
8315     */
8316    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8317        return false;
8318    }
8319
8320    /**
8321     * Dispatch a generic motion event to the currently focused view.
8322     * <p>
8323     * Do not call this method directly.
8324     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8325     * </p>
8326     *
8327     * @param event The motion event to be dispatched.
8328     * @return True if the event was handled by the view, false otherwise.
8329     */
8330    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8331        return false;
8332    }
8333
8334    /**
8335     * Dispatch a pointer event.
8336     * <p>
8337     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8338     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8339     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8340     * and should not be expected to handle other pointing device features.
8341     * </p>
8342     *
8343     * @param event The motion event to be dispatched.
8344     * @return True if the event was handled by the view, false otherwise.
8345     * @hide
8346     */
8347    public final boolean dispatchPointerEvent(MotionEvent event) {
8348        if (event.isTouchEvent()) {
8349            return dispatchTouchEvent(event);
8350        } else {
8351            return dispatchGenericMotionEvent(event);
8352        }
8353    }
8354
8355    /**
8356     * Called when the window containing this view gains or loses window focus.
8357     * ViewGroups should override to route to their children.
8358     *
8359     * @param hasFocus True if the window containing this view now has focus,
8360     *        false otherwise.
8361     */
8362    public void dispatchWindowFocusChanged(boolean hasFocus) {
8363        onWindowFocusChanged(hasFocus);
8364    }
8365
8366    /**
8367     * Called when the window containing this view gains or loses focus.  Note
8368     * that this is separate from view focus: to receive key events, both
8369     * your view and its window must have focus.  If a window is displayed
8370     * on top of yours that takes input focus, then your own window will lose
8371     * focus but the view focus will remain unchanged.
8372     *
8373     * @param hasWindowFocus True if the window containing this view now has
8374     *        focus, false otherwise.
8375     */
8376    public void onWindowFocusChanged(boolean hasWindowFocus) {
8377        InputMethodManager imm = InputMethodManager.peekInstance();
8378        if (!hasWindowFocus) {
8379            if (isPressed()) {
8380                setPressed(false);
8381            }
8382            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8383                imm.focusOut(this);
8384            }
8385            removeLongPressCallback();
8386            removeTapCallback();
8387            onFocusLost();
8388        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8389            imm.focusIn(this);
8390        }
8391        refreshDrawableState();
8392    }
8393
8394    /**
8395     * Returns true if this view is in a window that currently has window focus.
8396     * Note that this is not the same as the view itself having focus.
8397     *
8398     * @return True if this view is in a window that currently has window focus.
8399     */
8400    public boolean hasWindowFocus() {
8401        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8402    }
8403
8404    /**
8405     * Dispatch a view visibility change down the view hierarchy.
8406     * ViewGroups should override to route to their children.
8407     * @param changedView The view whose visibility changed. Could be 'this' or
8408     * an ancestor view.
8409     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8410     * {@link #INVISIBLE} or {@link #GONE}.
8411     */
8412    protected void dispatchVisibilityChanged(@NonNull View changedView,
8413            @Visibility int visibility) {
8414        onVisibilityChanged(changedView, visibility);
8415    }
8416
8417    /**
8418     * Called when the visibility of the view or an ancestor of the view is changed.
8419     * @param changedView The view whose visibility changed. Could be 'this' or
8420     * an ancestor view.
8421     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8422     * {@link #INVISIBLE} or {@link #GONE}.
8423     */
8424    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8425        if (visibility == VISIBLE) {
8426            if (mAttachInfo != null) {
8427                initialAwakenScrollBars();
8428            } else {
8429                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8430            }
8431        }
8432    }
8433
8434    /**
8435     * Dispatch a hint about whether this view is displayed. For instance, when
8436     * a View moves out of the screen, it might receives a display hint indicating
8437     * the view is not displayed. Applications should not <em>rely</em> on this hint
8438     * as there is no guarantee that they will receive one.
8439     *
8440     * @param hint A hint about whether or not this view is displayed:
8441     * {@link #VISIBLE} or {@link #INVISIBLE}.
8442     */
8443    public void dispatchDisplayHint(@Visibility int hint) {
8444        onDisplayHint(hint);
8445    }
8446
8447    /**
8448     * Gives this view a hint about whether is displayed or not. For instance, when
8449     * a View moves out of the screen, it might receives a display hint indicating
8450     * the view is not displayed. Applications should not <em>rely</em> on this hint
8451     * as there is no guarantee that they will receive one.
8452     *
8453     * @param hint A hint about whether or not this view is displayed:
8454     * {@link #VISIBLE} or {@link #INVISIBLE}.
8455     */
8456    protected void onDisplayHint(@Visibility int hint) {
8457    }
8458
8459    /**
8460     * Dispatch a window visibility change down the view hierarchy.
8461     * ViewGroups should override to route to their children.
8462     *
8463     * @param visibility The new visibility of the window.
8464     *
8465     * @see #onWindowVisibilityChanged(int)
8466     */
8467    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8468        onWindowVisibilityChanged(visibility);
8469    }
8470
8471    /**
8472     * Called when the window containing has change its visibility
8473     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8474     * that this tells you whether or not your window is being made visible
8475     * to the window manager; this does <em>not</em> tell you whether or not
8476     * your window is obscured by other windows on the screen, even if it
8477     * is itself visible.
8478     *
8479     * @param visibility The new visibility of the window.
8480     */
8481    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8482        if (visibility == VISIBLE) {
8483            initialAwakenScrollBars();
8484        }
8485    }
8486
8487    /**
8488     * Returns the current visibility of the window this view is attached to
8489     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8490     *
8491     * @return Returns the current visibility of the view's window.
8492     */
8493    @Visibility
8494    public int getWindowVisibility() {
8495        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8496    }
8497
8498    /**
8499     * Retrieve the overall visible display size in which the window this view is
8500     * attached to has been positioned in.  This takes into account screen
8501     * decorations above the window, for both cases where the window itself
8502     * is being position inside of them or the window is being placed under
8503     * then and covered insets are used for the window to position its content
8504     * inside.  In effect, this tells you the available area where content can
8505     * be placed and remain visible to users.
8506     *
8507     * <p>This function requires an IPC back to the window manager to retrieve
8508     * the requested information, so should not be used in performance critical
8509     * code like drawing.
8510     *
8511     * @param outRect Filled in with the visible display frame.  If the view
8512     * is not attached to a window, this is simply the raw display size.
8513     */
8514    public void getWindowVisibleDisplayFrame(Rect outRect) {
8515        if (mAttachInfo != null) {
8516            try {
8517                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8518            } catch (RemoteException e) {
8519                return;
8520            }
8521            // XXX This is really broken, and probably all needs to be done
8522            // in the window manager, and we need to know more about whether
8523            // we want the area behind or in front of the IME.
8524            final Rect insets = mAttachInfo.mVisibleInsets;
8525            outRect.left += insets.left;
8526            outRect.top += insets.top;
8527            outRect.right -= insets.right;
8528            outRect.bottom -= insets.bottom;
8529            return;
8530        }
8531        // The view is not attached to a display so we don't have a context.
8532        // Make a best guess about the display size.
8533        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8534        d.getRectSize(outRect);
8535    }
8536
8537    /**
8538     * Dispatch a notification about a resource configuration change down
8539     * the view hierarchy.
8540     * ViewGroups should override to route to their children.
8541     *
8542     * @param newConfig The new resource configuration.
8543     *
8544     * @see #onConfigurationChanged(android.content.res.Configuration)
8545     */
8546    public void dispatchConfigurationChanged(Configuration newConfig) {
8547        onConfigurationChanged(newConfig);
8548    }
8549
8550    /**
8551     * Called when the current configuration of the resources being used
8552     * by the application have changed.  You can use this to decide when
8553     * to reload resources that can changed based on orientation and other
8554     * configuration characterstics.  You only need to use this if you are
8555     * not relying on the normal {@link android.app.Activity} mechanism of
8556     * recreating the activity instance upon a configuration change.
8557     *
8558     * @param newConfig The new resource configuration.
8559     */
8560    protected void onConfigurationChanged(Configuration newConfig) {
8561    }
8562
8563    /**
8564     * Private function to aggregate all per-view attributes in to the view
8565     * root.
8566     */
8567    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8568        performCollectViewAttributes(attachInfo, visibility);
8569    }
8570
8571    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8572        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8573            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8574                attachInfo.mKeepScreenOn = true;
8575            }
8576            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8577            ListenerInfo li = mListenerInfo;
8578            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8579                attachInfo.mHasSystemUiListeners = true;
8580            }
8581        }
8582    }
8583
8584    void needGlobalAttributesUpdate(boolean force) {
8585        final AttachInfo ai = mAttachInfo;
8586        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8587            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8588                    || ai.mHasSystemUiListeners) {
8589                ai.mRecomputeGlobalAttributes = true;
8590            }
8591        }
8592    }
8593
8594    /**
8595     * Returns whether the device is currently in touch mode.  Touch mode is entered
8596     * once the user begins interacting with the device by touch, and affects various
8597     * things like whether focus is always visible to the user.
8598     *
8599     * @return Whether the device is in touch mode.
8600     */
8601    @ViewDebug.ExportedProperty
8602    public boolean isInTouchMode() {
8603        if (mAttachInfo != null) {
8604            return mAttachInfo.mInTouchMode;
8605        } else {
8606            return ViewRootImpl.isInTouchMode();
8607        }
8608    }
8609
8610    /**
8611     * Returns the context the view is running in, through which it can
8612     * access the current theme, resources, etc.
8613     *
8614     * @return The view's Context.
8615     */
8616    @ViewDebug.CapturedViewProperty
8617    public final Context getContext() {
8618        return mContext;
8619    }
8620
8621    /**
8622     * Handle a key event before it is processed by any input method
8623     * associated with the view hierarchy.  This can be used to intercept
8624     * key events in special situations before the IME consumes them; a
8625     * typical example would be handling the BACK key to update the application's
8626     * UI instead of allowing the IME to see it and close itself.
8627     *
8628     * @param keyCode The value in event.getKeyCode().
8629     * @param event Description of the key event.
8630     * @return If you handled the event, return true. If you want to allow the
8631     *         event to be handled by the next receiver, return false.
8632     */
8633    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8634        return false;
8635    }
8636
8637    /**
8638     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8639     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8640     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8641     * is released, if the view is enabled and clickable.
8642     *
8643     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8644     * although some may elect to do so in some situations. Do not rely on this to
8645     * catch software key presses.
8646     *
8647     * @param keyCode A key code that represents the button pressed, from
8648     *                {@link android.view.KeyEvent}.
8649     * @param event   The KeyEvent object that defines the button action.
8650     */
8651    public boolean onKeyDown(int keyCode, KeyEvent event) {
8652        boolean result = false;
8653
8654        if (KeyEvent.isConfirmKey(keyCode)) {
8655            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8656                return true;
8657            }
8658            // Long clickable items don't necessarily have to be clickable
8659            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8660                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8661                    (event.getRepeatCount() == 0)) {
8662                setPressed(true);
8663                checkForLongClick(0);
8664                return true;
8665            }
8666        }
8667        return result;
8668    }
8669
8670    /**
8671     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8672     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8673     * the event).
8674     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8675     * although some may elect to do so in some situations. Do not rely on this to
8676     * catch software key presses.
8677     */
8678    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8679        return false;
8680    }
8681
8682    /**
8683     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8684     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8685     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8686     * {@link KeyEvent#KEYCODE_ENTER} is released.
8687     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8688     * although some may elect to do so in some situations. Do not rely on this to
8689     * catch software key presses.
8690     *
8691     * @param keyCode A key code that represents the button pressed, from
8692     *                {@link android.view.KeyEvent}.
8693     * @param event   The KeyEvent object that defines the button action.
8694     */
8695    public boolean onKeyUp(int keyCode, KeyEvent event) {
8696        if (KeyEvent.isConfirmKey(keyCode)) {
8697            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8698                return true;
8699            }
8700            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8701                setPressed(false);
8702
8703                if (!mHasPerformedLongPress) {
8704                    // This is a tap, so remove the longpress check
8705                    removeLongPressCallback();
8706                    return performClick();
8707                }
8708            }
8709        }
8710        return false;
8711    }
8712
8713    /**
8714     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8715     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8716     * the event).
8717     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8718     * although some may elect to do so in some situations. Do not rely on this to
8719     * catch software key presses.
8720     *
8721     * @param keyCode     A key code that represents the button pressed, from
8722     *                    {@link android.view.KeyEvent}.
8723     * @param repeatCount The number of times the action was made.
8724     * @param event       The KeyEvent object that defines the button action.
8725     */
8726    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8727        return false;
8728    }
8729
8730    /**
8731     * Called on the focused view when a key shortcut event is not handled.
8732     * Override this method to implement local key shortcuts for the View.
8733     * Key shortcuts can also be implemented by setting the
8734     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8735     *
8736     * @param keyCode The value in event.getKeyCode().
8737     * @param event Description of the key event.
8738     * @return If you handled the event, return true. If you want to allow the
8739     *         event to be handled by the next receiver, return false.
8740     */
8741    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8742        return false;
8743    }
8744
8745    /**
8746     * Check whether the called view is a text editor, in which case it
8747     * would make sense to automatically display a soft input window for
8748     * it.  Subclasses should override this if they implement
8749     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8750     * a call on that method would return a non-null InputConnection, and
8751     * they are really a first-class editor that the user would normally
8752     * start typing on when the go into a window containing your view.
8753     *
8754     * <p>The default implementation always returns false.  This does
8755     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8756     * will not be called or the user can not otherwise perform edits on your
8757     * view; it is just a hint to the system that this is not the primary
8758     * purpose of this view.
8759     *
8760     * @return Returns true if this view is a text editor, else false.
8761     */
8762    public boolean onCheckIsTextEditor() {
8763        return false;
8764    }
8765
8766    /**
8767     * Create a new InputConnection for an InputMethod to interact
8768     * with the view.  The default implementation returns null, since it doesn't
8769     * support input methods.  You can override this to implement such support.
8770     * This is only needed for views that take focus and text input.
8771     *
8772     * <p>When implementing this, you probably also want to implement
8773     * {@link #onCheckIsTextEditor()} to indicate you will return a
8774     * non-null InputConnection.</p>
8775     *
8776     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8777     * object correctly and in its entirety, so that the connected IME can rely
8778     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8779     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8780     * must be filled in with the correct cursor position for IMEs to work correctly
8781     * with your application.</p>
8782     *
8783     * @param outAttrs Fill in with attribute information about the connection.
8784     */
8785    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8786        return null;
8787    }
8788
8789    /**
8790     * Called by the {@link android.view.inputmethod.InputMethodManager}
8791     * when a view who is not the current
8792     * input connection target is trying to make a call on the manager.  The
8793     * default implementation returns false; you can override this to return
8794     * true for certain views if you are performing InputConnection proxying
8795     * to them.
8796     * @param view The View that is making the InputMethodManager call.
8797     * @return Return true to allow the call, false to reject.
8798     */
8799    public boolean checkInputConnectionProxy(View view) {
8800        return false;
8801    }
8802
8803    /**
8804     * Show the context menu for this view. It is not safe to hold on to the
8805     * menu after returning from this method.
8806     *
8807     * You should normally not overload this method. Overload
8808     * {@link #onCreateContextMenu(ContextMenu)} or define an
8809     * {@link OnCreateContextMenuListener} to add items to the context menu.
8810     *
8811     * @param menu The context menu to populate
8812     */
8813    public void createContextMenu(ContextMenu menu) {
8814        ContextMenuInfo menuInfo = getContextMenuInfo();
8815
8816        // Sets the current menu info so all items added to menu will have
8817        // my extra info set.
8818        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8819
8820        onCreateContextMenu(menu);
8821        ListenerInfo li = mListenerInfo;
8822        if (li != null && li.mOnCreateContextMenuListener != null) {
8823            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8824        }
8825
8826        // Clear the extra information so subsequent items that aren't mine don't
8827        // have my extra info.
8828        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8829
8830        if (mParent != null) {
8831            mParent.createContextMenu(menu);
8832        }
8833    }
8834
8835    /**
8836     * Views should implement this if they have extra information to associate
8837     * with the context menu. The return result is supplied as a parameter to
8838     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8839     * callback.
8840     *
8841     * @return Extra information about the item for which the context menu
8842     *         should be shown. This information will vary across different
8843     *         subclasses of View.
8844     */
8845    protected ContextMenuInfo getContextMenuInfo() {
8846        return null;
8847    }
8848
8849    /**
8850     * Views should implement this if the view itself is going to add items to
8851     * the context menu.
8852     *
8853     * @param menu the context menu to populate
8854     */
8855    protected void onCreateContextMenu(ContextMenu menu) {
8856    }
8857
8858    /**
8859     * Implement this method to handle trackball motion events.  The
8860     * <em>relative</em> movement of the trackball since the last event
8861     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8862     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8863     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8864     * they will often be fractional values, representing the more fine-grained
8865     * movement information available from a trackball).
8866     *
8867     * @param event The motion event.
8868     * @return True if the event was handled, false otherwise.
8869     */
8870    public boolean onTrackballEvent(MotionEvent event) {
8871        return false;
8872    }
8873
8874    /**
8875     * Implement this method to handle generic motion events.
8876     * <p>
8877     * Generic motion events describe joystick movements, mouse hovers, track pad
8878     * touches, scroll wheel movements and other input events.  The
8879     * {@link MotionEvent#getSource() source} of the motion event specifies
8880     * the class of input that was received.  Implementations of this method
8881     * must examine the bits in the source before processing the event.
8882     * The following code example shows how this is done.
8883     * </p><p>
8884     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8885     * are delivered to the view under the pointer.  All other generic motion events are
8886     * delivered to the focused view.
8887     * </p>
8888     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8889     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8890     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8891     *             // process the joystick movement...
8892     *             return true;
8893     *         }
8894     *     }
8895     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8896     *         switch (event.getAction()) {
8897     *             case MotionEvent.ACTION_HOVER_MOVE:
8898     *                 // process the mouse hover movement...
8899     *                 return true;
8900     *             case MotionEvent.ACTION_SCROLL:
8901     *                 // process the scroll wheel movement...
8902     *                 return true;
8903     *         }
8904     *     }
8905     *     return super.onGenericMotionEvent(event);
8906     * }</pre>
8907     *
8908     * @param event The generic motion event being processed.
8909     * @return True if the event was handled, false otherwise.
8910     */
8911    public boolean onGenericMotionEvent(MotionEvent event) {
8912        return false;
8913    }
8914
8915    /**
8916     * Implement this method to handle hover events.
8917     * <p>
8918     * This method is called whenever a pointer is hovering into, over, or out of the
8919     * bounds of a view and the view is not currently being touched.
8920     * Hover events are represented as pointer events with action
8921     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8922     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8923     * </p>
8924     * <ul>
8925     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8926     * when the pointer enters the bounds of the view.</li>
8927     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8928     * when the pointer has already entered the bounds of the view and has moved.</li>
8929     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8930     * when the pointer has exited the bounds of the view or when the pointer is
8931     * about to go down due to a button click, tap, or similar user action that
8932     * causes the view to be touched.</li>
8933     * </ul>
8934     * <p>
8935     * The view should implement this method to return true to indicate that it is
8936     * handling the hover event, such as by changing its drawable state.
8937     * </p><p>
8938     * The default implementation calls {@link #setHovered} to update the hovered state
8939     * of the view when a hover enter or hover exit event is received, if the view
8940     * is enabled and is clickable.  The default implementation also sends hover
8941     * accessibility events.
8942     * </p>
8943     *
8944     * @param event The motion event that describes the hover.
8945     * @return True if the view handled the hover event.
8946     *
8947     * @see #isHovered
8948     * @see #setHovered
8949     * @see #onHoverChanged
8950     */
8951    public boolean onHoverEvent(MotionEvent event) {
8952        // The root view may receive hover (or touch) events that are outside the bounds of
8953        // the window.  This code ensures that we only send accessibility events for
8954        // hovers that are actually within the bounds of the root view.
8955        final int action = event.getActionMasked();
8956        if (!mSendingHoverAccessibilityEvents) {
8957            if ((action == MotionEvent.ACTION_HOVER_ENTER
8958                    || action == MotionEvent.ACTION_HOVER_MOVE)
8959                    && !hasHoveredChild()
8960                    && pointInView(event.getX(), event.getY())) {
8961                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8962                mSendingHoverAccessibilityEvents = true;
8963            }
8964        } else {
8965            if (action == MotionEvent.ACTION_HOVER_EXIT
8966                    || (action == MotionEvent.ACTION_MOVE
8967                            && !pointInView(event.getX(), event.getY()))) {
8968                mSendingHoverAccessibilityEvents = false;
8969                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8970            }
8971        }
8972
8973        if (isHoverable()) {
8974            switch (action) {
8975                case MotionEvent.ACTION_HOVER_ENTER:
8976                    setHovered(true);
8977                    break;
8978                case MotionEvent.ACTION_HOVER_EXIT:
8979                    setHovered(false);
8980                    break;
8981            }
8982
8983            // Dispatch the event to onGenericMotionEvent before returning true.
8984            // This is to provide compatibility with existing applications that
8985            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8986            // break because of the new default handling for hoverable views
8987            // in onHoverEvent.
8988            // Note that onGenericMotionEvent will be called by default when
8989            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8990            dispatchGenericMotionEventInternal(event);
8991            // The event was already handled by calling setHovered(), so always
8992            // return true.
8993            return true;
8994        }
8995
8996        return false;
8997    }
8998
8999    /**
9000     * Returns true if the view should handle {@link #onHoverEvent}
9001     * by calling {@link #setHovered} to change its hovered state.
9002     *
9003     * @return True if the view is hoverable.
9004     */
9005    private boolean isHoverable() {
9006        final int viewFlags = mViewFlags;
9007        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9008            return false;
9009        }
9010
9011        return (viewFlags & CLICKABLE) == CLICKABLE
9012                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9013    }
9014
9015    /**
9016     * Returns true if the view is currently hovered.
9017     *
9018     * @return True if the view is currently hovered.
9019     *
9020     * @see #setHovered
9021     * @see #onHoverChanged
9022     */
9023    @ViewDebug.ExportedProperty
9024    public boolean isHovered() {
9025        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9026    }
9027
9028    /**
9029     * Sets whether the view is currently hovered.
9030     * <p>
9031     * Calling this method also changes the drawable state of the view.  This
9032     * enables the view to react to hover by using different drawable resources
9033     * to change its appearance.
9034     * </p><p>
9035     * The {@link #onHoverChanged} method is called when the hovered state changes.
9036     * </p>
9037     *
9038     * @param hovered True if the view is hovered.
9039     *
9040     * @see #isHovered
9041     * @see #onHoverChanged
9042     */
9043    public void setHovered(boolean hovered) {
9044        if (hovered) {
9045            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9046                mPrivateFlags |= PFLAG_HOVERED;
9047                refreshDrawableState();
9048                onHoverChanged(true);
9049            }
9050        } else {
9051            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9052                mPrivateFlags &= ~PFLAG_HOVERED;
9053                refreshDrawableState();
9054                onHoverChanged(false);
9055            }
9056        }
9057    }
9058
9059    /**
9060     * Implement this method to handle hover state changes.
9061     * <p>
9062     * This method is called whenever the hover state changes as a result of a
9063     * call to {@link #setHovered}.
9064     * </p>
9065     *
9066     * @param hovered The current hover state, as returned by {@link #isHovered}.
9067     *
9068     * @see #isHovered
9069     * @see #setHovered
9070     */
9071    public void onHoverChanged(boolean hovered) {
9072    }
9073
9074    /**
9075     * Implement this method to handle touch screen motion events.
9076     * <p>
9077     * If this method is used to detect click actions, it is recommended that
9078     * the actions be performed by implementing and calling
9079     * {@link #performClick()}. This will ensure consistent system behavior,
9080     * including:
9081     * <ul>
9082     * <li>obeying click sound preferences
9083     * <li>dispatching OnClickListener calls
9084     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9085     * accessibility features are enabled
9086     * </ul>
9087     *
9088     * @param event The motion event.
9089     * @return True if the event was handled, false otherwise.
9090     */
9091    public boolean onTouchEvent(MotionEvent event) {
9092        final float x = event.getX();
9093        final float y = event.getY();
9094        final int viewFlags = mViewFlags;
9095
9096        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9097            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9098                setPressed(false);
9099            }
9100            // A disabled view that is clickable still consumes the touch
9101            // events, it just doesn't respond to them.
9102            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9103                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9104        }
9105
9106        if (mTouchDelegate != null) {
9107            if (mTouchDelegate.onTouchEvent(event)) {
9108                return true;
9109            }
9110        }
9111
9112        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9113                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9114            switch (event.getAction()) {
9115                case MotionEvent.ACTION_UP:
9116                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9117                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9118                        // take focus if we don't have it already and we should in
9119                        // touch mode.
9120                        boolean focusTaken = false;
9121                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9122                            focusTaken = requestFocus();
9123                        }
9124
9125                        if (prepressed) {
9126                            // The button is being released before we actually
9127                            // showed it as pressed.  Make it show the pressed
9128                            // state now (before scheduling the click) to ensure
9129                            // the user sees it.
9130                            setPressed(true, x, y);
9131                       }
9132
9133                        if (!mHasPerformedLongPress) {
9134                            // This is a tap, so remove the longpress check
9135                            removeLongPressCallback();
9136
9137                            // Only perform take click actions if we were in the pressed state
9138                            if (!focusTaken) {
9139                                // Use a Runnable and post this rather than calling
9140                                // performClick directly. This lets other visual state
9141                                // of the view update before click actions start.
9142                                if (mPerformClick == null) {
9143                                    mPerformClick = new PerformClick();
9144                                }
9145                                if (!post(mPerformClick)) {
9146                                    performClick();
9147                                }
9148                            }
9149                        }
9150
9151                        if (mUnsetPressedState == null) {
9152                            mUnsetPressedState = new UnsetPressedState();
9153                        }
9154
9155                        if (prepressed) {
9156                            postDelayed(mUnsetPressedState,
9157                                    ViewConfiguration.getPressedStateDuration());
9158                        } else if (!post(mUnsetPressedState)) {
9159                            // If the post failed, unpress right now
9160                            mUnsetPressedState.run();
9161                        }
9162
9163                        removeTapCallback();
9164                    }
9165                    break;
9166
9167                case MotionEvent.ACTION_DOWN:
9168                    mHasPerformedLongPress = false;
9169
9170                    if (performButtonActionOnTouchDown(event)) {
9171                        break;
9172                    }
9173
9174                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9175                    boolean isInScrollingContainer = isInScrollingContainer();
9176
9177                    // For views inside a scrolling container, delay the pressed feedback for
9178                    // a short period in case this is a scroll.
9179                    if (isInScrollingContainer) {
9180                        mPrivateFlags |= PFLAG_PREPRESSED;
9181                        if (mPendingCheckForTap == null) {
9182                            mPendingCheckForTap = new CheckForTap();
9183                        }
9184                        mPendingCheckForTap.x = event.getX();
9185                        mPendingCheckForTap.y = event.getY();
9186                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9187                    } else {
9188                        // Not inside a scrolling container, so show the feedback right away
9189                        setPressed(true, x, y);
9190                        checkForLongClick(0);
9191                    }
9192                    break;
9193
9194                case MotionEvent.ACTION_CANCEL:
9195                    setPressed(false);
9196                    removeTapCallback();
9197                    removeLongPressCallback();
9198                    break;
9199
9200                case MotionEvent.ACTION_MOVE:
9201                    drawableHotspotChanged(x, y);
9202
9203                    // Be lenient about moving outside of buttons
9204                    if (!pointInView(x, y, mTouchSlop)) {
9205                        // Outside button
9206                        removeTapCallback();
9207                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9208                            // Remove any future long press/tap checks
9209                            removeLongPressCallback();
9210
9211                            setPressed(false);
9212                        }
9213                    }
9214                    break;
9215            }
9216
9217            return true;
9218        }
9219
9220        return false;
9221    }
9222
9223    /**
9224     * @hide
9225     */
9226    public boolean isInScrollingContainer() {
9227        ViewParent p = getParent();
9228        while (p != null && p instanceof ViewGroup) {
9229            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9230                return true;
9231            }
9232            p = p.getParent();
9233        }
9234        return false;
9235    }
9236
9237    /**
9238     * Remove the longpress detection timer.
9239     */
9240    private void removeLongPressCallback() {
9241        if (mPendingCheckForLongPress != null) {
9242          removeCallbacks(mPendingCheckForLongPress);
9243        }
9244    }
9245
9246    /**
9247     * Remove the pending click action
9248     */
9249    private void removePerformClickCallback() {
9250        if (mPerformClick != null) {
9251            removeCallbacks(mPerformClick);
9252        }
9253    }
9254
9255    /**
9256     * Remove the prepress detection timer.
9257     */
9258    private void removeUnsetPressCallback() {
9259        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9260            setPressed(false);
9261            removeCallbacks(mUnsetPressedState);
9262        }
9263    }
9264
9265    /**
9266     * Remove the tap detection timer.
9267     */
9268    private void removeTapCallback() {
9269        if (mPendingCheckForTap != null) {
9270            mPrivateFlags &= ~PFLAG_PREPRESSED;
9271            removeCallbacks(mPendingCheckForTap);
9272        }
9273    }
9274
9275    /**
9276     * Cancels a pending long press.  Your subclass can use this if you
9277     * want the context menu to come up if the user presses and holds
9278     * at the same place, but you don't want it to come up if they press
9279     * and then move around enough to cause scrolling.
9280     */
9281    public void cancelLongPress() {
9282        removeLongPressCallback();
9283
9284        /*
9285         * The prepressed state handled by the tap callback is a display
9286         * construct, but the tap callback will post a long press callback
9287         * less its own timeout. Remove it here.
9288         */
9289        removeTapCallback();
9290    }
9291
9292    /**
9293     * Remove the pending callback for sending a
9294     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9295     */
9296    private void removeSendViewScrolledAccessibilityEventCallback() {
9297        if (mSendViewScrolledAccessibilityEvent != null) {
9298            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9299            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9300        }
9301    }
9302
9303    /**
9304     * Sets the TouchDelegate for this View.
9305     */
9306    public void setTouchDelegate(TouchDelegate delegate) {
9307        mTouchDelegate = delegate;
9308    }
9309
9310    /**
9311     * Gets the TouchDelegate for this View.
9312     */
9313    public TouchDelegate getTouchDelegate() {
9314        return mTouchDelegate;
9315    }
9316
9317    /**
9318     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9319     *
9320     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9321     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9322     * available. This method should only be called for touch events.
9323     *
9324     * <p class="note">This api is not intended for most applications. Buffered dispatch
9325     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9326     * streams will not improve your input latency. Side effects include: increased latency,
9327     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9328     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9329     * you.</p>
9330     */
9331    public final void requestUnbufferedDispatch(MotionEvent event) {
9332        final int action = event.getAction();
9333        if (mAttachInfo == null
9334                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9335                || !event.isTouchEvent()) {
9336            return;
9337        }
9338        mAttachInfo.mUnbufferedDispatchRequested = true;
9339    }
9340
9341    /**
9342     * Set flags controlling behavior of this view.
9343     *
9344     * @param flags Constant indicating the value which should be set
9345     * @param mask Constant indicating the bit range that should be changed
9346     */
9347    void setFlags(int flags, int mask) {
9348        final boolean accessibilityEnabled =
9349                AccessibilityManager.getInstance(mContext).isEnabled();
9350        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9351
9352        int old = mViewFlags;
9353        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9354
9355        int changed = mViewFlags ^ old;
9356        if (changed == 0) {
9357            return;
9358        }
9359        int privateFlags = mPrivateFlags;
9360
9361        /* Check if the FOCUSABLE bit has changed */
9362        if (((changed & FOCUSABLE_MASK) != 0) &&
9363                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9364            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9365                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9366                /* Give up focus if we are no longer focusable */
9367                clearFocus();
9368            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9369                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9370                /*
9371                 * Tell the view system that we are now available to take focus
9372                 * if no one else already has it.
9373                 */
9374                if (mParent != null) mParent.focusableViewAvailable(this);
9375            }
9376        }
9377
9378        final int newVisibility = flags & VISIBILITY_MASK;
9379        if (newVisibility == VISIBLE) {
9380            if ((changed & VISIBILITY_MASK) != 0) {
9381                /*
9382                 * If this view is becoming visible, invalidate it in case it changed while
9383                 * it was not visible. Marking it drawn ensures that the invalidation will
9384                 * go through.
9385                 */
9386                mPrivateFlags |= PFLAG_DRAWN;
9387                invalidate(true);
9388
9389                needGlobalAttributesUpdate(true);
9390
9391                // a view becoming visible is worth notifying the parent
9392                // about in case nothing has focus.  even if this specific view
9393                // isn't focusable, it may contain something that is, so let
9394                // the root view try to give this focus if nothing else does.
9395                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9396                    mParent.focusableViewAvailable(this);
9397                }
9398            }
9399        }
9400
9401        /* Check if the GONE bit has changed */
9402        if ((changed & GONE) != 0) {
9403            needGlobalAttributesUpdate(false);
9404            requestLayout();
9405
9406            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9407                if (hasFocus()) clearFocus();
9408                clearAccessibilityFocus();
9409                destroyDrawingCache();
9410                if (mParent instanceof View) {
9411                    // GONE views noop invalidation, so invalidate the parent
9412                    ((View) mParent).invalidate(true);
9413                }
9414                // Mark the view drawn to ensure that it gets invalidated properly the next
9415                // time it is visible and gets invalidated
9416                mPrivateFlags |= PFLAG_DRAWN;
9417            }
9418            if (mAttachInfo != null) {
9419                mAttachInfo.mViewVisibilityChanged = true;
9420            }
9421        }
9422
9423        /* Check if the VISIBLE bit has changed */
9424        if ((changed & INVISIBLE) != 0) {
9425            needGlobalAttributesUpdate(false);
9426            /*
9427             * If this view is becoming invisible, set the DRAWN flag so that
9428             * the next invalidate() will not be skipped.
9429             */
9430            mPrivateFlags |= PFLAG_DRAWN;
9431
9432            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9433                // root view becoming invisible shouldn't clear focus and accessibility focus
9434                if (getRootView() != this) {
9435                    if (hasFocus()) clearFocus();
9436                    clearAccessibilityFocus();
9437                }
9438            }
9439            if (mAttachInfo != null) {
9440                mAttachInfo.mViewVisibilityChanged = true;
9441            }
9442        }
9443
9444        if ((changed & VISIBILITY_MASK) != 0) {
9445            // If the view is invisible, cleanup its display list to free up resources
9446            if (newVisibility != VISIBLE && mAttachInfo != null) {
9447                cleanupDraw();
9448            }
9449
9450            if (mParent instanceof ViewGroup) {
9451                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9452                        (changed & VISIBILITY_MASK), newVisibility);
9453                ((View) mParent).invalidate(true);
9454            } else if (mParent != null) {
9455                mParent.invalidateChild(this, null);
9456            }
9457            dispatchVisibilityChanged(this, newVisibility);
9458
9459            notifySubtreeAccessibilityStateChangedIfNeeded();
9460        }
9461
9462        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9463            destroyDrawingCache();
9464        }
9465
9466        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9467            destroyDrawingCache();
9468            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9469            invalidateParentCaches();
9470        }
9471
9472        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9473            destroyDrawingCache();
9474            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9475        }
9476
9477        if ((changed & DRAW_MASK) != 0) {
9478            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9479                if (mBackground != null) {
9480                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9481                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9482                } else {
9483                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9484                }
9485            } else {
9486                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9487            }
9488            requestLayout();
9489            invalidate(true);
9490        }
9491
9492        if ((changed & KEEP_SCREEN_ON) != 0) {
9493            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9494                mParent.recomputeViewAttributes(this);
9495            }
9496        }
9497
9498        if (accessibilityEnabled) {
9499            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9500                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9501                if (oldIncludeForAccessibility != includeForAccessibility()) {
9502                    notifySubtreeAccessibilityStateChangedIfNeeded();
9503                } else {
9504                    notifyViewAccessibilityStateChangedIfNeeded(
9505                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9506                }
9507            } else if ((changed & ENABLED_MASK) != 0) {
9508                notifyViewAccessibilityStateChangedIfNeeded(
9509                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9510            }
9511        }
9512    }
9513
9514    /**
9515     * Change the view's z order in the tree, so it's on top of other sibling
9516     * views. This ordering change may affect layout, if the parent container
9517     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9518     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9519     * method should be followed by calls to {@link #requestLayout()} and
9520     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9521     * with the new child ordering.
9522     *
9523     * @see ViewGroup#bringChildToFront(View)
9524     */
9525    public void bringToFront() {
9526        if (mParent != null) {
9527            mParent.bringChildToFront(this);
9528        }
9529    }
9530
9531    /**
9532     * This is called in response to an internal scroll in this view (i.e., the
9533     * view scrolled its own contents). This is typically as a result of
9534     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9535     * called.
9536     *
9537     * @param l Current horizontal scroll origin.
9538     * @param t Current vertical scroll origin.
9539     * @param oldl Previous horizontal scroll origin.
9540     * @param oldt Previous vertical scroll origin.
9541     */
9542    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9543        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9544            postSendViewScrolledAccessibilityEventCallback();
9545        }
9546
9547        mBackgroundSizeChanged = true;
9548
9549        final AttachInfo ai = mAttachInfo;
9550        if (ai != null) {
9551            ai.mViewScrollChanged = true;
9552        }
9553    }
9554
9555    /**
9556     * Interface definition for a callback to be invoked when the layout bounds of a view
9557     * changes due to layout processing.
9558     */
9559    public interface OnLayoutChangeListener {
9560        /**
9561         * Called when the layout bounds of a view changes due to layout processing.
9562         *
9563         * @param v The view whose bounds have changed.
9564         * @param left The new value of the view's left property.
9565         * @param top The new value of the view's top property.
9566         * @param right The new value of the view's right property.
9567         * @param bottom The new value of the view's bottom property.
9568         * @param oldLeft The previous value of the view's left property.
9569         * @param oldTop The previous value of the view's top property.
9570         * @param oldRight The previous value of the view's right property.
9571         * @param oldBottom The previous value of the view's bottom property.
9572         */
9573        void onLayoutChange(View v, int left, int top, int right, int bottom,
9574            int oldLeft, int oldTop, int oldRight, int oldBottom);
9575    }
9576
9577    /**
9578     * This is called during layout when the size of this view has changed. If
9579     * you were just added to the view hierarchy, you're called with the old
9580     * values of 0.
9581     *
9582     * @param w Current width of this view.
9583     * @param h Current height of this view.
9584     * @param oldw Old width of this view.
9585     * @param oldh Old height of this view.
9586     */
9587    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9588    }
9589
9590    /**
9591     * Called by draw to draw the child views. This may be overridden
9592     * by derived classes to gain control just before its children are drawn
9593     * (but after its own view has been drawn).
9594     * @param canvas the canvas on which to draw the view
9595     */
9596    protected void dispatchDraw(Canvas canvas) {
9597
9598    }
9599
9600    /**
9601     * Gets the parent of this view. Note that the parent is a
9602     * ViewParent and not necessarily a View.
9603     *
9604     * @return Parent of this view.
9605     */
9606    public final ViewParent getParent() {
9607        return mParent;
9608    }
9609
9610    /**
9611     * Set the horizontal scrolled position of your view. This will cause a call to
9612     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9613     * invalidated.
9614     * @param value the x position to scroll to
9615     */
9616    public void setScrollX(int value) {
9617        scrollTo(value, mScrollY);
9618    }
9619
9620    /**
9621     * Set the vertical scrolled position of your view. This will cause a call to
9622     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9623     * invalidated.
9624     * @param value the y position to scroll to
9625     */
9626    public void setScrollY(int value) {
9627        scrollTo(mScrollX, value);
9628    }
9629
9630    /**
9631     * Return the scrolled left position of this view. This is the left edge of
9632     * the displayed part of your view. You do not need to draw any pixels
9633     * farther left, since those are outside of the frame of your view on
9634     * screen.
9635     *
9636     * @return The left edge of the displayed part of your view, in pixels.
9637     */
9638    public final int getScrollX() {
9639        return mScrollX;
9640    }
9641
9642    /**
9643     * Return the scrolled top position of this view. This is the top edge of
9644     * the displayed part of your view. You do not need to draw any pixels above
9645     * it, since those are outside of the frame of your view on screen.
9646     *
9647     * @return The top edge of the displayed part of your view, in pixels.
9648     */
9649    public final int getScrollY() {
9650        return mScrollY;
9651    }
9652
9653    /**
9654     * Return the width of the your view.
9655     *
9656     * @return The width of your view, in pixels.
9657     */
9658    @ViewDebug.ExportedProperty(category = "layout")
9659    public final int getWidth() {
9660        return mRight - mLeft;
9661    }
9662
9663    /**
9664     * Return the height of your view.
9665     *
9666     * @return The height of your view, in pixels.
9667     */
9668    @ViewDebug.ExportedProperty(category = "layout")
9669    public final int getHeight() {
9670        return mBottom - mTop;
9671    }
9672
9673    /**
9674     * Return the visible drawing bounds of your view. Fills in the output
9675     * rectangle with the values from getScrollX(), getScrollY(),
9676     * getWidth(), and getHeight(). These bounds do not account for any
9677     * transformation properties currently set on the view, such as
9678     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9679     *
9680     * @param outRect The (scrolled) drawing bounds of the view.
9681     */
9682    public void getDrawingRect(Rect outRect) {
9683        outRect.left = mScrollX;
9684        outRect.top = mScrollY;
9685        outRect.right = mScrollX + (mRight - mLeft);
9686        outRect.bottom = mScrollY + (mBottom - mTop);
9687    }
9688
9689    /**
9690     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9691     * raw width component (that is the result is masked by
9692     * {@link #MEASURED_SIZE_MASK}).
9693     *
9694     * @return The raw measured width of this view.
9695     */
9696    public final int getMeasuredWidth() {
9697        return mMeasuredWidth & MEASURED_SIZE_MASK;
9698    }
9699
9700    /**
9701     * Return the full width measurement information for this view as computed
9702     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9703     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9704     * This should be used during measurement and layout calculations only. Use
9705     * {@link #getWidth()} to see how wide a view is after layout.
9706     *
9707     * @return The measured width of this view as a bit mask.
9708     */
9709    public final int getMeasuredWidthAndState() {
9710        return mMeasuredWidth;
9711    }
9712
9713    /**
9714     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9715     * raw width component (that is the result is masked by
9716     * {@link #MEASURED_SIZE_MASK}).
9717     *
9718     * @return The raw measured height of this view.
9719     */
9720    public final int getMeasuredHeight() {
9721        return mMeasuredHeight & MEASURED_SIZE_MASK;
9722    }
9723
9724    /**
9725     * Return the full height measurement information for this view as computed
9726     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9727     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9728     * This should be used during measurement and layout calculations only. Use
9729     * {@link #getHeight()} to see how wide a view is after layout.
9730     *
9731     * @return The measured width of this view as a bit mask.
9732     */
9733    public final int getMeasuredHeightAndState() {
9734        return mMeasuredHeight;
9735    }
9736
9737    /**
9738     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9739     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9740     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9741     * and the height component is at the shifted bits
9742     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9743     */
9744    public final int getMeasuredState() {
9745        return (mMeasuredWidth&MEASURED_STATE_MASK)
9746                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9747                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9748    }
9749
9750    /**
9751     * The transform matrix of this view, which is calculated based on the current
9752     * rotation, scale, and pivot properties.
9753     *
9754     * @see #getRotation()
9755     * @see #getScaleX()
9756     * @see #getScaleY()
9757     * @see #getPivotX()
9758     * @see #getPivotY()
9759     * @return The current transform matrix for the view
9760     */
9761    public Matrix getMatrix() {
9762        ensureTransformationInfo();
9763        final Matrix matrix = mTransformationInfo.mMatrix;
9764        mRenderNode.getMatrix(matrix);
9765        return matrix;
9766    }
9767
9768    /**
9769     * Returns true if the transform matrix is the identity matrix.
9770     * Recomputes the matrix if necessary.
9771     *
9772     * @return True if the transform matrix is the identity matrix, false otherwise.
9773     */
9774    final boolean hasIdentityMatrix() {
9775        return mRenderNode.hasIdentityMatrix();
9776    }
9777
9778    void ensureTransformationInfo() {
9779        if (mTransformationInfo == null) {
9780            mTransformationInfo = new TransformationInfo();
9781        }
9782    }
9783
9784   /**
9785     * Utility method to retrieve the inverse of the current mMatrix property.
9786     * We cache the matrix to avoid recalculating it when transform properties
9787     * have not changed.
9788     *
9789     * @return The inverse of the current matrix of this view.
9790     * @hide
9791     */
9792    public final Matrix getInverseMatrix() {
9793        ensureTransformationInfo();
9794        if (mTransformationInfo.mInverseMatrix == null) {
9795            mTransformationInfo.mInverseMatrix = new Matrix();
9796        }
9797        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9798        mRenderNode.getInverseMatrix(matrix);
9799        return matrix;
9800    }
9801
9802    /**
9803     * Gets the distance along the Z axis from the camera to this view.
9804     *
9805     * @see #setCameraDistance(float)
9806     *
9807     * @return The distance along the Z axis.
9808     */
9809    public float getCameraDistance() {
9810        final float dpi = mResources.getDisplayMetrics().densityDpi;
9811        return -(mRenderNode.getCameraDistance() * dpi);
9812    }
9813
9814    /**
9815     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9816     * views are drawn) from the camera to this view. The camera's distance
9817     * affects 3D transformations, for instance rotations around the X and Y
9818     * axis. If the rotationX or rotationY properties are changed and this view is
9819     * large (more than half the size of the screen), it is recommended to always
9820     * use a camera distance that's greater than the height (X axis rotation) or
9821     * the width (Y axis rotation) of this view.</p>
9822     *
9823     * <p>The distance of the camera from the view plane can have an affect on the
9824     * perspective distortion of the view when it is rotated around the x or y axis.
9825     * For example, a large distance will result in a large viewing angle, and there
9826     * will not be much perspective distortion of the view as it rotates. A short
9827     * distance may cause much more perspective distortion upon rotation, and can
9828     * also result in some drawing artifacts if the rotated view ends up partially
9829     * behind the camera (which is why the recommendation is to use a distance at
9830     * least as far as the size of the view, if the view is to be rotated.)</p>
9831     *
9832     * <p>The distance is expressed in "depth pixels." The default distance depends
9833     * on the screen density. For instance, on a medium density display, the
9834     * default distance is 1280. On a high density display, the default distance
9835     * is 1920.</p>
9836     *
9837     * <p>If you want to specify a distance that leads to visually consistent
9838     * results across various densities, use the following formula:</p>
9839     * <pre>
9840     * float scale = context.getResources().getDisplayMetrics().density;
9841     * view.setCameraDistance(distance * scale);
9842     * </pre>
9843     *
9844     * <p>The density scale factor of a high density display is 1.5,
9845     * and 1920 = 1280 * 1.5.</p>
9846     *
9847     * @param distance The distance in "depth pixels", if negative the opposite
9848     *        value is used
9849     *
9850     * @see #setRotationX(float)
9851     * @see #setRotationY(float)
9852     */
9853    public void setCameraDistance(float distance) {
9854        final float dpi = mResources.getDisplayMetrics().densityDpi;
9855
9856        invalidateViewProperty(true, false);
9857        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9858        invalidateViewProperty(false, false);
9859
9860        invalidateParentIfNeededAndWasQuickRejected();
9861    }
9862
9863    /**
9864     * The degrees that the view is rotated around the pivot point.
9865     *
9866     * @see #setRotation(float)
9867     * @see #getPivotX()
9868     * @see #getPivotY()
9869     *
9870     * @return The degrees of rotation.
9871     */
9872    @ViewDebug.ExportedProperty(category = "drawing")
9873    public float getRotation() {
9874        return mRenderNode.getRotation();
9875    }
9876
9877    /**
9878     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9879     * result in clockwise rotation.
9880     *
9881     * @param rotation The degrees of rotation.
9882     *
9883     * @see #getRotation()
9884     * @see #getPivotX()
9885     * @see #getPivotY()
9886     * @see #setRotationX(float)
9887     * @see #setRotationY(float)
9888     *
9889     * @attr ref android.R.styleable#View_rotation
9890     */
9891    public void setRotation(float rotation) {
9892        if (rotation != getRotation()) {
9893            // Double-invalidation is necessary to capture view's old and new areas
9894            invalidateViewProperty(true, false);
9895            mRenderNode.setRotation(rotation);
9896            invalidateViewProperty(false, true);
9897
9898            invalidateParentIfNeededAndWasQuickRejected();
9899            notifySubtreeAccessibilityStateChangedIfNeeded();
9900        }
9901    }
9902
9903    /**
9904     * The degrees that the view is rotated around the vertical axis through the pivot point.
9905     *
9906     * @see #getPivotX()
9907     * @see #getPivotY()
9908     * @see #setRotationY(float)
9909     *
9910     * @return The degrees of Y rotation.
9911     */
9912    @ViewDebug.ExportedProperty(category = "drawing")
9913    public float getRotationY() {
9914        return mRenderNode.getRotationY();
9915    }
9916
9917    /**
9918     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9919     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9920     * down the y axis.
9921     *
9922     * When rotating large views, it is recommended to adjust the camera distance
9923     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9924     *
9925     * @param rotationY The degrees of Y rotation.
9926     *
9927     * @see #getRotationY()
9928     * @see #getPivotX()
9929     * @see #getPivotY()
9930     * @see #setRotation(float)
9931     * @see #setRotationX(float)
9932     * @see #setCameraDistance(float)
9933     *
9934     * @attr ref android.R.styleable#View_rotationY
9935     */
9936    public void setRotationY(float rotationY) {
9937        if (rotationY != getRotationY()) {
9938            invalidateViewProperty(true, false);
9939            mRenderNode.setRotationY(rotationY);
9940            invalidateViewProperty(false, true);
9941
9942            invalidateParentIfNeededAndWasQuickRejected();
9943            notifySubtreeAccessibilityStateChangedIfNeeded();
9944        }
9945    }
9946
9947    /**
9948     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9949     *
9950     * @see #getPivotX()
9951     * @see #getPivotY()
9952     * @see #setRotationX(float)
9953     *
9954     * @return The degrees of X rotation.
9955     */
9956    @ViewDebug.ExportedProperty(category = "drawing")
9957    public float getRotationX() {
9958        return mRenderNode.getRotationX();
9959    }
9960
9961    /**
9962     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9963     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9964     * x axis.
9965     *
9966     * When rotating large views, it is recommended to adjust the camera distance
9967     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9968     *
9969     * @param rotationX The degrees of X rotation.
9970     *
9971     * @see #getRotationX()
9972     * @see #getPivotX()
9973     * @see #getPivotY()
9974     * @see #setRotation(float)
9975     * @see #setRotationY(float)
9976     * @see #setCameraDistance(float)
9977     *
9978     * @attr ref android.R.styleable#View_rotationX
9979     */
9980    public void setRotationX(float rotationX) {
9981        if (rotationX != getRotationX()) {
9982            invalidateViewProperty(true, false);
9983            mRenderNode.setRotationX(rotationX);
9984            invalidateViewProperty(false, true);
9985
9986            invalidateParentIfNeededAndWasQuickRejected();
9987            notifySubtreeAccessibilityStateChangedIfNeeded();
9988        }
9989    }
9990
9991    /**
9992     * The amount that the view is scaled in x around the pivot point, as a proportion of
9993     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9994     *
9995     * <p>By default, this is 1.0f.
9996     *
9997     * @see #getPivotX()
9998     * @see #getPivotY()
9999     * @return The scaling factor.
10000     */
10001    @ViewDebug.ExportedProperty(category = "drawing")
10002    public float getScaleX() {
10003        return mRenderNode.getScaleX();
10004    }
10005
10006    /**
10007     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10008     * the view's unscaled width. A value of 1 means that no scaling is applied.
10009     *
10010     * @param scaleX The scaling factor.
10011     * @see #getPivotX()
10012     * @see #getPivotY()
10013     *
10014     * @attr ref android.R.styleable#View_scaleX
10015     */
10016    public void setScaleX(float scaleX) {
10017        if (scaleX != getScaleX()) {
10018            invalidateViewProperty(true, false);
10019            mRenderNode.setScaleX(scaleX);
10020            invalidateViewProperty(false, true);
10021
10022            invalidateParentIfNeededAndWasQuickRejected();
10023            notifySubtreeAccessibilityStateChangedIfNeeded();
10024        }
10025    }
10026
10027    /**
10028     * The amount that the view is scaled in y around the pivot point, as a proportion of
10029     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10030     *
10031     * <p>By default, this is 1.0f.
10032     *
10033     * @see #getPivotX()
10034     * @see #getPivotY()
10035     * @return The scaling factor.
10036     */
10037    @ViewDebug.ExportedProperty(category = "drawing")
10038    public float getScaleY() {
10039        return mRenderNode.getScaleY();
10040    }
10041
10042    /**
10043     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10044     * the view's unscaled width. A value of 1 means that no scaling is applied.
10045     *
10046     * @param scaleY The scaling factor.
10047     * @see #getPivotX()
10048     * @see #getPivotY()
10049     *
10050     * @attr ref android.R.styleable#View_scaleY
10051     */
10052    public void setScaleY(float scaleY) {
10053        if (scaleY != getScaleY()) {
10054            invalidateViewProperty(true, false);
10055            mRenderNode.setScaleY(scaleY);
10056            invalidateViewProperty(false, true);
10057
10058            invalidateParentIfNeededAndWasQuickRejected();
10059            notifySubtreeAccessibilityStateChangedIfNeeded();
10060        }
10061    }
10062
10063    /**
10064     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10065     * and {@link #setScaleX(float) scaled}.
10066     *
10067     * @see #getRotation()
10068     * @see #getScaleX()
10069     * @see #getScaleY()
10070     * @see #getPivotY()
10071     * @return The x location of the pivot point.
10072     *
10073     * @attr ref android.R.styleable#View_transformPivotX
10074     */
10075    @ViewDebug.ExportedProperty(category = "drawing")
10076    public float getPivotX() {
10077        return mRenderNode.getPivotX();
10078    }
10079
10080    /**
10081     * Sets the x location of the point around which the view is
10082     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10083     * By default, the pivot point is centered on the object.
10084     * Setting this property disables this behavior and causes the view to use only the
10085     * explicitly set pivotX and pivotY values.
10086     *
10087     * @param pivotX The x location of the pivot point.
10088     * @see #getRotation()
10089     * @see #getScaleX()
10090     * @see #getScaleY()
10091     * @see #getPivotY()
10092     *
10093     * @attr ref android.R.styleable#View_transformPivotX
10094     */
10095    public void setPivotX(float pivotX) {
10096        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10097            invalidateViewProperty(true, false);
10098            mRenderNode.setPivotX(pivotX);
10099            invalidateViewProperty(false, true);
10100
10101            invalidateParentIfNeededAndWasQuickRejected();
10102        }
10103    }
10104
10105    /**
10106     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10107     * and {@link #setScaleY(float) scaled}.
10108     *
10109     * @see #getRotation()
10110     * @see #getScaleX()
10111     * @see #getScaleY()
10112     * @see #getPivotY()
10113     * @return The y location of the pivot point.
10114     *
10115     * @attr ref android.R.styleable#View_transformPivotY
10116     */
10117    @ViewDebug.ExportedProperty(category = "drawing")
10118    public float getPivotY() {
10119        return mRenderNode.getPivotY();
10120    }
10121
10122    /**
10123     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10124     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10125     * Setting this property disables this behavior and causes the view to use only the
10126     * explicitly set pivotX and pivotY values.
10127     *
10128     * @param pivotY The y location of the pivot point.
10129     * @see #getRotation()
10130     * @see #getScaleX()
10131     * @see #getScaleY()
10132     * @see #getPivotY()
10133     *
10134     * @attr ref android.R.styleable#View_transformPivotY
10135     */
10136    public void setPivotY(float pivotY) {
10137        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10138            invalidateViewProperty(true, false);
10139            mRenderNode.setPivotY(pivotY);
10140            invalidateViewProperty(false, true);
10141
10142            invalidateParentIfNeededAndWasQuickRejected();
10143        }
10144    }
10145
10146    /**
10147     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10148     * completely transparent and 1 means the view is completely opaque.
10149     *
10150     * <p>By default this is 1.0f.
10151     * @return The opacity of the view.
10152     */
10153    @ViewDebug.ExportedProperty(category = "drawing")
10154    public float getAlpha() {
10155        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10156    }
10157
10158    /**
10159     * Returns whether this View has content which overlaps.
10160     *
10161     * <p>This function, intended to be overridden by specific View types, is an optimization when
10162     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10163     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10164     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10165     * directly. An example of overlapping rendering is a TextView with a background image, such as
10166     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10167     * ImageView with only the foreground image. The default implementation returns true; subclasses
10168     * should override if they have cases which can be optimized.</p>
10169     *
10170     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10171     * necessitates that a View return true if it uses the methods internally without passing the
10172     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10173     *
10174     * @return true if the content in this view might overlap, false otherwise.
10175     */
10176    public boolean hasOverlappingRendering() {
10177        return true;
10178    }
10179
10180    /**
10181     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10182     * completely transparent and 1 means the view is completely opaque.</p>
10183     *
10184     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10185     * performance implications, especially for large views. It is best to use the alpha property
10186     * sparingly and transiently, as in the case of fading animations.</p>
10187     *
10188     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10189     * strongly recommended for performance reasons to either override
10190     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10191     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10192     *
10193     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10194     * responsible for applying the opacity itself.</p>
10195     *
10196     * <p>Note that if the view is backed by a
10197     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10198     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10199     * 1.0 will supercede the alpha of the layer paint.</p>
10200     *
10201     * @param alpha The opacity of the view.
10202     *
10203     * @see #hasOverlappingRendering()
10204     * @see #setLayerType(int, android.graphics.Paint)
10205     *
10206     * @attr ref android.R.styleable#View_alpha
10207     */
10208    public void setAlpha(float alpha) {
10209        ensureTransformationInfo();
10210        if (mTransformationInfo.mAlpha != alpha) {
10211            mTransformationInfo.mAlpha = alpha;
10212            if (onSetAlpha((int) (alpha * 255))) {
10213                mPrivateFlags |= PFLAG_ALPHA_SET;
10214                // subclass is handling alpha - don't optimize rendering cache invalidation
10215                invalidateParentCaches();
10216                invalidate(true);
10217            } else {
10218                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10219                invalidateViewProperty(true, false);
10220                mRenderNode.setAlpha(getFinalAlpha());
10221                notifyViewAccessibilityStateChangedIfNeeded(
10222                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10223            }
10224        }
10225    }
10226
10227    /**
10228     * Faster version of setAlpha() which performs the same steps except there are
10229     * no calls to invalidate(). The caller of this function should perform proper invalidation
10230     * on the parent and this object. The return value indicates whether the subclass handles
10231     * alpha (the return value for onSetAlpha()).
10232     *
10233     * @param alpha The new value for the alpha property
10234     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10235     *         the new value for the alpha property is different from the old value
10236     */
10237    boolean setAlphaNoInvalidation(float alpha) {
10238        ensureTransformationInfo();
10239        if (mTransformationInfo.mAlpha != alpha) {
10240            mTransformationInfo.mAlpha = alpha;
10241            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10242            if (subclassHandlesAlpha) {
10243                mPrivateFlags |= PFLAG_ALPHA_SET;
10244                return true;
10245            } else {
10246                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10247                mRenderNode.setAlpha(getFinalAlpha());
10248            }
10249        }
10250        return false;
10251    }
10252
10253    /**
10254     * This property is hidden and intended only for use by the Fade transition, which
10255     * animates it to produce a visual translucency that does not side-effect (or get
10256     * affected by) the real alpha property. This value is composited with the other
10257     * alpha value (and the AlphaAnimation value, when that is present) to produce
10258     * a final visual translucency result, which is what is passed into the DisplayList.
10259     *
10260     * @hide
10261     */
10262    public void setTransitionAlpha(float alpha) {
10263        ensureTransformationInfo();
10264        if (mTransformationInfo.mTransitionAlpha != alpha) {
10265            mTransformationInfo.mTransitionAlpha = alpha;
10266            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10267            invalidateViewProperty(true, false);
10268            mRenderNode.setAlpha(getFinalAlpha());
10269        }
10270    }
10271
10272    /**
10273     * Calculates the visual alpha of this view, which is a combination of the actual
10274     * alpha value and the transitionAlpha value (if set).
10275     */
10276    private float getFinalAlpha() {
10277        if (mTransformationInfo != null) {
10278            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10279        }
10280        return 1;
10281    }
10282
10283    /**
10284     * This property is hidden and intended only for use by the Fade transition, which
10285     * animates it to produce a visual translucency that does not side-effect (or get
10286     * affected by) the real alpha property. This value is composited with the other
10287     * alpha value (and the AlphaAnimation value, when that is present) to produce
10288     * a final visual translucency result, which is what is passed into the DisplayList.
10289     *
10290     * @hide
10291     */
10292    @ViewDebug.ExportedProperty(category = "drawing")
10293    public float getTransitionAlpha() {
10294        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10295    }
10296
10297    /**
10298     * Top position of this view relative to its parent.
10299     *
10300     * @return The top of this view, in pixels.
10301     */
10302    @ViewDebug.CapturedViewProperty
10303    public final int getTop() {
10304        return mTop;
10305    }
10306
10307    /**
10308     * Sets the top position of this view relative to its parent. This method is meant to be called
10309     * by the layout system and should not generally be called otherwise, because the property
10310     * may be changed at any time by the layout.
10311     *
10312     * @param top The top of this view, in pixels.
10313     */
10314    public final void setTop(int top) {
10315        if (top != mTop) {
10316            final boolean matrixIsIdentity = hasIdentityMatrix();
10317            if (matrixIsIdentity) {
10318                if (mAttachInfo != null) {
10319                    int minTop;
10320                    int yLoc;
10321                    if (top < mTop) {
10322                        minTop = top;
10323                        yLoc = top - mTop;
10324                    } else {
10325                        minTop = mTop;
10326                        yLoc = 0;
10327                    }
10328                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10329                }
10330            } else {
10331                // Double-invalidation is necessary to capture view's old and new areas
10332                invalidate(true);
10333            }
10334
10335            int width = mRight - mLeft;
10336            int oldHeight = mBottom - mTop;
10337
10338            mTop = top;
10339            mRenderNode.setTop(mTop);
10340
10341            sizeChange(width, mBottom - mTop, width, oldHeight);
10342
10343            if (!matrixIsIdentity) {
10344                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10345                invalidate(true);
10346            }
10347            mBackgroundSizeChanged = true;
10348            invalidateParentIfNeeded();
10349            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10350                // View was rejected last time it was drawn by its parent; this may have changed
10351                invalidateParentIfNeeded();
10352            }
10353        }
10354    }
10355
10356    /**
10357     * Bottom position of this view relative to its parent.
10358     *
10359     * @return The bottom of this view, in pixels.
10360     */
10361    @ViewDebug.CapturedViewProperty
10362    public final int getBottom() {
10363        return mBottom;
10364    }
10365
10366    /**
10367     * True if this view has changed since the last time being drawn.
10368     *
10369     * @return The dirty state of this view.
10370     */
10371    public boolean isDirty() {
10372        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10373    }
10374
10375    /**
10376     * Sets the bottom position of this view relative to its parent. This method is meant to be
10377     * called by the layout system and should not generally be called otherwise, because the
10378     * property may be changed at any time by the layout.
10379     *
10380     * @param bottom The bottom of this view, in pixels.
10381     */
10382    public final void setBottom(int bottom) {
10383        if (bottom != mBottom) {
10384            final boolean matrixIsIdentity = hasIdentityMatrix();
10385            if (matrixIsIdentity) {
10386                if (mAttachInfo != null) {
10387                    int maxBottom;
10388                    if (bottom < mBottom) {
10389                        maxBottom = mBottom;
10390                    } else {
10391                        maxBottom = bottom;
10392                    }
10393                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10394                }
10395            } else {
10396                // Double-invalidation is necessary to capture view's old and new areas
10397                invalidate(true);
10398            }
10399
10400            int width = mRight - mLeft;
10401            int oldHeight = mBottom - mTop;
10402
10403            mBottom = bottom;
10404            mRenderNode.setBottom(mBottom);
10405
10406            sizeChange(width, mBottom - mTop, width, oldHeight);
10407
10408            if (!matrixIsIdentity) {
10409                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10410                invalidate(true);
10411            }
10412            mBackgroundSizeChanged = true;
10413            invalidateParentIfNeeded();
10414            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10415                // View was rejected last time it was drawn by its parent; this may have changed
10416                invalidateParentIfNeeded();
10417            }
10418        }
10419    }
10420
10421    /**
10422     * Left position of this view relative to its parent.
10423     *
10424     * @return The left edge of this view, in pixels.
10425     */
10426    @ViewDebug.CapturedViewProperty
10427    public final int getLeft() {
10428        return mLeft;
10429    }
10430
10431    /**
10432     * Sets the left position of this view relative to its parent. This method is meant to be called
10433     * by the layout system and should not generally be called otherwise, because the property
10434     * may be changed at any time by the layout.
10435     *
10436     * @param left The left of this view, in pixels.
10437     */
10438    public final void setLeft(int left) {
10439        if (left != mLeft) {
10440            final boolean matrixIsIdentity = hasIdentityMatrix();
10441            if (matrixIsIdentity) {
10442                if (mAttachInfo != null) {
10443                    int minLeft;
10444                    int xLoc;
10445                    if (left < mLeft) {
10446                        minLeft = left;
10447                        xLoc = left - mLeft;
10448                    } else {
10449                        minLeft = mLeft;
10450                        xLoc = 0;
10451                    }
10452                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10453                }
10454            } else {
10455                // Double-invalidation is necessary to capture view's old and new areas
10456                invalidate(true);
10457            }
10458
10459            int oldWidth = mRight - mLeft;
10460            int height = mBottom - mTop;
10461
10462            mLeft = left;
10463            mRenderNode.setLeft(left);
10464
10465            sizeChange(mRight - mLeft, height, oldWidth, height);
10466
10467            if (!matrixIsIdentity) {
10468                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10469                invalidate(true);
10470            }
10471            mBackgroundSizeChanged = true;
10472            invalidateParentIfNeeded();
10473            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10474                // View was rejected last time it was drawn by its parent; this may have changed
10475                invalidateParentIfNeeded();
10476            }
10477        }
10478    }
10479
10480    /**
10481     * Right position of this view relative to its parent.
10482     *
10483     * @return The right edge of this view, in pixels.
10484     */
10485    @ViewDebug.CapturedViewProperty
10486    public final int getRight() {
10487        return mRight;
10488    }
10489
10490    /**
10491     * Sets the right position of this view relative to its parent. This method is meant to be called
10492     * by the layout system and should not generally be called otherwise, because the property
10493     * may be changed at any time by the layout.
10494     *
10495     * @param right The right of this view, in pixels.
10496     */
10497    public final void setRight(int right) {
10498        if (right != mRight) {
10499            final boolean matrixIsIdentity = hasIdentityMatrix();
10500            if (matrixIsIdentity) {
10501                if (mAttachInfo != null) {
10502                    int maxRight;
10503                    if (right < mRight) {
10504                        maxRight = mRight;
10505                    } else {
10506                        maxRight = right;
10507                    }
10508                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10509                }
10510            } else {
10511                // Double-invalidation is necessary to capture view's old and new areas
10512                invalidate(true);
10513            }
10514
10515            int oldWidth = mRight - mLeft;
10516            int height = mBottom - mTop;
10517
10518            mRight = right;
10519            mRenderNode.setRight(mRight);
10520
10521            sizeChange(mRight - mLeft, height, oldWidth, height);
10522
10523            if (!matrixIsIdentity) {
10524                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10525                invalidate(true);
10526            }
10527            mBackgroundSizeChanged = true;
10528            invalidateParentIfNeeded();
10529            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10530                // View was rejected last time it was drawn by its parent; this may have changed
10531                invalidateParentIfNeeded();
10532            }
10533        }
10534    }
10535
10536    /**
10537     * The visual x position of this view, in pixels. This is equivalent to the
10538     * {@link #setTranslationX(float) translationX} property plus the current
10539     * {@link #getLeft() left} property.
10540     *
10541     * @return The visual x position of this view, in pixels.
10542     */
10543    @ViewDebug.ExportedProperty(category = "drawing")
10544    public float getX() {
10545        return mLeft + getTranslationX();
10546    }
10547
10548    /**
10549     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10550     * {@link #setTranslationX(float) translationX} property to be the difference between
10551     * the x value passed in and the current {@link #getLeft() left} property.
10552     *
10553     * @param x The visual x position of this view, in pixels.
10554     */
10555    public void setX(float x) {
10556        setTranslationX(x - mLeft);
10557    }
10558
10559    /**
10560     * The visual y position of this view, in pixels. This is equivalent to the
10561     * {@link #setTranslationY(float) translationY} property plus the current
10562     * {@link #getTop() top} property.
10563     *
10564     * @return The visual y position of this view, in pixels.
10565     */
10566    @ViewDebug.ExportedProperty(category = "drawing")
10567    public float getY() {
10568        return mTop + getTranslationY();
10569    }
10570
10571    /**
10572     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10573     * {@link #setTranslationY(float) translationY} property to be the difference between
10574     * the y value passed in and the current {@link #getTop() top} property.
10575     *
10576     * @param y The visual y position of this view, in pixels.
10577     */
10578    public void setY(float y) {
10579        setTranslationY(y - mTop);
10580    }
10581
10582    /**
10583     * The visual z position of this view, in pixels. This is equivalent to the
10584     * {@link #setTranslationZ(float) translationZ} property plus the current
10585     * {@link #getElevation() elevation} property.
10586     *
10587     * @return The visual z position of this view, in pixels.
10588     */
10589    @ViewDebug.ExportedProperty(category = "drawing")
10590    public float getZ() {
10591        return getElevation() + getTranslationZ();
10592    }
10593
10594    /**
10595     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10596     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10597     * the x value passed in and the current {@link #getElevation() elevation} property.
10598     *
10599     * @param z The visual z position of this view, in pixels.
10600     */
10601    public void setZ(float z) {
10602        setTranslationZ(z - getElevation());
10603    }
10604
10605    /**
10606     * The base elevation of this view relative to its parent, in pixels.
10607     *
10608     * @return The base depth position of the view, in pixels.
10609     */
10610    @ViewDebug.ExportedProperty(category = "drawing")
10611    public float getElevation() {
10612        return mRenderNode.getElevation();
10613    }
10614
10615    /**
10616     * Sets the base elevation of this view, in pixels.
10617     *
10618     * @attr ref android.R.styleable#View_elevation
10619     */
10620    public void setElevation(float elevation) {
10621        if (elevation != getElevation()) {
10622            invalidateViewProperty(true, false);
10623            mRenderNode.setElevation(elevation);
10624            invalidateViewProperty(false, true);
10625
10626            invalidateParentIfNeededAndWasQuickRejected();
10627        }
10628    }
10629
10630    /**
10631     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10632     * This position is post-layout, in addition to wherever the object's
10633     * layout placed it.
10634     *
10635     * @return The horizontal position of this view relative to its left position, in pixels.
10636     */
10637    @ViewDebug.ExportedProperty(category = "drawing")
10638    public float getTranslationX() {
10639        return mRenderNode.getTranslationX();
10640    }
10641
10642    /**
10643     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10644     * This effectively positions the object post-layout, in addition to wherever the object's
10645     * layout placed it.
10646     *
10647     * @param translationX The horizontal position of this view relative to its left position,
10648     * in pixels.
10649     *
10650     * @attr ref android.R.styleable#View_translationX
10651     */
10652    public void setTranslationX(float translationX) {
10653        if (translationX != getTranslationX()) {
10654            invalidateViewProperty(true, false);
10655            mRenderNode.setTranslationX(translationX);
10656            invalidateViewProperty(false, true);
10657
10658            invalidateParentIfNeededAndWasQuickRejected();
10659            notifySubtreeAccessibilityStateChangedIfNeeded();
10660        }
10661    }
10662
10663    /**
10664     * The vertical location of this view relative to its {@link #getTop() top} position.
10665     * This position is post-layout, in addition to wherever the object's
10666     * layout placed it.
10667     *
10668     * @return The vertical position of this view relative to its top position,
10669     * in pixels.
10670     */
10671    @ViewDebug.ExportedProperty(category = "drawing")
10672    public float getTranslationY() {
10673        return mRenderNode.getTranslationY();
10674    }
10675
10676    /**
10677     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10678     * This effectively positions the object post-layout, in addition to wherever the object's
10679     * layout placed it.
10680     *
10681     * @param translationY The vertical position of this view relative to its top position,
10682     * in pixels.
10683     *
10684     * @attr ref android.R.styleable#View_translationY
10685     */
10686    public void setTranslationY(float translationY) {
10687        if (translationY != getTranslationY()) {
10688            invalidateViewProperty(true, false);
10689            mRenderNode.setTranslationY(translationY);
10690            invalidateViewProperty(false, true);
10691
10692            invalidateParentIfNeededAndWasQuickRejected();
10693        }
10694    }
10695
10696    /**
10697     * The depth location of this view relative to its {@link #getElevation() elevation}.
10698     *
10699     * @return The depth of this view relative to its elevation.
10700     */
10701    @ViewDebug.ExportedProperty(category = "drawing")
10702    public float getTranslationZ() {
10703        return mRenderNode.getTranslationZ();
10704    }
10705
10706    /**
10707     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10708     *
10709     * @attr ref android.R.styleable#View_translationZ
10710     */
10711    public void setTranslationZ(float translationZ) {
10712        if (translationZ != getTranslationZ()) {
10713            invalidateViewProperty(true, false);
10714            mRenderNode.setTranslationZ(translationZ);
10715            invalidateViewProperty(false, true);
10716
10717            invalidateParentIfNeededAndWasQuickRejected();
10718        }
10719    }
10720
10721    /**
10722     * Returns the current StateListAnimator if exists.
10723     *
10724     * @return StateListAnimator or null if it does not exists
10725     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10726     */
10727    public StateListAnimator getStateListAnimator() {
10728        return mStateListAnimator;
10729    }
10730
10731    /**
10732     * Attaches the provided StateListAnimator to this View.
10733     * <p>
10734     * Any previously attached StateListAnimator will be detached.
10735     *
10736     * @param stateListAnimator The StateListAnimator to update the view
10737     * @see {@link android.animation.StateListAnimator}
10738     */
10739    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10740        if (mStateListAnimator == stateListAnimator) {
10741            return;
10742        }
10743        if (mStateListAnimator != null) {
10744            mStateListAnimator.setTarget(null);
10745        }
10746        mStateListAnimator = stateListAnimator;
10747        if (stateListAnimator != null) {
10748            stateListAnimator.setTarget(this);
10749            if (isAttachedToWindow()) {
10750                stateListAnimator.setState(getDrawableState());
10751            }
10752        }
10753    }
10754
10755    /**
10756     * Deprecated, pending removal
10757     *
10758     * @hide
10759     */
10760    @Deprecated
10761    public void setOutline(@Nullable Outline outline) {}
10762
10763    /**
10764     * Returns whether the Outline should be used to clip the contents of the View.
10765     * <p>
10766     * Note that this flag will only be respected if the View's Outline returns true from
10767     * {@link Outline#canClip()}.
10768     *
10769     * @see #setOutlineProvider(ViewOutlineProvider)
10770     * @see #setClipToOutline(boolean)
10771     */
10772    public final boolean getClipToOutline() {
10773        return mRenderNode.getClipToOutline();
10774    }
10775
10776    /**
10777     * Sets whether the View's Outline should be used to clip the contents of the View.
10778     * <p>
10779     * Note that this flag will only be respected if the View's Outline returns true from
10780     * {@link Outline#canClip()}.
10781     *
10782     * @see #setOutlineProvider(ViewOutlineProvider)
10783     * @see #getClipToOutline()
10784     */
10785    public void setClipToOutline(boolean clipToOutline) {
10786        damageInParent();
10787        if (getClipToOutline() != clipToOutline) {
10788            mRenderNode.setClipToOutline(clipToOutline);
10789        }
10790    }
10791
10792    /**
10793     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10794     * the shape of the shadow it casts, and enables outline clipping.
10795     * <p>
10796     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10797     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10798     * outline provider with this method allows this behavior to be overridden.
10799     * <p>
10800     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10801     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10802     * <p>
10803     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10804     *
10805     * @see #setClipToOutline(boolean)
10806     * @see #getClipToOutline()
10807     * @see #getOutlineProvider()
10808     */
10809    public void setOutlineProvider(ViewOutlineProvider provider) {
10810        mOutlineProvider = provider;
10811        invalidateOutline();
10812    }
10813
10814    /**
10815     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10816     * that defines the shape of the shadow it casts, and enables outline clipping.
10817     *
10818     * @see #setOutlineProvider(ViewOutlineProvider)
10819     */
10820    public ViewOutlineProvider getOutlineProvider() {
10821        return mOutlineProvider;
10822    }
10823
10824    /**
10825     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10826     *
10827     * @see #setOutlineProvider(ViewOutlineProvider)
10828     */
10829    public void invalidateOutline() {
10830        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10831        if (mAttachInfo == null) return;
10832
10833        final Outline outline = mAttachInfo.mTmpOutline;
10834        outline.setEmpty();
10835
10836        if (mOutlineProvider == null) {
10837            // no provider, remove outline
10838            mRenderNode.setOutline(null);
10839        } else {
10840            mOutlineProvider.getOutline(this, outline);
10841            mRenderNode.setOutline(outline);
10842        }
10843
10844        notifySubtreeAccessibilityStateChangedIfNeeded();
10845        invalidateViewProperty(false, false);
10846    }
10847
10848    /**
10849     * Private API to be used for reveal animation
10850     *
10851     * @hide
10852     */
10853    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10854            float x, float y, float radius) {
10855        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10856        invalidateViewProperty(false, false);
10857    }
10858
10859    /**
10860     * Hit rectangle in parent's coordinates
10861     *
10862     * @param outRect The hit rectangle of the view.
10863     */
10864    public void getHitRect(Rect outRect) {
10865        if (hasIdentityMatrix() || mAttachInfo == null) {
10866            outRect.set(mLeft, mTop, mRight, mBottom);
10867        } else {
10868            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10869            tmpRect.set(0, 0, getWidth(), getHeight());
10870            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10871            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10872                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10873        }
10874    }
10875
10876    /**
10877     * Determines whether the given point, in local coordinates is inside the view.
10878     */
10879    /*package*/ final boolean pointInView(float localX, float localY) {
10880        return localX >= 0 && localX < (mRight - mLeft)
10881                && localY >= 0 && localY < (mBottom - mTop);
10882    }
10883
10884    /**
10885     * Utility method to determine whether the given point, in local coordinates,
10886     * is inside the view, where the area of the view is expanded by the slop factor.
10887     * This method is called while processing touch-move events to determine if the event
10888     * is still within the view.
10889     *
10890     * @hide
10891     */
10892    public boolean pointInView(float localX, float localY, float slop) {
10893        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10894                localY < ((mBottom - mTop) + slop);
10895    }
10896
10897    /**
10898     * When a view has focus and the user navigates away from it, the next view is searched for
10899     * starting from the rectangle filled in by this method.
10900     *
10901     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10902     * of the view.  However, if your view maintains some idea of internal selection,
10903     * such as a cursor, or a selected row or column, you should override this method and
10904     * fill in a more specific rectangle.
10905     *
10906     * @param r The rectangle to fill in, in this view's coordinates.
10907     */
10908    public void getFocusedRect(Rect r) {
10909        getDrawingRect(r);
10910    }
10911
10912    /**
10913     * If some part of this view is not clipped by any of its parents, then
10914     * return that area in r in global (root) coordinates. To convert r to local
10915     * coordinates (without taking possible View rotations into account), offset
10916     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10917     * If the view is completely clipped or translated out, return false.
10918     *
10919     * @param r If true is returned, r holds the global coordinates of the
10920     *        visible portion of this view.
10921     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10922     *        between this view and its root. globalOffet may be null.
10923     * @return true if r is non-empty (i.e. part of the view is visible at the
10924     *         root level.
10925     */
10926    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10927        int width = mRight - mLeft;
10928        int height = mBottom - mTop;
10929        if (width > 0 && height > 0) {
10930            r.set(0, 0, width, height);
10931            if (globalOffset != null) {
10932                globalOffset.set(-mScrollX, -mScrollY);
10933            }
10934            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10935        }
10936        return false;
10937    }
10938
10939    public final boolean getGlobalVisibleRect(Rect r) {
10940        return getGlobalVisibleRect(r, null);
10941    }
10942
10943    public final boolean getLocalVisibleRect(Rect r) {
10944        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10945        if (getGlobalVisibleRect(r, offset)) {
10946            r.offset(-offset.x, -offset.y); // make r local
10947            return true;
10948        }
10949        return false;
10950    }
10951
10952    /**
10953     * Offset this view's vertical location by the specified number of pixels.
10954     *
10955     * @param offset the number of pixels to offset the view by
10956     */
10957    public void offsetTopAndBottom(int offset) {
10958        if (offset != 0) {
10959            final boolean matrixIsIdentity = hasIdentityMatrix();
10960            if (matrixIsIdentity) {
10961                if (isHardwareAccelerated()) {
10962                    invalidateViewProperty(false, false);
10963                } else {
10964                    final ViewParent p = mParent;
10965                    if (p != null && mAttachInfo != null) {
10966                        final Rect r = mAttachInfo.mTmpInvalRect;
10967                        int minTop;
10968                        int maxBottom;
10969                        int yLoc;
10970                        if (offset < 0) {
10971                            minTop = mTop + offset;
10972                            maxBottom = mBottom;
10973                            yLoc = offset;
10974                        } else {
10975                            minTop = mTop;
10976                            maxBottom = mBottom + offset;
10977                            yLoc = 0;
10978                        }
10979                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10980                        p.invalidateChild(this, r);
10981                    }
10982                }
10983            } else {
10984                invalidateViewProperty(false, false);
10985            }
10986
10987            mTop += offset;
10988            mBottom += offset;
10989            mRenderNode.offsetTopAndBottom(offset);
10990            if (isHardwareAccelerated()) {
10991                invalidateViewProperty(false, false);
10992            } else {
10993                if (!matrixIsIdentity) {
10994                    invalidateViewProperty(false, true);
10995                }
10996                invalidateParentIfNeeded();
10997            }
10998            notifySubtreeAccessibilityStateChangedIfNeeded();
10999        }
11000    }
11001
11002    /**
11003     * Offset this view's horizontal location by the specified amount of pixels.
11004     *
11005     * @param offset the number of pixels to offset the view by
11006     */
11007    public void offsetLeftAndRight(int offset) {
11008        if (offset != 0) {
11009            final boolean matrixIsIdentity = hasIdentityMatrix();
11010            if (matrixIsIdentity) {
11011                if (isHardwareAccelerated()) {
11012                    invalidateViewProperty(false, false);
11013                } else {
11014                    final ViewParent p = mParent;
11015                    if (p != null && mAttachInfo != null) {
11016                        final Rect r = mAttachInfo.mTmpInvalRect;
11017                        int minLeft;
11018                        int maxRight;
11019                        if (offset < 0) {
11020                            minLeft = mLeft + offset;
11021                            maxRight = mRight;
11022                        } else {
11023                            minLeft = mLeft;
11024                            maxRight = mRight + offset;
11025                        }
11026                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11027                        p.invalidateChild(this, r);
11028                    }
11029                }
11030            } else {
11031                invalidateViewProperty(false, false);
11032            }
11033
11034            mLeft += offset;
11035            mRight += offset;
11036            mRenderNode.offsetLeftAndRight(offset);
11037            if (isHardwareAccelerated()) {
11038                invalidateViewProperty(false, false);
11039            } else {
11040                if (!matrixIsIdentity) {
11041                    invalidateViewProperty(false, true);
11042                }
11043                invalidateParentIfNeeded();
11044            }
11045            notifySubtreeAccessibilityStateChangedIfNeeded();
11046        }
11047    }
11048
11049    /**
11050     * Get the LayoutParams associated with this view. All views should have
11051     * layout parameters. These supply parameters to the <i>parent</i> of this
11052     * view specifying how it should be arranged. There are many subclasses of
11053     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11054     * of ViewGroup that are responsible for arranging their children.
11055     *
11056     * This method may return null if this View is not attached to a parent
11057     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11058     * was not invoked successfully. When a View is attached to a parent
11059     * ViewGroup, this method must not return null.
11060     *
11061     * @return The LayoutParams associated with this view, or null if no
11062     *         parameters have been set yet
11063     */
11064    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11065    public ViewGroup.LayoutParams getLayoutParams() {
11066        return mLayoutParams;
11067    }
11068
11069    /**
11070     * Set the layout parameters associated with this view. These supply
11071     * parameters to the <i>parent</i> of this view specifying how it should be
11072     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11073     * correspond to the different subclasses of ViewGroup that are responsible
11074     * for arranging their children.
11075     *
11076     * @param params The layout parameters for this view, cannot be null
11077     */
11078    public void setLayoutParams(ViewGroup.LayoutParams params) {
11079        if (params == null) {
11080            throw new NullPointerException("Layout parameters cannot be null");
11081        }
11082        mLayoutParams = params;
11083        resolveLayoutParams();
11084        if (mParent instanceof ViewGroup) {
11085            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11086        }
11087        requestLayout();
11088    }
11089
11090    /**
11091     * Resolve the layout parameters depending on the resolved layout direction
11092     *
11093     * @hide
11094     */
11095    public void resolveLayoutParams() {
11096        if (mLayoutParams != null) {
11097            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11098        }
11099    }
11100
11101    /**
11102     * Set the scrolled position of your view. This will cause a call to
11103     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11104     * invalidated.
11105     * @param x the x position to scroll to
11106     * @param y the y position to scroll to
11107     */
11108    public void scrollTo(int x, int y) {
11109        if (mScrollX != x || mScrollY != y) {
11110            int oldX = mScrollX;
11111            int oldY = mScrollY;
11112            mScrollX = x;
11113            mScrollY = y;
11114            invalidateParentCaches();
11115            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11116            if (!awakenScrollBars()) {
11117                postInvalidateOnAnimation();
11118            }
11119        }
11120    }
11121
11122    /**
11123     * Move the scrolled position of your view. This will cause a call to
11124     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11125     * invalidated.
11126     * @param x the amount of pixels to scroll by horizontally
11127     * @param y the amount of pixels to scroll by vertically
11128     */
11129    public void scrollBy(int x, int y) {
11130        scrollTo(mScrollX + x, mScrollY + y);
11131    }
11132
11133    /**
11134     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11135     * animation to fade the scrollbars out after a default delay. If a subclass
11136     * provides animated scrolling, the start delay should equal the duration
11137     * of the scrolling animation.</p>
11138     *
11139     * <p>The animation starts only if at least one of the scrollbars is
11140     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11141     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11142     * this method returns true, and false otherwise. If the animation is
11143     * started, this method calls {@link #invalidate()}; in that case the
11144     * caller should not call {@link #invalidate()}.</p>
11145     *
11146     * <p>This method should be invoked every time a subclass directly updates
11147     * the scroll parameters.</p>
11148     *
11149     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11150     * and {@link #scrollTo(int, int)}.</p>
11151     *
11152     * @return true if the animation is played, false otherwise
11153     *
11154     * @see #awakenScrollBars(int)
11155     * @see #scrollBy(int, int)
11156     * @see #scrollTo(int, int)
11157     * @see #isHorizontalScrollBarEnabled()
11158     * @see #isVerticalScrollBarEnabled()
11159     * @see #setHorizontalScrollBarEnabled(boolean)
11160     * @see #setVerticalScrollBarEnabled(boolean)
11161     */
11162    protected boolean awakenScrollBars() {
11163        return mScrollCache != null &&
11164                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11165    }
11166
11167    /**
11168     * Trigger the scrollbars to draw.
11169     * This method differs from awakenScrollBars() only in its default duration.
11170     * initialAwakenScrollBars() will show the scroll bars for longer than
11171     * usual to give the user more of a chance to notice them.
11172     *
11173     * @return true if the animation is played, false otherwise.
11174     */
11175    private boolean initialAwakenScrollBars() {
11176        return mScrollCache != null &&
11177                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11178    }
11179
11180    /**
11181     * <p>
11182     * Trigger the scrollbars to draw. When invoked this method starts an
11183     * animation to fade the scrollbars out after a fixed delay. If a subclass
11184     * provides animated scrolling, the start delay should equal the duration of
11185     * the scrolling animation.
11186     * </p>
11187     *
11188     * <p>
11189     * The animation starts only if at least one of the scrollbars is enabled,
11190     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11191     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11192     * this method returns true, and false otherwise. If the animation is
11193     * started, this method calls {@link #invalidate()}; in that case the caller
11194     * should not call {@link #invalidate()}.
11195     * </p>
11196     *
11197     * <p>
11198     * This method should be invoked everytime a subclass directly updates the
11199     * scroll parameters.
11200     * </p>
11201     *
11202     * @param startDelay the delay, in milliseconds, after which the animation
11203     *        should start; when the delay is 0, the animation starts
11204     *        immediately
11205     * @return true if the animation is played, false otherwise
11206     *
11207     * @see #scrollBy(int, int)
11208     * @see #scrollTo(int, int)
11209     * @see #isHorizontalScrollBarEnabled()
11210     * @see #isVerticalScrollBarEnabled()
11211     * @see #setHorizontalScrollBarEnabled(boolean)
11212     * @see #setVerticalScrollBarEnabled(boolean)
11213     */
11214    protected boolean awakenScrollBars(int startDelay) {
11215        return awakenScrollBars(startDelay, true);
11216    }
11217
11218    /**
11219     * <p>
11220     * Trigger the scrollbars to draw. When invoked this method starts an
11221     * animation to fade the scrollbars out after a fixed delay. If a subclass
11222     * provides animated scrolling, the start delay should equal the duration of
11223     * the scrolling animation.
11224     * </p>
11225     *
11226     * <p>
11227     * The animation starts only if at least one of the scrollbars is enabled,
11228     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11229     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11230     * this method returns true, and false otherwise. If the animation is
11231     * started, this method calls {@link #invalidate()} if the invalidate parameter
11232     * is set to true; in that case the caller
11233     * should not call {@link #invalidate()}.
11234     * </p>
11235     *
11236     * <p>
11237     * This method should be invoked everytime a subclass directly updates the
11238     * scroll parameters.
11239     * </p>
11240     *
11241     * @param startDelay the delay, in milliseconds, after which the animation
11242     *        should start; when the delay is 0, the animation starts
11243     *        immediately
11244     *
11245     * @param invalidate Wheter this method should call invalidate
11246     *
11247     * @return true if the animation is played, false otherwise
11248     *
11249     * @see #scrollBy(int, int)
11250     * @see #scrollTo(int, int)
11251     * @see #isHorizontalScrollBarEnabled()
11252     * @see #isVerticalScrollBarEnabled()
11253     * @see #setHorizontalScrollBarEnabled(boolean)
11254     * @see #setVerticalScrollBarEnabled(boolean)
11255     */
11256    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11257        final ScrollabilityCache scrollCache = mScrollCache;
11258
11259        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11260            return false;
11261        }
11262
11263        if (scrollCache.scrollBar == null) {
11264            scrollCache.scrollBar = new ScrollBarDrawable();
11265        }
11266
11267        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11268
11269            if (invalidate) {
11270                // Invalidate to show the scrollbars
11271                postInvalidateOnAnimation();
11272            }
11273
11274            if (scrollCache.state == ScrollabilityCache.OFF) {
11275                // FIXME: this is copied from WindowManagerService.
11276                // We should get this value from the system when it
11277                // is possible to do so.
11278                final int KEY_REPEAT_FIRST_DELAY = 750;
11279                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11280            }
11281
11282            // Tell mScrollCache when we should start fading. This may
11283            // extend the fade start time if one was already scheduled
11284            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11285            scrollCache.fadeStartTime = fadeStartTime;
11286            scrollCache.state = ScrollabilityCache.ON;
11287
11288            // Schedule our fader to run, unscheduling any old ones first
11289            if (mAttachInfo != null) {
11290                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11291                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11292            }
11293
11294            return true;
11295        }
11296
11297        return false;
11298    }
11299
11300    /**
11301     * Do not invalidate views which are not visible and which are not running an animation. They
11302     * will not get drawn and they should not set dirty flags as if they will be drawn
11303     */
11304    private boolean skipInvalidate() {
11305        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11306                (!(mParent instanceof ViewGroup) ||
11307                        !((ViewGroup) mParent).isViewTransitioning(this));
11308    }
11309
11310    /**
11311     * Mark the area defined by dirty as needing to be drawn. If the view is
11312     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11313     * point in the future.
11314     * <p>
11315     * This must be called from a UI thread. To call from a non-UI thread, call
11316     * {@link #postInvalidate()}.
11317     * <p>
11318     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11319     * {@code dirty}.
11320     *
11321     * @param dirty the rectangle representing the bounds of the dirty region
11322     */
11323    public void invalidate(Rect dirty) {
11324        final int scrollX = mScrollX;
11325        final int scrollY = mScrollY;
11326        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11327                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11328    }
11329
11330    /**
11331     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11332     * coordinates of the dirty rect are relative to the view. If the view is
11333     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11334     * point in the future.
11335     * <p>
11336     * This must be called from a UI thread. To call from a non-UI thread, call
11337     * {@link #postInvalidate()}.
11338     *
11339     * @param l the left position of the dirty region
11340     * @param t the top position of the dirty region
11341     * @param r the right position of the dirty region
11342     * @param b the bottom position of the dirty region
11343     */
11344    public void invalidate(int l, int t, int r, int b) {
11345        final int scrollX = mScrollX;
11346        final int scrollY = mScrollY;
11347        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11348    }
11349
11350    /**
11351     * Invalidate the whole view. If the view is visible,
11352     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11353     * the future.
11354     * <p>
11355     * This must be called from a UI thread. To call from a non-UI thread, call
11356     * {@link #postInvalidate()}.
11357     */
11358    public void invalidate() {
11359        invalidate(true);
11360    }
11361
11362    /**
11363     * This is where the invalidate() work actually happens. A full invalidate()
11364     * causes the drawing cache to be invalidated, but this function can be
11365     * called with invalidateCache set to false to skip that invalidation step
11366     * for cases that do not need it (for example, a component that remains at
11367     * the same dimensions with the same content).
11368     *
11369     * @param invalidateCache Whether the drawing cache for this view should be
11370     *            invalidated as well. This is usually true for a full
11371     *            invalidate, but may be set to false if the View's contents or
11372     *            dimensions have not changed.
11373     */
11374    void invalidate(boolean invalidateCache) {
11375        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11376    }
11377
11378    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11379            boolean fullInvalidate) {
11380        if (mGhostView != null) {
11381            mGhostView.invalidate(invalidateCache);
11382            return;
11383        }
11384
11385        if (skipInvalidate()) {
11386            return;
11387        }
11388
11389        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11390                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11391                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11392                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11393            if (fullInvalidate) {
11394                mLastIsOpaque = isOpaque();
11395                mPrivateFlags &= ~PFLAG_DRAWN;
11396            }
11397
11398            mPrivateFlags |= PFLAG_DIRTY;
11399
11400            if (invalidateCache) {
11401                mPrivateFlags |= PFLAG_INVALIDATED;
11402                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11403            }
11404
11405            // Propagate the damage rectangle to the parent view.
11406            final AttachInfo ai = mAttachInfo;
11407            final ViewParent p = mParent;
11408            if (p != null && ai != null && l < r && t < b) {
11409                final Rect damage = ai.mTmpInvalRect;
11410                damage.set(l, t, r, b);
11411                p.invalidateChild(this, damage);
11412            }
11413
11414            // Damage the entire projection receiver, if necessary.
11415            if (mBackground != null && mBackground.isProjected()) {
11416                final View receiver = getProjectionReceiver();
11417                if (receiver != null) {
11418                    receiver.damageInParent();
11419                }
11420            }
11421
11422            // Damage the entire IsolatedZVolume receiving this view's shadow.
11423            if (isHardwareAccelerated() && getZ() != 0) {
11424                damageShadowReceiver();
11425            }
11426        }
11427    }
11428
11429    /**
11430     * @return this view's projection receiver, or {@code null} if none exists
11431     */
11432    private View getProjectionReceiver() {
11433        ViewParent p = getParent();
11434        while (p != null && p instanceof View) {
11435            final View v = (View) p;
11436            if (v.isProjectionReceiver()) {
11437                return v;
11438            }
11439            p = p.getParent();
11440        }
11441
11442        return null;
11443    }
11444
11445    /**
11446     * @return whether the view is a projection receiver
11447     */
11448    private boolean isProjectionReceiver() {
11449        return mBackground != null;
11450    }
11451
11452    /**
11453     * Damage area of the screen that can be covered by this View's shadow.
11454     *
11455     * This method will guarantee that any changes to shadows cast by a View
11456     * are damaged on the screen for future redraw.
11457     */
11458    private void damageShadowReceiver() {
11459        final AttachInfo ai = mAttachInfo;
11460        if (ai != null) {
11461            ViewParent p = getParent();
11462            if (p != null && p instanceof ViewGroup) {
11463                final ViewGroup vg = (ViewGroup) p;
11464                vg.damageInParent();
11465            }
11466        }
11467    }
11468
11469    /**
11470     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11471     * set any flags or handle all of the cases handled by the default invalidation methods.
11472     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11473     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11474     * walk up the hierarchy, transforming the dirty rect as necessary.
11475     *
11476     * The method also handles normal invalidation logic if display list properties are not
11477     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11478     * backup approach, to handle these cases used in the various property-setting methods.
11479     *
11480     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11481     * are not being used in this view
11482     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11483     * list properties are not being used in this view
11484     */
11485    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11486        if (!isHardwareAccelerated()
11487                || !mRenderNode.isValid()
11488                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11489            if (invalidateParent) {
11490                invalidateParentCaches();
11491            }
11492            if (forceRedraw) {
11493                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11494            }
11495            invalidate(false);
11496        } else {
11497            damageInParent();
11498        }
11499        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11500            damageShadowReceiver();
11501        }
11502    }
11503
11504    /**
11505     * Tells the parent view to damage this view's bounds.
11506     *
11507     * @hide
11508     */
11509    protected void damageInParent() {
11510        final AttachInfo ai = mAttachInfo;
11511        final ViewParent p = mParent;
11512        if (p != null && ai != null) {
11513            final Rect r = ai.mTmpInvalRect;
11514            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11515            if (mParent instanceof ViewGroup) {
11516                ((ViewGroup) mParent).damageChild(this, r);
11517            } else {
11518                mParent.invalidateChild(this, r);
11519            }
11520        }
11521    }
11522
11523    /**
11524     * Utility method to transform a given Rect by the current matrix of this view.
11525     */
11526    void transformRect(final Rect rect) {
11527        if (!getMatrix().isIdentity()) {
11528            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11529            boundingRect.set(rect);
11530            getMatrix().mapRect(boundingRect);
11531            rect.set((int) Math.floor(boundingRect.left),
11532                    (int) Math.floor(boundingRect.top),
11533                    (int) Math.ceil(boundingRect.right),
11534                    (int) Math.ceil(boundingRect.bottom));
11535        }
11536    }
11537
11538    /**
11539     * Used to indicate that the parent of this view should clear its caches. This functionality
11540     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11541     * which is necessary when various parent-managed properties of the view change, such as
11542     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11543     * clears the parent caches and does not causes an invalidate event.
11544     *
11545     * @hide
11546     */
11547    protected void invalidateParentCaches() {
11548        if (mParent instanceof View) {
11549            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11550        }
11551    }
11552
11553    /**
11554     * Used to indicate that the parent of this view should be invalidated. This functionality
11555     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11556     * which is necessary when various parent-managed properties of the view change, such as
11557     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11558     * an invalidation event to the parent.
11559     *
11560     * @hide
11561     */
11562    protected void invalidateParentIfNeeded() {
11563        if (isHardwareAccelerated() && mParent instanceof View) {
11564            ((View) mParent).invalidate(true);
11565        }
11566    }
11567
11568    /**
11569     * @hide
11570     */
11571    protected void invalidateParentIfNeededAndWasQuickRejected() {
11572        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11573            // View was rejected last time it was drawn by its parent; this may have changed
11574            invalidateParentIfNeeded();
11575        }
11576    }
11577
11578    /**
11579     * Indicates whether this View is opaque. An opaque View guarantees that it will
11580     * draw all the pixels overlapping its bounds using a fully opaque color.
11581     *
11582     * Subclasses of View should override this method whenever possible to indicate
11583     * whether an instance is opaque. Opaque Views are treated in a special way by
11584     * the View hierarchy, possibly allowing it to perform optimizations during
11585     * invalidate/draw passes.
11586     *
11587     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11588     */
11589    @ViewDebug.ExportedProperty(category = "drawing")
11590    public boolean isOpaque() {
11591        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11592                getFinalAlpha() >= 1.0f;
11593    }
11594
11595    /**
11596     * @hide
11597     */
11598    protected void computeOpaqueFlags() {
11599        // Opaque if:
11600        //   - Has a background
11601        //   - Background is opaque
11602        //   - Doesn't have scrollbars or scrollbars overlay
11603
11604        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11605            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11606        } else {
11607            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11608        }
11609
11610        final int flags = mViewFlags;
11611        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11612                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11613                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11614            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11615        } else {
11616            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11617        }
11618    }
11619
11620    /**
11621     * @hide
11622     */
11623    protected boolean hasOpaqueScrollbars() {
11624        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11625    }
11626
11627    /**
11628     * @return A handler associated with the thread running the View. This
11629     * handler can be used to pump events in the UI events queue.
11630     */
11631    public Handler getHandler() {
11632        final AttachInfo attachInfo = mAttachInfo;
11633        if (attachInfo != null) {
11634            return attachInfo.mHandler;
11635        }
11636        return null;
11637    }
11638
11639    /**
11640     * Gets the view root associated with the View.
11641     * @return The view root, or null if none.
11642     * @hide
11643     */
11644    public ViewRootImpl getViewRootImpl() {
11645        if (mAttachInfo != null) {
11646            return mAttachInfo.mViewRootImpl;
11647        }
11648        return null;
11649    }
11650
11651    /**
11652     * @hide
11653     */
11654    public HardwareRenderer getHardwareRenderer() {
11655        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11656    }
11657
11658    /**
11659     * <p>Causes the Runnable to be added to the message queue.
11660     * The runnable will be run on the user interface thread.</p>
11661     *
11662     * @param action The Runnable that will be executed.
11663     *
11664     * @return Returns true if the Runnable was successfully placed in to the
11665     *         message queue.  Returns false on failure, usually because the
11666     *         looper processing the message queue is exiting.
11667     *
11668     * @see #postDelayed
11669     * @see #removeCallbacks
11670     */
11671    public boolean post(Runnable action) {
11672        final AttachInfo attachInfo = mAttachInfo;
11673        if (attachInfo != null) {
11674            return attachInfo.mHandler.post(action);
11675        }
11676        // Assume that post will succeed later
11677        ViewRootImpl.getRunQueue().post(action);
11678        return true;
11679    }
11680
11681    /**
11682     * <p>Causes the Runnable to be added to the message queue, to be run
11683     * after the specified amount of time elapses.
11684     * The runnable will be run on the user interface thread.</p>
11685     *
11686     * @param action The Runnable that will be executed.
11687     * @param delayMillis The delay (in milliseconds) until the Runnable
11688     *        will be executed.
11689     *
11690     * @return true if the Runnable was successfully placed in to the
11691     *         message queue.  Returns false on failure, usually because the
11692     *         looper processing the message queue is exiting.  Note that a
11693     *         result of true does not mean the Runnable will be processed --
11694     *         if the looper is quit before the delivery time of the message
11695     *         occurs then the message will be dropped.
11696     *
11697     * @see #post
11698     * @see #removeCallbacks
11699     */
11700    public boolean postDelayed(Runnable action, long delayMillis) {
11701        final AttachInfo attachInfo = mAttachInfo;
11702        if (attachInfo != null) {
11703            return attachInfo.mHandler.postDelayed(action, delayMillis);
11704        }
11705        // Assume that post will succeed later
11706        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11707        return true;
11708    }
11709
11710    /**
11711     * <p>Causes the Runnable to execute on the next animation time step.
11712     * The runnable will be run on the user interface thread.</p>
11713     *
11714     * @param action The Runnable that will be executed.
11715     *
11716     * @see #postOnAnimationDelayed
11717     * @see #removeCallbacks
11718     */
11719    public void postOnAnimation(Runnable action) {
11720        final AttachInfo attachInfo = mAttachInfo;
11721        if (attachInfo != null) {
11722            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11723                    Choreographer.CALLBACK_ANIMATION, action, null);
11724        } else {
11725            // Assume that post will succeed later
11726            ViewRootImpl.getRunQueue().post(action);
11727        }
11728    }
11729
11730    /**
11731     * <p>Causes the Runnable to execute on the next animation time step,
11732     * after the specified amount of time elapses.
11733     * The runnable will be run on the user interface thread.</p>
11734     *
11735     * @param action The Runnable that will be executed.
11736     * @param delayMillis The delay (in milliseconds) until the Runnable
11737     *        will be executed.
11738     *
11739     * @see #postOnAnimation
11740     * @see #removeCallbacks
11741     */
11742    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11743        final AttachInfo attachInfo = mAttachInfo;
11744        if (attachInfo != null) {
11745            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11746                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11747        } else {
11748            // Assume that post will succeed later
11749            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11750        }
11751    }
11752
11753    /**
11754     * <p>Removes the specified Runnable from the message queue.</p>
11755     *
11756     * @param action The Runnable to remove from the message handling queue
11757     *
11758     * @return true if this view could ask the Handler to remove the Runnable,
11759     *         false otherwise. When the returned value is true, the Runnable
11760     *         may or may not have been actually removed from the message queue
11761     *         (for instance, if the Runnable was not in the queue already.)
11762     *
11763     * @see #post
11764     * @see #postDelayed
11765     * @see #postOnAnimation
11766     * @see #postOnAnimationDelayed
11767     */
11768    public boolean removeCallbacks(Runnable action) {
11769        if (action != null) {
11770            final AttachInfo attachInfo = mAttachInfo;
11771            if (attachInfo != null) {
11772                attachInfo.mHandler.removeCallbacks(action);
11773                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11774                        Choreographer.CALLBACK_ANIMATION, action, null);
11775            }
11776            // Assume that post will succeed later
11777            ViewRootImpl.getRunQueue().removeCallbacks(action);
11778        }
11779        return true;
11780    }
11781
11782    /**
11783     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11784     * Use this to invalidate the View from a non-UI thread.</p>
11785     *
11786     * <p>This method can be invoked from outside of the UI thread
11787     * only when this View is attached to a window.</p>
11788     *
11789     * @see #invalidate()
11790     * @see #postInvalidateDelayed(long)
11791     */
11792    public void postInvalidate() {
11793        postInvalidateDelayed(0);
11794    }
11795
11796    /**
11797     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11798     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11799     *
11800     * <p>This method can be invoked from outside of the UI thread
11801     * only when this View is attached to a window.</p>
11802     *
11803     * @param left The left coordinate of the rectangle to invalidate.
11804     * @param top The top coordinate of the rectangle to invalidate.
11805     * @param right The right coordinate of the rectangle to invalidate.
11806     * @param bottom The bottom coordinate of the rectangle to invalidate.
11807     *
11808     * @see #invalidate(int, int, int, int)
11809     * @see #invalidate(Rect)
11810     * @see #postInvalidateDelayed(long, int, int, int, int)
11811     */
11812    public void postInvalidate(int left, int top, int right, int bottom) {
11813        postInvalidateDelayed(0, left, top, right, bottom);
11814    }
11815
11816    /**
11817     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11818     * loop. Waits for the specified amount of time.</p>
11819     *
11820     * <p>This method can be invoked from outside of the UI thread
11821     * only when this View is attached to a window.</p>
11822     *
11823     * @param delayMilliseconds the duration in milliseconds to delay the
11824     *         invalidation by
11825     *
11826     * @see #invalidate()
11827     * @see #postInvalidate()
11828     */
11829    public void postInvalidateDelayed(long delayMilliseconds) {
11830        // We try only with the AttachInfo because there's no point in invalidating
11831        // if we are not attached to our window
11832        final AttachInfo attachInfo = mAttachInfo;
11833        if (attachInfo != null) {
11834            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11835        }
11836    }
11837
11838    /**
11839     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11840     * through the event loop. Waits for the specified amount of time.</p>
11841     *
11842     * <p>This method can be invoked from outside of the UI thread
11843     * only when this View is attached to a window.</p>
11844     *
11845     * @param delayMilliseconds the duration in milliseconds to delay the
11846     *         invalidation by
11847     * @param left The left coordinate of the rectangle to invalidate.
11848     * @param top The top coordinate of the rectangle to invalidate.
11849     * @param right The right coordinate of the rectangle to invalidate.
11850     * @param bottom The bottom coordinate of the rectangle to invalidate.
11851     *
11852     * @see #invalidate(int, int, int, int)
11853     * @see #invalidate(Rect)
11854     * @see #postInvalidate(int, int, int, int)
11855     */
11856    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11857            int right, int bottom) {
11858
11859        // We try only with the AttachInfo because there's no point in invalidating
11860        // if we are not attached to our window
11861        final AttachInfo attachInfo = mAttachInfo;
11862        if (attachInfo != null) {
11863            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11864            info.target = this;
11865            info.left = left;
11866            info.top = top;
11867            info.right = right;
11868            info.bottom = bottom;
11869
11870            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11871        }
11872    }
11873
11874    /**
11875     * <p>Cause an invalidate to happen on the next animation time step, typically the
11876     * next display frame.</p>
11877     *
11878     * <p>This method can be invoked from outside of the UI thread
11879     * only when this View is attached to a window.</p>
11880     *
11881     * @see #invalidate()
11882     */
11883    public void postInvalidateOnAnimation() {
11884        // We try only with the AttachInfo because there's no point in invalidating
11885        // if we are not attached to our window
11886        final AttachInfo attachInfo = mAttachInfo;
11887        if (attachInfo != null) {
11888            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11889        }
11890    }
11891
11892    /**
11893     * <p>Cause an invalidate of the specified area to happen on the next animation
11894     * time step, typically the next display frame.</p>
11895     *
11896     * <p>This method can be invoked from outside of the UI thread
11897     * only when this View is attached to a window.</p>
11898     *
11899     * @param left The left coordinate of the rectangle to invalidate.
11900     * @param top The top coordinate of the rectangle to invalidate.
11901     * @param right The right coordinate of the rectangle to invalidate.
11902     * @param bottom The bottom coordinate of the rectangle to invalidate.
11903     *
11904     * @see #invalidate(int, int, int, int)
11905     * @see #invalidate(Rect)
11906     */
11907    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11908        // We try only with the AttachInfo because there's no point in invalidating
11909        // if we are not attached to our window
11910        final AttachInfo attachInfo = mAttachInfo;
11911        if (attachInfo != null) {
11912            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11913            info.target = this;
11914            info.left = left;
11915            info.top = top;
11916            info.right = right;
11917            info.bottom = bottom;
11918
11919            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11920        }
11921    }
11922
11923    /**
11924     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11925     * This event is sent at most once every
11926     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11927     */
11928    private void postSendViewScrolledAccessibilityEventCallback() {
11929        if (mSendViewScrolledAccessibilityEvent == null) {
11930            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11931        }
11932        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11933            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11934            postDelayed(mSendViewScrolledAccessibilityEvent,
11935                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11936        }
11937    }
11938
11939    /**
11940     * Called by a parent to request that a child update its values for mScrollX
11941     * and mScrollY if necessary. This will typically be done if the child is
11942     * animating a scroll using a {@link android.widget.Scroller Scroller}
11943     * object.
11944     */
11945    public void computeScroll() {
11946    }
11947
11948    /**
11949     * <p>Indicate whether the horizontal edges are faded when the view is
11950     * scrolled horizontally.</p>
11951     *
11952     * @return true if the horizontal edges should are faded on scroll, false
11953     *         otherwise
11954     *
11955     * @see #setHorizontalFadingEdgeEnabled(boolean)
11956     *
11957     * @attr ref android.R.styleable#View_requiresFadingEdge
11958     */
11959    public boolean isHorizontalFadingEdgeEnabled() {
11960        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11961    }
11962
11963    /**
11964     * <p>Define whether the horizontal edges should be faded when this view
11965     * is scrolled horizontally.</p>
11966     *
11967     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11968     *                                    be faded when the view is scrolled
11969     *                                    horizontally
11970     *
11971     * @see #isHorizontalFadingEdgeEnabled()
11972     *
11973     * @attr ref android.R.styleable#View_requiresFadingEdge
11974     */
11975    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11976        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11977            if (horizontalFadingEdgeEnabled) {
11978                initScrollCache();
11979            }
11980
11981            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11982        }
11983    }
11984
11985    /**
11986     * <p>Indicate whether the vertical edges are faded when the view is
11987     * scrolled horizontally.</p>
11988     *
11989     * @return true if the vertical edges should are faded on scroll, false
11990     *         otherwise
11991     *
11992     * @see #setVerticalFadingEdgeEnabled(boolean)
11993     *
11994     * @attr ref android.R.styleable#View_requiresFadingEdge
11995     */
11996    public boolean isVerticalFadingEdgeEnabled() {
11997        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11998    }
11999
12000    /**
12001     * <p>Define whether the vertical edges should be faded when this view
12002     * is scrolled vertically.</p>
12003     *
12004     * @param verticalFadingEdgeEnabled true if the vertical edges should
12005     *                                  be faded when the view is scrolled
12006     *                                  vertically
12007     *
12008     * @see #isVerticalFadingEdgeEnabled()
12009     *
12010     * @attr ref android.R.styleable#View_requiresFadingEdge
12011     */
12012    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12013        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12014            if (verticalFadingEdgeEnabled) {
12015                initScrollCache();
12016            }
12017
12018            mViewFlags ^= FADING_EDGE_VERTICAL;
12019        }
12020    }
12021
12022    /**
12023     * Returns the strength, or intensity, of the top faded edge. The strength is
12024     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12025     * returns 0.0 or 1.0 but no value in between.
12026     *
12027     * Subclasses should override this method to provide a smoother fade transition
12028     * when scrolling occurs.
12029     *
12030     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12031     */
12032    protected float getTopFadingEdgeStrength() {
12033        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12034    }
12035
12036    /**
12037     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12038     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12039     * returns 0.0 or 1.0 but no value in between.
12040     *
12041     * Subclasses should override this method to provide a smoother fade transition
12042     * when scrolling occurs.
12043     *
12044     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12045     */
12046    protected float getBottomFadingEdgeStrength() {
12047        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12048                computeVerticalScrollRange() ? 1.0f : 0.0f;
12049    }
12050
12051    /**
12052     * Returns the strength, or intensity, of the left faded edge. The strength is
12053     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12054     * returns 0.0 or 1.0 but no value in between.
12055     *
12056     * Subclasses should override this method to provide a smoother fade transition
12057     * when scrolling occurs.
12058     *
12059     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12060     */
12061    protected float getLeftFadingEdgeStrength() {
12062        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12063    }
12064
12065    /**
12066     * Returns the strength, or intensity, of the right faded edge. The strength is
12067     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12068     * returns 0.0 or 1.0 but no value in between.
12069     *
12070     * Subclasses should override this method to provide a smoother fade transition
12071     * when scrolling occurs.
12072     *
12073     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12074     */
12075    protected float getRightFadingEdgeStrength() {
12076        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12077                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12078    }
12079
12080    /**
12081     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12082     * scrollbar is not drawn by default.</p>
12083     *
12084     * @return true if the horizontal scrollbar should be painted, false
12085     *         otherwise
12086     *
12087     * @see #setHorizontalScrollBarEnabled(boolean)
12088     */
12089    public boolean isHorizontalScrollBarEnabled() {
12090        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12091    }
12092
12093    /**
12094     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12095     * scrollbar is not drawn by default.</p>
12096     *
12097     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12098     *                                   be painted
12099     *
12100     * @see #isHorizontalScrollBarEnabled()
12101     */
12102    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12103        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12104            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12105            computeOpaqueFlags();
12106            resolvePadding();
12107        }
12108    }
12109
12110    /**
12111     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12112     * scrollbar is not drawn by default.</p>
12113     *
12114     * @return true if the vertical scrollbar should be painted, false
12115     *         otherwise
12116     *
12117     * @see #setVerticalScrollBarEnabled(boolean)
12118     */
12119    public boolean isVerticalScrollBarEnabled() {
12120        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12121    }
12122
12123    /**
12124     * <p>Define whether the vertical scrollbar should be drawn or not. The
12125     * scrollbar is not drawn by default.</p>
12126     *
12127     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12128     *                                 be painted
12129     *
12130     * @see #isVerticalScrollBarEnabled()
12131     */
12132    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12133        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12134            mViewFlags ^= SCROLLBARS_VERTICAL;
12135            computeOpaqueFlags();
12136            resolvePadding();
12137        }
12138    }
12139
12140    /**
12141     * @hide
12142     */
12143    protected void recomputePadding() {
12144        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12145    }
12146
12147    /**
12148     * Define whether scrollbars will fade when the view is not scrolling.
12149     *
12150     * @param fadeScrollbars wheter to enable fading
12151     *
12152     * @attr ref android.R.styleable#View_fadeScrollbars
12153     */
12154    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12155        initScrollCache();
12156        final ScrollabilityCache scrollabilityCache = mScrollCache;
12157        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12158        if (fadeScrollbars) {
12159            scrollabilityCache.state = ScrollabilityCache.OFF;
12160        } else {
12161            scrollabilityCache.state = ScrollabilityCache.ON;
12162        }
12163    }
12164
12165    /**
12166     *
12167     * Returns true if scrollbars will fade when this view is not scrolling
12168     *
12169     * @return true if scrollbar fading is enabled
12170     *
12171     * @attr ref android.R.styleable#View_fadeScrollbars
12172     */
12173    public boolean isScrollbarFadingEnabled() {
12174        return mScrollCache != null && mScrollCache.fadeScrollBars;
12175    }
12176
12177    /**
12178     *
12179     * Returns the delay before scrollbars fade.
12180     *
12181     * @return the delay before scrollbars fade
12182     *
12183     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12184     */
12185    public int getScrollBarDefaultDelayBeforeFade() {
12186        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12187                mScrollCache.scrollBarDefaultDelayBeforeFade;
12188    }
12189
12190    /**
12191     * Define the delay before scrollbars fade.
12192     *
12193     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12194     *
12195     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12196     */
12197    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12198        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12199    }
12200
12201    /**
12202     *
12203     * Returns the scrollbar fade duration.
12204     *
12205     * @return the scrollbar fade duration
12206     *
12207     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12208     */
12209    public int getScrollBarFadeDuration() {
12210        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12211                mScrollCache.scrollBarFadeDuration;
12212    }
12213
12214    /**
12215     * Define the scrollbar fade duration.
12216     *
12217     * @param scrollBarFadeDuration - the scrollbar fade duration
12218     *
12219     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12220     */
12221    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12222        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12223    }
12224
12225    /**
12226     *
12227     * Returns the scrollbar size.
12228     *
12229     * @return the scrollbar size
12230     *
12231     * @attr ref android.R.styleable#View_scrollbarSize
12232     */
12233    public int getScrollBarSize() {
12234        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12235                mScrollCache.scrollBarSize;
12236    }
12237
12238    /**
12239     * Define the scrollbar size.
12240     *
12241     * @param scrollBarSize - the scrollbar size
12242     *
12243     * @attr ref android.R.styleable#View_scrollbarSize
12244     */
12245    public void setScrollBarSize(int scrollBarSize) {
12246        getScrollCache().scrollBarSize = scrollBarSize;
12247    }
12248
12249    /**
12250     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12251     * inset. When inset, they add to the padding of the view. And the scrollbars
12252     * can be drawn inside the padding area or on the edge of the view. For example,
12253     * if a view has a background drawable and you want to draw the scrollbars
12254     * inside the padding specified by the drawable, you can use
12255     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12256     * appear at the edge of the view, ignoring the padding, then you can use
12257     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12258     * @param style the style of the scrollbars. Should be one of
12259     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12260     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12261     * @see #SCROLLBARS_INSIDE_OVERLAY
12262     * @see #SCROLLBARS_INSIDE_INSET
12263     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12264     * @see #SCROLLBARS_OUTSIDE_INSET
12265     *
12266     * @attr ref android.R.styleable#View_scrollbarStyle
12267     */
12268    public void setScrollBarStyle(@ScrollBarStyle int style) {
12269        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12270            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12271            computeOpaqueFlags();
12272            resolvePadding();
12273        }
12274    }
12275
12276    /**
12277     * <p>Returns the current scrollbar style.</p>
12278     * @return the current scrollbar style
12279     * @see #SCROLLBARS_INSIDE_OVERLAY
12280     * @see #SCROLLBARS_INSIDE_INSET
12281     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12282     * @see #SCROLLBARS_OUTSIDE_INSET
12283     *
12284     * @attr ref android.R.styleable#View_scrollbarStyle
12285     */
12286    @ViewDebug.ExportedProperty(mapping = {
12287            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12288            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12289            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12290            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12291    })
12292    @ScrollBarStyle
12293    public int getScrollBarStyle() {
12294        return mViewFlags & SCROLLBARS_STYLE_MASK;
12295    }
12296
12297    /**
12298     * <p>Compute the horizontal range that the horizontal scrollbar
12299     * represents.</p>
12300     *
12301     * <p>The range is expressed in arbitrary units that must be the same as the
12302     * units used by {@link #computeHorizontalScrollExtent()} and
12303     * {@link #computeHorizontalScrollOffset()}.</p>
12304     *
12305     * <p>The default range is the drawing width of this view.</p>
12306     *
12307     * @return the total horizontal range represented by the horizontal
12308     *         scrollbar
12309     *
12310     * @see #computeHorizontalScrollExtent()
12311     * @see #computeHorizontalScrollOffset()
12312     * @see android.widget.ScrollBarDrawable
12313     */
12314    protected int computeHorizontalScrollRange() {
12315        return getWidth();
12316    }
12317
12318    /**
12319     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12320     * within the horizontal range. This value is used to compute the position
12321     * of the thumb within the scrollbar's track.</p>
12322     *
12323     * <p>The range is expressed in arbitrary units that must be the same as the
12324     * units used by {@link #computeHorizontalScrollRange()} and
12325     * {@link #computeHorizontalScrollExtent()}.</p>
12326     *
12327     * <p>The default offset is the scroll offset of this view.</p>
12328     *
12329     * @return the horizontal offset of the scrollbar's thumb
12330     *
12331     * @see #computeHorizontalScrollRange()
12332     * @see #computeHorizontalScrollExtent()
12333     * @see android.widget.ScrollBarDrawable
12334     */
12335    protected int computeHorizontalScrollOffset() {
12336        return mScrollX;
12337    }
12338
12339    /**
12340     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12341     * within the horizontal range. This value is used to compute the length
12342     * of the thumb within the scrollbar's track.</p>
12343     *
12344     * <p>The range is expressed in arbitrary units that must be the same as the
12345     * units used by {@link #computeHorizontalScrollRange()} and
12346     * {@link #computeHorizontalScrollOffset()}.</p>
12347     *
12348     * <p>The default extent is the drawing width of this view.</p>
12349     *
12350     * @return the horizontal extent of the scrollbar's thumb
12351     *
12352     * @see #computeHorizontalScrollRange()
12353     * @see #computeHorizontalScrollOffset()
12354     * @see android.widget.ScrollBarDrawable
12355     */
12356    protected int computeHorizontalScrollExtent() {
12357        return getWidth();
12358    }
12359
12360    /**
12361     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12362     *
12363     * <p>The range is expressed in arbitrary units that must be the same as the
12364     * units used by {@link #computeVerticalScrollExtent()} and
12365     * {@link #computeVerticalScrollOffset()}.</p>
12366     *
12367     * @return the total vertical range represented by the vertical scrollbar
12368     *
12369     * <p>The default range is the drawing height of this view.</p>
12370     *
12371     * @see #computeVerticalScrollExtent()
12372     * @see #computeVerticalScrollOffset()
12373     * @see android.widget.ScrollBarDrawable
12374     */
12375    protected int computeVerticalScrollRange() {
12376        return getHeight();
12377    }
12378
12379    /**
12380     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12381     * within the horizontal range. This value is used to compute the position
12382     * of the thumb within the scrollbar's track.</p>
12383     *
12384     * <p>The range is expressed in arbitrary units that must be the same as the
12385     * units used by {@link #computeVerticalScrollRange()} and
12386     * {@link #computeVerticalScrollExtent()}.</p>
12387     *
12388     * <p>The default offset is the scroll offset of this view.</p>
12389     *
12390     * @return the vertical offset of the scrollbar's thumb
12391     *
12392     * @see #computeVerticalScrollRange()
12393     * @see #computeVerticalScrollExtent()
12394     * @see android.widget.ScrollBarDrawable
12395     */
12396    protected int computeVerticalScrollOffset() {
12397        return mScrollY;
12398    }
12399
12400    /**
12401     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12402     * within the vertical range. This value is used to compute the length
12403     * of the thumb within the scrollbar's track.</p>
12404     *
12405     * <p>The range is expressed in arbitrary units that must be the same as the
12406     * units used by {@link #computeVerticalScrollRange()} and
12407     * {@link #computeVerticalScrollOffset()}.</p>
12408     *
12409     * <p>The default extent is the drawing height of this view.</p>
12410     *
12411     * @return the vertical extent of the scrollbar's thumb
12412     *
12413     * @see #computeVerticalScrollRange()
12414     * @see #computeVerticalScrollOffset()
12415     * @see android.widget.ScrollBarDrawable
12416     */
12417    protected int computeVerticalScrollExtent() {
12418        return getHeight();
12419    }
12420
12421    /**
12422     * Check if this view can be scrolled horizontally in a certain direction.
12423     *
12424     * @param direction Negative to check scrolling left, positive to check scrolling right.
12425     * @return true if this view can be scrolled in the specified direction, false otherwise.
12426     */
12427    public boolean canScrollHorizontally(int direction) {
12428        final int offset = computeHorizontalScrollOffset();
12429        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12430        if (range == 0) return false;
12431        if (direction < 0) {
12432            return offset > 0;
12433        } else {
12434            return offset < range - 1;
12435        }
12436    }
12437
12438    /**
12439     * Check if this view can be scrolled vertically in a certain direction.
12440     *
12441     * @param direction Negative to check scrolling up, positive to check scrolling down.
12442     * @return true if this view can be scrolled in the specified direction, false otherwise.
12443     */
12444    public boolean canScrollVertically(int direction) {
12445        final int offset = computeVerticalScrollOffset();
12446        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12447        if (range == 0) return false;
12448        if (direction < 0) {
12449            return offset > 0;
12450        } else {
12451            return offset < range - 1;
12452        }
12453    }
12454
12455    /**
12456     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12457     * scrollbars are painted only if they have been awakened first.</p>
12458     *
12459     * @param canvas the canvas on which to draw the scrollbars
12460     *
12461     * @see #awakenScrollBars(int)
12462     */
12463    protected final void onDrawScrollBars(Canvas canvas) {
12464        // scrollbars are drawn only when the animation is running
12465        final ScrollabilityCache cache = mScrollCache;
12466        if (cache != null) {
12467
12468            int state = cache.state;
12469
12470            if (state == ScrollabilityCache.OFF) {
12471                return;
12472            }
12473
12474            boolean invalidate = false;
12475
12476            if (state == ScrollabilityCache.FADING) {
12477                // We're fading -- get our fade interpolation
12478                if (cache.interpolatorValues == null) {
12479                    cache.interpolatorValues = new float[1];
12480                }
12481
12482                float[] values = cache.interpolatorValues;
12483
12484                // Stops the animation if we're done
12485                if (cache.scrollBarInterpolator.timeToValues(values) ==
12486                        Interpolator.Result.FREEZE_END) {
12487                    cache.state = ScrollabilityCache.OFF;
12488                } else {
12489                    cache.scrollBar.setAlpha(Math.round(values[0]));
12490                }
12491
12492                // This will make the scroll bars inval themselves after
12493                // drawing. We only want this when we're fading so that
12494                // we prevent excessive redraws
12495                invalidate = true;
12496            } else {
12497                // We're just on -- but we may have been fading before so
12498                // reset alpha
12499                cache.scrollBar.setAlpha(255);
12500            }
12501
12502
12503            final int viewFlags = mViewFlags;
12504
12505            final boolean drawHorizontalScrollBar =
12506                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12507            final boolean drawVerticalScrollBar =
12508                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12509                && !isVerticalScrollBarHidden();
12510
12511            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12512                final int width = mRight - mLeft;
12513                final int height = mBottom - mTop;
12514
12515                final ScrollBarDrawable scrollBar = cache.scrollBar;
12516
12517                final int scrollX = mScrollX;
12518                final int scrollY = mScrollY;
12519                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12520
12521                int left;
12522                int top;
12523                int right;
12524                int bottom;
12525
12526                if (drawHorizontalScrollBar) {
12527                    int size = scrollBar.getSize(false);
12528                    if (size <= 0) {
12529                        size = cache.scrollBarSize;
12530                    }
12531
12532                    scrollBar.setParameters(computeHorizontalScrollRange(),
12533                                            computeHorizontalScrollOffset(),
12534                                            computeHorizontalScrollExtent(), false);
12535                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12536                            getVerticalScrollbarWidth() : 0;
12537                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12538                    left = scrollX + (mPaddingLeft & inside);
12539                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12540                    bottom = top + size;
12541                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12542                    if (invalidate) {
12543                        invalidate(left, top, right, bottom);
12544                    }
12545                }
12546
12547                if (drawVerticalScrollBar) {
12548                    int size = scrollBar.getSize(true);
12549                    if (size <= 0) {
12550                        size = cache.scrollBarSize;
12551                    }
12552
12553                    scrollBar.setParameters(computeVerticalScrollRange(),
12554                                            computeVerticalScrollOffset(),
12555                                            computeVerticalScrollExtent(), true);
12556                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12557                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12558                        verticalScrollbarPosition = isLayoutRtl() ?
12559                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12560                    }
12561                    switch (verticalScrollbarPosition) {
12562                        default:
12563                        case SCROLLBAR_POSITION_RIGHT:
12564                            left = scrollX + width - size - (mUserPaddingRight & inside);
12565                            break;
12566                        case SCROLLBAR_POSITION_LEFT:
12567                            left = scrollX + (mUserPaddingLeft & inside);
12568                            break;
12569                    }
12570                    top = scrollY + (mPaddingTop & inside);
12571                    right = left + size;
12572                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12573                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12574                    if (invalidate) {
12575                        invalidate(left, top, right, bottom);
12576                    }
12577                }
12578            }
12579        }
12580    }
12581
12582    /**
12583     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12584     * FastScroller is visible.
12585     * @return whether to temporarily hide the vertical scrollbar
12586     * @hide
12587     */
12588    protected boolean isVerticalScrollBarHidden() {
12589        return false;
12590    }
12591
12592    /**
12593     * <p>Draw the horizontal scrollbar if
12594     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12595     *
12596     * @param canvas the canvas on which to draw the scrollbar
12597     * @param scrollBar the scrollbar's drawable
12598     *
12599     * @see #isHorizontalScrollBarEnabled()
12600     * @see #computeHorizontalScrollRange()
12601     * @see #computeHorizontalScrollExtent()
12602     * @see #computeHorizontalScrollOffset()
12603     * @see android.widget.ScrollBarDrawable
12604     * @hide
12605     */
12606    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12607            int l, int t, int r, int b) {
12608        scrollBar.setBounds(l, t, r, b);
12609        scrollBar.draw(canvas);
12610    }
12611
12612    /**
12613     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12614     * returns true.</p>
12615     *
12616     * @param canvas the canvas on which to draw the scrollbar
12617     * @param scrollBar the scrollbar's drawable
12618     *
12619     * @see #isVerticalScrollBarEnabled()
12620     * @see #computeVerticalScrollRange()
12621     * @see #computeVerticalScrollExtent()
12622     * @see #computeVerticalScrollOffset()
12623     * @see android.widget.ScrollBarDrawable
12624     * @hide
12625     */
12626    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12627            int l, int t, int r, int b) {
12628        scrollBar.setBounds(l, t, r, b);
12629        scrollBar.draw(canvas);
12630    }
12631
12632    /**
12633     * Implement this to do your drawing.
12634     *
12635     * @param canvas the canvas on which the background will be drawn
12636     */
12637    protected void onDraw(Canvas canvas) {
12638    }
12639
12640    /*
12641     * Caller is responsible for calling requestLayout if necessary.
12642     * (This allows addViewInLayout to not request a new layout.)
12643     */
12644    void assignParent(ViewParent parent) {
12645        if (mParent == null) {
12646            mParent = parent;
12647        } else if (parent == null) {
12648            mParent = null;
12649        } else {
12650            throw new RuntimeException("view " + this + " being added, but"
12651                    + " it already has a parent");
12652        }
12653    }
12654
12655    /**
12656     * This is called when the view is attached to a window.  At this point it
12657     * has a Surface and will start drawing.  Note that this function is
12658     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12659     * however it may be called any time before the first onDraw -- including
12660     * before or after {@link #onMeasure(int, int)}.
12661     *
12662     * @see #onDetachedFromWindow()
12663     */
12664    protected void onAttachedToWindow() {
12665        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12666            mParent.requestTransparentRegion(this);
12667        }
12668
12669        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12670            initialAwakenScrollBars();
12671            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12672        }
12673
12674        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12675
12676        jumpDrawablesToCurrentState();
12677
12678        resetSubtreeAccessibilityStateChanged();
12679
12680        invalidateOutline();
12681
12682        if (isFocused()) {
12683            InputMethodManager imm = InputMethodManager.peekInstance();
12684            imm.focusIn(this);
12685        }
12686    }
12687
12688    /**
12689     * Resolve all RTL related properties.
12690     *
12691     * @return true if resolution of RTL properties has been done
12692     *
12693     * @hide
12694     */
12695    public boolean resolveRtlPropertiesIfNeeded() {
12696        if (!needRtlPropertiesResolution()) return false;
12697
12698        // Order is important here: LayoutDirection MUST be resolved first
12699        if (!isLayoutDirectionResolved()) {
12700            resolveLayoutDirection();
12701            resolveLayoutParams();
12702        }
12703        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12704        if (!isTextDirectionResolved()) {
12705            resolveTextDirection();
12706        }
12707        if (!isTextAlignmentResolved()) {
12708            resolveTextAlignment();
12709        }
12710        // Should resolve Drawables before Padding because we need the layout direction of the
12711        // Drawable to correctly resolve Padding.
12712        if (!isDrawablesResolved()) {
12713            resolveDrawables();
12714        }
12715        if (!isPaddingResolved()) {
12716            resolvePadding();
12717        }
12718        onRtlPropertiesChanged(getLayoutDirection());
12719        return true;
12720    }
12721
12722    /**
12723     * Reset resolution of all RTL related properties.
12724     *
12725     * @hide
12726     */
12727    public void resetRtlProperties() {
12728        resetResolvedLayoutDirection();
12729        resetResolvedTextDirection();
12730        resetResolvedTextAlignment();
12731        resetResolvedPadding();
12732        resetResolvedDrawables();
12733    }
12734
12735    /**
12736     * @see #onScreenStateChanged(int)
12737     */
12738    void dispatchScreenStateChanged(int screenState) {
12739        onScreenStateChanged(screenState);
12740    }
12741
12742    /**
12743     * This method is called whenever the state of the screen this view is
12744     * attached to changes. A state change will usually occurs when the screen
12745     * turns on or off (whether it happens automatically or the user does it
12746     * manually.)
12747     *
12748     * @param screenState The new state of the screen. Can be either
12749     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12750     */
12751    public void onScreenStateChanged(int screenState) {
12752    }
12753
12754    /**
12755     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12756     */
12757    private boolean hasRtlSupport() {
12758        return mContext.getApplicationInfo().hasRtlSupport();
12759    }
12760
12761    /**
12762     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12763     * RTL not supported)
12764     */
12765    private boolean isRtlCompatibilityMode() {
12766        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12767        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12768    }
12769
12770    /**
12771     * @return true if RTL properties need resolution.
12772     *
12773     */
12774    private boolean needRtlPropertiesResolution() {
12775        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12776    }
12777
12778    /**
12779     * Called when any RTL property (layout direction or text direction or text alignment) has
12780     * been changed.
12781     *
12782     * Subclasses need to override this method to take care of cached information that depends on the
12783     * resolved layout direction, or to inform child views that inherit their layout direction.
12784     *
12785     * The default implementation does nothing.
12786     *
12787     * @param layoutDirection the direction of the layout
12788     *
12789     * @see #LAYOUT_DIRECTION_LTR
12790     * @see #LAYOUT_DIRECTION_RTL
12791     */
12792    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12793    }
12794
12795    /**
12796     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12797     * that the parent directionality can and will be resolved before its children.
12798     *
12799     * @return true if resolution has been done, false otherwise.
12800     *
12801     * @hide
12802     */
12803    public boolean resolveLayoutDirection() {
12804        // Clear any previous layout direction resolution
12805        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12806
12807        if (hasRtlSupport()) {
12808            // Set resolved depending on layout direction
12809            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12810                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12811                case LAYOUT_DIRECTION_INHERIT:
12812                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12813                    // later to get the correct resolved value
12814                    if (!canResolveLayoutDirection()) return false;
12815
12816                    // Parent has not yet resolved, LTR is still the default
12817                    try {
12818                        if (!mParent.isLayoutDirectionResolved()) return false;
12819
12820                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12821                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12822                        }
12823                    } catch (AbstractMethodError e) {
12824                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12825                                " does not fully implement ViewParent", e);
12826                    }
12827                    break;
12828                case LAYOUT_DIRECTION_RTL:
12829                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12830                    break;
12831                case LAYOUT_DIRECTION_LOCALE:
12832                    if((LAYOUT_DIRECTION_RTL ==
12833                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12834                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12835                    }
12836                    break;
12837                default:
12838                    // Nothing to do, LTR by default
12839            }
12840        }
12841
12842        // Set to resolved
12843        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12844        return true;
12845    }
12846
12847    /**
12848     * Check if layout direction resolution can be done.
12849     *
12850     * @return true if layout direction resolution can be done otherwise return false.
12851     */
12852    public boolean canResolveLayoutDirection() {
12853        switch (getRawLayoutDirection()) {
12854            case LAYOUT_DIRECTION_INHERIT:
12855                if (mParent != null) {
12856                    try {
12857                        return mParent.canResolveLayoutDirection();
12858                    } catch (AbstractMethodError e) {
12859                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12860                                " does not fully implement ViewParent", e);
12861                    }
12862                }
12863                return false;
12864
12865            default:
12866                return true;
12867        }
12868    }
12869
12870    /**
12871     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12872     * {@link #onMeasure(int, int)}.
12873     *
12874     * @hide
12875     */
12876    public void resetResolvedLayoutDirection() {
12877        // Reset the current resolved bits
12878        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12879    }
12880
12881    /**
12882     * @return true if the layout direction is inherited.
12883     *
12884     * @hide
12885     */
12886    public boolean isLayoutDirectionInherited() {
12887        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12888    }
12889
12890    /**
12891     * @return true if layout direction has been resolved.
12892     */
12893    public boolean isLayoutDirectionResolved() {
12894        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12895    }
12896
12897    /**
12898     * Return if padding has been resolved
12899     *
12900     * @hide
12901     */
12902    boolean isPaddingResolved() {
12903        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12904    }
12905
12906    /**
12907     * Resolves padding depending on layout direction, if applicable, and
12908     * recomputes internal padding values to adjust for scroll bars.
12909     *
12910     * @hide
12911     */
12912    public void resolvePadding() {
12913        final int resolvedLayoutDirection = getLayoutDirection();
12914
12915        if (!isRtlCompatibilityMode()) {
12916            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12917            // If start / end padding are defined, they will be resolved (hence overriding) to
12918            // left / right or right / left depending on the resolved layout direction.
12919            // If start / end padding are not defined, use the left / right ones.
12920            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12921                Rect padding = sThreadLocal.get();
12922                if (padding == null) {
12923                    padding = new Rect();
12924                    sThreadLocal.set(padding);
12925                }
12926                mBackground.getPadding(padding);
12927                if (!mLeftPaddingDefined) {
12928                    mUserPaddingLeftInitial = padding.left;
12929                }
12930                if (!mRightPaddingDefined) {
12931                    mUserPaddingRightInitial = padding.right;
12932                }
12933            }
12934            switch (resolvedLayoutDirection) {
12935                case LAYOUT_DIRECTION_RTL:
12936                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12937                        mUserPaddingRight = mUserPaddingStart;
12938                    } else {
12939                        mUserPaddingRight = mUserPaddingRightInitial;
12940                    }
12941                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12942                        mUserPaddingLeft = mUserPaddingEnd;
12943                    } else {
12944                        mUserPaddingLeft = mUserPaddingLeftInitial;
12945                    }
12946                    break;
12947                case LAYOUT_DIRECTION_LTR:
12948                default:
12949                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12950                        mUserPaddingLeft = mUserPaddingStart;
12951                    } else {
12952                        mUserPaddingLeft = mUserPaddingLeftInitial;
12953                    }
12954                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12955                        mUserPaddingRight = mUserPaddingEnd;
12956                    } else {
12957                        mUserPaddingRight = mUserPaddingRightInitial;
12958                    }
12959            }
12960
12961            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12962        }
12963
12964        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12965        onRtlPropertiesChanged(resolvedLayoutDirection);
12966
12967        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12968    }
12969
12970    /**
12971     * Reset the resolved layout direction.
12972     *
12973     * @hide
12974     */
12975    public void resetResolvedPadding() {
12976        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12977    }
12978
12979    /**
12980     * This is called when the view is detached from a window.  At this point it
12981     * no longer has a surface for drawing.
12982     *
12983     * @see #onAttachedToWindow()
12984     */
12985    protected void onDetachedFromWindow() {
12986    }
12987
12988    /**
12989     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12990     * after onDetachedFromWindow().
12991     *
12992     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12993     * The super method should be called at the end of the overriden method to ensure
12994     * subclasses are destroyed first
12995     *
12996     * @hide
12997     */
12998    protected void onDetachedFromWindowInternal() {
12999        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13000        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13001
13002        removeUnsetPressCallback();
13003        removeLongPressCallback();
13004        removePerformClickCallback();
13005        removeSendViewScrolledAccessibilityEventCallback();
13006        stopNestedScroll();
13007
13008        destroyDrawingCache();
13009
13010        cleanupDraw();
13011        mCurrentAnimation = null;
13012    }
13013
13014    private void cleanupDraw() {
13015        resetDisplayList();
13016        if (mAttachInfo != null) {
13017            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13018        }
13019    }
13020
13021    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13022    }
13023
13024    /**
13025     * @return The number of times this view has been attached to a window
13026     */
13027    protected int getWindowAttachCount() {
13028        return mWindowAttachCount;
13029    }
13030
13031    /**
13032     * Retrieve a unique token identifying the window this view is attached to.
13033     * @return Return the window's token for use in
13034     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13035     */
13036    public IBinder getWindowToken() {
13037        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13038    }
13039
13040    /**
13041     * Retrieve the {@link WindowId} for the window this view is
13042     * currently attached to.
13043     */
13044    public WindowId getWindowId() {
13045        if (mAttachInfo == null) {
13046            return null;
13047        }
13048        if (mAttachInfo.mWindowId == null) {
13049            try {
13050                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13051                        mAttachInfo.mWindowToken);
13052                mAttachInfo.mWindowId = new WindowId(
13053                        mAttachInfo.mIWindowId);
13054            } catch (RemoteException e) {
13055            }
13056        }
13057        return mAttachInfo.mWindowId;
13058    }
13059
13060    /**
13061     * Retrieve a unique token identifying the top-level "real" window of
13062     * the window that this view is attached to.  That is, this is like
13063     * {@link #getWindowToken}, except if the window this view in is a panel
13064     * window (attached to another containing window), then the token of
13065     * the containing window is returned instead.
13066     *
13067     * @return Returns the associated window token, either
13068     * {@link #getWindowToken()} or the containing window's token.
13069     */
13070    public IBinder getApplicationWindowToken() {
13071        AttachInfo ai = mAttachInfo;
13072        if (ai != null) {
13073            IBinder appWindowToken = ai.mPanelParentWindowToken;
13074            if (appWindowToken == null) {
13075                appWindowToken = ai.mWindowToken;
13076            }
13077            return appWindowToken;
13078        }
13079        return null;
13080    }
13081
13082    /**
13083     * Gets the logical display to which the view's window has been attached.
13084     *
13085     * @return The logical display, or null if the view is not currently attached to a window.
13086     */
13087    public Display getDisplay() {
13088        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13089    }
13090
13091    /**
13092     * Retrieve private session object this view hierarchy is using to
13093     * communicate with the window manager.
13094     * @return the session object to communicate with the window manager
13095     */
13096    /*package*/ IWindowSession getWindowSession() {
13097        return mAttachInfo != null ? mAttachInfo.mSession : null;
13098    }
13099
13100    /**
13101     * @param info the {@link android.view.View.AttachInfo} to associated with
13102     *        this view
13103     */
13104    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13105        //System.out.println("Attached! " + this);
13106        mAttachInfo = info;
13107        if (mOverlay != null) {
13108            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13109        }
13110        mWindowAttachCount++;
13111        // We will need to evaluate the drawable state at least once.
13112        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13113        if (mFloatingTreeObserver != null) {
13114            info.mTreeObserver.merge(mFloatingTreeObserver);
13115            mFloatingTreeObserver = null;
13116        }
13117        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13118            mAttachInfo.mScrollContainers.add(this);
13119            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13120        }
13121        performCollectViewAttributes(mAttachInfo, visibility);
13122        onAttachedToWindow();
13123
13124        ListenerInfo li = mListenerInfo;
13125        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13126                li != null ? li.mOnAttachStateChangeListeners : null;
13127        if (listeners != null && listeners.size() > 0) {
13128            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13129            // perform the dispatching. The iterator is a safe guard against listeners that
13130            // could mutate the list by calling the various add/remove methods. This prevents
13131            // the array from being modified while we iterate it.
13132            for (OnAttachStateChangeListener listener : listeners) {
13133                listener.onViewAttachedToWindow(this);
13134            }
13135        }
13136
13137        int vis = info.mWindowVisibility;
13138        if (vis != GONE) {
13139            onWindowVisibilityChanged(vis);
13140        }
13141        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13142            // If nobody has evaluated the drawable state yet, then do it now.
13143            refreshDrawableState();
13144        }
13145        needGlobalAttributesUpdate(false);
13146    }
13147
13148    void dispatchDetachedFromWindow() {
13149        AttachInfo info = mAttachInfo;
13150        if (info != null) {
13151            int vis = info.mWindowVisibility;
13152            if (vis != GONE) {
13153                onWindowVisibilityChanged(GONE);
13154            }
13155        }
13156
13157        onDetachedFromWindow();
13158        onDetachedFromWindowInternal();
13159
13160        ListenerInfo li = mListenerInfo;
13161        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13162                li != null ? li.mOnAttachStateChangeListeners : null;
13163        if (listeners != null && listeners.size() > 0) {
13164            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13165            // perform the dispatching. The iterator is a safe guard against listeners that
13166            // could mutate the list by calling the various add/remove methods. This prevents
13167            // the array from being modified while we iterate it.
13168            for (OnAttachStateChangeListener listener : listeners) {
13169                listener.onViewDetachedFromWindow(this);
13170            }
13171        }
13172
13173        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13174            mAttachInfo.mScrollContainers.remove(this);
13175            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13176        }
13177
13178        mAttachInfo = null;
13179        if (mOverlay != null) {
13180            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13181        }
13182    }
13183
13184    /**
13185     * Cancel any deferred high-level input events that were previously posted to the event queue.
13186     *
13187     * <p>Many views post high-level events such as click handlers to the event queue
13188     * to run deferred in order to preserve a desired user experience - clearing visible
13189     * pressed states before executing, etc. This method will abort any events of this nature
13190     * that are currently in flight.</p>
13191     *
13192     * <p>Custom views that generate their own high-level deferred input events should override
13193     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13194     *
13195     * <p>This will also cancel pending input events for any child views.</p>
13196     *
13197     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13198     * This will not impact newer events posted after this call that may occur as a result of
13199     * lower-level input events still waiting in the queue. If you are trying to prevent
13200     * double-submitted  events for the duration of some sort of asynchronous transaction
13201     * you should also take other steps to protect against unexpected double inputs e.g. calling
13202     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13203     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13204     */
13205    public final void cancelPendingInputEvents() {
13206        dispatchCancelPendingInputEvents();
13207    }
13208
13209    /**
13210     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13211     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13212     */
13213    void dispatchCancelPendingInputEvents() {
13214        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13215        onCancelPendingInputEvents();
13216        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13217            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13218                    " did not call through to super.onCancelPendingInputEvents()");
13219        }
13220    }
13221
13222    /**
13223     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13224     * a parent view.
13225     *
13226     * <p>This method is responsible for removing any pending high-level input events that were
13227     * posted to the event queue to run later. Custom view classes that post their own deferred
13228     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13229     * {@link android.os.Handler} should override this method, call
13230     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13231     * </p>
13232     */
13233    public void onCancelPendingInputEvents() {
13234        removePerformClickCallback();
13235        cancelLongPress();
13236        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13237    }
13238
13239    /**
13240     * Store this view hierarchy's frozen state into the given container.
13241     *
13242     * @param container The SparseArray in which to save the view's state.
13243     *
13244     * @see #restoreHierarchyState(android.util.SparseArray)
13245     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13246     * @see #onSaveInstanceState()
13247     */
13248    public void saveHierarchyState(SparseArray<Parcelable> container) {
13249        dispatchSaveInstanceState(container);
13250    }
13251
13252    /**
13253     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13254     * this view and its children. May be overridden to modify how freezing happens to a
13255     * view's children; for example, some views may want to not store state for their children.
13256     *
13257     * @param container The SparseArray in which to save the view's state.
13258     *
13259     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13260     * @see #saveHierarchyState(android.util.SparseArray)
13261     * @see #onSaveInstanceState()
13262     */
13263    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13264        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13265            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13266            Parcelable state = onSaveInstanceState();
13267            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13268                throw new IllegalStateException(
13269                        "Derived class did not call super.onSaveInstanceState()");
13270            }
13271            if (state != null) {
13272                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13273                // + ": " + state);
13274                container.put(mID, state);
13275            }
13276        }
13277    }
13278
13279    /**
13280     * Hook allowing a view to generate a representation of its internal state
13281     * that can later be used to create a new instance with that same state.
13282     * This state should only contain information that is not persistent or can
13283     * not be reconstructed later. For example, you will never store your
13284     * current position on screen because that will be computed again when a
13285     * new instance of the view is placed in its view hierarchy.
13286     * <p>
13287     * Some examples of things you may store here: the current cursor position
13288     * in a text view (but usually not the text itself since that is stored in a
13289     * content provider or other persistent storage), the currently selected
13290     * item in a list view.
13291     *
13292     * @return Returns a Parcelable object containing the view's current dynamic
13293     *         state, or null if there is nothing interesting to save. The
13294     *         default implementation returns null.
13295     * @see #onRestoreInstanceState(android.os.Parcelable)
13296     * @see #saveHierarchyState(android.util.SparseArray)
13297     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13298     * @see #setSaveEnabled(boolean)
13299     */
13300    protected Parcelable onSaveInstanceState() {
13301        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13302        return BaseSavedState.EMPTY_STATE;
13303    }
13304
13305    /**
13306     * Restore this view hierarchy's frozen state from the given container.
13307     *
13308     * @param container The SparseArray which holds previously frozen states.
13309     *
13310     * @see #saveHierarchyState(android.util.SparseArray)
13311     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13312     * @see #onRestoreInstanceState(android.os.Parcelable)
13313     */
13314    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13315        dispatchRestoreInstanceState(container);
13316    }
13317
13318    /**
13319     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13320     * state for this view and its children. May be overridden to modify how restoring
13321     * happens to a view's children; for example, some views may want to not store state
13322     * for their children.
13323     *
13324     * @param container The SparseArray which holds previously saved state.
13325     *
13326     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13327     * @see #restoreHierarchyState(android.util.SparseArray)
13328     * @see #onRestoreInstanceState(android.os.Parcelable)
13329     */
13330    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13331        if (mID != NO_ID) {
13332            Parcelable state = container.get(mID);
13333            if (state != null) {
13334                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13335                // + ": " + state);
13336                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13337                onRestoreInstanceState(state);
13338                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13339                    throw new IllegalStateException(
13340                            "Derived class did not call super.onRestoreInstanceState()");
13341                }
13342            }
13343        }
13344    }
13345
13346    /**
13347     * Hook allowing a view to re-apply a representation of its internal state that had previously
13348     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13349     * null state.
13350     *
13351     * @param state The frozen state that had previously been returned by
13352     *        {@link #onSaveInstanceState}.
13353     *
13354     * @see #onSaveInstanceState()
13355     * @see #restoreHierarchyState(android.util.SparseArray)
13356     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13357     */
13358    protected void onRestoreInstanceState(Parcelable state) {
13359        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13360        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13361            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13362                    + "received " + state.getClass().toString() + " instead. This usually happens "
13363                    + "when two views of different type have the same id in the same hierarchy. "
13364                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13365                    + "other views do not use the same id.");
13366        }
13367    }
13368
13369    /**
13370     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13371     *
13372     * @return the drawing start time in milliseconds
13373     */
13374    public long getDrawingTime() {
13375        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13376    }
13377
13378    /**
13379     * <p>Enables or disables the duplication of the parent's state into this view. When
13380     * duplication is enabled, this view gets its drawable state from its parent rather
13381     * than from its own internal properties.</p>
13382     *
13383     * <p>Note: in the current implementation, setting this property to true after the
13384     * view was added to a ViewGroup might have no effect at all. This property should
13385     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13386     *
13387     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13388     * property is enabled, an exception will be thrown.</p>
13389     *
13390     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13391     * parent, these states should not be affected by this method.</p>
13392     *
13393     * @param enabled True to enable duplication of the parent's drawable state, false
13394     *                to disable it.
13395     *
13396     * @see #getDrawableState()
13397     * @see #isDuplicateParentStateEnabled()
13398     */
13399    public void setDuplicateParentStateEnabled(boolean enabled) {
13400        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13401    }
13402
13403    /**
13404     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13405     *
13406     * @return True if this view's drawable state is duplicated from the parent,
13407     *         false otherwise
13408     *
13409     * @see #getDrawableState()
13410     * @see #setDuplicateParentStateEnabled(boolean)
13411     */
13412    public boolean isDuplicateParentStateEnabled() {
13413        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13414    }
13415
13416    /**
13417     * <p>Specifies the type of layer backing this view. The layer can be
13418     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13419     * {@link #LAYER_TYPE_HARDWARE}.</p>
13420     *
13421     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13422     * instance that controls how the layer is composed on screen. The following
13423     * properties of the paint are taken into account when composing the layer:</p>
13424     * <ul>
13425     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13426     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13427     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13428     * </ul>
13429     *
13430     * <p>If this view has an alpha value set to < 1.0 by calling
13431     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13432     * by this view's alpha value.</p>
13433     *
13434     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13435     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13436     * for more information on when and how to use layers.</p>
13437     *
13438     * @param layerType The type of layer to use with this view, must be one of
13439     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13440     *        {@link #LAYER_TYPE_HARDWARE}
13441     * @param paint The paint used to compose the layer. This argument is optional
13442     *        and can be null. It is ignored when the layer type is
13443     *        {@link #LAYER_TYPE_NONE}
13444     *
13445     * @see #getLayerType()
13446     * @see #LAYER_TYPE_NONE
13447     * @see #LAYER_TYPE_SOFTWARE
13448     * @see #LAYER_TYPE_HARDWARE
13449     * @see #setAlpha(float)
13450     *
13451     * @attr ref android.R.styleable#View_layerType
13452     */
13453    public void setLayerType(int layerType, Paint paint) {
13454        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13455            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13456                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13457        }
13458
13459        boolean typeChanged = mRenderNode.setLayerType(layerType);
13460
13461        if (!typeChanged) {
13462            setLayerPaint(paint);
13463            return;
13464        }
13465
13466        // Destroy any previous software drawing cache if needed
13467        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13468            destroyDrawingCache();
13469        }
13470
13471        mLayerType = layerType;
13472        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13473        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13474        mRenderNode.setLayerPaint(mLayerPaint);
13475
13476        // draw() behaves differently if we are on a layer, so we need to
13477        // invalidate() here
13478        invalidateParentCaches();
13479        invalidate(true);
13480    }
13481
13482    /**
13483     * Updates the {@link Paint} object used with the current layer (used only if the current
13484     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13485     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13486     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13487     * ensure that the view gets redrawn immediately.
13488     *
13489     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13490     * instance that controls how the layer is composed on screen. The following
13491     * properties of the paint are taken into account when composing the layer:</p>
13492     * <ul>
13493     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13494     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13495     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13496     * </ul>
13497     *
13498     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13499     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13500     *
13501     * @param paint The paint used to compose the layer. This argument is optional
13502     *        and can be null. It is ignored when the layer type is
13503     *        {@link #LAYER_TYPE_NONE}
13504     *
13505     * @see #setLayerType(int, android.graphics.Paint)
13506     */
13507    public void setLayerPaint(Paint paint) {
13508        int layerType = getLayerType();
13509        if (layerType != LAYER_TYPE_NONE) {
13510            mLayerPaint = paint == null ? new Paint() : paint;
13511            if (layerType == LAYER_TYPE_HARDWARE) {
13512                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13513                    invalidateViewProperty(false, false);
13514                }
13515            } else {
13516                invalidate();
13517            }
13518        }
13519    }
13520
13521    /**
13522     * Indicates whether this view has a static layer. A view with layer type
13523     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13524     * dynamic.
13525     */
13526    boolean hasStaticLayer() {
13527        return true;
13528    }
13529
13530    /**
13531     * Indicates what type of layer is currently associated with this view. By default
13532     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13533     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13534     * for more information on the different types of layers.
13535     *
13536     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13537     *         {@link #LAYER_TYPE_HARDWARE}
13538     *
13539     * @see #setLayerType(int, android.graphics.Paint)
13540     * @see #buildLayer()
13541     * @see #LAYER_TYPE_NONE
13542     * @see #LAYER_TYPE_SOFTWARE
13543     * @see #LAYER_TYPE_HARDWARE
13544     */
13545    public int getLayerType() {
13546        return mLayerType;
13547    }
13548
13549    /**
13550     * Forces this view's layer to be created and this view to be rendered
13551     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13552     * invoking this method will have no effect.
13553     *
13554     * This method can for instance be used to render a view into its layer before
13555     * starting an animation. If this view is complex, rendering into the layer
13556     * before starting the animation will avoid skipping frames.
13557     *
13558     * @throws IllegalStateException If this view is not attached to a window
13559     *
13560     * @see #setLayerType(int, android.graphics.Paint)
13561     */
13562    public void buildLayer() {
13563        if (mLayerType == LAYER_TYPE_NONE) return;
13564
13565        final AttachInfo attachInfo = mAttachInfo;
13566        if (attachInfo == null) {
13567            throw new IllegalStateException("This view must be attached to a window first");
13568        }
13569
13570        if (getWidth() == 0 || getHeight() == 0) {
13571            return;
13572        }
13573
13574        switch (mLayerType) {
13575            case LAYER_TYPE_HARDWARE:
13576                // The only part of a hardware layer we can build in response to
13577                // this call is to ensure the display list is up to date.
13578                // The actual rendering of the display list into the layer must
13579                // be done at playback time
13580                updateDisplayListIfDirty();
13581                break;
13582            case LAYER_TYPE_SOFTWARE:
13583                buildDrawingCache(true);
13584                break;
13585        }
13586    }
13587
13588    /**
13589     * If this View draws with a HardwareLayer, returns it.
13590     * Otherwise returns null
13591     *
13592     * TODO: Only TextureView uses this, can we eliminate it?
13593     */
13594    HardwareLayer getHardwareLayer() {
13595        return null;
13596    }
13597
13598    /**
13599     * Destroys all hardware rendering resources. This method is invoked
13600     * when the system needs to reclaim resources. Upon execution of this
13601     * method, you should free any OpenGL resources created by the view.
13602     *
13603     * Note: you <strong>must</strong> call
13604     * <code>super.destroyHardwareResources()</code> when overriding
13605     * this method.
13606     *
13607     * @hide
13608     */
13609    protected void destroyHardwareResources() {
13610        // Although the Layer will be destroyed by RenderNode, we want to release
13611        // the staging display list, which is also a signal to RenderNode that it's
13612        // safe to free its copy of the display list as it knows that we will
13613        // push an updated DisplayList if we try to draw again
13614        resetDisplayList();
13615    }
13616
13617    /**
13618     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13619     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13620     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13621     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13622     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13623     * null.</p>
13624     *
13625     * <p>Enabling the drawing cache is similar to
13626     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13627     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13628     * drawing cache has no effect on rendering because the system uses a different mechanism
13629     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13630     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13631     * for information on how to enable software and hardware layers.</p>
13632     *
13633     * <p>This API can be used to manually generate
13634     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13635     * {@link #getDrawingCache()}.</p>
13636     *
13637     * @param enabled true to enable the drawing cache, false otherwise
13638     *
13639     * @see #isDrawingCacheEnabled()
13640     * @see #getDrawingCache()
13641     * @see #buildDrawingCache()
13642     * @see #setLayerType(int, android.graphics.Paint)
13643     */
13644    public void setDrawingCacheEnabled(boolean enabled) {
13645        mCachingFailed = false;
13646        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13647    }
13648
13649    /**
13650     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13651     *
13652     * @return true if the drawing cache is enabled
13653     *
13654     * @see #setDrawingCacheEnabled(boolean)
13655     * @see #getDrawingCache()
13656     */
13657    @ViewDebug.ExportedProperty(category = "drawing")
13658    public boolean isDrawingCacheEnabled() {
13659        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13660    }
13661
13662    /**
13663     * Debugging utility which recursively outputs the dirty state of a view and its
13664     * descendants.
13665     *
13666     * @hide
13667     */
13668    @SuppressWarnings({"UnusedDeclaration"})
13669    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13670        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13671                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13672                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13673                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13674        if (clear) {
13675            mPrivateFlags &= clearMask;
13676        }
13677        if (this instanceof ViewGroup) {
13678            ViewGroup parent = (ViewGroup) this;
13679            final int count = parent.getChildCount();
13680            for (int i = 0; i < count; i++) {
13681                final View child = parent.getChildAt(i);
13682                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13683            }
13684        }
13685    }
13686
13687    /**
13688     * This method is used by ViewGroup to cause its children to restore or recreate their
13689     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13690     * to recreate its own display list, which would happen if it went through the normal
13691     * draw/dispatchDraw mechanisms.
13692     *
13693     * @hide
13694     */
13695    protected void dispatchGetDisplayList() {}
13696
13697    /**
13698     * A view that is not attached or hardware accelerated cannot create a display list.
13699     * This method checks these conditions and returns the appropriate result.
13700     *
13701     * @return true if view has the ability to create a display list, false otherwise.
13702     *
13703     * @hide
13704     */
13705    public boolean canHaveDisplayList() {
13706        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13707    }
13708
13709    private void updateDisplayListIfDirty() {
13710        final RenderNode renderNode = mRenderNode;
13711        if (!canHaveDisplayList()) {
13712            // can't populate RenderNode, don't try
13713            return;
13714        }
13715
13716        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13717                || !renderNode.isValid()
13718                || (mRecreateDisplayList)) {
13719            // Don't need to recreate the display list, just need to tell our
13720            // children to restore/recreate theirs
13721            if (renderNode.isValid()
13722                    && !mRecreateDisplayList) {
13723                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13724                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13725                dispatchGetDisplayList();
13726
13727                return; // no work needed
13728            }
13729
13730            // If we got here, we're recreating it. Mark it as such to ensure that
13731            // we copy in child display lists into ours in drawChild()
13732            mRecreateDisplayList = true;
13733
13734            int width = mRight - mLeft;
13735            int height = mBottom - mTop;
13736            int layerType = getLayerType();
13737
13738            final HardwareCanvas canvas = renderNode.start(width, height);
13739            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13740
13741            try {
13742                final HardwareLayer layer = getHardwareLayer();
13743                if (layer != null && layer.isValid()) {
13744                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13745                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13746                    buildDrawingCache(true);
13747                    Bitmap cache = getDrawingCache(true);
13748                    if (cache != null) {
13749                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13750                    }
13751                } else {
13752                    computeScroll();
13753
13754                    canvas.translate(-mScrollX, -mScrollY);
13755                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13756                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13757
13758                    // Fast path for layouts with no backgrounds
13759                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13760                        dispatchDraw(canvas);
13761                        if (mOverlay != null && !mOverlay.isEmpty()) {
13762                            mOverlay.getOverlayView().draw(canvas);
13763                        }
13764                    } else {
13765                        draw(canvas);
13766                    }
13767                }
13768            } finally {
13769                renderNode.end(canvas);
13770                setDisplayListProperties(renderNode);
13771            }
13772        } else {
13773            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13774            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13775        }
13776    }
13777
13778    /**
13779     * Returns a RenderNode with View draw content recorded, which can be
13780     * used to draw this view again without executing its draw method.
13781     *
13782     * @return A RenderNode ready to replay, or null if caching is not enabled.
13783     *
13784     * @hide
13785     */
13786    public RenderNode getDisplayList() {
13787        updateDisplayListIfDirty();
13788        return mRenderNode;
13789    }
13790
13791    private void resetDisplayList() {
13792        if (mRenderNode.isValid()) {
13793            mRenderNode.destroyDisplayListData();
13794        }
13795
13796        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13797            mBackgroundRenderNode.destroyDisplayListData();
13798        }
13799    }
13800
13801    /**
13802     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13803     *
13804     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13805     *
13806     * @see #getDrawingCache(boolean)
13807     */
13808    public Bitmap getDrawingCache() {
13809        return getDrawingCache(false);
13810    }
13811
13812    /**
13813     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13814     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13815     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13816     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13817     * request the drawing cache by calling this method and draw it on screen if the
13818     * returned bitmap is not null.</p>
13819     *
13820     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13821     * this method will create a bitmap of the same size as this view. Because this bitmap
13822     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13823     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13824     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13825     * size than the view. This implies that your application must be able to handle this
13826     * size.</p>
13827     *
13828     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13829     *        the current density of the screen when the application is in compatibility
13830     *        mode.
13831     *
13832     * @return A bitmap representing this view or null if cache is disabled.
13833     *
13834     * @see #setDrawingCacheEnabled(boolean)
13835     * @see #isDrawingCacheEnabled()
13836     * @see #buildDrawingCache(boolean)
13837     * @see #destroyDrawingCache()
13838     */
13839    public Bitmap getDrawingCache(boolean autoScale) {
13840        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13841            return null;
13842        }
13843        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13844            buildDrawingCache(autoScale);
13845        }
13846        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13847    }
13848
13849    /**
13850     * <p>Frees the resources used by the drawing cache. If you call
13851     * {@link #buildDrawingCache()} manually without calling
13852     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13853     * should cleanup the cache with this method afterwards.</p>
13854     *
13855     * @see #setDrawingCacheEnabled(boolean)
13856     * @see #buildDrawingCache()
13857     * @see #getDrawingCache()
13858     */
13859    public void destroyDrawingCache() {
13860        if (mDrawingCache != null) {
13861            mDrawingCache.recycle();
13862            mDrawingCache = null;
13863        }
13864        if (mUnscaledDrawingCache != null) {
13865            mUnscaledDrawingCache.recycle();
13866            mUnscaledDrawingCache = null;
13867        }
13868    }
13869
13870    /**
13871     * Setting a solid background color for the drawing cache's bitmaps will improve
13872     * performance and memory usage. Note, though that this should only be used if this
13873     * view will always be drawn on top of a solid color.
13874     *
13875     * @param color The background color to use for the drawing cache's bitmap
13876     *
13877     * @see #setDrawingCacheEnabled(boolean)
13878     * @see #buildDrawingCache()
13879     * @see #getDrawingCache()
13880     */
13881    public void setDrawingCacheBackgroundColor(int color) {
13882        if (color != mDrawingCacheBackgroundColor) {
13883            mDrawingCacheBackgroundColor = color;
13884            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13885        }
13886    }
13887
13888    /**
13889     * @see #setDrawingCacheBackgroundColor(int)
13890     *
13891     * @return The background color to used for the drawing cache's bitmap
13892     */
13893    public int getDrawingCacheBackgroundColor() {
13894        return mDrawingCacheBackgroundColor;
13895    }
13896
13897    /**
13898     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13899     *
13900     * @see #buildDrawingCache(boolean)
13901     */
13902    public void buildDrawingCache() {
13903        buildDrawingCache(false);
13904    }
13905
13906    /**
13907     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13908     *
13909     * <p>If you call {@link #buildDrawingCache()} manually without calling
13910     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13911     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13912     *
13913     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13914     * this method will create a bitmap of the same size as this view. Because this bitmap
13915     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13916     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13917     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13918     * size than the view. This implies that your application must be able to handle this
13919     * size.</p>
13920     *
13921     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13922     * you do not need the drawing cache bitmap, calling this method will increase memory
13923     * usage and cause the view to be rendered in software once, thus negatively impacting
13924     * performance.</p>
13925     *
13926     * @see #getDrawingCache()
13927     * @see #destroyDrawingCache()
13928     */
13929    public void buildDrawingCache(boolean autoScale) {
13930        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13931                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13932            mCachingFailed = false;
13933
13934            int width = mRight - mLeft;
13935            int height = mBottom - mTop;
13936
13937            final AttachInfo attachInfo = mAttachInfo;
13938            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13939
13940            if (autoScale && scalingRequired) {
13941                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13942                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13943            }
13944
13945            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13946            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13947            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13948
13949            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13950            final long drawingCacheSize =
13951                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13952            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13953                if (width > 0 && height > 0) {
13954                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13955                            + projectedBitmapSize + " bytes, only "
13956                            + drawingCacheSize + " available");
13957                }
13958                destroyDrawingCache();
13959                mCachingFailed = true;
13960                return;
13961            }
13962
13963            boolean clear = true;
13964            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13965
13966            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13967                Bitmap.Config quality;
13968                if (!opaque) {
13969                    // Never pick ARGB_4444 because it looks awful
13970                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13971                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13972                        case DRAWING_CACHE_QUALITY_AUTO:
13973                        case DRAWING_CACHE_QUALITY_LOW:
13974                        case DRAWING_CACHE_QUALITY_HIGH:
13975                        default:
13976                            quality = Bitmap.Config.ARGB_8888;
13977                            break;
13978                    }
13979                } else {
13980                    // Optimization for translucent windows
13981                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13982                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13983                }
13984
13985                // Try to cleanup memory
13986                if (bitmap != null) bitmap.recycle();
13987
13988                try {
13989                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13990                            width, height, quality);
13991                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13992                    if (autoScale) {
13993                        mDrawingCache = bitmap;
13994                    } else {
13995                        mUnscaledDrawingCache = bitmap;
13996                    }
13997                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13998                } catch (OutOfMemoryError e) {
13999                    // If there is not enough memory to create the bitmap cache, just
14000                    // ignore the issue as bitmap caches are not required to draw the
14001                    // view hierarchy
14002                    if (autoScale) {
14003                        mDrawingCache = null;
14004                    } else {
14005                        mUnscaledDrawingCache = null;
14006                    }
14007                    mCachingFailed = true;
14008                    return;
14009                }
14010
14011                clear = drawingCacheBackgroundColor != 0;
14012            }
14013
14014            Canvas canvas;
14015            if (attachInfo != null) {
14016                canvas = attachInfo.mCanvas;
14017                if (canvas == null) {
14018                    canvas = new Canvas();
14019                }
14020                canvas.setBitmap(bitmap);
14021                // Temporarily clobber the cached Canvas in case one of our children
14022                // is also using a drawing cache. Without this, the children would
14023                // steal the canvas by attaching their own bitmap to it and bad, bad
14024                // thing would happen (invisible views, corrupted drawings, etc.)
14025                attachInfo.mCanvas = null;
14026            } else {
14027                // This case should hopefully never or seldom happen
14028                canvas = new Canvas(bitmap);
14029            }
14030
14031            if (clear) {
14032                bitmap.eraseColor(drawingCacheBackgroundColor);
14033            }
14034
14035            computeScroll();
14036            final int restoreCount = canvas.save();
14037
14038            if (autoScale && scalingRequired) {
14039                final float scale = attachInfo.mApplicationScale;
14040                canvas.scale(scale, scale);
14041            }
14042
14043            canvas.translate(-mScrollX, -mScrollY);
14044
14045            mPrivateFlags |= PFLAG_DRAWN;
14046            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14047                    mLayerType != LAYER_TYPE_NONE) {
14048                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14049            }
14050
14051            // Fast path for layouts with no backgrounds
14052            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14053                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14054                dispatchDraw(canvas);
14055                if (mOverlay != null && !mOverlay.isEmpty()) {
14056                    mOverlay.getOverlayView().draw(canvas);
14057                }
14058            } else {
14059                draw(canvas);
14060            }
14061
14062            canvas.restoreToCount(restoreCount);
14063            canvas.setBitmap(null);
14064
14065            if (attachInfo != null) {
14066                // Restore the cached Canvas for our siblings
14067                attachInfo.mCanvas = canvas;
14068            }
14069        }
14070    }
14071
14072    /**
14073     * Create a snapshot of the view into a bitmap.  We should probably make
14074     * some form of this public, but should think about the API.
14075     */
14076    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14077        int width = mRight - mLeft;
14078        int height = mBottom - mTop;
14079
14080        final AttachInfo attachInfo = mAttachInfo;
14081        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14082        width = (int) ((width * scale) + 0.5f);
14083        height = (int) ((height * scale) + 0.5f);
14084
14085        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14086                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14087        if (bitmap == null) {
14088            throw new OutOfMemoryError();
14089        }
14090
14091        Resources resources = getResources();
14092        if (resources != null) {
14093            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14094        }
14095
14096        Canvas canvas;
14097        if (attachInfo != null) {
14098            canvas = attachInfo.mCanvas;
14099            if (canvas == null) {
14100                canvas = new Canvas();
14101            }
14102            canvas.setBitmap(bitmap);
14103            // Temporarily clobber the cached Canvas in case one of our children
14104            // is also using a drawing cache. Without this, the children would
14105            // steal the canvas by attaching their own bitmap to it and bad, bad
14106            // things would happen (invisible views, corrupted drawings, etc.)
14107            attachInfo.mCanvas = null;
14108        } else {
14109            // This case should hopefully never or seldom happen
14110            canvas = new Canvas(bitmap);
14111        }
14112
14113        if ((backgroundColor & 0xff000000) != 0) {
14114            bitmap.eraseColor(backgroundColor);
14115        }
14116
14117        computeScroll();
14118        final int restoreCount = canvas.save();
14119        canvas.scale(scale, scale);
14120        canvas.translate(-mScrollX, -mScrollY);
14121
14122        // Temporarily remove the dirty mask
14123        int flags = mPrivateFlags;
14124        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14125
14126        // Fast path for layouts with no backgrounds
14127        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14128            dispatchDraw(canvas);
14129            if (mOverlay != null && !mOverlay.isEmpty()) {
14130                mOverlay.getOverlayView().draw(canvas);
14131            }
14132        } else {
14133            draw(canvas);
14134        }
14135
14136        mPrivateFlags = flags;
14137
14138        canvas.restoreToCount(restoreCount);
14139        canvas.setBitmap(null);
14140
14141        if (attachInfo != null) {
14142            // Restore the cached Canvas for our siblings
14143            attachInfo.mCanvas = canvas;
14144        }
14145
14146        return bitmap;
14147    }
14148
14149    /**
14150     * Indicates whether this View is currently in edit mode. A View is usually
14151     * in edit mode when displayed within a developer tool. For instance, if
14152     * this View is being drawn by a visual user interface builder, this method
14153     * should return true.
14154     *
14155     * Subclasses should check the return value of this method to provide
14156     * different behaviors if their normal behavior might interfere with the
14157     * host environment. For instance: the class spawns a thread in its
14158     * constructor, the drawing code relies on device-specific features, etc.
14159     *
14160     * This method is usually checked in the drawing code of custom widgets.
14161     *
14162     * @return True if this View is in edit mode, false otherwise.
14163     */
14164    public boolean isInEditMode() {
14165        return false;
14166    }
14167
14168    /**
14169     * If the View draws content inside its padding and enables fading edges,
14170     * it needs to support padding offsets. Padding offsets are added to the
14171     * fading edges to extend the length of the fade so that it covers pixels
14172     * drawn inside the padding.
14173     *
14174     * Subclasses of this class should override this method if they need
14175     * to draw content inside the padding.
14176     *
14177     * @return True if padding offset must be applied, false otherwise.
14178     *
14179     * @see #getLeftPaddingOffset()
14180     * @see #getRightPaddingOffset()
14181     * @see #getTopPaddingOffset()
14182     * @see #getBottomPaddingOffset()
14183     *
14184     * @since CURRENT
14185     */
14186    protected boolean isPaddingOffsetRequired() {
14187        return false;
14188    }
14189
14190    /**
14191     * Amount by which to extend the left fading region. Called only when
14192     * {@link #isPaddingOffsetRequired()} returns true.
14193     *
14194     * @return The left padding offset in pixels.
14195     *
14196     * @see #isPaddingOffsetRequired()
14197     *
14198     * @since CURRENT
14199     */
14200    protected int getLeftPaddingOffset() {
14201        return 0;
14202    }
14203
14204    /**
14205     * Amount by which to extend the right fading region. Called only when
14206     * {@link #isPaddingOffsetRequired()} returns true.
14207     *
14208     * @return The right padding offset in pixels.
14209     *
14210     * @see #isPaddingOffsetRequired()
14211     *
14212     * @since CURRENT
14213     */
14214    protected int getRightPaddingOffset() {
14215        return 0;
14216    }
14217
14218    /**
14219     * Amount by which to extend the top fading region. Called only when
14220     * {@link #isPaddingOffsetRequired()} returns true.
14221     *
14222     * @return The top padding offset in pixels.
14223     *
14224     * @see #isPaddingOffsetRequired()
14225     *
14226     * @since CURRENT
14227     */
14228    protected int getTopPaddingOffset() {
14229        return 0;
14230    }
14231
14232    /**
14233     * Amount by which to extend the bottom fading region. Called only when
14234     * {@link #isPaddingOffsetRequired()} returns true.
14235     *
14236     * @return The bottom padding offset in pixels.
14237     *
14238     * @see #isPaddingOffsetRequired()
14239     *
14240     * @since CURRENT
14241     */
14242    protected int getBottomPaddingOffset() {
14243        return 0;
14244    }
14245
14246    /**
14247     * @hide
14248     * @param offsetRequired
14249     */
14250    protected int getFadeTop(boolean offsetRequired) {
14251        int top = mPaddingTop;
14252        if (offsetRequired) top += getTopPaddingOffset();
14253        return top;
14254    }
14255
14256    /**
14257     * @hide
14258     * @param offsetRequired
14259     */
14260    protected int getFadeHeight(boolean offsetRequired) {
14261        int padding = mPaddingTop;
14262        if (offsetRequired) padding += getTopPaddingOffset();
14263        return mBottom - mTop - mPaddingBottom - padding;
14264    }
14265
14266    /**
14267     * <p>Indicates whether this view is attached to a hardware accelerated
14268     * window or not.</p>
14269     *
14270     * <p>Even if this method returns true, it does not mean that every call
14271     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14272     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14273     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14274     * window is hardware accelerated,
14275     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14276     * return false, and this method will return true.</p>
14277     *
14278     * @return True if the view is attached to a window and the window is
14279     *         hardware accelerated; false in any other case.
14280     */
14281    @ViewDebug.ExportedProperty(category = "drawing")
14282    public boolean isHardwareAccelerated() {
14283        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14284    }
14285
14286    /**
14287     * Sets a rectangular area on this view to which the view will be clipped
14288     * when it is drawn. Setting the value to null will remove the clip bounds
14289     * and the view will draw normally, using its full bounds.
14290     *
14291     * @param clipBounds The rectangular area, in the local coordinates of
14292     * this view, to which future drawing operations will be clipped.
14293     */
14294    public void setClipBounds(Rect clipBounds) {
14295        if (clipBounds != null) {
14296            if (clipBounds.equals(mClipBounds)) {
14297                return;
14298            }
14299            if (mClipBounds == null) {
14300                invalidate();
14301                mClipBounds = new Rect(clipBounds);
14302            } else {
14303                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14304                        Math.min(mClipBounds.top, clipBounds.top),
14305                        Math.max(mClipBounds.right, clipBounds.right),
14306                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14307                mClipBounds.set(clipBounds);
14308            }
14309        } else {
14310            if (mClipBounds != null) {
14311                invalidate();
14312                mClipBounds = null;
14313            }
14314        }
14315        mRenderNode.setClipBounds(mClipBounds);
14316    }
14317
14318    /**
14319     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14320     *
14321     * @return A copy of the current clip bounds if clip bounds are set,
14322     * otherwise null.
14323     */
14324    public Rect getClipBounds() {
14325        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14326    }
14327
14328    /**
14329     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14330     * case of an active Animation being run on the view.
14331     */
14332    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14333            Animation a, boolean scalingRequired) {
14334        Transformation invalidationTransform;
14335        final int flags = parent.mGroupFlags;
14336        final boolean initialized = a.isInitialized();
14337        if (!initialized) {
14338            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14339            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14340            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14341            onAnimationStart();
14342        }
14343
14344        final Transformation t = parent.getChildTransformation();
14345        boolean more = a.getTransformation(drawingTime, t, 1f);
14346        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14347            if (parent.mInvalidationTransformation == null) {
14348                parent.mInvalidationTransformation = new Transformation();
14349            }
14350            invalidationTransform = parent.mInvalidationTransformation;
14351            a.getTransformation(drawingTime, invalidationTransform, 1f);
14352        } else {
14353            invalidationTransform = t;
14354        }
14355
14356        if (more) {
14357            if (!a.willChangeBounds()) {
14358                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14359                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14360                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14361                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14362                    // The child need to draw an animation, potentially offscreen, so
14363                    // make sure we do not cancel invalidate requests
14364                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14365                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14366                }
14367            } else {
14368                if (parent.mInvalidateRegion == null) {
14369                    parent.mInvalidateRegion = new RectF();
14370                }
14371                final RectF region = parent.mInvalidateRegion;
14372                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14373                        invalidationTransform);
14374
14375                // The child need to draw an animation, potentially offscreen, so
14376                // make sure we do not cancel invalidate requests
14377                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14378
14379                final int left = mLeft + (int) region.left;
14380                final int top = mTop + (int) region.top;
14381                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14382                        top + (int) (region.height() + .5f));
14383            }
14384        }
14385        return more;
14386    }
14387
14388    /**
14389     * This method is called by getDisplayList() when a display list is recorded for a View.
14390     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14391     */
14392    void setDisplayListProperties(RenderNode renderNode) {
14393        if (renderNode != null) {
14394            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14395            if (mParent instanceof ViewGroup) {
14396                renderNode.setClipToBounds(
14397                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14398            }
14399            float alpha = 1;
14400            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14401                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14402                ViewGroup parentVG = (ViewGroup) mParent;
14403                final Transformation t = parentVG.getChildTransformation();
14404                if (parentVG.getChildStaticTransformation(this, t)) {
14405                    final int transformType = t.getTransformationType();
14406                    if (transformType != Transformation.TYPE_IDENTITY) {
14407                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14408                            alpha = t.getAlpha();
14409                        }
14410                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14411                            renderNode.setStaticMatrix(t.getMatrix());
14412                        }
14413                    }
14414                }
14415            }
14416            if (mTransformationInfo != null) {
14417                alpha *= getFinalAlpha();
14418                if (alpha < 1) {
14419                    final int multipliedAlpha = (int) (255 * alpha);
14420                    if (onSetAlpha(multipliedAlpha)) {
14421                        alpha = 1;
14422                    }
14423                }
14424                renderNode.setAlpha(alpha);
14425            } else if (alpha < 1) {
14426                renderNode.setAlpha(alpha);
14427            }
14428        }
14429    }
14430
14431    /**
14432     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14433     * This draw() method is an implementation detail and is not intended to be overridden or
14434     * to be called from anywhere else other than ViewGroup.drawChild().
14435     */
14436    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14437        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14438        boolean more = false;
14439        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14440        final int flags = parent.mGroupFlags;
14441
14442        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14443            parent.getChildTransformation().clear();
14444            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14445        }
14446
14447        Transformation transformToApply = null;
14448        boolean concatMatrix = false;
14449
14450        boolean scalingRequired = false;
14451        boolean caching;
14452        int layerType = getLayerType();
14453
14454        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14455        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14456                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14457            caching = true;
14458            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14459            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14460        } else {
14461            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14462        }
14463
14464        final Animation a = getAnimation();
14465        if (a != null) {
14466            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14467            concatMatrix = a.willChangeTransformationMatrix();
14468            if (concatMatrix) {
14469                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14470            }
14471            transformToApply = parent.getChildTransformation();
14472        } else {
14473            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14474                // No longer animating: clear out old animation matrix
14475                mRenderNode.setAnimationMatrix(null);
14476                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14477            }
14478            if (!usingRenderNodeProperties &&
14479                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14480                final Transformation t = parent.getChildTransformation();
14481                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14482                if (hasTransform) {
14483                    final int transformType = t.getTransformationType();
14484                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14485                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14486                }
14487            }
14488        }
14489
14490        concatMatrix |= !childHasIdentityMatrix;
14491
14492        // Sets the flag as early as possible to allow draw() implementations
14493        // to call invalidate() successfully when doing animations
14494        mPrivateFlags |= PFLAG_DRAWN;
14495
14496        if (!concatMatrix &&
14497                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14498                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14499                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14500                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14501            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14502            return more;
14503        }
14504        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14505
14506        if (hardwareAccelerated) {
14507            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14508            // retain the flag's value temporarily in the mRecreateDisplayList flag
14509            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14510            mPrivateFlags &= ~PFLAG_INVALIDATED;
14511        }
14512
14513        RenderNode renderNode = null;
14514        Bitmap cache = null;
14515        boolean hasDisplayList = false;
14516        if (caching) {
14517            if (!hardwareAccelerated) {
14518                if (layerType != LAYER_TYPE_NONE) {
14519                    layerType = LAYER_TYPE_SOFTWARE;
14520                    buildDrawingCache(true);
14521                }
14522                cache = getDrawingCache(true);
14523            } else {
14524                switch (layerType) {
14525                    case LAYER_TYPE_SOFTWARE:
14526                        if (usingRenderNodeProperties) {
14527                            hasDisplayList = canHaveDisplayList();
14528                        } else {
14529                            buildDrawingCache(true);
14530                            cache = getDrawingCache(true);
14531                        }
14532                        break;
14533                    case LAYER_TYPE_HARDWARE:
14534                        if (usingRenderNodeProperties) {
14535                            hasDisplayList = canHaveDisplayList();
14536                        }
14537                        break;
14538                    case LAYER_TYPE_NONE:
14539                        // Delay getting the display list until animation-driven alpha values are
14540                        // set up and possibly passed on to the view
14541                        hasDisplayList = canHaveDisplayList();
14542                        break;
14543                }
14544            }
14545        }
14546        usingRenderNodeProperties &= hasDisplayList;
14547        if (usingRenderNodeProperties) {
14548            renderNode = getDisplayList();
14549            if (!renderNode.isValid()) {
14550                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14551                // to getDisplayList(), the display list will be marked invalid and we should not
14552                // try to use it again.
14553                renderNode = null;
14554                hasDisplayList = false;
14555                usingRenderNodeProperties = false;
14556            }
14557        }
14558
14559        int sx = 0;
14560        int sy = 0;
14561        if (!hasDisplayList) {
14562            computeScroll();
14563            sx = mScrollX;
14564            sy = mScrollY;
14565        }
14566
14567        final boolean hasNoCache = cache == null || hasDisplayList;
14568        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14569                layerType != LAYER_TYPE_HARDWARE;
14570
14571        int restoreTo = -1;
14572        if (!usingRenderNodeProperties || transformToApply != null) {
14573            restoreTo = canvas.save();
14574        }
14575        if (offsetForScroll) {
14576            canvas.translate(mLeft - sx, mTop - sy);
14577        } else {
14578            if (!usingRenderNodeProperties) {
14579                canvas.translate(mLeft, mTop);
14580            }
14581            if (scalingRequired) {
14582                if (usingRenderNodeProperties) {
14583                    // TODO: Might not need this if we put everything inside the DL
14584                    restoreTo = canvas.save();
14585                }
14586                // mAttachInfo cannot be null, otherwise scalingRequired == false
14587                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14588                canvas.scale(scale, scale);
14589            }
14590        }
14591
14592        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14593        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14594                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14595            if (transformToApply != null || !childHasIdentityMatrix) {
14596                int transX = 0;
14597                int transY = 0;
14598
14599                if (offsetForScroll) {
14600                    transX = -sx;
14601                    transY = -sy;
14602                }
14603
14604                if (transformToApply != null) {
14605                    if (concatMatrix) {
14606                        if (usingRenderNodeProperties) {
14607                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14608                        } else {
14609                            // Undo the scroll translation, apply the transformation matrix,
14610                            // then redo the scroll translate to get the correct result.
14611                            canvas.translate(-transX, -transY);
14612                            canvas.concat(transformToApply.getMatrix());
14613                            canvas.translate(transX, transY);
14614                        }
14615                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14616                    }
14617
14618                    float transformAlpha = transformToApply.getAlpha();
14619                    if (transformAlpha < 1) {
14620                        alpha *= transformAlpha;
14621                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14622                    }
14623                }
14624
14625                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14626                    canvas.translate(-transX, -transY);
14627                    canvas.concat(getMatrix());
14628                    canvas.translate(transX, transY);
14629                }
14630            }
14631
14632            // Deal with alpha if it is or used to be <1
14633            if (alpha < 1 ||
14634                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14635                if (alpha < 1) {
14636                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14637                } else {
14638                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14639                }
14640                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14641                if (hasNoCache) {
14642                    final int multipliedAlpha = (int) (255 * alpha);
14643                    if (!onSetAlpha(multipliedAlpha)) {
14644                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14645                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14646                                layerType != LAYER_TYPE_NONE) {
14647                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14648                        }
14649                        if (usingRenderNodeProperties) {
14650                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14651                        } else  if (layerType == LAYER_TYPE_NONE) {
14652                            final int scrollX = hasDisplayList ? 0 : sx;
14653                            final int scrollY = hasDisplayList ? 0 : sy;
14654                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14655                                    scrollY + mBottom - mTop, 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 ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14669                !usingRenderNodeProperties && cache == null) {
14670            if (offsetForScroll) {
14671                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14672            } else {
14673                if (!scalingRequired || cache == null) {
14674                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14675                } else {
14676                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14677                }
14678            }
14679        }
14680
14681        if (!usingRenderNodeProperties && hasDisplayList) {
14682            renderNode = getDisplayList();
14683            if (!renderNode.isValid()) {
14684                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14685                // to getDisplayList(), the display list will be marked invalid and we should not
14686                // try to use it again.
14687                renderNode = null;
14688                hasDisplayList = false;
14689            }
14690        }
14691
14692        if (hasNoCache) {
14693            boolean layerRendered = false;
14694            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14695                final HardwareLayer layer = getHardwareLayer();
14696                if (layer != null && layer.isValid()) {
14697                    mLayerPaint.setAlpha((int) (alpha * 255));
14698                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14699                    layerRendered = true;
14700                } else {
14701                    final int scrollX = hasDisplayList ? 0 : sx;
14702                    final int scrollY = hasDisplayList ? 0 : sy;
14703                    canvas.saveLayer(scrollX, scrollY,
14704                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14705                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14706                }
14707            }
14708
14709            if (!layerRendered) {
14710                if (!hasDisplayList) {
14711                    // Fast path for layouts with no backgrounds
14712                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14713                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14714                        dispatchDraw(canvas);
14715                    } else {
14716                        draw(canvas);
14717                    }
14718                } else {
14719                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14720                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14721                }
14722            }
14723        } else if (cache != null) {
14724            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14725            Paint cachePaint;
14726
14727            if (layerType == LAYER_TYPE_NONE) {
14728                cachePaint = parent.mCachePaint;
14729                if (cachePaint == null) {
14730                    cachePaint = new Paint();
14731                    cachePaint.setDither(false);
14732                    parent.mCachePaint = cachePaint;
14733                }
14734                if (alpha < 1) {
14735                    cachePaint.setAlpha((int) (alpha * 255));
14736                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14737                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14738                    cachePaint.setAlpha(255);
14739                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14740                }
14741            } else {
14742                cachePaint = mLayerPaint;
14743                cachePaint.setAlpha((int) (alpha * 255));
14744            }
14745            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14746        }
14747
14748        if (restoreTo >= 0) {
14749            canvas.restoreToCount(restoreTo);
14750        }
14751
14752        if (a != null && !more) {
14753            if (!hardwareAccelerated && !a.getFillAfter()) {
14754                onSetAlpha(255);
14755            }
14756            parent.finishAnimatingView(this, a);
14757        }
14758
14759        if (more && hardwareAccelerated) {
14760            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14761                // alpha animations should cause the child to recreate its display list
14762                invalidate(true);
14763            }
14764        }
14765
14766        mRecreateDisplayList = false;
14767
14768        return more;
14769    }
14770
14771    /**
14772     * Manually render this view (and all of its children) to the given Canvas.
14773     * The view must have already done a full layout before this function is
14774     * called.  When implementing a view, implement
14775     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14776     * If you do need to override this method, call the superclass version.
14777     *
14778     * @param canvas The Canvas to which the View is rendered.
14779     */
14780    public void draw(Canvas canvas) {
14781        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
14782        if (mClipBounds != null && !usingRenderNodeProperties) {
14783            canvas.clipRect(mClipBounds);
14784        }
14785        final int privateFlags = mPrivateFlags;
14786        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14787                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14788        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14789
14790        /*
14791         * Draw traversal performs several drawing steps which must be executed
14792         * in the appropriate order:
14793         *
14794         *      1. Draw the background
14795         *      2. If necessary, save the canvas' layers to prepare for fading
14796         *      3. Draw view's content
14797         *      4. Draw children
14798         *      5. If necessary, draw the fading edges and restore layers
14799         *      6. Draw decorations (scrollbars for instance)
14800         */
14801
14802        // Step 1, draw the background, if needed
14803        int saveCount;
14804
14805        if (!dirtyOpaque) {
14806            drawBackground(canvas);
14807        }
14808
14809        // skip step 2 & 5 if possible (common case)
14810        final int viewFlags = mViewFlags;
14811        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14812        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14813        if (!verticalEdges && !horizontalEdges) {
14814            // Step 3, draw the content
14815            if (!dirtyOpaque) onDraw(canvas);
14816
14817            // Step 4, draw the children
14818            dispatchDraw(canvas);
14819
14820            // Step 6, draw decorations (scrollbars)
14821            onDrawScrollBars(canvas);
14822
14823            if (mOverlay != null && !mOverlay.isEmpty()) {
14824                mOverlay.getOverlayView().dispatchDraw(canvas);
14825            }
14826
14827            // we're done...
14828            return;
14829        }
14830
14831        /*
14832         * Here we do the full fledged routine...
14833         * (this is an uncommon case where speed matters less,
14834         * this is why we repeat some of the tests that have been
14835         * done above)
14836         */
14837
14838        boolean drawTop = false;
14839        boolean drawBottom = false;
14840        boolean drawLeft = false;
14841        boolean drawRight = false;
14842
14843        float topFadeStrength = 0.0f;
14844        float bottomFadeStrength = 0.0f;
14845        float leftFadeStrength = 0.0f;
14846        float rightFadeStrength = 0.0f;
14847
14848        // Step 2, save the canvas' layers
14849        int paddingLeft = mPaddingLeft;
14850
14851        final boolean offsetRequired = isPaddingOffsetRequired();
14852        if (offsetRequired) {
14853            paddingLeft += getLeftPaddingOffset();
14854        }
14855
14856        int left = mScrollX + paddingLeft;
14857        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14858        int top = mScrollY + getFadeTop(offsetRequired);
14859        int bottom = top + getFadeHeight(offsetRequired);
14860
14861        if (offsetRequired) {
14862            right += getRightPaddingOffset();
14863            bottom += getBottomPaddingOffset();
14864        }
14865
14866        final ScrollabilityCache scrollabilityCache = mScrollCache;
14867        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14868        int length = (int) fadeHeight;
14869
14870        // clip the fade length if top and bottom fades overlap
14871        // overlapping fades produce odd-looking artifacts
14872        if (verticalEdges && (top + length > bottom - length)) {
14873            length = (bottom - top) / 2;
14874        }
14875
14876        // also clip horizontal fades if necessary
14877        if (horizontalEdges && (left + length > right - length)) {
14878            length = (right - left) / 2;
14879        }
14880
14881        if (verticalEdges) {
14882            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14883            drawTop = topFadeStrength * fadeHeight > 1.0f;
14884            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14885            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14886        }
14887
14888        if (horizontalEdges) {
14889            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14890            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14891            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14892            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14893        }
14894
14895        saveCount = canvas.getSaveCount();
14896
14897        int solidColor = getSolidColor();
14898        if (solidColor == 0) {
14899            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14900
14901            if (drawTop) {
14902                canvas.saveLayer(left, top, right, top + length, null, flags);
14903            }
14904
14905            if (drawBottom) {
14906                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14907            }
14908
14909            if (drawLeft) {
14910                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14911            }
14912
14913            if (drawRight) {
14914                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14915            }
14916        } else {
14917            scrollabilityCache.setFadeColor(solidColor);
14918        }
14919
14920        // Step 3, draw the content
14921        if (!dirtyOpaque) onDraw(canvas);
14922
14923        // Step 4, draw the children
14924        dispatchDraw(canvas);
14925
14926        // Step 5, draw the fade effect and restore layers
14927        final Paint p = scrollabilityCache.paint;
14928        final Matrix matrix = scrollabilityCache.matrix;
14929        final Shader fade = scrollabilityCache.shader;
14930
14931        if (drawTop) {
14932            matrix.setScale(1, fadeHeight * topFadeStrength);
14933            matrix.postTranslate(left, top);
14934            fade.setLocalMatrix(matrix);
14935            p.setShader(fade);
14936            canvas.drawRect(left, top, right, top + length, p);
14937        }
14938
14939        if (drawBottom) {
14940            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14941            matrix.postRotate(180);
14942            matrix.postTranslate(left, bottom);
14943            fade.setLocalMatrix(matrix);
14944            p.setShader(fade);
14945            canvas.drawRect(left, bottom - length, right, bottom, p);
14946        }
14947
14948        if (drawLeft) {
14949            matrix.setScale(1, fadeHeight * leftFadeStrength);
14950            matrix.postRotate(-90);
14951            matrix.postTranslate(left, top);
14952            fade.setLocalMatrix(matrix);
14953            p.setShader(fade);
14954            canvas.drawRect(left, top, left + length, bottom, p);
14955        }
14956
14957        if (drawRight) {
14958            matrix.setScale(1, fadeHeight * rightFadeStrength);
14959            matrix.postRotate(90);
14960            matrix.postTranslate(right, top);
14961            fade.setLocalMatrix(matrix);
14962            p.setShader(fade);
14963            canvas.drawRect(right - length, top, right, bottom, p);
14964        }
14965
14966        canvas.restoreToCount(saveCount);
14967
14968        // Step 6, draw decorations (scrollbars)
14969        onDrawScrollBars(canvas);
14970
14971        if (mOverlay != null && !mOverlay.isEmpty()) {
14972            mOverlay.getOverlayView().dispatchDraw(canvas);
14973        }
14974    }
14975
14976    /**
14977     * Draws the background onto the specified canvas.
14978     *
14979     * @param canvas Canvas on which to draw the background
14980     */
14981    private void drawBackground(Canvas canvas) {
14982        final Drawable background = mBackground;
14983        if (background == null) {
14984            return;
14985        }
14986
14987        if (mBackgroundSizeChanged) {
14988            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14989            mBackgroundSizeChanged = false;
14990            invalidateOutline();
14991        }
14992
14993        // Attempt to use a display list if requested.
14994        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14995                && mAttachInfo.mHardwareRenderer != null) {
14996            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
14997
14998            final RenderNode displayList = mBackgroundRenderNode;
14999            if (displayList != null && displayList.isValid()) {
15000                setBackgroundDisplayListProperties(displayList);
15001                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15002                return;
15003            }
15004        }
15005
15006        final int scrollX = mScrollX;
15007        final int scrollY = mScrollY;
15008        if ((scrollX | scrollY) == 0) {
15009            background.draw(canvas);
15010        } else {
15011            canvas.translate(scrollX, scrollY);
15012            background.draw(canvas);
15013            canvas.translate(-scrollX, -scrollY);
15014        }
15015    }
15016
15017    /**
15018     * Set up background drawable display list properties.
15019     *
15020     * @param displayList Valid display list for the background drawable
15021     */
15022    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15023        displayList.setTranslationX(mScrollX);
15024        displayList.setTranslationY(mScrollY);
15025    }
15026
15027    /**
15028     * Creates a new display list or updates the existing display list for the
15029     * specified Drawable.
15030     *
15031     * @param drawable Drawable for which to create a display list
15032     * @param renderNode Existing RenderNode, or {@code null}
15033     * @return A valid display list for the specified drawable
15034     */
15035    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15036        if (renderNode == null) {
15037            renderNode = RenderNode.create(drawable.getClass().getName());
15038        }
15039
15040        final Rect bounds = drawable.getBounds();
15041        final int width = bounds.width();
15042        final int height = bounds.height();
15043        final HardwareCanvas canvas = renderNode.start(width, height);
15044        try {
15045            drawable.draw(canvas);
15046        } finally {
15047            renderNode.end(canvas);
15048        }
15049
15050        // Set up drawable properties that are view-independent.
15051        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15052        renderNode.setProjectBackwards(drawable.isProjected());
15053        renderNode.setProjectionReceiver(true);
15054        renderNode.setClipToBounds(false);
15055        return renderNode;
15056    }
15057
15058    /**
15059     * Returns the overlay for this view, creating it if it does not yet exist.
15060     * Adding drawables to the overlay will cause them to be displayed whenever
15061     * the view itself is redrawn. Objects in the overlay should be actively
15062     * managed: remove them when they should not be displayed anymore. The
15063     * overlay will always have the same size as its host view.
15064     *
15065     * <p>Note: Overlays do not currently work correctly with {@link
15066     * SurfaceView} or {@link TextureView}; contents in overlays for these
15067     * types of views may not display correctly.</p>
15068     *
15069     * @return The ViewOverlay object for this view.
15070     * @see ViewOverlay
15071     */
15072    public ViewOverlay getOverlay() {
15073        if (mOverlay == null) {
15074            mOverlay = new ViewOverlay(mContext, this);
15075        }
15076        return mOverlay;
15077    }
15078
15079    /**
15080     * Override this if your view is known to always be drawn on top of a solid color background,
15081     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15082     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15083     * should be set to 0xFF.
15084     *
15085     * @see #setVerticalFadingEdgeEnabled(boolean)
15086     * @see #setHorizontalFadingEdgeEnabled(boolean)
15087     *
15088     * @return The known solid color background for this view, or 0 if the color may vary
15089     */
15090    @ViewDebug.ExportedProperty(category = "drawing")
15091    public int getSolidColor() {
15092        return 0;
15093    }
15094
15095    /**
15096     * Build a human readable string representation of the specified view flags.
15097     *
15098     * @param flags the view flags to convert to a string
15099     * @return a String representing the supplied flags
15100     */
15101    private static String printFlags(int flags) {
15102        String output = "";
15103        int numFlags = 0;
15104        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15105            output += "TAKES_FOCUS";
15106            numFlags++;
15107        }
15108
15109        switch (flags & VISIBILITY_MASK) {
15110        case INVISIBLE:
15111            if (numFlags > 0) {
15112                output += " ";
15113            }
15114            output += "INVISIBLE";
15115            // USELESS HERE numFlags++;
15116            break;
15117        case GONE:
15118            if (numFlags > 0) {
15119                output += " ";
15120            }
15121            output += "GONE";
15122            // USELESS HERE numFlags++;
15123            break;
15124        default:
15125            break;
15126        }
15127        return output;
15128    }
15129
15130    /**
15131     * Build a human readable string representation of the specified private
15132     * view flags.
15133     *
15134     * @param privateFlags the private view flags to convert to a string
15135     * @return a String representing the supplied flags
15136     */
15137    private static String printPrivateFlags(int privateFlags) {
15138        String output = "";
15139        int numFlags = 0;
15140
15141        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15142            output += "WANTS_FOCUS";
15143            numFlags++;
15144        }
15145
15146        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15147            if (numFlags > 0) {
15148                output += " ";
15149            }
15150            output += "FOCUSED";
15151            numFlags++;
15152        }
15153
15154        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15155            if (numFlags > 0) {
15156                output += " ";
15157            }
15158            output += "SELECTED";
15159            numFlags++;
15160        }
15161
15162        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15163            if (numFlags > 0) {
15164                output += " ";
15165            }
15166            output += "IS_ROOT_NAMESPACE";
15167            numFlags++;
15168        }
15169
15170        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15171            if (numFlags > 0) {
15172                output += " ";
15173            }
15174            output += "HAS_BOUNDS";
15175            numFlags++;
15176        }
15177
15178        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15179            if (numFlags > 0) {
15180                output += " ";
15181            }
15182            output += "DRAWN";
15183            // USELESS HERE numFlags++;
15184        }
15185        return output;
15186    }
15187
15188    /**
15189     * <p>Indicates whether or not this view's layout will be requested during
15190     * the next hierarchy layout pass.</p>
15191     *
15192     * @return true if the layout will be forced during next layout pass
15193     */
15194    public boolean isLayoutRequested() {
15195        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15196    }
15197
15198    /**
15199     * Return true if o is a ViewGroup that is laying out using optical bounds.
15200     * @hide
15201     */
15202    public static boolean isLayoutModeOptical(Object o) {
15203        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15204    }
15205
15206    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15207        Insets parentInsets = mParent instanceof View ?
15208                ((View) mParent).getOpticalInsets() : Insets.NONE;
15209        Insets childInsets = getOpticalInsets();
15210        return setFrame(
15211                left   + parentInsets.left - childInsets.left,
15212                top    + parentInsets.top  - childInsets.top,
15213                right  + parentInsets.left + childInsets.right,
15214                bottom + parentInsets.top  + childInsets.bottom);
15215    }
15216
15217    /**
15218     * Assign a size and position to a view and all of its
15219     * descendants
15220     *
15221     * <p>This is the second phase of the layout mechanism.
15222     * (The first is measuring). In this phase, each parent calls
15223     * layout on all of its children to position them.
15224     * This is typically done using the child measurements
15225     * that were stored in the measure pass().</p>
15226     *
15227     * <p>Derived classes should not override this method.
15228     * Derived classes with children should override
15229     * onLayout. In that method, they should
15230     * call layout on each of their children.</p>
15231     *
15232     * @param l Left position, relative to parent
15233     * @param t Top position, relative to parent
15234     * @param r Right position, relative to parent
15235     * @param b Bottom position, relative to parent
15236     */
15237    @SuppressWarnings({"unchecked"})
15238    public void layout(int l, int t, int r, int b) {
15239        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15240            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15241            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15242        }
15243
15244        int oldL = mLeft;
15245        int oldT = mTop;
15246        int oldB = mBottom;
15247        int oldR = mRight;
15248
15249        boolean changed = isLayoutModeOptical(mParent) ?
15250                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15251
15252        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15253            onLayout(changed, l, t, r, b);
15254            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15255
15256            ListenerInfo li = mListenerInfo;
15257            if (li != null && li.mOnLayoutChangeListeners != null) {
15258                ArrayList<OnLayoutChangeListener> listenersCopy =
15259                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15260                int numListeners = listenersCopy.size();
15261                for (int i = 0; i < numListeners; ++i) {
15262                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15263                }
15264            }
15265        }
15266
15267        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15268        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15269    }
15270
15271    /**
15272     * Called from layout when this view should
15273     * assign a size and position to each of its children.
15274     *
15275     * Derived classes with children should override
15276     * this method and call layout on each of
15277     * their children.
15278     * @param changed This is a new size or position for this view
15279     * @param left Left position, relative to parent
15280     * @param top Top position, relative to parent
15281     * @param right Right position, relative to parent
15282     * @param bottom Bottom position, relative to parent
15283     */
15284    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15285    }
15286
15287    /**
15288     * Assign a size and position to this view.
15289     *
15290     * This is called from layout.
15291     *
15292     * @param left Left position, relative to parent
15293     * @param top Top position, relative to parent
15294     * @param right Right position, relative to parent
15295     * @param bottom Bottom position, relative to parent
15296     * @return true if the new size and position are different than the
15297     *         previous ones
15298     * {@hide}
15299     */
15300    protected boolean setFrame(int left, int top, int right, int bottom) {
15301        boolean changed = false;
15302
15303        if (DBG) {
15304            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15305                    + right + "," + bottom + ")");
15306        }
15307
15308        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15309            changed = true;
15310
15311            // Remember our drawn bit
15312            int drawn = mPrivateFlags & PFLAG_DRAWN;
15313
15314            int oldWidth = mRight - mLeft;
15315            int oldHeight = mBottom - mTop;
15316            int newWidth = right - left;
15317            int newHeight = bottom - top;
15318            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15319
15320            // Invalidate our old position
15321            invalidate(sizeChanged);
15322
15323            mLeft = left;
15324            mTop = top;
15325            mRight = right;
15326            mBottom = bottom;
15327            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15328
15329            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15330
15331
15332            if (sizeChanged) {
15333                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15334            }
15335
15336            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15337                // If we are visible, force the DRAWN bit to on so that
15338                // this invalidate will go through (at least to our parent).
15339                // This is because someone may have invalidated this view
15340                // before this call to setFrame came in, thereby clearing
15341                // the DRAWN bit.
15342                mPrivateFlags |= PFLAG_DRAWN;
15343                invalidate(sizeChanged);
15344                // parent display list may need to be recreated based on a change in the bounds
15345                // of any child
15346                invalidateParentCaches();
15347            }
15348
15349            // Reset drawn bit to original value (invalidate turns it off)
15350            mPrivateFlags |= drawn;
15351
15352            mBackgroundSizeChanged = true;
15353
15354            notifySubtreeAccessibilityStateChangedIfNeeded();
15355        }
15356        return changed;
15357    }
15358
15359    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15360        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15361        if (mOverlay != null) {
15362            mOverlay.getOverlayView().setRight(newWidth);
15363            mOverlay.getOverlayView().setBottom(newHeight);
15364        }
15365        invalidateOutline();
15366    }
15367
15368    /**
15369     * Finalize inflating a view from XML.  This is called as the last phase
15370     * of inflation, after all child views have been added.
15371     *
15372     * <p>Even if the subclass overrides onFinishInflate, they should always be
15373     * sure to call the super method, so that we get called.
15374     */
15375    protected void onFinishInflate() {
15376    }
15377
15378    /**
15379     * Returns the resources associated with this view.
15380     *
15381     * @return Resources object.
15382     */
15383    public Resources getResources() {
15384        return mResources;
15385    }
15386
15387    /**
15388     * Invalidates the specified Drawable.
15389     *
15390     * @param drawable the drawable to invalidate
15391     */
15392    @Override
15393    public void invalidateDrawable(@NonNull Drawable drawable) {
15394        if (verifyDrawable(drawable)) {
15395            final Rect dirty = drawable.getDirtyBounds();
15396            final int scrollX = mScrollX;
15397            final int scrollY = mScrollY;
15398
15399            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15400                    dirty.right + scrollX, dirty.bottom + scrollY);
15401
15402            invalidateOutline();
15403        }
15404    }
15405
15406    /**
15407     * Schedules an action on a drawable to occur at a specified time.
15408     *
15409     * @param who the recipient of the action
15410     * @param what the action to run on the drawable
15411     * @param when the time at which the action must occur. Uses the
15412     *        {@link SystemClock#uptimeMillis} timebase.
15413     */
15414    @Override
15415    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15416        if (verifyDrawable(who) && what != null) {
15417            final long delay = when - SystemClock.uptimeMillis();
15418            if (mAttachInfo != null) {
15419                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15420                        Choreographer.CALLBACK_ANIMATION, what, who,
15421                        Choreographer.subtractFrameDelay(delay));
15422            } else {
15423                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15424            }
15425        }
15426    }
15427
15428    /**
15429     * Cancels a scheduled action on a drawable.
15430     *
15431     * @param who the recipient of the action
15432     * @param what the action to cancel
15433     */
15434    @Override
15435    public void unscheduleDrawable(Drawable who, Runnable what) {
15436        if (verifyDrawable(who) && what != null) {
15437            if (mAttachInfo != null) {
15438                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15439                        Choreographer.CALLBACK_ANIMATION, what, who);
15440            }
15441            ViewRootImpl.getRunQueue().removeCallbacks(what);
15442        }
15443    }
15444
15445    /**
15446     * Unschedule any events associated with the given Drawable.  This can be
15447     * used when selecting a new Drawable into a view, so that the previous
15448     * one is completely unscheduled.
15449     *
15450     * @param who The Drawable to unschedule.
15451     *
15452     * @see #drawableStateChanged
15453     */
15454    public void unscheduleDrawable(Drawable who) {
15455        if (mAttachInfo != null && who != null) {
15456            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15457                    Choreographer.CALLBACK_ANIMATION, null, who);
15458        }
15459    }
15460
15461    /**
15462     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15463     * that the View directionality can and will be resolved before its Drawables.
15464     *
15465     * Will call {@link View#onResolveDrawables} when resolution is done.
15466     *
15467     * @hide
15468     */
15469    protected void resolveDrawables() {
15470        // Drawables resolution may need to happen before resolving the layout direction (which is
15471        // done only during the measure() call).
15472        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15473        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15474        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15475        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15476        // direction to be resolved as its resolved value will be the same as its raw value.
15477        if (!isLayoutDirectionResolved() &&
15478                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15479            return;
15480        }
15481
15482        final int layoutDirection = isLayoutDirectionResolved() ?
15483                getLayoutDirection() : getRawLayoutDirection();
15484
15485        if (mBackground != null) {
15486            mBackground.setLayoutDirection(layoutDirection);
15487        }
15488        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15489        onResolveDrawables(layoutDirection);
15490    }
15491
15492    /**
15493     * Called when layout direction has been resolved.
15494     *
15495     * The default implementation does nothing.
15496     *
15497     * @param layoutDirection The resolved layout direction.
15498     *
15499     * @see #LAYOUT_DIRECTION_LTR
15500     * @see #LAYOUT_DIRECTION_RTL
15501     *
15502     * @hide
15503     */
15504    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15505    }
15506
15507    /**
15508     * @hide
15509     */
15510    protected void resetResolvedDrawables() {
15511        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15512    }
15513
15514    private boolean isDrawablesResolved() {
15515        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15516    }
15517
15518    /**
15519     * If your view subclass is displaying its own Drawable objects, it should
15520     * override this function and return true for any Drawable it is
15521     * displaying.  This allows animations for those drawables to be
15522     * scheduled.
15523     *
15524     * <p>Be sure to call through to the super class when overriding this
15525     * function.
15526     *
15527     * @param who The Drawable to verify.  Return true if it is one you are
15528     *            displaying, else return the result of calling through to the
15529     *            super class.
15530     *
15531     * @return boolean If true than the Drawable is being displayed in the
15532     *         view; else false and it is not allowed to animate.
15533     *
15534     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15535     * @see #drawableStateChanged()
15536     */
15537    protected boolean verifyDrawable(Drawable who) {
15538        return who == mBackground;
15539    }
15540
15541    /**
15542     * This function is called whenever the state of the view changes in such
15543     * a way that it impacts the state of drawables being shown.
15544     * <p>
15545     * If the View has a StateListAnimator, it will also be called to run necessary state
15546     * change animations.
15547     * <p>
15548     * Be sure to call through to the superclass when overriding this function.
15549     *
15550     * @see Drawable#setState(int[])
15551     */
15552    protected void drawableStateChanged() {
15553        final Drawable d = mBackground;
15554        if (d != null && d.isStateful()) {
15555            d.setState(getDrawableState());
15556        }
15557
15558        if (mStateListAnimator != null) {
15559            mStateListAnimator.setState(getDrawableState());
15560        }
15561    }
15562
15563    /**
15564     * This function is called whenever the view hotspot changes and needs to
15565     * be propagated to drawables managed by the view.
15566     * <p>
15567     * Be sure to call through to the superclass when overriding this function.
15568     *
15569     * @param x hotspot x coordinate
15570     * @param y hotspot y coordinate
15571     */
15572    public void drawableHotspotChanged(float x, float y) {
15573        if (mBackground != null) {
15574            mBackground.setHotspot(x, y);
15575        }
15576    }
15577
15578    /**
15579     * Call this to force a view to update its drawable state. This will cause
15580     * drawableStateChanged to be called on this view. Views that are interested
15581     * in the new state should call getDrawableState.
15582     *
15583     * @see #drawableStateChanged
15584     * @see #getDrawableState
15585     */
15586    public void refreshDrawableState() {
15587        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15588        drawableStateChanged();
15589
15590        ViewParent parent = mParent;
15591        if (parent != null) {
15592            parent.childDrawableStateChanged(this);
15593        }
15594    }
15595
15596    /**
15597     * Return an array of resource IDs of the drawable states representing the
15598     * current state of the view.
15599     *
15600     * @return The current drawable state
15601     *
15602     * @see Drawable#setState(int[])
15603     * @see #drawableStateChanged()
15604     * @see #onCreateDrawableState(int)
15605     */
15606    public final int[] getDrawableState() {
15607        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15608            return mDrawableState;
15609        } else {
15610            mDrawableState = onCreateDrawableState(0);
15611            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15612            return mDrawableState;
15613        }
15614    }
15615
15616    /**
15617     * Generate the new {@link android.graphics.drawable.Drawable} state for
15618     * this view. This is called by the view
15619     * system when the cached Drawable state is determined to be invalid.  To
15620     * retrieve the current state, you should use {@link #getDrawableState}.
15621     *
15622     * @param extraSpace if non-zero, this is the number of extra entries you
15623     * would like in the returned array in which you can place your own
15624     * states.
15625     *
15626     * @return Returns an array holding the current {@link Drawable} state of
15627     * the view.
15628     *
15629     * @see #mergeDrawableStates(int[], int[])
15630     */
15631    protected int[] onCreateDrawableState(int extraSpace) {
15632        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15633                mParent instanceof View) {
15634            return ((View) mParent).onCreateDrawableState(extraSpace);
15635        }
15636
15637        int[] drawableState;
15638
15639        int privateFlags = mPrivateFlags;
15640
15641        int viewStateIndex = 0;
15642        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15643        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15644        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15645        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15646        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15647        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15648        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15649                HardwareRenderer.isAvailable()) {
15650            // This is set if HW acceleration is requested, even if the current
15651            // process doesn't allow it.  This is just to allow app preview
15652            // windows to better match their app.
15653            viewStateIndex |= VIEW_STATE_ACCELERATED;
15654        }
15655        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15656
15657        final int privateFlags2 = mPrivateFlags2;
15658        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15659        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15660
15661        drawableState = VIEW_STATE_SETS[viewStateIndex];
15662
15663        //noinspection ConstantIfStatement
15664        if (false) {
15665            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15666            Log.i("View", toString()
15667                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15668                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15669                    + " fo=" + hasFocus()
15670                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15671                    + " wf=" + hasWindowFocus()
15672                    + ": " + Arrays.toString(drawableState));
15673        }
15674
15675        if (extraSpace == 0) {
15676            return drawableState;
15677        }
15678
15679        final int[] fullState;
15680        if (drawableState != null) {
15681            fullState = new int[drawableState.length + extraSpace];
15682            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15683        } else {
15684            fullState = new int[extraSpace];
15685        }
15686
15687        return fullState;
15688    }
15689
15690    /**
15691     * Merge your own state values in <var>additionalState</var> into the base
15692     * state values <var>baseState</var> that were returned by
15693     * {@link #onCreateDrawableState(int)}.
15694     *
15695     * @param baseState The base state values returned by
15696     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15697     * own additional state values.
15698     *
15699     * @param additionalState The additional state values you would like
15700     * added to <var>baseState</var>; this array is not modified.
15701     *
15702     * @return As a convenience, the <var>baseState</var> array you originally
15703     * passed into the function is returned.
15704     *
15705     * @see #onCreateDrawableState(int)
15706     */
15707    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15708        final int N = baseState.length;
15709        int i = N - 1;
15710        while (i >= 0 && baseState[i] == 0) {
15711            i--;
15712        }
15713        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15714        return baseState;
15715    }
15716
15717    /**
15718     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15719     * on all Drawable objects associated with this view.
15720     * <p>
15721     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15722     * attached to this view.
15723     */
15724    public void jumpDrawablesToCurrentState() {
15725        if (mBackground != null) {
15726            mBackground.jumpToCurrentState();
15727        }
15728        if (mStateListAnimator != null) {
15729            mStateListAnimator.jumpToCurrentState();
15730        }
15731    }
15732
15733    /**
15734     * Sets the background color for this view.
15735     * @param color the color of the background
15736     */
15737    @RemotableViewMethod
15738    public void setBackgroundColor(int color) {
15739        if (mBackground instanceof ColorDrawable) {
15740            ((ColorDrawable) mBackground.mutate()).setColor(color);
15741            computeOpaqueFlags();
15742            mBackgroundResource = 0;
15743        } else {
15744            setBackground(new ColorDrawable(color));
15745        }
15746    }
15747
15748    /**
15749     * Set the background to a given resource. The resource should refer to
15750     * a Drawable object or 0 to remove the background.
15751     * @param resid The identifier of the resource.
15752     *
15753     * @attr ref android.R.styleable#View_background
15754     */
15755    @RemotableViewMethod
15756    public void setBackgroundResource(int resid) {
15757        if (resid != 0 && resid == mBackgroundResource) {
15758            return;
15759        }
15760
15761        Drawable d = null;
15762        if (resid != 0) {
15763            d = mContext.getDrawable(resid);
15764        }
15765        setBackground(d);
15766
15767        mBackgroundResource = resid;
15768    }
15769
15770    /**
15771     * Set the background to a given Drawable, or remove the background. If the
15772     * background has padding, this View's padding is set to the background's
15773     * padding. However, when a background is removed, this View's padding isn't
15774     * touched. If setting the padding is desired, please use
15775     * {@link #setPadding(int, int, int, int)}.
15776     *
15777     * @param background The Drawable to use as the background, or null to remove the
15778     *        background
15779     */
15780    public void setBackground(Drawable background) {
15781        //noinspection deprecation
15782        setBackgroundDrawable(background);
15783    }
15784
15785    /**
15786     * @deprecated use {@link #setBackground(Drawable)} instead
15787     */
15788    @Deprecated
15789    public void setBackgroundDrawable(Drawable background) {
15790        computeOpaqueFlags();
15791
15792        if (background == mBackground) {
15793            return;
15794        }
15795
15796        boolean requestLayout = false;
15797
15798        mBackgroundResource = 0;
15799
15800        /*
15801         * Regardless of whether we're setting a new background or not, we want
15802         * to clear the previous drawable.
15803         */
15804        if (mBackground != null) {
15805            mBackground.setCallback(null);
15806            unscheduleDrawable(mBackground);
15807        }
15808
15809        if (background != null) {
15810            Rect padding = sThreadLocal.get();
15811            if (padding == null) {
15812                padding = new Rect();
15813                sThreadLocal.set(padding);
15814            }
15815            resetResolvedDrawables();
15816            background.setLayoutDirection(getLayoutDirection());
15817            if (background.getPadding(padding)) {
15818                resetResolvedPadding();
15819                switch (background.getLayoutDirection()) {
15820                    case LAYOUT_DIRECTION_RTL:
15821                        mUserPaddingLeftInitial = padding.right;
15822                        mUserPaddingRightInitial = padding.left;
15823                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15824                        break;
15825                    case LAYOUT_DIRECTION_LTR:
15826                    default:
15827                        mUserPaddingLeftInitial = padding.left;
15828                        mUserPaddingRightInitial = padding.right;
15829                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15830                }
15831                mLeftPaddingDefined = false;
15832                mRightPaddingDefined = false;
15833            }
15834
15835            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15836            // if it has a different minimum size, we should layout again
15837            if (mBackground == null
15838                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15839                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15840                requestLayout = true;
15841            }
15842
15843            background.setCallback(this);
15844            if (background.isStateful()) {
15845                background.setState(getDrawableState());
15846            }
15847            background.setVisible(getVisibility() == VISIBLE, false);
15848            mBackground = background;
15849
15850            applyBackgroundTint();
15851
15852            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15853                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15854                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15855                requestLayout = true;
15856            }
15857        } else {
15858            /* Remove the background */
15859            mBackground = null;
15860
15861            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15862                /*
15863                 * This view ONLY drew the background before and we're removing
15864                 * the background, so now it won't draw anything
15865                 * (hence we SKIP_DRAW)
15866                 */
15867                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15868                mPrivateFlags |= PFLAG_SKIP_DRAW;
15869            }
15870
15871            /*
15872             * When the background is set, we try to apply its padding to this
15873             * View. When the background is removed, we don't touch this View's
15874             * padding. This is noted in the Javadocs. Hence, we don't need to
15875             * requestLayout(), the invalidate() below is sufficient.
15876             */
15877
15878            // The old background's minimum size could have affected this
15879            // View's layout, so let's requestLayout
15880            requestLayout = true;
15881        }
15882
15883        computeOpaqueFlags();
15884
15885        if (requestLayout) {
15886            requestLayout();
15887        }
15888
15889        mBackgroundSizeChanged = true;
15890        invalidate(true);
15891    }
15892
15893    /**
15894     * Gets the background drawable
15895     *
15896     * @return The drawable used as the background for this view, if any.
15897     *
15898     * @see #setBackground(Drawable)
15899     *
15900     * @attr ref android.R.styleable#View_background
15901     */
15902    public Drawable getBackground() {
15903        return mBackground;
15904    }
15905
15906    /**
15907     * Applies a tint to the background drawable. Does not modify the current tint
15908     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15909     * <p>
15910     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15911     * mutate the drawable and apply the specified tint and tint mode using
15912     * {@link Drawable#setTint(ColorStateList, PorterDuff.Mode)}.
15913     *
15914     * @param tint the tint to apply, may be {@code null} to clear tint
15915     *
15916     * @attr ref android.R.styleable#View_backgroundTint
15917     * @see #getBackgroundTint()
15918     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15919     */
15920    public void setBackgroundTint(@Nullable ColorStateList tint) {
15921        mBackgroundTint = tint;
15922        mHasBackgroundTint = true;
15923
15924        applyBackgroundTint();
15925    }
15926
15927    /**
15928     * @return the tint applied to the background drawable
15929     * @attr ref android.R.styleable#View_backgroundTint
15930     * @see #setBackgroundTint(ColorStateList)
15931     */
15932    @Nullable
15933    public ColorStateList getBackgroundTint() {
15934        return mBackgroundTint;
15935    }
15936
15937    /**
15938     * Specifies the blending mode used to apply the tint specified by
15939     * {@link #setBackgroundTint(ColorStateList)}} to the background drawable.
15940     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15941     *
15942     * @param tintMode the blending mode used to apply the tint, may be
15943     *                 {@code null} to clear tint
15944     * @attr ref android.R.styleable#View_backgroundTintMode
15945     * @see #getBackgroundTintMode()
15946     * @see Drawable#setTint(ColorStateList, PorterDuff.Mode)
15947     */
15948    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15949        mBackgroundTintMode = tintMode;
15950
15951        applyBackgroundTint();
15952    }
15953
15954    /**
15955     * @return the blending mode used to apply the tint to the background drawable
15956     * @attr ref android.R.styleable#View_backgroundTintMode
15957     * @see #setBackgroundTintMode(PorterDuff.Mode)
15958     */
15959    @Nullable
15960    public PorterDuff.Mode getBackgroundTintMode() {
15961        return mBackgroundTintMode;
15962    }
15963
15964    private void applyBackgroundTint() {
15965        if (mBackground != null && mHasBackgroundTint) {
15966            mBackground = mBackground.mutate();
15967            mBackground.setTint(mBackgroundTint, mBackgroundTintMode);
15968        }
15969    }
15970
15971    /**
15972     * Sets the padding. The view may add on the space required to display
15973     * the scrollbars, depending on the style and visibility of the scrollbars.
15974     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15975     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15976     * from the values set in this call.
15977     *
15978     * @attr ref android.R.styleable#View_padding
15979     * @attr ref android.R.styleable#View_paddingBottom
15980     * @attr ref android.R.styleable#View_paddingLeft
15981     * @attr ref android.R.styleable#View_paddingRight
15982     * @attr ref android.R.styleable#View_paddingTop
15983     * @param left the left padding in pixels
15984     * @param top the top padding in pixels
15985     * @param right the right padding in pixels
15986     * @param bottom the bottom padding in pixels
15987     */
15988    public void setPadding(int left, int top, int right, int bottom) {
15989        resetResolvedPadding();
15990
15991        mUserPaddingStart = UNDEFINED_PADDING;
15992        mUserPaddingEnd = UNDEFINED_PADDING;
15993
15994        mUserPaddingLeftInitial = left;
15995        mUserPaddingRightInitial = right;
15996
15997        mLeftPaddingDefined = true;
15998        mRightPaddingDefined = true;
15999
16000        internalSetPadding(left, top, right, bottom);
16001    }
16002
16003    /**
16004     * @hide
16005     */
16006    protected void internalSetPadding(int left, int top, int right, int bottom) {
16007        mUserPaddingLeft = left;
16008        mUserPaddingRight = right;
16009        mUserPaddingBottom = bottom;
16010
16011        final int viewFlags = mViewFlags;
16012        boolean changed = false;
16013
16014        // Common case is there are no scroll bars.
16015        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16016            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16017                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16018                        ? 0 : getVerticalScrollbarWidth();
16019                switch (mVerticalScrollbarPosition) {
16020                    case SCROLLBAR_POSITION_DEFAULT:
16021                        if (isLayoutRtl()) {
16022                            left += offset;
16023                        } else {
16024                            right += offset;
16025                        }
16026                        break;
16027                    case SCROLLBAR_POSITION_RIGHT:
16028                        right += offset;
16029                        break;
16030                    case SCROLLBAR_POSITION_LEFT:
16031                        left += offset;
16032                        break;
16033                }
16034            }
16035            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16036                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16037                        ? 0 : getHorizontalScrollbarHeight();
16038            }
16039        }
16040
16041        if (mPaddingLeft != left) {
16042            changed = true;
16043            mPaddingLeft = left;
16044        }
16045        if (mPaddingTop != top) {
16046            changed = true;
16047            mPaddingTop = top;
16048        }
16049        if (mPaddingRight != right) {
16050            changed = true;
16051            mPaddingRight = right;
16052        }
16053        if (mPaddingBottom != bottom) {
16054            changed = true;
16055            mPaddingBottom = bottom;
16056        }
16057
16058        if (changed) {
16059            requestLayout();
16060        }
16061    }
16062
16063    /**
16064     * Sets the relative padding. The view may add on the space required to display
16065     * the scrollbars, depending on the style and visibility of the scrollbars.
16066     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16067     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16068     * from the values set in this call.
16069     *
16070     * @attr ref android.R.styleable#View_padding
16071     * @attr ref android.R.styleable#View_paddingBottom
16072     * @attr ref android.R.styleable#View_paddingStart
16073     * @attr ref android.R.styleable#View_paddingEnd
16074     * @attr ref android.R.styleable#View_paddingTop
16075     * @param start the start padding in pixels
16076     * @param top the top padding in pixels
16077     * @param end the end padding in pixels
16078     * @param bottom the bottom padding in pixels
16079     */
16080    public void setPaddingRelative(int start, int top, int end, int bottom) {
16081        resetResolvedPadding();
16082
16083        mUserPaddingStart = start;
16084        mUserPaddingEnd = end;
16085        mLeftPaddingDefined = true;
16086        mRightPaddingDefined = true;
16087
16088        switch(getLayoutDirection()) {
16089            case LAYOUT_DIRECTION_RTL:
16090                mUserPaddingLeftInitial = end;
16091                mUserPaddingRightInitial = start;
16092                internalSetPadding(end, top, start, bottom);
16093                break;
16094            case LAYOUT_DIRECTION_LTR:
16095            default:
16096                mUserPaddingLeftInitial = start;
16097                mUserPaddingRightInitial = end;
16098                internalSetPadding(start, top, end, bottom);
16099        }
16100    }
16101
16102    /**
16103     * Returns the top padding of this view.
16104     *
16105     * @return the top padding in pixels
16106     */
16107    public int getPaddingTop() {
16108        return mPaddingTop;
16109    }
16110
16111    /**
16112     * Returns the bottom padding of this view. If there are inset and enabled
16113     * scrollbars, this value may include the space required to display the
16114     * scrollbars as well.
16115     *
16116     * @return the bottom padding in pixels
16117     */
16118    public int getPaddingBottom() {
16119        return mPaddingBottom;
16120    }
16121
16122    /**
16123     * Returns the left padding of this view. If there are inset and enabled
16124     * scrollbars, this value may include the space required to display the
16125     * scrollbars as well.
16126     *
16127     * @return the left padding in pixels
16128     */
16129    public int getPaddingLeft() {
16130        if (!isPaddingResolved()) {
16131            resolvePadding();
16132        }
16133        return mPaddingLeft;
16134    }
16135
16136    /**
16137     * Returns the start padding of this view depending on its resolved layout direction.
16138     * If there are inset and enabled scrollbars, this value may include the space
16139     * required to display the scrollbars as well.
16140     *
16141     * @return the start padding in pixels
16142     */
16143    public int getPaddingStart() {
16144        if (!isPaddingResolved()) {
16145            resolvePadding();
16146        }
16147        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16148                mPaddingRight : mPaddingLeft;
16149    }
16150
16151    /**
16152     * Returns the right padding of this view. If there are inset and enabled
16153     * scrollbars, this value may include the space required to display the
16154     * scrollbars as well.
16155     *
16156     * @return the right padding in pixels
16157     */
16158    public int getPaddingRight() {
16159        if (!isPaddingResolved()) {
16160            resolvePadding();
16161        }
16162        return mPaddingRight;
16163    }
16164
16165    /**
16166     * Returns the end padding of this view depending on its resolved layout direction.
16167     * If there are inset and enabled scrollbars, this value may include the space
16168     * required to display the scrollbars as well.
16169     *
16170     * @return the end padding in pixels
16171     */
16172    public int getPaddingEnd() {
16173        if (!isPaddingResolved()) {
16174            resolvePadding();
16175        }
16176        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16177                mPaddingLeft : mPaddingRight;
16178    }
16179
16180    /**
16181     * Return if the padding as been set thru relative values
16182     * {@link #setPaddingRelative(int, int, int, int)} or thru
16183     * @attr ref android.R.styleable#View_paddingStart or
16184     * @attr ref android.R.styleable#View_paddingEnd
16185     *
16186     * @return true if the padding is relative or false if it is not.
16187     */
16188    public boolean isPaddingRelative() {
16189        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16190    }
16191
16192    Insets computeOpticalInsets() {
16193        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16194    }
16195
16196    /**
16197     * @hide
16198     */
16199    public void resetPaddingToInitialValues() {
16200        if (isRtlCompatibilityMode()) {
16201            mPaddingLeft = mUserPaddingLeftInitial;
16202            mPaddingRight = mUserPaddingRightInitial;
16203            return;
16204        }
16205        if (isLayoutRtl()) {
16206            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16207            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16208        } else {
16209            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16210            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16211        }
16212    }
16213
16214    /**
16215     * @hide
16216     */
16217    public Insets getOpticalInsets() {
16218        if (mLayoutInsets == null) {
16219            mLayoutInsets = computeOpticalInsets();
16220        }
16221        return mLayoutInsets;
16222    }
16223
16224    /**
16225     * Set this view's optical insets.
16226     *
16227     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16228     * property. Views that compute their own optical insets should call it as part of measurement.
16229     * This method does not request layout. If you are setting optical insets outside of
16230     * measure/layout itself you will want to call requestLayout() yourself.
16231     * </p>
16232     * @hide
16233     */
16234    public void setOpticalInsets(Insets insets) {
16235        mLayoutInsets = insets;
16236    }
16237
16238    /**
16239     * Changes the selection state of this view. A view can be selected or not.
16240     * Note that selection is not the same as focus. Views are typically
16241     * selected in the context of an AdapterView like ListView or GridView;
16242     * the selected view is the view that is highlighted.
16243     *
16244     * @param selected true if the view must be selected, false otherwise
16245     */
16246    public void setSelected(boolean selected) {
16247        //noinspection DoubleNegation
16248        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16249            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16250            if (!selected) resetPressedState();
16251            invalidate(true);
16252            refreshDrawableState();
16253            dispatchSetSelected(selected);
16254            notifyViewAccessibilityStateChangedIfNeeded(
16255                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16256        }
16257    }
16258
16259    /**
16260     * Dispatch setSelected to all of this View's children.
16261     *
16262     * @see #setSelected(boolean)
16263     *
16264     * @param selected The new selected state
16265     */
16266    protected void dispatchSetSelected(boolean selected) {
16267    }
16268
16269    /**
16270     * Indicates the selection state of this view.
16271     *
16272     * @return true if the view is selected, false otherwise
16273     */
16274    @ViewDebug.ExportedProperty
16275    public boolean isSelected() {
16276        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16277    }
16278
16279    /**
16280     * Changes the activated state of this view. A view can be activated or not.
16281     * Note that activation is not the same as selection.  Selection is
16282     * a transient property, representing the view (hierarchy) the user is
16283     * currently interacting with.  Activation is a longer-term state that the
16284     * user can move views in and out of.  For example, in a list view with
16285     * single or multiple selection enabled, the views in the current selection
16286     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16287     * here.)  The activated state is propagated down to children of the view it
16288     * is set on.
16289     *
16290     * @param activated true if the view must be activated, false otherwise
16291     */
16292    public void setActivated(boolean activated) {
16293        //noinspection DoubleNegation
16294        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16295            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16296            invalidate(true);
16297            refreshDrawableState();
16298            dispatchSetActivated(activated);
16299        }
16300    }
16301
16302    /**
16303     * Dispatch setActivated to all of this View's children.
16304     *
16305     * @see #setActivated(boolean)
16306     *
16307     * @param activated The new activated state
16308     */
16309    protected void dispatchSetActivated(boolean activated) {
16310    }
16311
16312    /**
16313     * Indicates the activation state of this view.
16314     *
16315     * @return true if the view is activated, false otherwise
16316     */
16317    @ViewDebug.ExportedProperty
16318    public boolean isActivated() {
16319        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16320    }
16321
16322    /**
16323     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16324     * observer can be used to get notifications when global events, like
16325     * layout, happen.
16326     *
16327     * The returned ViewTreeObserver observer is not guaranteed to remain
16328     * valid for the lifetime of this View. If the caller of this method keeps
16329     * a long-lived reference to ViewTreeObserver, it should always check for
16330     * the return value of {@link ViewTreeObserver#isAlive()}.
16331     *
16332     * @return The ViewTreeObserver for this view's hierarchy.
16333     */
16334    public ViewTreeObserver getViewTreeObserver() {
16335        if (mAttachInfo != null) {
16336            return mAttachInfo.mTreeObserver;
16337        }
16338        if (mFloatingTreeObserver == null) {
16339            mFloatingTreeObserver = new ViewTreeObserver();
16340        }
16341        return mFloatingTreeObserver;
16342    }
16343
16344    /**
16345     * <p>Finds the topmost view in the current view hierarchy.</p>
16346     *
16347     * @return the topmost view containing this view
16348     */
16349    public View getRootView() {
16350        if (mAttachInfo != null) {
16351            final View v = mAttachInfo.mRootView;
16352            if (v != null) {
16353                return v;
16354            }
16355        }
16356
16357        View parent = this;
16358
16359        while (parent.mParent != null && parent.mParent instanceof View) {
16360            parent = (View) parent.mParent;
16361        }
16362
16363        return parent;
16364    }
16365
16366    /**
16367     * Transforms a motion event from view-local coordinates to on-screen
16368     * coordinates.
16369     *
16370     * @param ev the view-local motion event
16371     * @return false if the transformation could not be applied
16372     * @hide
16373     */
16374    public boolean toGlobalMotionEvent(MotionEvent ev) {
16375        final AttachInfo info = mAttachInfo;
16376        if (info == null) {
16377            return false;
16378        }
16379
16380        final Matrix m = info.mTmpMatrix;
16381        m.set(Matrix.IDENTITY_MATRIX);
16382        transformMatrixToGlobal(m);
16383        ev.transform(m);
16384        return true;
16385    }
16386
16387    /**
16388     * Transforms a motion event from on-screen coordinates to view-local
16389     * coordinates.
16390     *
16391     * @param ev the on-screen motion event
16392     * @return false if the transformation could not be applied
16393     * @hide
16394     */
16395    public boolean toLocalMotionEvent(MotionEvent ev) {
16396        final AttachInfo info = mAttachInfo;
16397        if (info == null) {
16398            return false;
16399        }
16400
16401        final Matrix m = info.mTmpMatrix;
16402        m.set(Matrix.IDENTITY_MATRIX);
16403        transformMatrixToLocal(m);
16404        ev.transform(m);
16405        return true;
16406    }
16407
16408    /**
16409     * Modifies the input matrix such that it maps view-local coordinates to
16410     * on-screen coordinates.
16411     *
16412     * @param m input matrix to modify
16413     * @hide
16414     */
16415    public void transformMatrixToGlobal(Matrix m) {
16416        final ViewParent parent = mParent;
16417        if (parent instanceof View) {
16418            final View vp = (View) parent;
16419            vp.transformMatrixToGlobal(m);
16420            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16421        } else if (parent instanceof ViewRootImpl) {
16422            final ViewRootImpl vr = (ViewRootImpl) parent;
16423            vr.transformMatrixToGlobal(m);
16424            m.preTranslate(0, -vr.mCurScrollY);
16425        }
16426
16427        m.preTranslate(mLeft, mTop);
16428
16429        if (!hasIdentityMatrix()) {
16430            m.preConcat(getMatrix());
16431        }
16432    }
16433
16434    /**
16435     * Modifies the input matrix such that it maps on-screen coordinates to
16436     * view-local coordinates.
16437     *
16438     * @param m input matrix to modify
16439     * @hide
16440     */
16441    public void transformMatrixToLocal(Matrix m) {
16442        final ViewParent parent = mParent;
16443        if (parent instanceof View) {
16444            final View vp = (View) parent;
16445            vp.transformMatrixToLocal(m);
16446            m.postTranslate(vp.mScrollX, vp.mScrollY);
16447        } else if (parent instanceof ViewRootImpl) {
16448            final ViewRootImpl vr = (ViewRootImpl) parent;
16449            vr.transformMatrixToLocal(m);
16450            m.postTranslate(0, vr.mCurScrollY);
16451        }
16452
16453        m.postTranslate(-mLeft, -mTop);
16454
16455        if (!hasIdentityMatrix()) {
16456            m.postConcat(getInverseMatrix());
16457        }
16458    }
16459
16460    /**
16461     * @hide
16462     */
16463    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16464            @ViewDebug.IntToString(from = 0, to = "x"),
16465            @ViewDebug.IntToString(from = 1, to = "y")
16466    })
16467    public int[] getLocationOnScreen() {
16468        int[] location = new int[2];
16469        getLocationOnScreen(location);
16470        return location;
16471    }
16472
16473    /**
16474     * <p>Computes the coordinates of this view on the screen. The argument
16475     * must be an array of two integers. After the method returns, the array
16476     * contains the x and y location in that order.</p>
16477     *
16478     * @param location an array of two integers in which to hold the coordinates
16479     */
16480    public void getLocationOnScreen(int[] location) {
16481        getLocationInWindow(location);
16482
16483        final AttachInfo info = mAttachInfo;
16484        if (info != null) {
16485            location[0] += info.mWindowLeft;
16486            location[1] += info.mWindowTop;
16487        }
16488    }
16489
16490    /**
16491     * <p>Computes the coordinates of this view in its window. The argument
16492     * must be an array of two integers. After the method returns, the array
16493     * contains the x and y location in that order.</p>
16494     *
16495     * @param location an array of two integers in which to hold the coordinates
16496     */
16497    public void getLocationInWindow(int[] location) {
16498        if (location == null || location.length < 2) {
16499            throw new IllegalArgumentException("location must be an array of two integers");
16500        }
16501
16502        if (mAttachInfo == null) {
16503            // When the view is not attached to a window, this method does not make sense
16504            location[0] = location[1] = 0;
16505            return;
16506        }
16507
16508        float[] position = mAttachInfo.mTmpTransformLocation;
16509        position[0] = position[1] = 0.0f;
16510
16511        if (!hasIdentityMatrix()) {
16512            getMatrix().mapPoints(position);
16513        }
16514
16515        position[0] += mLeft;
16516        position[1] += mTop;
16517
16518        ViewParent viewParent = mParent;
16519        while (viewParent instanceof View) {
16520            final View view = (View) viewParent;
16521
16522            position[0] -= view.mScrollX;
16523            position[1] -= view.mScrollY;
16524
16525            if (!view.hasIdentityMatrix()) {
16526                view.getMatrix().mapPoints(position);
16527            }
16528
16529            position[0] += view.mLeft;
16530            position[1] += view.mTop;
16531
16532            viewParent = view.mParent;
16533         }
16534
16535        if (viewParent instanceof ViewRootImpl) {
16536            // *cough*
16537            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16538            position[1] -= vr.mCurScrollY;
16539        }
16540
16541        location[0] = (int) (position[0] + 0.5f);
16542        location[1] = (int) (position[1] + 0.5f);
16543    }
16544
16545    /**
16546     * {@hide}
16547     * @param id the id of the view to be found
16548     * @return the view of the specified id, null if cannot be found
16549     */
16550    protected View findViewTraversal(int id) {
16551        if (id == mID) {
16552            return this;
16553        }
16554        return null;
16555    }
16556
16557    /**
16558     * {@hide}
16559     * @param tag the tag of the view to be found
16560     * @return the view of specified tag, null if cannot be found
16561     */
16562    protected View findViewWithTagTraversal(Object tag) {
16563        if (tag != null && tag.equals(mTag)) {
16564            return this;
16565        }
16566        return null;
16567    }
16568
16569    /**
16570     * {@hide}
16571     * @param predicate The predicate to evaluate.
16572     * @param childToSkip If not null, ignores this child during the recursive traversal.
16573     * @return The first view that matches the predicate or null.
16574     */
16575    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16576        if (predicate.apply(this)) {
16577            return this;
16578        }
16579        return null;
16580    }
16581
16582    /**
16583     * Look for a child view with the given id.  If this view has the given
16584     * id, return this view.
16585     *
16586     * @param id The id to search for.
16587     * @return The view that has the given id in the hierarchy or null
16588     */
16589    public final View findViewById(int id) {
16590        if (id < 0) {
16591            return null;
16592        }
16593        return findViewTraversal(id);
16594    }
16595
16596    /**
16597     * Finds a view by its unuque and stable accessibility id.
16598     *
16599     * @param accessibilityId The searched accessibility id.
16600     * @return The found view.
16601     */
16602    final View findViewByAccessibilityId(int accessibilityId) {
16603        if (accessibilityId < 0) {
16604            return null;
16605        }
16606        return findViewByAccessibilityIdTraversal(accessibilityId);
16607    }
16608
16609    /**
16610     * Performs the traversal to find a view by its unuque and stable accessibility id.
16611     *
16612     * <strong>Note:</strong>This method does not stop at the root namespace
16613     * boundary since the user can touch the screen at an arbitrary location
16614     * potentially crossing the root namespace bounday which will send an
16615     * accessibility event to accessibility services and they should be able
16616     * to obtain the event source. Also accessibility ids are guaranteed to be
16617     * unique in the window.
16618     *
16619     * @param accessibilityId The accessibility id.
16620     * @return The found view.
16621     *
16622     * @hide
16623     */
16624    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16625        if (getAccessibilityViewId() == accessibilityId) {
16626            return this;
16627        }
16628        return null;
16629    }
16630
16631    /**
16632     * Look for a child view with the given tag.  If this view has the given
16633     * tag, return this view.
16634     *
16635     * @param tag The tag to search for, using "tag.equals(getTag())".
16636     * @return The View that has the given tag in the hierarchy or null
16637     */
16638    public final View findViewWithTag(Object tag) {
16639        if (tag == null) {
16640            return null;
16641        }
16642        return findViewWithTagTraversal(tag);
16643    }
16644
16645    /**
16646     * {@hide}
16647     * Look for a child view that matches the specified predicate.
16648     * If this view matches the predicate, return this view.
16649     *
16650     * @param predicate The predicate to evaluate.
16651     * @return The first view that matches the predicate or null.
16652     */
16653    public final View findViewByPredicate(Predicate<View> predicate) {
16654        return findViewByPredicateTraversal(predicate, null);
16655    }
16656
16657    /**
16658     * {@hide}
16659     * Look for a child view that matches the specified predicate,
16660     * starting with the specified view and its descendents and then
16661     * recusively searching the ancestors and siblings of that view
16662     * until this view is reached.
16663     *
16664     * This method is useful in cases where the predicate does not match
16665     * a single unique view (perhaps multiple views use the same id)
16666     * and we are trying to find the view that is "closest" in scope to the
16667     * starting view.
16668     *
16669     * @param start The view to start from.
16670     * @param predicate The predicate to evaluate.
16671     * @return The first view that matches the predicate or null.
16672     */
16673    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16674        View childToSkip = null;
16675        for (;;) {
16676            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16677            if (view != null || start == this) {
16678                return view;
16679            }
16680
16681            ViewParent parent = start.getParent();
16682            if (parent == null || !(parent instanceof View)) {
16683                return null;
16684            }
16685
16686            childToSkip = start;
16687            start = (View) parent;
16688        }
16689    }
16690
16691    /**
16692     * Sets the identifier for this view. The identifier does not have to be
16693     * unique in this view's hierarchy. The identifier should be a positive
16694     * number.
16695     *
16696     * @see #NO_ID
16697     * @see #getId()
16698     * @see #findViewById(int)
16699     *
16700     * @param id a number used to identify the view
16701     *
16702     * @attr ref android.R.styleable#View_id
16703     */
16704    public void setId(int id) {
16705        mID = id;
16706        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16707            mID = generateViewId();
16708        }
16709    }
16710
16711    /**
16712     * {@hide}
16713     *
16714     * @param isRoot true if the view belongs to the root namespace, false
16715     *        otherwise
16716     */
16717    public void setIsRootNamespace(boolean isRoot) {
16718        if (isRoot) {
16719            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16720        } else {
16721            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16722        }
16723    }
16724
16725    /**
16726     * {@hide}
16727     *
16728     * @return true if the view belongs to the root namespace, false otherwise
16729     */
16730    public boolean isRootNamespace() {
16731        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16732    }
16733
16734    /**
16735     * Returns this view's identifier.
16736     *
16737     * @return a positive integer used to identify the view or {@link #NO_ID}
16738     *         if the view has no ID
16739     *
16740     * @see #setId(int)
16741     * @see #findViewById(int)
16742     * @attr ref android.R.styleable#View_id
16743     */
16744    @ViewDebug.CapturedViewProperty
16745    public int getId() {
16746        return mID;
16747    }
16748
16749    /**
16750     * Returns this view's tag.
16751     *
16752     * @return the Object stored in this view as a tag, or {@code null} if not
16753     *         set
16754     *
16755     * @see #setTag(Object)
16756     * @see #getTag(int)
16757     */
16758    @ViewDebug.ExportedProperty
16759    public Object getTag() {
16760        return mTag;
16761    }
16762
16763    /**
16764     * Sets the tag associated with this view. A tag can be used to mark
16765     * a view in its hierarchy and does not have to be unique within the
16766     * hierarchy. Tags can also be used to store data within a view without
16767     * resorting to another data structure.
16768     *
16769     * @param tag an Object to tag the view with
16770     *
16771     * @see #getTag()
16772     * @see #setTag(int, Object)
16773     */
16774    public void setTag(final Object tag) {
16775        mTag = tag;
16776    }
16777
16778    /**
16779     * Returns the tag associated with this view and the specified key.
16780     *
16781     * @param key The key identifying the tag
16782     *
16783     * @return the Object stored in this view as a tag, or {@code null} if not
16784     *         set
16785     *
16786     * @see #setTag(int, Object)
16787     * @see #getTag()
16788     */
16789    public Object getTag(int key) {
16790        if (mKeyedTags != null) return mKeyedTags.get(key);
16791        return null;
16792    }
16793
16794    /**
16795     * Sets a tag associated with this view and a key. A tag can be used
16796     * to mark a view in its hierarchy and does not have to be unique within
16797     * the hierarchy. Tags can also be used to store data within a view
16798     * without resorting to another data structure.
16799     *
16800     * The specified key should be an id declared in the resources of the
16801     * application to ensure it is unique (see the <a
16802     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16803     * Keys identified as belonging to
16804     * the Android framework or not associated with any package will cause
16805     * an {@link IllegalArgumentException} to be thrown.
16806     *
16807     * @param key The key identifying the tag
16808     * @param tag An Object to tag the view with
16809     *
16810     * @throws IllegalArgumentException If they specified key is not valid
16811     *
16812     * @see #setTag(Object)
16813     * @see #getTag(int)
16814     */
16815    public void setTag(int key, final Object tag) {
16816        // If the package id is 0x00 or 0x01, it's either an undefined package
16817        // or a framework id
16818        if ((key >>> 24) < 2) {
16819            throw new IllegalArgumentException("The key must be an application-specific "
16820                    + "resource id.");
16821        }
16822
16823        setKeyedTag(key, tag);
16824    }
16825
16826    /**
16827     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16828     * framework id.
16829     *
16830     * @hide
16831     */
16832    public void setTagInternal(int key, Object tag) {
16833        if ((key >>> 24) != 0x1) {
16834            throw new IllegalArgumentException("The key must be a framework-specific "
16835                    + "resource id.");
16836        }
16837
16838        setKeyedTag(key, tag);
16839    }
16840
16841    private void setKeyedTag(int key, Object tag) {
16842        if (mKeyedTags == null) {
16843            mKeyedTags = new SparseArray<Object>(2);
16844        }
16845
16846        mKeyedTags.put(key, tag);
16847    }
16848
16849    /**
16850     * Prints information about this view in the log output, with the tag
16851     * {@link #VIEW_LOG_TAG}.
16852     *
16853     * @hide
16854     */
16855    public void debug() {
16856        debug(0);
16857    }
16858
16859    /**
16860     * Prints information about this view in the log output, with the tag
16861     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16862     * indentation defined by the <code>depth</code>.
16863     *
16864     * @param depth the indentation level
16865     *
16866     * @hide
16867     */
16868    protected void debug(int depth) {
16869        String output = debugIndent(depth - 1);
16870
16871        output += "+ " + this;
16872        int id = getId();
16873        if (id != -1) {
16874            output += " (id=" + id + ")";
16875        }
16876        Object tag = getTag();
16877        if (tag != null) {
16878            output += " (tag=" + tag + ")";
16879        }
16880        Log.d(VIEW_LOG_TAG, output);
16881
16882        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16883            output = debugIndent(depth) + " FOCUSED";
16884            Log.d(VIEW_LOG_TAG, output);
16885        }
16886
16887        output = debugIndent(depth);
16888        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16889                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16890                + "} ";
16891        Log.d(VIEW_LOG_TAG, output);
16892
16893        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16894                || mPaddingBottom != 0) {
16895            output = debugIndent(depth);
16896            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16897                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16898            Log.d(VIEW_LOG_TAG, output);
16899        }
16900
16901        output = debugIndent(depth);
16902        output += "mMeasureWidth=" + mMeasuredWidth +
16903                " mMeasureHeight=" + mMeasuredHeight;
16904        Log.d(VIEW_LOG_TAG, output);
16905
16906        output = debugIndent(depth);
16907        if (mLayoutParams == null) {
16908            output += "BAD! no layout params";
16909        } else {
16910            output = mLayoutParams.debug(output);
16911        }
16912        Log.d(VIEW_LOG_TAG, output);
16913
16914        output = debugIndent(depth);
16915        output += "flags={";
16916        output += View.printFlags(mViewFlags);
16917        output += "}";
16918        Log.d(VIEW_LOG_TAG, output);
16919
16920        output = debugIndent(depth);
16921        output += "privateFlags={";
16922        output += View.printPrivateFlags(mPrivateFlags);
16923        output += "}";
16924        Log.d(VIEW_LOG_TAG, output);
16925    }
16926
16927    /**
16928     * Creates a string of whitespaces used for indentation.
16929     *
16930     * @param depth the indentation level
16931     * @return a String containing (depth * 2 + 3) * 2 white spaces
16932     *
16933     * @hide
16934     */
16935    protected static String debugIndent(int depth) {
16936        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16937        for (int i = 0; i < (depth * 2) + 3; i++) {
16938            spaces.append(' ').append(' ');
16939        }
16940        return spaces.toString();
16941    }
16942
16943    /**
16944     * <p>Return the offset of the widget's text baseline from the widget's top
16945     * boundary. If this widget does not support baseline alignment, this
16946     * method returns -1. </p>
16947     *
16948     * @return the offset of the baseline within the widget's bounds or -1
16949     *         if baseline alignment is not supported
16950     */
16951    @ViewDebug.ExportedProperty(category = "layout")
16952    public int getBaseline() {
16953        return -1;
16954    }
16955
16956    /**
16957     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16958     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16959     * a layout pass.
16960     *
16961     * @return whether the view hierarchy is currently undergoing a layout pass
16962     */
16963    public boolean isInLayout() {
16964        ViewRootImpl viewRoot = getViewRootImpl();
16965        return (viewRoot != null && viewRoot.isInLayout());
16966    }
16967
16968    /**
16969     * Call this when something has changed which has invalidated the
16970     * layout of this view. This will schedule a layout pass of the view
16971     * tree. This should not be called while the view hierarchy is currently in a layout
16972     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16973     * end of the current layout pass (and then layout will run again) or after the current
16974     * frame is drawn and the next layout occurs.
16975     *
16976     * <p>Subclasses which override this method should call the superclass method to
16977     * handle possible request-during-layout errors correctly.</p>
16978     */
16979    public void requestLayout() {
16980        if (mMeasureCache != null) mMeasureCache.clear();
16981
16982        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16983            // Only trigger request-during-layout logic if this is the view requesting it,
16984            // not the views in its parent hierarchy
16985            ViewRootImpl viewRoot = getViewRootImpl();
16986            if (viewRoot != null && viewRoot.isInLayout()) {
16987                if (!viewRoot.requestLayoutDuringLayout(this)) {
16988                    return;
16989                }
16990            }
16991            mAttachInfo.mViewRequestingLayout = this;
16992        }
16993
16994        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16995        mPrivateFlags |= PFLAG_INVALIDATED;
16996
16997        if (mParent != null && !mParent.isLayoutRequested()) {
16998            mParent.requestLayout();
16999        }
17000        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17001            mAttachInfo.mViewRequestingLayout = null;
17002        }
17003    }
17004
17005    /**
17006     * Forces this view to be laid out during the next layout pass.
17007     * This method does not call requestLayout() or forceLayout()
17008     * on the parent.
17009     */
17010    public void forceLayout() {
17011        if (mMeasureCache != null) mMeasureCache.clear();
17012
17013        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17014        mPrivateFlags |= PFLAG_INVALIDATED;
17015    }
17016
17017    /**
17018     * <p>
17019     * This is called to find out how big a view should be. The parent
17020     * supplies constraint information in the width and height parameters.
17021     * </p>
17022     *
17023     * <p>
17024     * The actual measurement work of a view is performed in
17025     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17026     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17027     * </p>
17028     *
17029     *
17030     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17031     *        parent
17032     * @param heightMeasureSpec Vertical space requirements as imposed by the
17033     *        parent
17034     *
17035     * @see #onMeasure(int, int)
17036     */
17037    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17038        boolean optical = isLayoutModeOptical(this);
17039        if (optical != isLayoutModeOptical(mParent)) {
17040            Insets insets = getOpticalInsets();
17041            int oWidth  = insets.left + insets.right;
17042            int oHeight = insets.top  + insets.bottom;
17043            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17044            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17045        }
17046
17047        // Suppress sign extension for the low bytes
17048        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17049        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17050
17051        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17052                widthMeasureSpec != mOldWidthMeasureSpec ||
17053                heightMeasureSpec != mOldHeightMeasureSpec) {
17054
17055            // first clears the measured dimension flag
17056            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17057
17058            resolveRtlPropertiesIfNeeded();
17059
17060            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17061                    mMeasureCache.indexOfKey(key);
17062            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17063                // measure ourselves, this should set the measured dimension flag back
17064                onMeasure(widthMeasureSpec, heightMeasureSpec);
17065                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17066            } else {
17067                long value = mMeasureCache.valueAt(cacheIndex);
17068                // Casting a long to int drops the high 32 bits, no mask needed
17069                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17070                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17071            }
17072
17073            // flag not set, setMeasuredDimension() was not invoked, we raise
17074            // an exception to warn the developer
17075            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17076                throw new IllegalStateException("onMeasure() did not set the"
17077                        + " measured dimension by calling"
17078                        + " setMeasuredDimension()");
17079            }
17080
17081            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17082        }
17083
17084        mOldWidthMeasureSpec = widthMeasureSpec;
17085        mOldHeightMeasureSpec = heightMeasureSpec;
17086
17087        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17088                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17089    }
17090
17091    /**
17092     * <p>
17093     * Measure the view and its content to determine the measured width and the
17094     * measured height. This method is invoked by {@link #measure(int, int)} and
17095     * should be overriden by subclasses to provide accurate and efficient
17096     * measurement of their contents.
17097     * </p>
17098     *
17099     * <p>
17100     * <strong>CONTRACT:</strong> When overriding this method, you
17101     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17102     * measured width and height of this view. Failure to do so will trigger an
17103     * <code>IllegalStateException</code>, thrown by
17104     * {@link #measure(int, int)}. Calling the superclass'
17105     * {@link #onMeasure(int, int)} is a valid use.
17106     * </p>
17107     *
17108     * <p>
17109     * The base class implementation of measure defaults to the background size,
17110     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17111     * override {@link #onMeasure(int, int)} to provide better measurements of
17112     * their content.
17113     * </p>
17114     *
17115     * <p>
17116     * If this method is overridden, it is the subclass's responsibility to make
17117     * sure the measured height and width are at least the view's minimum height
17118     * and width ({@link #getSuggestedMinimumHeight()} and
17119     * {@link #getSuggestedMinimumWidth()}).
17120     * </p>
17121     *
17122     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17123     *                         The requirements are encoded with
17124     *                         {@link android.view.View.MeasureSpec}.
17125     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17126     *                         The requirements are encoded with
17127     *                         {@link android.view.View.MeasureSpec}.
17128     *
17129     * @see #getMeasuredWidth()
17130     * @see #getMeasuredHeight()
17131     * @see #setMeasuredDimension(int, int)
17132     * @see #getSuggestedMinimumHeight()
17133     * @see #getSuggestedMinimumWidth()
17134     * @see android.view.View.MeasureSpec#getMode(int)
17135     * @see android.view.View.MeasureSpec#getSize(int)
17136     */
17137    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17138        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17139                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17140    }
17141
17142    /**
17143     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17144     * measured width and measured height. Failing to do so will trigger an
17145     * exception at measurement time.</p>
17146     *
17147     * @param measuredWidth The measured width of this view.  May be a complex
17148     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17149     * {@link #MEASURED_STATE_TOO_SMALL}.
17150     * @param measuredHeight The measured height of this view.  May be a complex
17151     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17152     * {@link #MEASURED_STATE_TOO_SMALL}.
17153     */
17154    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17155        boolean optical = isLayoutModeOptical(this);
17156        if (optical != isLayoutModeOptical(mParent)) {
17157            Insets insets = getOpticalInsets();
17158            int opticalWidth  = insets.left + insets.right;
17159            int opticalHeight = insets.top  + insets.bottom;
17160
17161            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17162            measuredHeight += optical ? opticalHeight : -opticalHeight;
17163        }
17164        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17165    }
17166
17167    /**
17168     * Sets the measured dimension without extra processing for things like optical bounds.
17169     * Useful for reapplying consistent values that have already been cooked with adjustments
17170     * for optical bounds, etc. such as those from the measurement cache.
17171     *
17172     * @param measuredWidth The measured width of this view.  May be a complex
17173     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17174     * {@link #MEASURED_STATE_TOO_SMALL}.
17175     * @param measuredHeight The measured height of this view.  May be a complex
17176     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17177     * {@link #MEASURED_STATE_TOO_SMALL}.
17178     */
17179    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17180        mMeasuredWidth = measuredWidth;
17181        mMeasuredHeight = measuredHeight;
17182
17183        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17184    }
17185
17186    /**
17187     * Merge two states as returned by {@link #getMeasuredState()}.
17188     * @param curState The current state as returned from a view or the result
17189     * of combining multiple views.
17190     * @param newState The new view state to combine.
17191     * @return Returns a new integer reflecting the combination of the two
17192     * states.
17193     */
17194    public static int combineMeasuredStates(int curState, int newState) {
17195        return curState | newState;
17196    }
17197
17198    /**
17199     * Version of {@link #resolveSizeAndState(int, int, int)}
17200     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17201     */
17202    public static int resolveSize(int size, int measureSpec) {
17203        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17204    }
17205
17206    /**
17207     * Utility to reconcile a desired size and state, with constraints imposed
17208     * by a MeasureSpec.  Will take the desired size, unless a different size
17209     * is imposed by the constraints.  The returned value is a compound integer,
17210     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17211     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17212     * size is smaller than the size the view wants to be.
17213     *
17214     * @param size How big the view wants to be
17215     * @param measureSpec Constraints imposed by the parent
17216     * @return Size information bit mask as defined by
17217     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17218     */
17219    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17220        int result = size;
17221        int specMode = MeasureSpec.getMode(measureSpec);
17222        int specSize =  MeasureSpec.getSize(measureSpec);
17223        switch (specMode) {
17224        case MeasureSpec.UNSPECIFIED:
17225            result = size;
17226            break;
17227        case MeasureSpec.AT_MOST:
17228            if (specSize < size) {
17229                result = specSize | MEASURED_STATE_TOO_SMALL;
17230            } else {
17231                result = size;
17232            }
17233            break;
17234        case MeasureSpec.EXACTLY:
17235            result = specSize;
17236            break;
17237        }
17238        return result | (childMeasuredState&MEASURED_STATE_MASK);
17239    }
17240
17241    /**
17242     * Utility to return a default size. Uses the supplied size if the
17243     * MeasureSpec imposed no constraints. Will get larger if allowed
17244     * by the MeasureSpec.
17245     *
17246     * @param size Default size for this view
17247     * @param measureSpec Constraints imposed by the parent
17248     * @return The size this view should be.
17249     */
17250    public static int getDefaultSize(int size, int measureSpec) {
17251        int result = size;
17252        int specMode = MeasureSpec.getMode(measureSpec);
17253        int specSize = MeasureSpec.getSize(measureSpec);
17254
17255        switch (specMode) {
17256        case MeasureSpec.UNSPECIFIED:
17257            result = size;
17258            break;
17259        case MeasureSpec.AT_MOST:
17260        case MeasureSpec.EXACTLY:
17261            result = specSize;
17262            break;
17263        }
17264        return result;
17265    }
17266
17267    /**
17268     * Returns the suggested minimum height that the view should use. This
17269     * returns the maximum of the view's minimum height
17270     * and the background's minimum height
17271     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17272     * <p>
17273     * When being used in {@link #onMeasure(int, int)}, the caller should still
17274     * ensure the returned height is within the requirements of the parent.
17275     *
17276     * @return The suggested minimum height of the view.
17277     */
17278    protected int getSuggestedMinimumHeight() {
17279        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17280
17281    }
17282
17283    /**
17284     * Returns the suggested minimum width that the view should use. This
17285     * returns the maximum of the view's minimum width)
17286     * and the background's minimum width
17287     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17288     * <p>
17289     * When being used in {@link #onMeasure(int, int)}, the caller should still
17290     * ensure the returned width is within the requirements of the parent.
17291     *
17292     * @return The suggested minimum width of the view.
17293     */
17294    protected int getSuggestedMinimumWidth() {
17295        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17296    }
17297
17298    /**
17299     * Returns the minimum height of the view.
17300     *
17301     * @return the minimum height the view will try to be.
17302     *
17303     * @see #setMinimumHeight(int)
17304     *
17305     * @attr ref android.R.styleable#View_minHeight
17306     */
17307    public int getMinimumHeight() {
17308        return mMinHeight;
17309    }
17310
17311    /**
17312     * Sets the minimum height of the view. It is not guaranteed the view will
17313     * be able to achieve this minimum height (for example, if its parent layout
17314     * constrains it with less available height).
17315     *
17316     * @param minHeight The minimum height the view will try to be.
17317     *
17318     * @see #getMinimumHeight()
17319     *
17320     * @attr ref android.R.styleable#View_minHeight
17321     */
17322    public void setMinimumHeight(int minHeight) {
17323        mMinHeight = minHeight;
17324        requestLayout();
17325    }
17326
17327    /**
17328     * Returns the minimum width of the view.
17329     *
17330     * @return the minimum width the view will try to be.
17331     *
17332     * @see #setMinimumWidth(int)
17333     *
17334     * @attr ref android.R.styleable#View_minWidth
17335     */
17336    public int getMinimumWidth() {
17337        return mMinWidth;
17338    }
17339
17340    /**
17341     * Sets the minimum width of the view. It is not guaranteed the view will
17342     * be able to achieve this minimum width (for example, if its parent layout
17343     * constrains it with less available width).
17344     *
17345     * @param minWidth The minimum width the view will try to be.
17346     *
17347     * @see #getMinimumWidth()
17348     *
17349     * @attr ref android.R.styleable#View_minWidth
17350     */
17351    public void setMinimumWidth(int minWidth) {
17352        mMinWidth = minWidth;
17353        requestLayout();
17354
17355    }
17356
17357    /**
17358     * Get the animation currently associated with this view.
17359     *
17360     * @return The animation that is currently playing or
17361     *         scheduled to play for this view.
17362     */
17363    public Animation getAnimation() {
17364        return mCurrentAnimation;
17365    }
17366
17367    /**
17368     * Start the specified animation now.
17369     *
17370     * @param animation the animation to start now
17371     */
17372    public void startAnimation(Animation animation) {
17373        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17374        setAnimation(animation);
17375        invalidateParentCaches();
17376        invalidate(true);
17377    }
17378
17379    /**
17380     * Cancels any animations for this view.
17381     */
17382    public void clearAnimation() {
17383        if (mCurrentAnimation != null) {
17384            mCurrentAnimation.detach();
17385        }
17386        mCurrentAnimation = null;
17387        invalidateParentIfNeeded();
17388    }
17389
17390    /**
17391     * Sets the next animation to play for this view.
17392     * If you want the animation to play immediately, use
17393     * {@link #startAnimation(android.view.animation.Animation)} instead.
17394     * This method provides allows fine-grained
17395     * control over the start time and invalidation, but you
17396     * must make sure that 1) the animation has a start time set, and
17397     * 2) the view's parent (which controls animations on its children)
17398     * will be invalidated when the animation is supposed to
17399     * start.
17400     *
17401     * @param animation The next animation, or null.
17402     */
17403    public void setAnimation(Animation animation) {
17404        mCurrentAnimation = animation;
17405
17406        if (animation != null) {
17407            // If the screen is off assume the animation start time is now instead of
17408            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17409            // would cause the animation to start when the screen turns back on
17410            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17411                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17412                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17413            }
17414            animation.reset();
17415        }
17416    }
17417
17418    /**
17419     * Invoked by a parent ViewGroup to notify the start of the animation
17420     * currently associated with this view. If you override this method,
17421     * always call super.onAnimationStart();
17422     *
17423     * @see #setAnimation(android.view.animation.Animation)
17424     * @see #getAnimation()
17425     */
17426    protected void onAnimationStart() {
17427        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17428    }
17429
17430    /**
17431     * Invoked by a parent ViewGroup to notify the end of the animation
17432     * currently associated with this view. If you override this method,
17433     * always call super.onAnimationEnd();
17434     *
17435     * @see #setAnimation(android.view.animation.Animation)
17436     * @see #getAnimation()
17437     */
17438    protected void onAnimationEnd() {
17439        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17440    }
17441
17442    /**
17443     * Invoked if there is a Transform that involves alpha. Subclass that can
17444     * draw themselves with the specified alpha should return true, and then
17445     * respect that alpha when their onDraw() is called. If this returns false
17446     * then the view may be redirected to draw into an offscreen buffer to
17447     * fulfill the request, which will look fine, but may be slower than if the
17448     * subclass handles it internally. The default implementation returns false.
17449     *
17450     * @param alpha The alpha (0..255) to apply to the view's drawing
17451     * @return true if the view can draw with the specified alpha.
17452     */
17453    protected boolean onSetAlpha(int alpha) {
17454        return false;
17455    }
17456
17457    /**
17458     * This is used by the RootView to perform an optimization when
17459     * the view hierarchy contains one or several SurfaceView.
17460     * SurfaceView is always considered transparent, but its children are not,
17461     * therefore all View objects remove themselves from the global transparent
17462     * region (passed as a parameter to this function).
17463     *
17464     * @param region The transparent region for this ViewAncestor (window).
17465     *
17466     * @return Returns true if the effective visibility of the view at this
17467     * point is opaque, regardless of the transparent region; returns false
17468     * if it is possible for underlying windows to be seen behind the view.
17469     *
17470     * {@hide}
17471     */
17472    public boolean gatherTransparentRegion(Region region) {
17473        final AttachInfo attachInfo = mAttachInfo;
17474        if (region != null && attachInfo != null) {
17475            final int pflags = mPrivateFlags;
17476            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17477                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17478                // remove it from the transparent region.
17479                final int[] location = attachInfo.mTransparentLocation;
17480                getLocationInWindow(location);
17481                region.op(location[0], location[1], location[0] + mRight - mLeft,
17482                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17483            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17484                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17485                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17486                // exists, so we remove the background drawable's non-transparent
17487                // parts from this transparent region.
17488                applyDrawableToTransparentRegion(mBackground, region);
17489            }
17490        }
17491        return true;
17492    }
17493
17494    /**
17495     * Play a sound effect for this view.
17496     *
17497     * <p>The framework will play sound effects for some built in actions, such as
17498     * clicking, but you may wish to play these effects in your widget,
17499     * for instance, for internal navigation.
17500     *
17501     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17502     * {@link #isSoundEffectsEnabled()} is true.
17503     *
17504     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17505     */
17506    public void playSoundEffect(int soundConstant) {
17507        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17508            return;
17509        }
17510        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17511    }
17512
17513    /**
17514     * BZZZTT!!1!
17515     *
17516     * <p>Provide haptic feedback to the user for this view.
17517     *
17518     * <p>The framework will provide haptic feedback for some built in actions,
17519     * such as long presses, but you may wish to provide feedback for your
17520     * own widget.
17521     *
17522     * <p>The feedback will only be performed if
17523     * {@link #isHapticFeedbackEnabled()} is true.
17524     *
17525     * @param feedbackConstant One of the constants defined in
17526     * {@link HapticFeedbackConstants}
17527     */
17528    public boolean performHapticFeedback(int feedbackConstant) {
17529        return performHapticFeedback(feedbackConstant, 0);
17530    }
17531
17532    /**
17533     * BZZZTT!!1!
17534     *
17535     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17536     *
17537     * @param feedbackConstant One of the constants defined in
17538     * {@link HapticFeedbackConstants}
17539     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17540     */
17541    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17542        if (mAttachInfo == null) {
17543            return false;
17544        }
17545        //noinspection SimplifiableIfStatement
17546        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17547                && !isHapticFeedbackEnabled()) {
17548            return false;
17549        }
17550        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17551                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17552    }
17553
17554    /**
17555     * Request that the visibility of the status bar or other screen/window
17556     * decorations be changed.
17557     *
17558     * <p>This method is used to put the over device UI into temporary modes
17559     * where the user's attention is focused more on the application content,
17560     * by dimming or hiding surrounding system affordances.  This is typically
17561     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17562     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17563     * to be placed behind the action bar (and with these flags other system
17564     * affordances) so that smooth transitions between hiding and showing them
17565     * can be done.
17566     *
17567     * <p>Two representative examples of the use of system UI visibility is
17568     * implementing a content browsing application (like a magazine reader)
17569     * and a video playing application.
17570     *
17571     * <p>The first code shows a typical implementation of a View in a content
17572     * browsing application.  In this implementation, the application goes
17573     * into a content-oriented mode by hiding the status bar and action bar,
17574     * and putting the navigation elements into lights out mode.  The user can
17575     * then interact with content while in this mode.  Such an application should
17576     * provide an easy way for the user to toggle out of the mode (such as to
17577     * check information in the status bar or access notifications).  In the
17578     * implementation here, this is done simply by tapping on the content.
17579     *
17580     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17581     *      content}
17582     *
17583     * <p>This second code sample shows a typical implementation of a View
17584     * in a video playing application.  In this situation, while the video is
17585     * playing the application would like to go into a complete full-screen mode,
17586     * to use as much of the display as possible for the video.  When in this state
17587     * the user can not interact with the application; the system intercepts
17588     * touching on the screen to pop the UI out of full screen mode.  See
17589     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17590     *
17591     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17592     *      content}
17593     *
17594     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17595     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17596     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17597     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17598     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17599     */
17600    public void setSystemUiVisibility(int visibility) {
17601        if (visibility != mSystemUiVisibility) {
17602            mSystemUiVisibility = visibility;
17603            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17604                mParent.recomputeViewAttributes(this);
17605            }
17606        }
17607    }
17608
17609    /**
17610     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17611     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17612     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17613     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17614     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17615     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17616     */
17617    public int getSystemUiVisibility() {
17618        return mSystemUiVisibility;
17619    }
17620
17621    /**
17622     * Returns the current system UI visibility that is currently set for
17623     * the entire window.  This is the combination of the
17624     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17625     * views in the window.
17626     */
17627    public int getWindowSystemUiVisibility() {
17628        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17629    }
17630
17631    /**
17632     * Override to find out when the window's requested system UI visibility
17633     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17634     * This is different from the callbacks received through
17635     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17636     * in that this is only telling you about the local request of the window,
17637     * not the actual values applied by the system.
17638     */
17639    public void onWindowSystemUiVisibilityChanged(int visible) {
17640    }
17641
17642    /**
17643     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17644     * the view hierarchy.
17645     */
17646    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17647        onWindowSystemUiVisibilityChanged(visible);
17648    }
17649
17650    /**
17651     * Set a listener to receive callbacks when the visibility of the system bar changes.
17652     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17653     */
17654    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17655        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17656        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17657            mParent.recomputeViewAttributes(this);
17658        }
17659    }
17660
17661    /**
17662     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17663     * the view hierarchy.
17664     */
17665    public void dispatchSystemUiVisibilityChanged(int visibility) {
17666        ListenerInfo li = mListenerInfo;
17667        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17668            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17669                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17670        }
17671    }
17672
17673    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17674        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17675        if (val != mSystemUiVisibility) {
17676            setSystemUiVisibility(val);
17677            return true;
17678        }
17679        return false;
17680    }
17681
17682    /** @hide */
17683    public void setDisabledSystemUiVisibility(int flags) {
17684        if (mAttachInfo != null) {
17685            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17686                mAttachInfo.mDisabledSystemUiVisibility = flags;
17687                if (mParent != null) {
17688                    mParent.recomputeViewAttributes(this);
17689                }
17690            }
17691        }
17692    }
17693
17694    /**
17695     * Creates an image that the system displays during the drag and drop
17696     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17697     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17698     * appearance as the given View. The default also positions the center of the drag shadow
17699     * directly under the touch point. If no View is provided (the constructor with no parameters
17700     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17701     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17702     * default is an invisible drag shadow.
17703     * <p>
17704     * You are not required to use the View you provide to the constructor as the basis of the
17705     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17706     * anything you want as the drag shadow.
17707     * </p>
17708     * <p>
17709     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17710     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17711     *  size and position of the drag shadow. It uses this data to construct a
17712     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17713     *  so that your application can draw the shadow image in the Canvas.
17714     * </p>
17715     *
17716     * <div class="special reference">
17717     * <h3>Developer Guides</h3>
17718     * <p>For a guide to implementing drag and drop features, read the
17719     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17720     * </div>
17721     */
17722    public static class DragShadowBuilder {
17723        private final WeakReference<View> mView;
17724
17725        /**
17726         * Constructs a shadow image builder based on a View. By default, the resulting drag
17727         * shadow will have the same appearance and dimensions as the View, with the touch point
17728         * over the center of the View.
17729         * @param view A View. Any View in scope can be used.
17730         */
17731        public DragShadowBuilder(View view) {
17732            mView = new WeakReference<View>(view);
17733        }
17734
17735        /**
17736         * Construct a shadow builder object with no associated View.  This
17737         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17738         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17739         * to supply the drag shadow's dimensions and appearance without
17740         * reference to any View object. If they are not overridden, then the result is an
17741         * invisible drag shadow.
17742         */
17743        public DragShadowBuilder() {
17744            mView = new WeakReference<View>(null);
17745        }
17746
17747        /**
17748         * Returns the View object that had been passed to the
17749         * {@link #View.DragShadowBuilder(View)}
17750         * constructor.  If that View parameter was {@code null} or if the
17751         * {@link #View.DragShadowBuilder()}
17752         * constructor was used to instantiate the builder object, this method will return
17753         * null.
17754         *
17755         * @return The View object associate with this builder object.
17756         */
17757        @SuppressWarnings({"JavadocReference"})
17758        final public View getView() {
17759            return mView.get();
17760        }
17761
17762        /**
17763         * Provides the metrics for the shadow image. These include the dimensions of
17764         * the shadow image, and the point within that shadow that should
17765         * be centered under the touch location while dragging.
17766         * <p>
17767         * The default implementation sets the dimensions of the shadow to be the
17768         * same as the dimensions of the View itself and centers the shadow under
17769         * the touch point.
17770         * </p>
17771         *
17772         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17773         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17774         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17775         * image.
17776         *
17777         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17778         * shadow image that should be underneath the touch point during the drag and drop
17779         * operation. Your application must set {@link android.graphics.Point#x} to the
17780         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17781         */
17782        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17783            final View view = mView.get();
17784            if (view != null) {
17785                shadowSize.set(view.getWidth(), view.getHeight());
17786                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17787            } else {
17788                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17789            }
17790        }
17791
17792        /**
17793         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17794         * based on the dimensions it received from the
17795         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17796         *
17797         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17798         */
17799        public void onDrawShadow(Canvas canvas) {
17800            final View view = mView.get();
17801            if (view != null) {
17802                view.draw(canvas);
17803            } else {
17804                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17805            }
17806        }
17807    }
17808
17809    /**
17810     * Starts a drag and drop operation. When your application calls this method, it passes a
17811     * {@link android.view.View.DragShadowBuilder} object to the system. The
17812     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17813     * to get metrics for the drag shadow, and then calls the object's
17814     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17815     * <p>
17816     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17817     *  drag events to all the View objects in your application that are currently visible. It does
17818     *  this either by calling the View object's drag listener (an implementation of
17819     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17820     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17821     *  Both are passed a {@link android.view.DragEvent} object that has a
17822     *  {@link android.view.DragEvent#getAction()} value of
17823     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17824     * </p>
17825     * <p>
17826     * Your application can invoke startDrag() on any attached View object. The View object does not
17827     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17828     * be related to the View the user selected for dragging.
17829     * </p>
17830     * @param data A {@link android.content.ClipData} object pointing to the data to be
17831     * transferred by the drag and drop operation.
17832     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17833     * drag shadow.
17834     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17835     * drop operation. This Object is put into every DragEvent object sent by the system during the
17836     * current drag.
17837     * <p>
17838     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17839     * to the target Views. For example, it can contain flags that differentiate between a
17840     * a copy operation and a move operation.
17841     * </p>
17842     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17843     * so the parameter should be set to 0.
17844     * @return {@code true} if the method completes successfully, or
17845     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17846     * do a drag, and so no drag operation is in progress.
17847     */
17848    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17849            Object myLocalState, int flags) {
17850        if (ViewDebug.DEBUG_DRAG) {
17851            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17852        }
17853        boolean okay = false;
17854
17855        Point shadowSize = new Point();
17856        Point shadowTouchPoint = new Point();
17857        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17858
17859        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17860                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17861            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17862        }
17863
17864        if (ViewDebug.DEBUG_DRAG) {
17865            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17866                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17867        }
17868        Surface surface = new Surface();
17869        try {
17870            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17871                    flags, shadowSize.x, shadowSize.y, surface);
17872            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17873                    + " surface=" + surface);
17874            if (token != null) {
17875                Canvas canvas = surface.lockCanvas(null);
17876                try {
17877                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17878                    shadowBuilder.onDrawShadow(canvas);
17879                } finally {
17880                    surface.unlockCanvasAndPost(canvas);
17881                }
17882
17883                final ViewRootImpl root = getViewRootImpl();
17884
17885                // Cache the local state object for delivery with DragEvents
17886                root.setLocalDragState(myLocalState);
17887
17888                // repurpose 'shadowSize' for the last touch point
17889                root.getLastTouchPoint(shadowSize);
17890
17891                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17892                        shadowSize.x, shadowSize.y,
17893                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17894                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17895
17896                // Off and running!  Release our local surface instance; the drag
17897                // shadow surface is now managed by the system process.
17898                surface.release();
17899            }
17900        } catch (Exception e) {
17901            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17902            surface.destroy();
17903        }
17904
17905        return okay;
17906    }
17907
17908    /**
17909     * Handles drag events sent by the system following a call to
17910     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17911     *<p>
17912     * When the system calls this method, it passes a
17913     * {@link android.view.DragEvent} object. A call to
17914     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17915     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17916     * operation.
17917     * @param event The {@link android.view.DragEvent} sent by the system.
17918     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17919     * in DragEvent, indicating the type of drag event represented by this object.
17920     * @return {@code true} if the method was successful, otherwise {@code false}.
17921     * <p>
17922     *  The method should return {@code true} in response to an action type of
17923     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17924     *  operation.
17925     * </p>
17926     * <p>
17927     *  The method should also return {@code true} in response to an action type of
17928     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17929     *  {@code false} if it didn't.
17930     * </p>
17931     */
17932    public boolean onDragEvent(DragEvent event) {
17933        return false;
17934    }
17935
17936    /**
17937     * Detects if this View is enabled and has a drag event listener.
17938     * If both are true, then it calls the drag event listener with the
17939     * {@link android.view.DragEvent} it received. If the drag event listener returns
17940     * {@code true}, then dispatchDragEvent() returns {@code true}.
17941     * <p>
17942     * For all other cases, the method calls the
17943     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17944     * method and returns its result.
17945     * </p>
17946     * <p>
17947     * This ensures that a drag event is always consumed, even if the View does not have a drag
17948     * event listener. However, if the View has a listener and the listener returns true, then
17949     * onDragEvent() is not called.
17950     * </p>
17951     */
17952    public boolean dispatchDragEvent(DragEvent event) {
17953        ListenerInfo li = mListenerInfo;
17954        //noinspection SimplifiableIfStatement
17955        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17956                && li.mOnDragListener.onDrag(this, event)) {
17957            return true;
17958        }
17959        return onDragEvent(event);
17960    }
17961
17962    boolean canAcceptDrag() {
17963        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17964    }
17965
17966    /**
17967     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17968     * it is ever exposed at all.
17969     * @hide
17970     */
17971    public void onCloseSystemDialogs(String reason) {
17972    }
17973
17974    /**
17975     * Given a Drawable whose bounds have been set to draw into this view,
17976     * update a Region being computed for
17977     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17978     * that any non-transparent parts of the Drawable are removed from the
17979     * given transparent region.
17980     *
17981     * @param dr The Drawable whose transparency is to be applied to the region.
17982     * @param region A Region holding the current transparency information,
17983     * where any parts of the region that are set are considered to be
17984     * transparent.  On return, this region will be modified to have the
17985     * transparency information reduced by the corresponding parts of the
17986     * Drawable that are not transparent.
17987     * {@hide}
17988     */
17989    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17990        if (DBG) {
17991            Log.i("View", "Getting transparent region for: " + this);
17992        }
17993        final Region r = dr.getTransparentRegion();
17994        final Rect db = dr.getBounds();
17995        final AttachInfo attachInfo = mAttachInfo;
17996        if (r != null && attachInfo != null) {
17997            final int w = getRight()-getLeft();
17998            final int h = getBottom()-getTop();
17999            if (db.left > 0) {
18000                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18001                r.op(0, 0, db.left, h, Region.Op.UNION);
18002            }
18003            if (db.right < w) {
18004                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18005                r.op(db.right, 0, w, h, Region.Op.UNION);
18006            }
18007            if (db.top > 0) {
18008                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18009                r.op(0, 0, w, db.top, Region.Op.UNION);
18010            }
18011            if (db.bottom < h) {
18012                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18013                r.op(0, db.bottom, w, h, Region.Op.UNION);
18014            }
18015            final int[] location = attachInfo.mTransparentLocation;
18016            getLocationInWindow(location);
18017            r.translate(location[0], location[1]);
18018            region.op(r, Region.Op.INTERSECT);
18019        } else {
18020            region.op(db, Region.Op.DIFFERENCE);
18021        }
18022    }
18023
18024    private void checkForLongClick(int delayOffset) {
18025        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18026            mHasPerformedLongPress = false;
18027
18028            if (mPendingCheckForLongPress == null) {
18029                mPendingCheckForLongPress = new CheckForLongPress();
18030            }
18031            mPendingCheckForLongPress.rememberWindowAttachCount();
18032            postDelayed(mPendingCheckForLongPress,
18033                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18034        }
18035    }
18036
18037    /**
18038     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18039     * LayoutInflater} class, which provides a full range of options for view inflation.
18040     *
18041     * @param context The Context object for your activity or application.
18042     * @param resource The resource ID to inflate
18043     * @param root A view group that will be the parent.  Used to properly inflate the
18044     * layout_* parameters.
18045     * @see LayoutInflater
18046     */
18047    public static View inflate(Context context, int resource, ViewGroup root) {
18048        LayoutInflater factory = LayoutInflater.from(context);
18049        return factory.inflate(resource, root);
18050    }
18051
18052    /**
18053     * Scroll the view with standard behavior for scrolling beyond the normal
18054     * content boundaries. Views that call this method should override
18055     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18056     * results of an over-scroll operation.
18057     *
18058     * Views can use this method to handle any touch or fling-based scrolling.
18059     *
18060     * @param deltaX Change in X in pixels
18061     * @param deltaY Change in Y in pixels
18062     * @param scrollX Current X scroll value in pixels before applying deltaX
18063     * @param scrollY Current Y scroll value in pixels before applying deltaY
18064     * @param scrollRangeX Maximum content scroll range along the X axis
18065     * @param scrollRangeY Maximum content scroll range along the Y axis
18066     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18067     *          along the X axis.
18068     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18069     *          along the Y axis.
18070     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18071     * @return true if scrolling was clamped to an over-scroll boundary along either
18072     *          axis, false otherwise.
18073     */
18074    @SuppressWarnings({"UnusedParameters"})
18075    protected boolean overScrollBy(int deltaX, int deltaY,
18076            int scrollX, int scrollY,
18077            int scrollRangeX, int scrollRangeY,
18078            int maxOverScrollX, int maxOverScrollY,
18079            boolean isTouchEvent) {
18080        final int overScrollMode = mOverScrollMode;
18081        final boolean canScrollHorizontal =
18082                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18083        final boolean canScrollVertical =
18084                computeVerticalScrollRange() > computeVerticalScrollExtent();
18085        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18086                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18087        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18088                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18089
18090        int newScrollX = scrollX + deltaX;
18091        if (!overScrollHorizontal) {
18092            maxOverScrollX = 0;
18093        }
18094
18095        int newScrollY = scrollY + deltaY;
18096        if (!overScrollVertical) {
18097            maxOverScrollY = 0;
18098        }
18099
18100        // Clamp values if at the limits and record
18101        final int left = -maxOverScrollX;
18102        final int right = maxOverScrollX + scrollRangeX;
18103        final int top = -maxOverScrollY;
18104        final int bottom = maxOverScrollY + scrollRangeY;
18105
18106        boolean clampedX = false;
18107        if (newScrollX > right) {
18108            newScrollX = right;
18109            clampedX = true;
18110        } else if (newScrollX < left) {
18111            newScrollX = left;
18112            clampedX = true;
18113        }
18114
18115        boolean clampedY = false;
18116        if (newScrollY > bottom) {
18117            newScrollY = bottom;
18118            clampedY = true;
18119        } else if (newScrollY < top) {
18120            newScrollY = top;
18121            clampedY = true;
18122        }
18123
18124        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18125
18126        return clampedX || clampedY;
18127    }
18128
18129    /**
18130     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18131     * respond to the results of an over-scroll operation.
18132     *
18133     * @param scrollX New X scroll value in pixels
18134     * @param scrollY New Y scroll value in pixels
18135     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18136     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18137     */
18138    protected void onOverScrolled(int scrollX, int scrollY,
18139            boolean clampedX, boolean clampedY) {
18140        // Intentionally empty.
18141    }
18142
18143    /**
18144     * Returns the over-scroll mode for this view. The result will be
18145     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18146     * (allow over-scrolling only if the view content is larger than the container),
18147     * or {@link #OVER_SCROLL_NEVER}.
18148     *
18149     * @return This view's over-scroll mode.
18150     */
18151    public int getOverScrollMode() {
18152        return mOverScrollMode;
18153    }
18154
18155    /**
18156     * Set the over-scroll mode for this view. Valid over-scroll modes are
18157     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18158     * (allow over-scrolling only if the view content is larger than the container),
18159     * or {@link #OVER_SCROLL_NEVER}.
18160     *
18161     * Setting the over-scroll mode of a view will have an effect only if the
18162     * view is capable of scrolling.
18163     *
18164     * @param overScrollMode The new over-scroll mode for this view.
18165     */
18166    public void setOverScrollMode(int overScrollMode) {
18167        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18168                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18169                overScrollMode != OVER_SCROLL_NEVER) {
18170            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18171        }
18172        mOverScrollMode = overScrollMode;
18173    }
18174
18175    /**
18176     * Enable or disable nested scrolling for this view.
18177     *
18178     * <p>If this property is set to true the view will be permitted to initiate nested
18179     * scrolling operations with a compatible parent view in the current hierarchy. If this
18180     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18181     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18182     * the nested scroll.</p>
18183     *
18184     * @param enabled true to enable nested scrolling, false to disable
18185     *
18186     * @see #isNestedScrollingEnabled()
18187     */
18188    public void setNestedScrollingEnabled(boolean enabled) {
18189        if (enabled) {
18190            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18191        } else {
18192            stopNestedScroll();
18193            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18194        }
18195    }
18196
18197    /**
18198     * Returns true if nested scrolling is enabled for this view.
18199     *
18200     * <p>If nested scrolling is enabled and this View class implementation supports it,
18201     * this view will act as a nested scrolling child view when applicable, forwarding data
18202     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18203     * parent.</p>
18204     *
18205     * @return true if nested scrolling is enabled
18206     *
18207     * @see #setNestedScrollingEnabled(boolean)
18208     */
18209    public boolean isNestedScrollingEnabled() {
18210        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18211                PFLAG3_NESTED_SCROLLING_ENABLED;
18212    }
18213
18214    /**
18215     * Begin a nestable scroll operation along the given axes.
18216     *
18217     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18218     *
18219     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18220     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18221     * In the case of touch scrolling the nested scroll will be terminated automatically in
18222     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18223     * In the event of programmatic scrolling the caller must explicitly call
18224     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18225     *
18226     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18227     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18228     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18229     *
18230     * <p>At each incremental step of the scroll the caller should invoke
18231     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18232     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18233     * parent at least partially consumed the scroll and the caller should adjust the amount it
18234     * scrolls by.</p>
18235     *
18236     * <p>After applying the remainder of the scroll delta the caller should invoke
18237     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18238     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18239     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18240     * </p>
18241     *
18242     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18243     *             {@link #SCROLL_AXIS_VERTICAL}.
18244     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18245     *         the current gesture.
18246     *
18247     * @see #stopNestedScroll()
18248     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18249     * @see #dispatchNestedScroll(int, int, int, int, int[])
18250     */
18251    public boolean startNestedScroll(int axes) {
18252        if (hasNestedScrollingParent()) {
18253            // Already in progress
18254            return true;
18255        }
18256        if (isNestedScrollingEnabled()) {
18257            ViewParent p = getParent();
18258            View child = this;
18259            while (p != null) {
18260                try {
18261                    if (p.onStartNestedScroll(child, this, axes)) {
18262                        mNestedScrollingParent = p;
18263                        p.onNestedScrollAccepted(child, this, axes);
18264                        return true;
18265                    }
18266                } catch (AbstractMethodError e) {
18267                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18268                            "method onStartNestedScroll", e);
18269                    // Allow the search upward to continue
18270                }
18271                if (p instanceof View) {
18272                    child = (View) p;
18273                }
18274                p = p.getParent();
18275            }
18276        }
18277        return false;
18278    }
18279
18280    /**
18281     * Stop a nested scroll in progress.
18282     *
18283     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18284     *
18285     * @see #startNestedScroll(int)
18286     */
18287    public void stopNestedScroll() {
18288        if (mNestedScrollingParent != null) {
18289            mNestedScrollingParent.onStopNestedScroll(this);
18290            mNestedScrollingParent = null;
18291        }
18292    }
18293
18294    /**
18295     * Returns true if this view has a nested scrolling parent.
18296     *
18297     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18298     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18299     *
18300     * @return whether this view has a nested scrolling parent
18301     */
18302    public boolean hasNestedScrollingParent() {
18303        return mNestedScrollingParent != null;
18304    }
18305
18306    /**
18307     * Dispatch one step of a nested scroll in progress.
18308     *
18309     * <p>Implementations of views that support nested scrolling should call this to report
18310     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18311     * is not currently in progress or nested scrolling is not
18312     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18313     *
18314     * <p>Compatible View implementations should also call
18315     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18316     * consuming a component of the scroll event themselves.</p>
18317     *
18318     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18319     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18320     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18321     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18322     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18323     *                       in local view coordinates of this view from before this operation
18324     *                       to after it completes. View implementations may use this to adjust
18325     *                       expected input coordinate tracking.
18326     * @return true if the event was dispatched, false if it could not be dispatched.
18327     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18328     */
18329    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18330            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18331        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18332            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18333                int startX = 0;
18334                int startY = 0;
18335                if (offsetInWindow != null) {
18336                    getLocationInWindow(offsetInWindow);
18337                    startX = offsetInWindow[0];
18338                    startY = offsetInWindow[1];
18339                }
18340
18341                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18342                        dxUnconsumed, dyUnconsumed);
18343
18344                if (offsetInWindow != null) {
18345                    getLocationInWindow(offsetInWindow);
18346                    offsetInWindow[0] -= startX;
18347                    offsetInWindow[1] -= startY;
18348                }
18349                return true;
18350            } else if (offsetInWindow != null) {
18351                // No motion, no dispatch. Keep offsetInWindow up to date.
18352                offsetInWindow[0] = 0;
18353                offsetInWindow[1] = 0;
18354            }
18355        }
18356        return false;
18357    }
18358
18359    /**
18360     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18361     *
18362     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18363     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18364     * scrolling operation to consume some or all of the scroll operation before the child view
18365     * consumes it.</p>
18366     *
18367     * @param dx Horizontal scroll distance in pixels
18368     * @param dy Vertical scroll distance in pixels
18369     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18370     *                 and consumed[1] the consumed dy.
18371     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18372     *                       in local view coordinates of this view from before this operation
18373     *                       to after it completes. View implementations may use this to adjust
18374     *                       expected input coordinate tracking.
18375     * @return true if the parent consumed some or all of the scroll delta
18376     * @see #dispatchNestedScroll(int, int, int, int, int[])
18377     */
18378    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18379        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18380            if (dx != 0 || dy != 0) {
18381                int startX = 0;
18382                int startY = 0;
18383                if (offsetInWindow != null) {
18384                    getLocationInWindow(offsetInWindow);
18385                    startX = offsetInWindow[0];
18386                    startY = offsetInWindow[1];
18387                }
18388
18389                if (consumed == null) {
18390                    if (mTempNestedScrollConsumed == null) {
18391                        mTempNestedScrollConsumed = new int[2];
18392                    }
18393                    consumed = mTempNestedScrollConsumed;
18394                }
18395                consumed[0] = 0;
18396                consumed[1] = 0;
18397                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18398
18399                if (offsetInWindow != null) {
18400                    getLocationInWindow(offsetInWindow);
18401                    offsetInWindow[0] -= startX;
18402                    offsetInWindow[1] -= startY;
18403                }
18404                return consumed[0] != 0 || consumed[1] != 0;
18405            } else if (offsetInWindow != null) {
18406                offsetInWindow[0] = 0;
18407                offsetInWindow[1] = 0;
18408            }
18409        }
18410        return false;
18411    }
18412
18413    /**
18414     * Dispatch a fling to a nested scrolling parent.
18415     *
18416     * <p>This method should be used to indicate that a nested scrolling child has detected
18417     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18418     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18419     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18420     * along a scrollable axis.</p>
18421     *
18422     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18423     * its own content, it can use this method to delegate the fling to its nested scrolling
18424     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18425     *
18426     * @param velocityX Horizontal fling velocity in pixels per second
18427     * @param velocityY Vertical fling velocity in pixels per second
18428     * @param consumed true if the child consumed the fling, false otherwise
18429     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18430     */
18431    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18432        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18433            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18434        }
18435        return false;
18436    }
18437
18438    /**
18439     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18440     *
18441     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18442     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18443     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18444     * before the child view consumes it. If this method returns <code>true</code>, a nested
18445     * parent view consumed the fling and this view should not scroll as a result.</p>
18446     *
18447     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18448     * the fling at a time. If a parent view consumed the fling this method will return false.
18449     * Custom view implementations should account for this in two ways:</p>
18450     *
18451     * <ul>
18452     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18453     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18454     *     position regardless.</li>
18455     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18456     *     even to settle back to a valid idle position.</li>
18457     * </ul>
18458     *
18459     * <p>Views should also not offer fling velocities to nested parent views along an axis
18460     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18461     * should not offer a horizontal fling velocity to its parents since scrolling along that
18462     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18463     *
18464     * @param velocityX Horizontal fling velocity in pixels per second
18465     * @param velocityY Vertical fling velocity in pixels per second
18466     * @return true if a nested scrolling parent consumed the fling
18467     */
18468    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18469        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18470            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18471        }
18472        return false;
18473    }
18474
18475    /**
18476     * Gets a scale factor that determines the distance the view should scroll
18477     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18478     * @return The vertical scroll scale factor.
18479     * @hide
18480     */
18481    protected float getVerticalScrollFactor() {
18482        if (mVerticalScrollFactor == 0) {
18483            TypedValue outValue = new TypedValue();
18484            if (!mContext.getTheme().resolveAttribute(
18485                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18486                throw new IllegalStateException(
18487                        "Expected theme to define listPreferredItemHeight.");
18488            }
18489            mVerticalScrollFactor = outValue.getDimension(
18490                    mContext.getResources().getDisplayMetrics());
18491        }
18492        return mVerticalScrollFactor;
18493    }
18494
18495    /**
18496     * Gets a scale factor that determines the distance the view should scroll
18497     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18498     * @return The horizontal scroll scale factor.
18499     * @hide
18500     */
18501    protected float getHorizontalScrollFactor() {
18502        // TODO: Should use something else.
18503        return getVerticalScrollFactor();
18504    }
18505
18506    /**
18507     * Return the value specifying the text direction or policy that was set with
18508     * {@link #setTextDirection(int)}.
18509     *
18510     * @return the defined text direction. It can be one of:
18511     *
18512     * {@link #TEXT_DIRECTION_INHERIT},
18513     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18514     * {@link #TEXT_DIRECTION_ANY_RTL},
18515     * {@link #TEXT_DIRECTION_LTR},
18516     * {@link #TEXT_DIRECTION_RTL},
18517     * {@link #TEXT_DIRECTION_LOCALE}
18518     *
18519     * @attr ref android.R.styleable#View_textDirection
18520     *
18521     * @hide
18522     */
18523    @ViewDebug.ExportedProperty(category = "text", mapping = {
18524            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18525            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18526            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18527            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18528            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18529            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18530    })
18531    public int getRawTextDirection() {
18532        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18533    }
18534
18535    /**
18536     * Set the text direction.
18537     *
18538     * @param textDirection the direction to set. Should be one of:
18539     *
18540     * {@link #TEXT_DIRECTION_INHERIT},
18541     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18542     * {@link #TEXT_DIRECTION_ANY_RTL},
18543     * {@link #TEXT_DIRECTION_LTR},
18544     * {@link #TEXT_DIRECTION_RTL},
18545     * {@link #TEXT_DIRECTION_LOCALE}
18546     *
18547     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18548     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18549     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18550     *
18551     * @attr ref android.R.styleable#View_textDirection
18552     */
18553    public void setTextDirection(int textDirection) {
18554        if (getRawTextDirection() != textDirection) {
18555            // Reset the current text direction and the resolved one
18556            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18557            resetResolvedTextDirection();
18558            // Set the new text direction
18559            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18560            // Do resolution
18561            resolveTextDirection();
18562            // Notify change
18563            onRtlPropertiesChanged(getLayoutDirection());
18564            // Refresh
18565            requestLayout();
18566            invalidate(true);
18567        }
18568    }
18569
18570    /**
18571     * Return the resolved text direction.
18572     *
18573     * @return the resolved text direction. Returns one of:
18574     *
18575     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18576     * {@link #TEXT_DIRECTION_ANY_RTL},
18577     * {@link #TEXT_DIRECTION_LTR},
18578     * {@link #TEXT_DIRECTION_RTL},
18579     * {@link #TEXT_DIRECTION_LOCALE}
18580     *
18581     * @attr ref android.R.styleable#View_textDirection
18582     */
18583    @ViewDebug.ExportedProperty(category = "text", mapping = {
18584            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18585            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18586            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18587            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18588            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18589            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18590    })
18591    public int getTextDirection() {
18592        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18593    }
18594
18595    /**
18596     * Resolve the text direction.
18597     *
18598     * @return true if resolution has been done, false otherwise.
18599     *
18600     * @hide
18601     */
18602    public boolean resolveTextDirection() {
18603        // Reset any previous text direction resolution
18604        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18605
18606        if (hasRtlSupport()) {
18607            // Set resolved text direction flag depending on text direction flag
18608            final int textDirection = getRawTextDirection();
18609            switch(textDirection) {
18610                case TEXT_DIRECTION_INHERIT:
18611                    if (!canResolveTextDirection()) {
18612                        // We cannot do the resolution if there is no parent, so use the default one
18613                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18614                        // Resolution will need to happen again later
18615                        return false;
18616                    }
18617
18618                    // Parent has not yet resolved, so we still return the default
18619                    try {
18620                        if (!mParent.isTextDirectionResolved()) {
18621                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18622                            // Resolution will need to happen again later
18623                            return false;
18624                        }
18625                    } catch (AbstractMethodError e) {
18626                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18627                                " does not fully implement ViewParent", e);
18628                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18629                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18630                        return true;
18631                    }
18632
18633                    // Set current resolved direction to the same value as the parent's one
18634                    int parentResolvedDirection;
18635                    try {
18636                        parentResolvedDirection = mParent.getTextDirection();
18637                    } catch (AbstractMethodError e) {
18638                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18639                                " does not fully implement ViewParent", e);
18640                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18641                    }
18642                    switch (parentResolvedDirection) {
18643                        case TEXT_DIRECTION_FIRST_STRONG:
18644                        case TEXT_DIRECTION_ANY_RTL:
18645                        case TEXT_DIRECTION_LTR:
18646                        case TEXT_DIRECTION_RTL:
18647                        case TEXT_DIRECTION_LOCALE:
18648                            mPrivateFlags2 |=
18649                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18650                            break;
18651                        default:
18652                            // Default resolved direction is "first strong" heuristic
18653                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18654                    }
18655                    break;
18656                case TEXT_DIRECTION_FIRST_STRONG:
18657                case TEXT_DIRECTION_ANY_RTL:
18658                case TEXT_DIRECTION_LTR:
18659                case TEXT_DIRECTION_RTL:
18660                case TEXT_DIRECTION_LOCALE:
18661                    // Resolved direction is the same as text direction
18662                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18663                    break;
18664                default:
18665                    // Default resolved direction is "first strong" heuristic
18666                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18667            }
18668        } else {
18669            // Default resolved direction is "first strong" heuristic
18670            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18671        }
18672
18673        // Set to resolved
18674        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18675        return true;
18676    }
18677
18678    /**
18679     * Check if text direction resolution can be done.
18680     *
18681     * @return true if text direction resolution can be done otherwise return false.
18682     */
18683    public boolean canResolveTextDirection() {
18684        switch (getRawTextDirection()) {
18685            case TEXT_DIRECTION_INHERIT:
18686                if (mParent != null) {
18687                    try {
18688                        return mParent.canResolveTextDirection();
18689                    } catch (AbstractMethodError e) {
18690                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18691                                " does not fully implement ViewParent", e);
18692                    }
18693                }
18694                return false;
18695
18696            default:
18697                return true;
18698        }
18699    }
18700
18701    /**
18702     * Reset resolved text direction. Text direction will be resolved during a call to
18703     * {@link #onMeasure(int, int)}.
18704     *
18705     * @hide
18706     */
18707    public void resetResolvedTextDirection() {
18708        // Reset any previous text direction resolution
18709        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18710        // Set to default value
18711        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18712    }
18713
18714    /**
18715     * @return true if text direction is inherited.
18716     *
18717     * @hide
18718     */
18719    public boolean isTextDirectionInherited() {
18720        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18721    }
18722
18723    /**
18724     * @return true if text direction is resolved.
18725     */
18726    public boolean isTextDirectionResolved() {
18727        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18728    }
18729
18730    /**
18731     * Return the value specifying the text alignment or policy that was set with
18732     * {@link #setTextAlignment(int)}.
18733     *
18734     * @return the defined text alignment. It can be one of:
18735     *
18736     * {@link #TEXT_ALIGNMENT_INHERIT},
18737     * {@link #TEXT_ALIGNMENT_GRAVITY},
18738     * {@link #TEXT_ALIGNMENT_CENTER},
18739     * {@link #TEXT_ALIGNMENT_TEXT_START},
18740     * {@link #TEXT_ALIGNMENT_TEXT_END},
18741     * {@link #TEXT_ALIGNMENT_VIEW_START},
18742     * {@link #TEXT_ALIGNMENT_VIEW_END}
18743     *
18744     * @attr ref android.R.styleable#View_textAlignment
18745     *
18746     * @hide
18747     */
18748    @ViewDebug.ExportedProperty(category = "text", mapping = {
18749            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18750            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18751            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18752            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18753            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18754            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18755            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18756    })
18757    @TextAlignment
18758    public int getRawTextAlignment() {
18759        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18760    }
18761
18762    /**
18763     * Set the text alignment.
18764     *
18765     * @param textAlignment The text alignment to set. Should be one of
18766     *
18767     * {@link #TEXT_ALIGNMENT_INHERIT},
18768     * {@link #TEXT_ALIGNMENT_GRAVITY},
18769     * {@link #TEXT_ALIGNMENT_CENTER},
18770     * {@link #TEXT_ALIGNMENT_TEXT_START},
18771     * {@link #TEXT_ALIGNMENT_TEXT_END},
18772     * {@link #TEXT_ALIGNMENT_VIEW_START},
18773     * {@link #TEXT_ALIGNMENT_VIEW_END}
18774     *
18775     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18776     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18777     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18778     *
18779     * @attr ref android.R.styleable#View_textAlignment
18780     */
18781    public void setTextAlignment(@TextAlignment int textAlignment) {
18782        if (textAlignment != getRawTextAlignment()) {
18783            // Reset the current and resolved text alignment
18784            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18785            resetResolvedTextAlignment();
18786            // Set the new text alignment
18787            mPrivateFlags2 |=
18788                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18789            // Do resolution
18790            resolveTextAlignment();
18791            // Notify change
18792            onRtlPropertiesChanged(getLayoutDirection());
18793            // Refresh
18794            requestLayout();
18795            invalidate(true);
18796        }
18797    }
18798
18799    /**
18800     * Return the resolved text alignment.
18801     *
18802     * @return the resolved text alignment. Returns one of:
18803     *
18804     * {@link #TEXT_ALIGNMENT_GRAVITY},
18805     * {@link #TEXT_ALIGNMENT_CENTER},
18806     * {@link #TEXT_ALIGNMENT_TEXT_START},
18807     * {@link #TEXT_ALIGNMENT_TEXT_END},
18808     * {@link #TEXT_ALIGNMENT_VIEW_START},
18809     * {@link #TEXT_ALIGNMENT_VIEW_END}
18810     *
18811     * @attr ref android.R.styleable#View_textAlignment
18812     */
18813    @ViewDebug.ExportedProperty(category = "text", mapping = {
18814            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18815            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18816            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18817            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18818            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18819            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18820            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18821    })
18822    @TextAlignment
18823    public int getTextAlignment() {
18824        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18825                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18826    }
18827
18828    /**
18829     * Resolve the text alignment.
18830     *
18831     * @return true if resolution has been done, false otherwise.
18832     *
18833     * @hide
18834     */
18835    public boolean resolveTextAlignment() {
18836        // Reset any previous text alignment resolution
18837        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18838
18839        if (hasRtlSupport()) {
18840            // Set resolved text alignment flag depending on text alignment flag
18841            final int textAlignment = getRawTextAlignment();
18842            switch (textAlignment) {
18843                case TEXT_ALIGNMENT_INHERIT:
18844                    // Check if we can resolve the text alignment
18845                    if (!canResolveTextAlignment()) {
18846                        // We cannot do the resolution if there is no parent so use the default
18847                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18848                        // Resolution will need to happen again later
18849                        return false;
18850                    }
18851
18852                    // Parent has not yet resolved, so we still return the default
18853                    try {
18854                        if (!mParent.isTextAlignmentResolved()) {
18855                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18856                            // Resolution will need to happen again later
18857                            return false;
18858                        }
18859                    } catch (AbstractMethodError e) {
18860                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18861                                " does not fully implement ViewParent", e);
18862                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18863                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18864                        return true;
18865                    }
18866
18867                    int parentResolvedTextAlignment;
18868                    try {
18869                        parentResolvedTextAlignment = mParent.getTextAlignment();
18870                    } catch (AbstractMethodError e) {
18871                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18872                                " does not fully implement ViewParent", e);
18873                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18874                    }
18875                    switch (parentResolvedTextAlignment) {
18876                        case TEXT_ALIGNMENT_GRAVITY:
18877                        case TEXT_ALIGNMENT_TEXT_START:
18878                        case TEXT_ALIGNMENT_TEXT_END:
18879                        case TEXT_ALIGNMENT_CENTER:
18880                        case TEXT_ALIGNMENT_VIEW_START:
18881                        case TEXT_ALIGNMENT_VIEW_END:
18882                            // Resolved text alignment is the same as the parent resolved
18883                            // text alignment
18884                            mPrivateFlags2 |=
18885                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18886                            break;
18887                        default:
18888                            // Use default resolved text alignment
18889                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18890                    }
18891                    break;
18892                case TEXT_ALIGNMENT_GRAVITY:
18893                case TEXT_ALIGNMENT_TEXT_START:
18894                case TEXT_ALIGNMENT_TEXT_END:
18895                case TEXT_ALIGNMENT_CENTER:
18896                case TEXT_ALIGNMENT_VIEW_START:
18897                case TEXT_ALIGNMENT_VIEW_END:
18898                    // Resolved text alignment is the same as text alignment
18899                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18900                    break;
18901                default:
18902                    // Use default resolved text alignment
18903                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18904            }
18905        } else {
18906            // Use default resolved text alignment
18907            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18908        }
18909
18910        // Set the resolved
18911        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18912        return true;
18913    }
18914
18915    /**
18916     * Check if text alignment resolution can be done.
18917     *
18918     * @return true if text alignment resolution can be done otherwise return false.
18919     */
18920    public boolean canResolveTextAlignment() {
18921        switch (getRawTextAlignment()) {
18922            case TEXT_DIRECTION_INHERIT:
18923                if (mParent != null) {
18924                    try {
18925                        return mParent.canResolveTextAlignment();
18926                    } catch (AbstractMethodError e) {
18927                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18928                                " does not fully implement ViewParent", e);
18929                    }
18930                }
18931                return false;
18932
18933            default:
18934                return true;
18935        }
18936    }
18937
18938    /**
18939     * Reset resolved text alignment. Text alignment will be resolved during a call to
18940     * {@link #onMeasure(int, int)}.
18941     *
18942     * @hide
18943     */
18944    public void resetResolvedTextAlignment() {
18945        // Reset any previous text alignment resolution
18946        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18947        // Set to default
18948        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18949    }
18950
18951    /**
18952     * @return true if text alignment is inherited.
18953     *
18954     * @hide
18955     */
18956    public boolean isTextAlignmentInherited() {
18957        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18958    }
18959
18960    /**
18961     * @return true if text alignment is resolved.
18962     */
18963    public boolean isTextAlignmentResolved() {
18964        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18965    }
18966
18967    /**
18968     * Generate a value suitable for use in {@link #setId(int)}.
18969     * This value will not collide with ID values generated at build time by aapt for R.id.
18970     *
18971     * @return a generated ID value
18972     */
18973    public static int generateViewId() {
18974        for (;;) {
18975            final int result = sNextGeneratedId.get();
18976            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18977            int newValue = result + 1;
18978            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18979            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18980                return result;
18981            }
18982        }
18983    }
18984
18985    /**
18986     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18987     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18988     *                           a normal View or a ViewGroup with
18989     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18990     * @hide
18991     */
18992    public void captureTransitioningViews(List<View> transitioningViews) {
18993        if (getVisibility() == View.VISIBLE) {
18994            transitioningViews.add(this);
18995        }
18996    }
18997
18998    /**
18999     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19000     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19001     * @hide
19002     */
19003    public void findNamedViews(Map<String, View> namedElements) {
19004        if (getVisibility() == VISIBLE) {
19005            String transitionName = getTransitionName();
19006            if (transitionName != null) {
19007                namedElements.put(transitionName, this);
19008            }
19009        }
19010    }
19011
19012    //
19013    // Properties
19014    //
19015    /**
19016     * A Property wrapper around the <code>alpha</code> functionality handled by the
19017     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19018     */
19019    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19020        @Override
19021        public void setValue(View object, float value) {
19022            object.setAlpha(value);
19023        }
19024
19025        @Override
19026        public Float get(View object) {
19027            return object.getAlpha();
19028        }
19029    };
19030
19031    /**
19032     * A Property wrapper around the <code>translationX</code> functionality handled by the
19033     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19034     */
19035    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19036        @Override
19037        public void setValue(View object, float value) {
19038            object.setTranslationX(value);
19039        }
19040
19041                @Override
19042        public Float get(View object) {
19043            return object.getTranslationX();
19044        }
19045    };
19046
19047    /**
19048     * A Property wrapper around the <code>translationY</code> functionality handled by the
19049     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19050     */
19051    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19052        @Override
19053        public void setValue(View object, float value) {
19054            object.setTranslationY(value);
19055        }
19056
19057        @Override
19058        public Float get(View object) {
19059            return object.getTranslationY();
19060        }
19061    };
19062
19063    /**
19064     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19065     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19066     */
19067    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19068        @Override
19069        public void setValue(View object, float value) {
19070            object.setTranslationZ(value);
19071        }
19072
19073        @Override
19074        public Float get(View object) {
19075            return object.getTranslationZ();
19076        }
19077    };
19078
19079    /**
19080     * A Property wrapper around the <code>x</code> functionality handled by the
19081     * {@link View#setX(float)} and {@link View#getX()} methods.
19082     */
19083    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19084        @Override
19085        public void setValue(View object, float value) {
19086            object.setX(value);
19087        }
19088
19089        @Override
19090        public Float get(View object) {
19091            return object.getX();
19092        }
19093    };
19094
19095    /**
19096     * A Property wrapper around the <code>y</code> functionality handled by the
19097     * {@link View#setY(float)} and {@link View#getY()} methods.
19098     */
19099    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19100        @Override
19101        public void setValue(View object, float value) {
19102            object.setY(value);
19103        }
19104
19105        @Override
19106        public Float get(View object) {
19107            return object.getY();
19108        }
19109    };
19110
19111    /**
19112     * A Property wrapper around the <code>z</code> functionality handled by the
19113     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19114     */
19115    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19116        @Override
19117        public void setValue(View object, float value) {
19118            object.setZ(value);
19119        }
19120
19121        @Override
19122        public Float get(View object) {
19123            return object.getZ();
19124        }
19125    };
19126
19127    /**
19128     * A Property wrapper around the <code>rotation</code> functionality handled by the
19129     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19130     */
19131    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19132        @Override
19133        public void setValue(View object, float value) {
19134            object.setRotation(value);
19135        }
19136
19137        @Override
19138        public Float get(View object) {
19139            return object.getRotation();
19140        }
19141    };
19142
19143    /**
19144     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19145     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19146     */
19147    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19148        @Override
19149        public void setValue(View object, float value) {
19150            object.setRotationX(value);
19151        }
19152
19153        @Override
19154        public Float get(View object) {
19155            return object.getRotationX();
19156        }
19157    };
19158
19159    /**
19160     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19161     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19162     */
19163    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19164        @Override
19165        public void setValue(View object, float value) {
19166            object.setRotationY(value);
19167        }
19168
19169        @Override
19170        public Float get(View object) {
19171            return object.getRotationY();
19172        }
19173    };
19174
19175    /**
19176     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19177     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19178     */
19179    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19180        @Override
19181        public void setValue(View object, float value) {
19182            object.setScaleX(value);
19183        }
19184
19185        @Override
19186        public Float get(View object) {
19187            return object.getScaleX();
19188        }
19189    };
19190
19191    /**
19192     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19193     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19194     */
19195    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19196        @Override
19197        public void setValue(View object, float value) {
19198            object.setScaleY(value);
19199        }
19200
19201        @Override
19202        public Float get(View object) {
19203            return object.getScaleY();
19204        }
19205    };
19206
19207    /**
19208     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19209     * Each MeasureSpec represents a requirement for either the width or the height.
19210     * A MeasureSpec is comprised of a size and a mode. There are three possible
19211     * modes:
19212     * <dl>
19213     * <dt>UNSPECIFIED</dt>
19214     * <dd>
19215     * The parent has not imposed any constraint on the child. It can be whatever size
19216     * it wants.
19217     * </dd>
19218     *
19219     * <dt>EXACTLY</dt>
19220     * <dd>
19221     * The parent has determined an exact size for the child. The child is going to be
19222     * given those bounds regardless of how big it wants to be.
19223     * </dd>
19224     *
19225     * <dt>AT_MOST</dt>
19226     * <dd>
19227     * The child can be as large as it wants up to the specified size.
19228     * </dd>
19229     * </dl>
19230     *
19231     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19232     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19233     */
19234    public static class MeasureSpec {
19235        private static final int MODE_SHIFT = 30;
19236        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19237
19238        /**
19239         * Measure specification mode: The parent has not imposed any constraint
19240         * on the child. It can be whatever size it wants.
19241         */
19242        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19243
19244        /**
19245         * Measure specification mode: The parent has determined an exact size
19246         * for the child. The child is going to be given those bounds regardless
19247         * of how big it wants to be.
19248         */
19249        public static final int EXACTLY     = 1 << MODE_SHIFT;
19250
19251        /**
19252         * Measure specification mode: The child can be as large as it wants up
19253         * to the specified size.
19254         */
19255        public static final int AT_MOST     = 2 << MODE_SHIFT;
19256
19257        /**
19258         * Creates a measure specification based on the supplied size and mode.
19259         *
19260         * The mode must always be one of the following:
19261         * <ul>
19262         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19263         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19264         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19265         * </ul>
19266         *
19267         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19268         * implementation was such that the order of arguments did not matter
19269         * and overflow in either value could impact the resulting MeasureSpec.
19270         * {@link android.widget.RelativeLayout} was affected by this bug.
19271         * Apps targeting API levels greater than 17 will get the fixed, more strict
19272         * behavior.</p>
19273         *
19274         * @param size the size of the measure specification
19275         * @param mode the mode of the measure specification
19276         * @return the measure specification based on size and mode
19277         */
19278        public static int makeMeasureSpec(int size, int mode) {
19279            if (sUseBrokenMakeMeasureSpec) {
19280                return size + mode;
19281            } else {
19282                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19283            }
19284        }
19285
19286        /**
19287         * Extracts the mode from the supplied measure specification.
19288         *
19289         * @param measureSpec the measure specification to extract the mode from
19290         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19291         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19292         *         {@link android.view.View.MeasureSpec#EXACTLY}
19293         */
19294        public static int getMode(int measureSpec) {
19295            return (measureSpec & MODE_MASK);
19296        }
19297
19298        /**
19299         * Extracts the size from the supplied measure specification.
19300         *
19301         * @param measureSpec the measure specification to extract the size from
19302         * @return the size in pixels defined in the supplied measure specification
19303         */
19304        public static int getSize(int measureSpec) {
19305            return (measureSpec & ~MODE_MASK);
19306        }
19307
19308        static int adjust(int measureSpec, int delta) {
19309            final int mode = getMode(measureSpec);
19310            if (mode == UNSPECIFIED) {
19311                // No need to adjust size for UNSPECIFIED mode.
19312                return makeMeasureSpec(0, UNSPECIFIED);
19313            }
19314            int size = getSize(measureSpec) + delta;
19315            if (size < 0) {
19316                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19317                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19318                size = 0;
19319            }
19320            return makeMeasureSpec(size, mode);
19321        }
19322
19323        /**
19324         * Returns a String representation of the specified measure
19325         * specification.
19326         *
19327         * @param measureSpec the measure specification to convert to a String
19328         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19329         */
19330        public static String toString(int measureSpec) {
19331            int mode = getMode(measureSpec);
19332            int size = getSize(measureSpec);
19333
19334            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19335
19336            if (mode == UNSPECIFIED)
19337                sb.append("UNSPECIFIED ");
19338            else if (mode == EXACTLY)
19339                sb.append("EXACTLY ");
19340            else if (mode == AT_MOST)
19341                sb.append("AT_MOST ");
19342            else
19343                sb.append(mode).append(" ");
19344
19345            sb.append(size);
19346            return sb.toString();
19347        }
19348    }
19349
19350    private final class CheckForLongPress implements Runnable {
19351        private int mOriginalWindowAttachCount;
19352
19353        @Override
19354        public void run() {
19355            if (isPressed() && (mParent != null)
19356                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19357                if (performLongClick()) {
19358                    mHasPerformedLongPress = true;
19359                }
19360            }
19361        }
19362
19363        public void rememberWindowAttachCount() {
19364            mOriginalWindowAttachCount = mWindowAttachCount;
19365        }
19366    }
19367
19368    private final class CheckForTap implements Runnable {
19369        public float x;
19370        public float y;
19371
19372        @Override
19373        public void run() {
19374            mPrivateFlags &= ~PFLAG_PREPRESSED;
19375            setPressed(true, x, y);
19376            checkForLongClick(ViewConfiguration.getTapTimeout());
19377        }
19378    }
19379
19380    private final class PerformClick implements Runnable {
19381        @Override
19382        public void run() {
19383            performClick();
19384        }
19385    }
19386
19387    /** @hide */
19388    public void hackTurnOffWindowResizeAnim(boolean off) {
19389        mAttachInfo.mTurnOffWindowResizeAnim = off;
19390    }
19391
19392    /**
19393     * This method returns a ViewPropertyAnimator object, which can be used to animate
19394     * specific properties on this View.
19395     *
19396     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19397     */
19398    public ViewPropertyAnimator animate() {
19399        if (mAnimator == null) {
19400            mAnimator = new ViewPropertyAnimator(this);
19401        }
19402        return mAnimator;
19403    }
19404
19405    /**
19406     * Sets the name of the View to be used to identify Views in Transitions.
19407     * Names should be unique in the View hierarchy.
19408     *
19409     * @param transitionName The name of the View to uniquely identify it for Transitions.
19410     */
19411    public final void setTransitionName(String transitionName) {
19412        mTransitionName = transitionName;
19413    }
19414
19415    /**
19416     * Returns the name of the View to be used to identify Views in Transitions.
19417     * Names should be unique in the View hierarchy.
19418     *
19419     * <p>This returns null if the View has not been given a name.</p>
19420     *
19421     * @return The name used of the View to be used to identify Views in Transitions or null
19422     * if no name has been given.
19423     */
19424    @ViewDebug.ExportedProperty
19425    public String getTransitionName() {
19426        return mTransitionName;
19427    }
19428
19429    /**
19430     * Interface definition for a callback to be invoked when a hardware key event is
19431     * dispatched to this view. The callback will be invoked before the key event is
19432     * given to the view. This is only useful for hardware keyboards; a software input
19433     * method has no obligation to trigger this listener.
19434     */
19435    public interface OnKeyListener {
19436        /**
19437         * Called when a hardware key is dispatched to a view. This allows listeners to
19438         * get a chance to respond before the target view.
19439         * <p>Key presses in software keyboards will generally NOT trigger this method,
19440         * although some may elect to do so in some situations. Do not assume a
19441         * software input method has to be key-based; even if it is, it may use key presses
19442         * in a different way than you expect, so there is no way to reliably catch soft
19443         * input key presses.
19444         *
19445         * @param v The view the key has been dispatched to.
19446         * @param keyCode The code for the physical key that was pressed
19447         * @param event The KeyEvent object containing full information about
19448         *        the event.
19449         * @return True if the listener has consumed the event, false otherwise.
19450         */
19451        boolean onKey(View v, int keyCode, KeyEvent event);
19452    }
19453
19454    /**
19455     * Interface definition for a callback to be invoked when a touch event is
19456     * dispatched to this view. The callback will be invoked before the touch
19457     * event is given to the view.
19458     */
19459    public interface OnTouchListener {
19460        /**
19461         * Called when a touch event is dispatched to a view. This allows listeners to
19462         * get a chance to respond before the target view.
19463         *
19464         * @param v The view the touch event has been dispatched to.
19465         * @param event The MotionEvent object containing full information about
19466         *        the event.
19467         * @return True if the listener has consumed the event, false otherwise.
19468         */
19469        boolean onTouch(View v, MotionEvent event);
19470    }
19471
19472    /**
19473     * Interface definition for a callback to be invoked when a hover event is
19474     * dispatched to this view. The callback will be invoked before the hover
19475     * event is given to the view.
19476     */
19477    public interface OnHoverListener {
19478        /**
19479         * Called when a hover event is dispatched to a view. This allows listeners to
19480         * get a chance to respond before the target view.
19481         *
19482         * @param v The view the hover event has been dispatched to.
19483         * @param event The MotionEvent object containing full information about
19484         *        the event.
19485         * @return True if the listener has consumed the event, false otherwise.
19486         */
19487        boolean onHover(View v, MotionEvent event);
19488    }
19489
19490    /**
19491     * Interface definition for a callback to be invoked when a generic motion event is
19492     * dispatched to this view. The callback will be invoked before the generic motion
19493     * event is given to the view.
19494     */
19495    public interface OnGenericMotionListener {
19496        /**
19497         * Called when a generic motion event is dispatched to a view. This allows listeners to
19498         * get a chance to respond before the target view.
19499         *
19500         * @param v The view the generic motion event has been dispatched to.
19501         * @param event The MotionEvent object containing full information about
19502         *        the event.
19503         * @return True if the listener has consumed the event, false otherwise.
19504         */
19505        boolean onGenericMotion(View v, MotionEvent event);
19506    }
19507
19508    /**
19509     * Interface definition for a callback to be invoked when a view has been clicked and held.
19510     */
19511    public interface OnLongClickListener {
19512        /**
19513         * Called when a view has been clicked and held.
19514         *
19515         * @param v The view that was clicked and held.
19516         *
19517         * @return true if the callback consumed the long click, false otherwise.
19518         */
19519        boolean onLongClick(View v);
19520    }
19521
19522    /**
19523     * Interface definition for a callback to be invoked when a drag is being dispatched
19524     * to this view.  The callback will be invoked before the hosting view's own
19525     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19526     * onDrag(event) behavior, it should return 'false' from this callback.
19527     *
19528     * <div class="special reference">
19529     * <h3>Developer Guides</h3>
19530     * <p>For a guide to implementing drag and drop features, read the
19531     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19532     * </div>
19533     */
19534    public interface OnDragListener {
19535        /**
19536         * Called when a drag event is dispatched to a view. This allows listeners
19537         * to get a chance to override base View behavior.
19538         *
19539         * @param v The View that received the drag event.
19540         * @param event The {@link android.view.DragEvent} object for the drag event.
19541         * @return {@code true} if the drag event was handled successfully, or {@code false}
19542         * if the drag event was not handled. Note that {@code false} will trigger the View
19543         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19544         */
19545        boolean onDrag(View v, DragEvent event);
19546    }
19547
19548    /**
19549     * Interface definition for a callback to be invoked when the focus state of
19550     * a view changed.
19551     */
19552    public interface OnFocusChangeListener {
19553        /**
19554         * Called when the focus state of a view has changed.
19555         *
19556         * @param v The view whose state has changed.
19557         * @param hasFocus The new focus state of v.
19558         */
19559        void onFocusChange(View v, boolean hasFocus);
19560    }
19561
19562    /**
19563     * Interface definition for a callback to be invoked when a view is clicked.
19564     */
19565    public interface OnClickListener {
19566        /**
19567         * Called when a view has been clicked.
19568         *
19569         * @param v The view that was clicked.
19570         */
19571        void onClick(View v);
19572    }
19573
19574    /**
19575     * Interface definition for a callback to be invoked when the context menu
19576     * for this view is being built.
19577     */
19578    public interface OnCreateContextMenuListener {
19579        /**
19580         * Called when the context menu for this view is being built. It is not
19581         * safe to hold onto the menu after this method returns.
19582         *
19583         * @param menu The context menu that is being built
19584         * @param v The view for which the context menu is being built
19585         * @param menuInfo Extra information about the item for which the
19586         *            context menu should be shown. This information will vary
19587         *            depending on the class of v.
19588         */
19589        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19590    }
19591
19592    /**
19593     * Interface definition for a callback to be invoked when the status bar changes
19594     * visibility.  This reports <strong>global</strong> changes to the system UI
19595     * state, not what the application is requesting.
19596     *
19597     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19598     */
19599    public interface OnSystemUiVisibilityChangeListener {
19600        /**
19601         * Called when the status bar changes visibility because of a call to
19602         * {@link View#setSystemUiVisibility(int)}.
19603         *
19604         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19605         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19606         * This tells you the <strong>global</strong> state of these UI visibility
19607         * flags, not what your app is currently applying.
19608         */
19609        public void onSystemUiVisibilityChange(int visibility);
19610    }
19611
19612    /**
19613     * Interface definition for a callback to be invoked when this view is attached
19614     * or detached from its window.
19615     */
19616    public interface OnAttachStateChangeListener {
19617        /**
19618         * Called when the view is attached to a window.
19619         * @param v The view that was attached
19620         */
19621        public void onViewAttachedToWindow(View v);
19622        /**
19623         * Called when the view is detached from a window.
19624         * @param v The view that was detached
19625         */
19626        public void onViewDetachedFromWindow(View v);
19627    }
19628
19629    /**
19630     * Listener for applying window insets on a view in a custom way.
19631     *
19632     * <p>Apps may choose to implement this interface if they want to apply custom policy
19633     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19634     * is set, its
19635     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19636     * method will be called instead of the View's own
19637     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19638     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19639     * the View's normal behavior as part of its own.</p>
19640     */
19641    public interface OnApplyWindowInsetsListener {
19642        /**
19643         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19644         * on a View, this listener method will be called instead of the view's own
19645         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19646         *
19647         * @param v The view applying window insets
19648         * @param insets The insets to apply
19649         * @return The insets supplied, minus any insets that were consumed
19650         */
19651        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19652    }
19653
19654    private final class UnsetPressedState implements Runnable {
19655        @Override
19656        public void run() {
19657            setPressed(false);
19658        }
19659    }
19660
19661    /**
19662     * Base class for derived classes that want to save and restore their own
19663     * state in {@link android.view.View#onSaveInstanceState()}.
19664     */
19665    public static class BaseSavedState extends AbsSavedState {
19666        /**
19667         * Constructor used when reading from a parcel. Reads the state of the superclass.
19668         *
19669         * @param source
19670         */
19671        public BaseSavedState(Parcel source) {
19672            super(source);
19673        }
19674
19675        /**
19676         * Constructor called by derived classes when creating their SavedState objects
19677         *
19678         * @param superState The state of the superclass of this view
19679         */
19680        public BaseSavedState(Parcelable superState) {
19681            super(superState);
19682        }
19683
19684        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19685                new Parcelable.Creator<BaseSavedState>() {
19686            public BaseSavedState createFromParcel(Parcel in) {
19687                return new BaseSavedState(in);
19688            }
19689
19690            public BaseSavedState[] newArray(int size) {
19691                return new BaseSavedState[size];
19692            }
19693        };
19694    }
19695
19696    /**
19697     * A set of information given to a view when it is attached to its parent
19698     * window.
19699     */
19700    final static class AttachInfo {
19701        interface Callbacks {
19702            void playSoundEffect(int effectId);
19703            boolean performHapticFeedback(int effectId, boolean always);
19704        }
19705
19706        /**
19707         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19708         * to a Handler. This class contains the target (View) to invalidate and
19709         * the coordinates of the dirty rectangle.
19710         *
19711         * For performance purposes, this class also implements a pool of up to
19712         * POOL_LIMIT objects that get reused. This reduces memory allocations
19713         * whenever possible.
19714         */
19715        static class InvalidateInfo {
19716            private static final int POOL_LIMIT = 10;
19717
19718            private static final SynchronizedPool<InvalidateInfo> sPool =
19719                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19720
19721            View target;
19722
19723            int left;
19724            int top;
19725            int right;
19726            int bottom;
19727
19728            public static InvalidateInfo obtain() {
19729                InvalidateInfo instance = sPool.acquire();
19730                return (instance != null) ? instance : new InvalidateInfo();
19731            }
19732
19733            public void recycle() {
19734                target = null;
19735                sPool.release(this);
19736            }
19737        }
19738
19739        final IWindowSession mSession;
19740
19741        final IWindow mWindow;
19742
19743        final IBinder mWindowToken;
19744
19745        final Display mDisplay;
19746
19747        final Callbacks mRootCallbacks;
19748
19749        IWindowId mIWindowId;
19750        WindowId mWindowId;
19751
19752        /**
19753         * The top view of the hierarchy.
19754         */
19755        View mRootView;
19756
19757        IBinder mPanelParentWindowToken;
19758
19759        boolean mHardwareAccelerated;
19760        boolean mHardwareAccelerationRequested;
19761        HardwareRenderer mHardwareRenderer;
19762
19763        /**
19764         * The state of the display to which the window is attached, as reported
19765         * by {@link Display#getState()}.  Note that the display state constants
19766         * declared by {@link Display} do not exactly line up with the screen state
19767         * constants declared by {@link View} (there are more display states than
19768         * screen states).
19769         */
19770        int mDisplayState = Display.STATE_UNKNOWN;
19771
19772        /**
19773         * Scale factor used by the compatibility mode
19774         */
19775        float mApplicationScale;
19776
19777        /**
19778         * Indicates whether the application is in compatibility mode
19779         */
19780        boolean mScalingRequired;
19781
19782        /**
19783         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19784         */
19785        boolean mTurnOffWindowResizeAnim;
19786
19787        /**
19788         * Left position of this view's window
19789         */
19790        int mWindowLeft;
19791
19792        /**
19793         * Top position of this view's window
19794         */
19795        int mWindowTop;
19796
19797        /**
19798         * Indicates whether views need to use 32-bit drawing caches
19799         */
19800        boolean mUse32BitDrawingCache;
19801
19802        /**
19803         * For windows that are full-screen but using insets to layout inside
19804         * of the screen areas, these are the current insets to appear inside
19805         * the overscan area of the display.
19806         */
19807        final Rect mOverscanInsets = new Rect();
19808
19809        /**
19810         * For windows that are full-screen but using insets to layout inside
19811         * of the screen decorations, these are the current insets for the
19812         * content of the window.
19813         */
19814        final Rect mContentInsets = 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         * actual visible parts of the window.
19820         */
19821        final Rect mVisibleInsets = 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         * stable system windows.
19827         */
19828        final Rect mStableInsets = new Rect();
19829
19830        /**
19831         * The internal insets given by this window.  This value is
19832         * supplied by the client (through
19833         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19834         * be given to the window manager when changed to be used in laying
19835         * out windows behind it.
19836         */
19837        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19838                = new ViewTreeObserver.InternalInsetsInfo();
19839
19840        /**
19841         * Set to true when mGivenInternalInsets is non-empty.
19842         */
19843        boolean mHasNonEmptyGivenInternalInsets;
19844
19845        /**
19846         * All views in the window's hierarchy that serve as scroll containers,
19847         * used to determine if the window can be resized or must be panned
19848         * to adjust for a soft input area.
19849         */
19850        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19851
19852        final KeyEvent.DispatcherState mKeyDispatchState
19853                = new KeyEvent.DispatcherState();
19854
19855        /**
19856         * Indicates whether the view's window currently has the focus.
19857         */
19858        boolean mHasWindowFocus;
19859
19860        /**
19861         * The current visibility of the window.
19862         */
19863        int mWindowVisibility;
19864
19865        /**
19866         * Indicates the time at which drawing started to occur.
19867         */
19868        long mDrawingTime;
19869
19870        /**
19871         * Indicates whether or not ignoring the DIRTY_MASK flags.
19872         */
19873        boolean mIgnoreDirtyState;
19874
19875        /**
19876         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19877         * to avoid clearing that flag prematurely.
19878         */
19879        boolean mSetIgnoreDirtyState = false;
19880
19881        /**
19882         * Indicates whether the view's window is currently in touch mode.
19883         */
19884        boolean mInTouchMode;
19885
19886        /**
19887         * Indicates whether the view has requested unbuffered input dispatching for the current
19888         * event stream.
19889         */
19890        boolean mUnbufferedDispatchRequested;
19891
19892        /**
19893         * Indicates that ViewAncestor should trigger a global layout change
19894         * the next time it performs a traversal
19895         */
19896        boolean mRecomputeGlobalAttributes;
19897
19898        /**
19899         * Always report new attributes at next traversal.
19900         */
19901        boolean mForceReportNewAttributes;
19902
19903        /**
19904         * Set during a traveral if any views want to keep the screen on.
19905         */
19906        boolean mKeepScreenOn;
19907
19908        /**
19909         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19910         */
19911        int mSystemUiVisibility;
19912
19913        /**
19914         * Hack to force certain system UI visibility flags to be cleared.
19915         */
19916        int mDisabledSystemUiVisibility;
19917
19918        /**
19919         * Last global system UI visibility reported by the window manager.
19920         */
19921        int mGlobalSystemUiVisibility;
19922
19923        /**
19924         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19925         * attached.
19926         */
19927        boolean mHasSystemUiListeners;
19928
19929        /**
19930         * Set if the window has requested to extend into the overscan region
19931         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19932         */
19933        boolean mOverscanRequested;
19934
19935        /**
19936         * Set if the visibility of any views has changed.
19937         */
19938        boolean mViewVisibilityChanged;
19939
19940        /**
19941         * Set to true if a view has been scrolled.
19942         */
19943        boolean mViewScrollChanged;
19944
19945        /**
19946         * Set to true if high contrast mode enabled
19947         */
19948        boolean mHighContrastText;
19949
19950        /**
19951         * Global to the view hierarchy used as a temporary for dealing with
19952         * x/y points in the transparent region computations.
19953         */
19954        final int[] mTransparentLocation = new int[2];
19955
19956        /**
19957         * Global to the view hierarchy used as a temporary for dealing with
19958         * x/y points in the ViewGroup.invalidateChild implementation.
19959         */
19960        final int[] mInvalidateChildLocation = new int[2];
19961
19962        /**
19963         * Global to the view hierarchy used as a temporary for dealng with
19964         * computing absolute on-screen location.
19965         */
19966        final int[] mTmpLocation = new int[2];
19967
19968        /**
19969         * Global to the view hierarchy used as a temporary for dealing with
19970         * x/y location when view is transformed.
19971         */
19972        final float[] mTmpTransformLocation = new float[2];
19973
19974        /**
19975         * The view tree observer used to dispatch global events like
19976         * layout, pre-draw, touch mode change, etc.
19977         */
19978        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19979
19980        /**
19981         * A Canvas used by the view hierarchy to perform bitmap caching.
19982         */
19983        Canvas mCanvas;
19984
19985        /**
19986         * The view root impl.
19987         */
19988        final ViewRootImpl mViewRootImpl;
19989
19990        /**
19991         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19992         * handler can be used to pump events in the UI events queue.
19993         */
19994        final Handler mHandler;
19995
19996        /**
19997         * Temporary for use in computing invalidate rectangles while
19998         * calling up the hierarchy.
19999         */
20000        final Rect mTmpInvalRect = new Rect();
20001
20002        /**
20003         * Temporary for use in computing hit areas with transformed views
20004         */
20005        final RectF mTmpTransformRect = new RectF();
20006
20007        /**
20008         * Temporary for use in transforming invalidation rect
20009         */
20010        final Matrix mTmpMatrix = new Matrix();
20011
20012        /**
20013         * Temporary for use in transforming invalidation rect
20014         */
20015        final Transformation mTmpTransformation = new Transformation();
20016
20017        /**
20018         * Temporary for use in querying outlines from OutlineProviders
20019         */
20020        final Outline mTmpOutline = new Outline();
20021
20022        /**
20023         * Temporary list for use in collecting focusable descendents of a view.
20024         */
20025        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20026
20027        /**
20028         * The id of the window for accessibility purposes.
20029         */
20030        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20031
20032        /**
20033         * Flags related to accessibility processing.
20034         *
20035         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20036         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20037         */
20038        int mAccessibilityFetchFlags;
20039
20040        /**
20041         * The drawable for highlighting accessibility focus.
20042         */
20043        Drawable mAccessibilityFocusDrawable;
20044
20045        /**
20046         * Show where the margins, bounds and layout bounds are for each view.
20047         */
20048        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20049
20050        /**
20051         * Point used to compute visible regions.
20052         */
20053        final Point mPoint = new Point();
20054
20055        /**
20056         * Used to track which View originated a requestLayout() call, used when
20057         * requestLayout() is called during layout.
20058         */
20059        View mViewRequestingLayout;
20060
20061        /**
20062         * Creates a new set of attachment information with the specified
20063         * events handler and thread.
20064         *
20065         * @param handler the events handler the view must use
20066         */
20067        AttachInfo(IWindowSession session, IWindow window, Display display,
20068                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20069            mSession = session;
20070            mWindow = window;
20071            mWindowToken = window.asBinder();
20072            mDisplay = display;
20073            mViewRootImpl = viewRootImpl;
20074            mHandler = handler;
20075            mRootCallbacks = effectPlayer;
20076        }
20077    }
20078
20079    /**
20080     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20081     * is supported. This avoids keeping too many unused fields in most
20082     * instances of View.</p>
20083     */
20084    private static class ScrollabilityCache implements Runnable {
20085
20086        /**
20087         * Scrollbars are not visible
20088         */
20089        public static final int OFF = 0;
20090
20091        /**
20092         * Scrollbars are visible
20093         */
20094        public static final int ON = 1;
20095
20096        /**
20097         * Scrollbars are fading away
20098         */
20099        public static final int FADING = 2;
20100
20101        public boolean fadeScrollBars;
20102
20103        public int fadingEdgeLength;
20104        public int scrollBarDefaultDelayBeforeFade;
20105        public int scrollBarFadeDuration;
20106
20107        public int scrollBarSize;
20108        public ScrollBarDrawable scrollBar;
20109        public float[] interpolatorValues;
20110        public View host;
20111
20112        public final Paint paint;
20113        public final Matrix matrix;
20114        public Shader shader;
20115
20116        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20117
20118        private static final float[] OPAQUE = { 255 };
20119        private static final float[] TRANSPARENT = { 0.0f };
20120
20121        /**
20122         * When fading should start. This time moves into the future every time
20123         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20124         */
20125        public long fadeStartTime;
20126
20127
20128        /**
20129         * The current state of the scrollbars: ON, OFF, or FADING
20130         */
20131        public int state = OFF;
20132
20133        private int mLastColor;
20134
20135        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20136            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20137            scrollBarSize = configuration.getScaledScrollBarSize();
20138            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20139            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20140
20141            paint = new Paint();
20142            matrix = new Matrix();
20143            // use use a height of 1, and then wack the matrix each time we
20144            // actually use it.
20145            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20146            paint.setShader(shader);
20147            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20148
20149            this.host = host;
20150        }
20151
20152        public void setFadeColor(int color) {
20153            if (color != mLastColor) {
20154                mLastColor = color;
20155
20156                if (color != 0) {
20157                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20158                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20159                    paint.setShader(shader);
20160                    // Restore the default transfer mode (src_over)
20161                    paint.setXfermode(null);
20162                } else {
20163                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20164                    paint.setShader(shader);
20165                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20166                }
20167            }
20168        }
20169
20170        public void run() {
20171            long now = AnimationUtils.currentAnimationTimeMillis();
20172            if (now >= fadeStartTime) {
20173
20174                // the animation fades the scrollbars out by changing
20175                // the opacity (alpha) from fully opaque to fully
20176                // transparent
20177                int nextFrame = (int) now;
20178                int framesCount = 0;
20179
20180                Interpolator interpolator = scrollBarInterpolator;
20181
20182                // Start opaque
20183                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20184
20185                // End transparent
20186                nextFrame += scrollBarFadeDuration;
20187                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20188
20189                state = FADING;
20190
20191                // Kick off the fade animation
20192                host.invalidate(true);
20193            }
20194        }
20195    }
20196
20197    /**
20198     * Resuable callback for sending
20199     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20200     */
20201    private class SendViewScrolledAccessibilityEvent implements Runnable {
20202        public volatile boolean mIsPending;
20203
20204        public void run() {
20205            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20206            mIsPending = false;
20207        }
20208    }
20209
20210    /**
20211     * <p>
20212     * This class represents a delegate that can be registered in a {@link View}
20213     * to enhance accessibility support via composition rather via inheritance.
20214     * It is specifically targeted to widget developers that extend basic View
20215     * classes i.e. classes in package android.view, that would like their
20216     * applications to be backwards compatible.
20217     * </p>
20218     * <div class="special reference">
20219     * <h3>Developer Guides</h3>
20220     * <p>For more information about making applications accessible, read the
20221     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20222     * developer guide.</p>
20223     * </div>
20224     * <p>
20225     * A scenario in which a developer would like to use an accessibility delegate
20226     * is overriding a method introduced in a later API version then the minimal API
20227     * version supported by the application. For example, the method
20228     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20229     * in API version 4 when the accessibility APIs were first introduced. If a
20230     * developer would like his application to run on API version 4 devices (assuming
20231     * all other APIs used by the application are version 4 or lower) and take advantage
20232     * of this method, instead of overriding the method which would break the application's
20233     * backwards compatibility, he can override the corresponding method in this
20234     * delegate and register the delegate in the target View if the API version of
20235     * the system is high enough i.e. the API version is same or higher to the API
20236     * version that introduced
20237     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20238     * </p>
20239     * <p>
20240     * Here is an example implementation:
20241     * </p>
20242     * <code><pre><p>
20243     * if (Build.VERSION.SDK_INT >= 14) {
20244     *     // If the API version is equal of higher than the version in
20245     *     // which onInitializeAccessibilityNodeInfo was introduced we
20246     *     // register a delegate with a customized implementation.
20247     *     View view = findViewById(R.id.view_id);
20248     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20249     *         public void onInitializeAccessibilityNodeInfo(View host,
20250     *                 AccessibilityNodeInfo info) {
20251     *             // Let the default implementation populate the info.
20252     *             super.onInitializeAccessibilityNodeInfo(host, info);
20253     *             // Set some other information.
20254     *             info.setEnabled(host.isEnabled());
20255     *         }
20256     *     });
20257     * }
20258     * </code></pre></p>
20259     * <p>
20260     * This delegate contains methods that correspond to the accessibility methods
20261     * in View. If a delegate has been specified the implementation in View hands
20262     * off handling to the corresponding method in this delegate. The default
20263     * implementation the delegate methods behaves exactly as the corresponding
20264     * method in View for the case of no accessibility delegate been set. Hence,
20265     * to customize the behavior of a View method, clients can override only the
20266     * corresponding delegate method without altering the behavior of the rest
20267     * accessibility related methods of the host view.
20268     * </p>
20269     */
20270    public static class AccessibilityDelegate {
20271
20272        /**
20273         * Sends an accessibility event of the given type. If accessibility is not
20274         * enabled this method has no effect.
20275         * <p>
20276         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20277         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20278         * been set.
20279         * </p>
20280         *
20281         * @param host The View hosting the delegate.
20282         * @param eventType The type of the event to send.
20283         *
20284         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20285         */
20286        public void sendAccessibilityEvent(View host, int eventType) {
20287            host.sendAccessibilityEventInternal(eventType);
20288        }
20289
20290        /**
20291         * Performs the specified accessibility action on the view. For
20292         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20293         * <p>
20294         * The default implementation behaves as
20295         * {@link View#performAccessibilityAction(int, Bundle)
20296         *  View#performAccessibilityAction(int, Bundle)} for the case of
20297         *  no accessibility delegate been set.
20298         * </p>
20299         *
20300         * @param action The action to perform.
20301         * @return Whether the action was performed.
20302         *
20303         * @see View#performAccessibilityAction(int, Bundle)
20304         *      View#performAccessibilityAction(int, Bundle)
20305         */
20306        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20307            return host.performAccessibilityActionInternal(action, args);
20308        }
20309
20310        /**
20311         * Sends an accessibility event. This method behaves exactly as
20312         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20313         * empty {@link AccessibilityEvent} and does not perform a check whether
20314         * accessibility is enabled.
20315         * <p>
20316         * The default implementation behaves as
20317         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20318         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20319         * the case of no accessibility delegate been set.
20320         * </p>
20321         *
20322         * @param host The View hosting the delegate.
20323         * @param event The event to send.
20324         *
20325         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20326         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20327         */
20328        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20329            host.sendAccessibilityEventUncheckedInternal(event);
20330        }
20331
20332        /**
20333         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20334         * to its children for adding their text content to the event.
20335         * <p>
20336         * The default implementation behaves as
20337         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20338         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20339         * the case of no accessibility delegate been set.
20340         * </p>
20341         *
20342         * @param host The View hosting the delegate.
20343         * @param event The event.
20344         * @return True if the event population was completed.
20345         *
20346         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20347         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20348         */
20349        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20350            return host.dispatchPopulateAccessibilityEventInternal(event);
20351        }
20352
20353        /**
20354         * Gives a chance to the host View to populate the accessibility event with its
20355         * text content.
20356         * <p>
20357         * The default implementation behaves as
20358         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20359         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20360         * the case of no accessibility delegate been set.
20361         * </p>
20362         *
20363         * @param host The View hosting the delegate.
20364         * @param event The accessibility event which to populate.
20365         *
20366         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20367         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20368         */
20369        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20370            host.onPopulateAccessibilityEventInternal(event);
20371        }
20372
20373        /**
20374         * Initializes an {@link AccessibilityEvent} with information about the
20375         * the host View which is the event source.
20376         * <p>
20377         * The default implementation behaves as
20378         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20379         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20380         * the case of no accessibility delegate been set.
20381         * </p>
20382         *
20383         * @param host The View hosting the delegate.
20384         * @param event The event to initialize.
20385         *
20386         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20387         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20388         */
20389        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20390            host.onInitializeAccessibilityEventInternal(event);
20391        }
20392
20393        /**
20394         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20395         * <p>
20396         * The default implementation behaves as
20397         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20398         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20399         * the case of no accessibility delegate been set.
20400         * </p>
20401         *
20402         * @param host The View hosting the delegate.
20403         * @param info The instance to initialize.
20404         *
20405         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20406         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20407         */
20408        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20409            host.onInitializeAccessibilityNodeInfoInternal(info);
20410        }
20411
20412        /**
20413         * Called when a child of the host View has requested sending an
20414         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20415         * to augment the event.
20416         * <p>
20417         * The default implementation behaves as
20418         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20419         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20420         * the case of no accessibility delegate been set.
20421         * </p>
20422         *
20423         * @param host The View hosting the delegate.
20424         * @param child The child which requests sending the event.
20425         * @param event The event to be sent.
20426         * @return True if the event should be sent
20427         *
20428         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20429         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20430         */
20431        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20432                AccessibilityEvent event) {
20433            return host.onRequestSendAccessibilityEventInternal(child, event);
20434        }
20435
20436        /**
20437         * Gets the provider for managing a virtual view hierarchy rooted at this View
20438         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20439         * that explore the window content.
20440         * <p>
20441         * The default implementation behaves as
20442         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20443         * the case of no accessibility delegate been set.
20444         * </p>
20445         *
20446         * @return The provider.
20447         *
20448         * @see AccessibilityNodeProvider
20449         */
20450        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20451            return null;
20452        }
20453
20454        /**
20455         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20456         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20457         * This method is responsible for obtaining an accessibility node info from a
20458         * pool of reusable instances and calling
20459         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20460         * view to initialize the former.
20461         * <p>
20462         * <strong>Note:</strong> The client is responsible for recycling the obtained
20463         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20464         * creation.
20465         * </p>
20466         * <p>
20467         * The default implementation behaves as
20468         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20469         * the case of no accessibility delegate been set.
20470         * </p>
20471         * @return A populated {@link AccessibilityNodeInfo}.
20472         *
20473         * @see AccessibilityNodeInfo
20474         *
20475         * @hide
20476         */
20477        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20478            return host.createAccessibilityNodeInfoInternal();
20479        }
20480    }
20481
20482    private class MatchIdPredicate implements Predicate<View> {
20483        public int mId;
20484
20485        @Override
20486        public boolean apply(View view) {
20487            return (view.mID == mId);
20488        }
20489    }
20490
20491    private class MatchLabelForPredicate implements Predicate<View> {
20492        private int mLabeledId;
20493
20494        @Override
20495        public boolean apply(View view) {
20496            return (view.mLabelForId == mLabeledId);
20497        }
20498    }
20499
20500    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20501        private int mChangeTypes = 0;
20502        private boolean mPosted;
20503        private boolean mPostedWithDelay;
20504        private long mLastEventTimeMillis;
20505
20506        @Override
20507        public void run() {
20508            mPosted = false;
20509            mPostedWithDelay = false;
20510            mLastEventTimeMillis = SystemClock.uptimeMillis();
20511            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20512                final AccessibilityEvent event = AccessibilityEvent.obtain();
20513                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20514                event.setContentChangeTypes(mChangeTypes);
20515                sendAccessibilityEventUnchecked(event);
20516            }
20517            mChangeTypes = 0;
20518        }
20519
20520        public void runOrPost(int changeType) {
20521            mChangeTypes |= changeType;
20522
20523            // If this is a live region or the child of a live region, collect
20524            // all events from this frame and send them on the next frame.
20525            if (inLiveRegion()) {
20526                // If we're already posted with a delay, remove that.
20527                if (mPostedWithDelay) {
20528                    removeCallbacks(this);
20529                    mPostedWithDelay = false;
20530                }
20531                // Only post if we're not already posted.
20532                if (!mPosted) {
20533                    post(this);
20534                    mPosted = true;
20535                }
20536                return;
20537            }
20538
20539            if (mPosted) {
20540                return;
20541            }
20542            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20543            final long minEventIntevalMillis =
20544                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20545            if (timeSinceLastMillis >= minEventIntevalMillis) {
20546                removeCallbacks(this);
20547                run();
20548            } else {
20549                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20550                mPosted = true;
20551                mPostedWithDelay = true;
20552            }
20553        }
20554    }
20555
20556    private boolean inLiveRegion() {
20557        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20558            return true;
20559        }
20560
20561        ViewParent parent = getParent();
20562        while (parent instanceof View) {
20563            if (((View) parent).getAccessibilityLiveRegion()
20564                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20565                return true;
20566            }
20567            parent = parent.getParent();
20568        }
20569
20570        return false;
20571    }
20572
20573    /**
20574     * Dump all private flags in readable format, useful for documentation and
20575     * sanity checking.
20576     */
20577    private static void dumpFlags() {
20578        final HashMap<String, String> found = Maps.newHashMap();
20579        try {
20580            for (Field field : View.class.getDeclaredFields()) {
20581                final int modifiers = field.getModifiers();
20582                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20583                    if (field.getType().equals(int.class)) {
20584                        final int value = field.getInt(null);
20585                        dumpFlag(found, field.getName(), value);
20586                    } else if (field.getType().equals(int[].class)) {
20587                        final int[] values = (int[]) field.get(null);
20588                        for (int i = 0; i < values.length; i++) {
20589                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20590                        }
20591                    }
20592                }
20593            }
20594        } catch (IllegalAccessException e) {
20595            throw new RuntimeException(e);
20596        }
20597
20598        final ArrayList<String> keys = Lists.newArrayList();
20599        keys.addAll(found.keySet());
20600        Collections.sort(keys);
20601        for (String key : keys) {
20602            Log.d(VIEW_LOG_TAG, found.get(key));
20603        }
20604    }
20605
20606    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20607        // Sort flags by prefix, then by bits, always keeping unique keys
20608        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20609        final int prefix = name.indexOf('_');
20610        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20611        final String output = bits + " " + name;
20612        found.put(key, output);
20613    }
20614}
20615