View.java revision fe361d2113b8f3c54797d7bd720ca739328bd7aa
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.PixelFormat;
39import android.graphics.Point;
40import android.graphics.PorterDuff;
41import android.graphics.PorterDuffXfermode;
42import android.graphics.Rect;
43import android.graphics.RectF;
44import android.graphics.Region;
45import android.graphics.Shader;
46import android.graphics.drawable.ColorDrawable;
47import android.graphics.drawable.Drawable;
48import android.hardware.display.DisplayManagerGlobal;
49import android.os.Bundle;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.Parcel;
53import android.os.Parcelable;
54import android.os.RemoteException;
55import android.os.SystemClock;
56import android.os.SystemProperties;
57import android.text.TextUtils;
58import android.util.AttributeSet;
59import android.util.FloatProperty;
60import android.util.LayoutDirection;
61import android.util.Log;
62import android.util.LongSparseLongArray;
63import android.util.Pools.SynchronizedPool;
64import android.util.Property;
65import android.util.SparseArray;
66import android.util.SuperNotCalledException;
67import android.util.TypedValue;
68import android.view.ContextMenu.ContextMenuInfo;
69import android.view.AccessibilityIterators.TextSegmentIterator;
70import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
71import android.view.AccessibilityIterators.WordTextSegmentIterator;
72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
73import android.view.accessibility.AccessibilityEvent;
74import android.view.accessibility.AccessibilityEventSource;
75import android.view.accessibility.AccessibilityManager;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeProvider;
78import android.view.animation.Animation;
79import android.view.animation.AnimationUtils;
80import android.view.animation.Transformation;
81import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.ScrollBarDrawable;
85
86import static android.os.Build.VERSION_CODES.*;
87import static java.lang.Math.max;
88
89import com.android.internal.R;
90import com.android.internal.util.Predicate;
91import com.android.internal.view.menu.MenuBuilder;
92
93import com.google.android.collect.Lists;
94import com.google.android.collect.Maps;
95
96import java.lang.annotation.Retention;
97import java.lang.annotation.RetentionPolicy;
98import java.lang.ref.WeakReference;
99import java.lang.reflect.Field;
100import java.lang.reflect.InvocationTargetException;
101import java.lang.reflect.Method;
102import java.lang.reflect.Modifier;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.HashMap;
107import java.util.List;
108import java.util.Locale;
109import java.util.Map;
110import java.util.concurrent.CopyOnWriteArrayList;
111import java.util.concurrent.atomic.AtomicInteger;
112
113/**
114 * <p>
115 * This class represents the basic building block for user interface components. A View
116 * occupies a rectangular area on the screen and is responsible for drawing and
117 * event handling. View is the base class for <em>widgets</em>, which are
118 * used to create interactive UI components (buttons, text fields, etc.). The
119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
120 * are invisible containers that hold other Views (or other ViewGroups) and define
121 * their layout properties.
122 * </p>
123 *
124 * <div class="special reference">
125 * <h3>Developer Guides</h3>
126 * <p>For information about using this class to develop your application's user interface,
127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
128 * </div>
129 *
130 * <a name="Using"></a>
131 * <h3>Using Views</h3>
132 * <p>
133 * All of the views in a window are arranged in a single tree. You can add views
134 * either from code or by specifying a tree of views in one or more XML layout
135 * files. There are many specialized subclasses of views that act as controls or
136 * are capable of displaying text, images, or other content.
137 * </p>
138 * <p>
139 * Once you have created a tree of views, there are typically a few types of
140 * common operations you may wish to perform:
141 * <ul>
142 * <li><strong>Set properties:</strong> for example setting the text of a
143 * {@link android.widget.TextView}. The available properties and the methods
144 * that set them will vary among the different subclasses of views. Note that
145 * properties that are known at build time can be set in the XML layout
146 * files.</li>
147 * <li><strong>Set focus:</strong> The framework will handled moving focus in
148 * response to user input. To force focus to a specific view, call
149 * {@link #requestFocus}.</li>
150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
151 * that will be notified when something interesting happens to the view. For
152 * example, all views will let you set a listener to be notified when the view
153 * gains or loses focus. You can register such a listener using
154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
155 * Other view subclasses offer more specialized listeners. For example, a Button
156 * exposes a listener to notify clients when the button is clicked.</li>
157 * <li><strong>Set visibility:</strong> You can hide or show views using
158 * {@link #setVisibility(int)}.</li>
159 * </ul>
160 * </p>
161 * <p><em>
162 * Note: The Android framework is responsible for measuring, laying out and
163 * drawing views. You should not call methods that perform these actions on
164 * views yourself unless you are actually implementing a
165 * {@link android.view.ViewGroup}.
166 * </em></p>
167 *
168 * <a name="Lifecycle"></a>
169 * <h3>Implementing a Custom View</h3>
170 *
171 * <p>
172 * To implement a custom view, you will usually begin by providing overrides for
173 * some of the standard methods that the framework calls on all views. You do
174 * not need to override all of these methods. In fact, you can start by just
175 * overriding {@link #onDraw(android.graphics.Canvas)}.
176 * <table border="2" width="85%" align="center" cellpadding="5">
177 *     <thead>
178 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
179 *     </thead>
180 *
181 *     <tbody>
182 *     <tr>
183 *         <td rowspan="2">Creation</td>
184 *         <td>Constructors</td>
185 *         <td>There is a form of the constructor that are called when the view
186 *         is created from code and a form that is called when the view is
187 *         inflated from a layout file. The second form should parse and apply
188 *         any attributes defined in the layout file.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onFinishInflate()}</code></td>
193 *         <td>Called after a view and all of its children has been inflated
194 *         from XML.</td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="3">Layout</td>
199 *         <td><code>{@link #onMeasure(int, int)}</code></td>
200 *         <td>Called to determine the size requirements for this view and all
201 *         of its children.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
206 *         <td>Called when this view should assign a size and position to all
207 *         of its children.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
212 *         <td>Called when the size of this view has changed.
213 *         </td>
214 *     </tr>
215 *
216 *     <tr>
217 *         <td>Drawing</td>
218 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
219 *         <td>Called when the view should render its content.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="4">Event processing</td>
225 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
226 *         <td>Called when a new hardware key event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
231 *         <td>Called when a hardware key up event occurs.
232 *         </td>
233 *     </tr>
234 *     <tr>
235 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
236 *         <td>Called when a trackball motion event occurs.
237 *         </td>
238 *     </tr>
239 *     <tr>
240 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
241 *         <td>Called when a touch screen motion event occurs.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="2">Focus</td>
247 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
248 *         <td>Called when the view gains or loses focus.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
254 *         <td>Called when the window containing the view gains or loses focus.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="3">Attaching</td>
260 *         <td><code>{@link #onAttachedToWindow()}</code></td>
261 *         <td>Called when the view is attached to a window.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onDetachedFromWindow}</code></td>
267 *         <td>Called when the view is detached from its window.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
273 *         <td>Called when the visibility of the window containing the view
274 *         has changed.
275 *         </td>
276 *     </tr>
277 *     </tbody>
278 *
279 * </table>
280 * </p>
281 *
282 * <a name="IDs"></a>
283 * <h3>IDs</h3>
284 * Views may have an integer id associated with them. These ids are typically
285 * assigned in the layout XML files, and are used to find specific views within
286 * the view tree. A common pattern is to:
287 * <ul>
288 * <li>Define a Button in the layout file and assign it a unique ID.
289 * <pre>
290 * &lt;Button
291 *     android:id="@+id/my_button"
292 *     android:layout_width="wrap_content"
293 *     android:layout_height="wrap_content"
294 *     android:text="@string/my_button_text"/&gt;
295 * </pre></li>
296 * <li>From the onCreate method of an Activity, find the Button
297 * <pre class="prettyprint">
298 *      Button myButton = (Button) findViewById(R.id.my_button);
299 * </pre></li>
300 * </ul>
301 * <p>
302 * View IDs need not be unique throughout the tree, but it is good practice to
303 * ensure that they are at least unique within the part of the tree you are
304 * searching.
305 * </p>
306 *
307 * <a name="Position"></a>
308 * <h3>Position</h3>
309 * <p>
310 * The geometry of a view is that of a rectangle. A view has a location,
311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
312 * two dimensions, expressed as a width and a height. The unit for location
313 * and dimensions is the pixel.
314 * </p>
315 *
316 * <p>
317 * It is possible to retrieve the location of a view by invoking the methods
318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
319 * coordinate of the rectangle representing the view. The latter returns the
320 * top, or Y, coordinate of the rectangle representing the view. These methods
321 * both return the location of the view relative to its parent. For instance,
322 * when getLeft() returns 20, that means the view is located 20 pixels to the
323 * right of the left edge of its direct parent.
324 * </p>
325 *
326 * <p>
327 * In addition, several convenience methods are offered to avoid unnecessary
328 * computations, namely {@link #getRight()} and {@link #getBottom()}.
329 * These methods return the coordinates of the right and bottom edges of the
330 * rectangle representing the view. For instance, calling {@link #getRight()}
331 * is similar to the following computation: <code>getLeft() + getWidth()</code>
332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
333 * </p>
334 *
335 * <a name="SizePaddingMargins"></a>
336 * <h3>Size, padding and margins</h3>
337 * <p>
338 * The size of a view is expressed with a width and a height. A view actually
339 * possess two pairs of width and height values.
340 * </p>
341 *
342 * <p>
343 * The first pair is known as <em>measured width</em> and
344 * <em>measured height</em>. These dimensions define how big a view wants to be
345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
347 * and {@link #getMeasuredHeight()}.
348 * </p>
349 *
350 * <p>
351 * The second pair is simply known as <em>width</em> and <em>height</em>, or
352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
353 * dimensions define the actual size of the view on screen, at drawing time and
354 * after layout. These values may, but do not have to, be different from the
355 * measured width and height. The width and height can be obtained by calling
356 * {@link #getWidth()} and {@link #getHeight()}.
357 * </p>
358 *
359 * <p>
360 * To measure its dimensions, a view takes into account its padding. The padding
361 * is expressed in pixels for the left, top, right and bottom parts of the view.
362 * Padding can be used to offset the content of the view by a specific amount of
363 * pixels. For instance, a left padding of 2 will push the view's content by
364 * 2 pixels to the right of the left edge. Padding can be set using the
365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
368 * {@link #getPaddingEnd()}.
369 * </p>
370 *
371 * <p>
372 * Even though a view can define a padding, it does not provide any support for
373 * margins. However, view groups provide such a support. Refer to
374 * {@link android.view.ViewGroup} and
375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
376 * </p>
377 *
378 * <a name="Layout"></a>
379 * <h3>Layout</h3>
380 * <p>
381 * Layout is a two pass process: a measure pass and a layout pass. The measuring
382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
383 * of the view tree. Each view pushes dimension specifications down the tree
384 * during the recursion. At the end of the measure pass, every view has stored
385 * its measurements. The second pass happens in
386 * {@link #layout(int,int,int,int)} and is also top-down. During
387 * this pass each parent is responsible for positioning all of its children
388 * using the sizes computed in the measure pass.
389 * </p>
390 *
391 * <p>
392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
393 * {@link #getMeasuredHeight()} values must be set, along with those for all of
394 * that view's descendants. A view's measured width and measured height values
395 * must respect the constraints imposed by the view's parents. This guarantees
396 * that at the end of the measure pass, all parents accept all of their
397 * children's measurements. A parent view may call measure() more than once on
398 * its children. For example, the parent may measure each child once with
399 * unspecified dimensions to find out how big they want to be, then call
400 * measure() on them again with actual numbers if the sum of all the children's
401 * unconstrained sizes is too big or too small.
402 * </p>
403 *
404 * <p>
405 * The measure pass uses two classes to communicate dimensions. The
406 * {@link MeasureSpec} class is used by views to tell their parents how they
407 * want to be measured and positioned. The base LayoutParams class just
408 * describes how big the view wants to be for both width and height. For each
409 * dimension, it can specify one of:
410 * <ul>
411 * <li> an exact number
412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
413 * (minus padding)
414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
415 * enclose its content (plus padding).
416 * </ul>
417 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
419 * an X and Y value.
420 * </p>
421 *
422 * <p>
423 * MeasureSpecs are used to push requirements down the tree from parent to
424 * child. A MeasureSpec can be in one of three modes:
425 * <ul>
426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
427 * of a child view. For example, a LinearLayout may call measure() on its child
428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
429 * tall the child view wants to be given a width of 240 pixels.
430 * <li>EXACTLY: This is used by the parent to impose an exact size on the
431 * child. The child must use this size, and guarantee that all of its
432 * descendants will fit within this size.
433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
434 * child. The child must guarantee that it and all of its descendants will fit
435 * within this size.
436 * </ul>
437 * </p>
438 *
439 * <p>
440 * To intiate a layout, call {@link #requestLayout}. This method is typically
441 * called by a view on itself when it believes that is can no longer fit within
442 * its current bounds.
443 * </p>
444 *
445 * <a name="Drawing"></a>
446 * <h3>Drawing</h3>
447 * <p>
448 * Drawing is handled by walking the tree and rendering each view that
449 * intersects the invalid region. Because the tree is traversed in-order,
450 * this means that parents will draw before (i.e., behind) their children, with
451 * siblings drawn in the order they appear in the tree.
452 * If you set a background drawable for a View, then the View will draw it for you
453 * before calling back to its <code>onDraw()</code> method.
454 * </p>
455 *
456 * <p>
457 * Note that the framework will not draw views that are not in the invalid region.
458 * </p>
459 *
460 * <p>
461 * To force a view to draw, call {@link #invalidate()}.
462 * </p>
463 *
464 * <a name="EventHandlingThreading"></a>
465 * <h3>Event Handling and Threading</h3>
466 * <p>
467 * The basic cycle of a view is as follows:
468 * <ol>
469 * <li>An event comes in and is dispatched to the appropriate view. The view
470 * handles the event and notifies any listeners.</li>
471 * <li>If in the course of processing the event, the view's bounds may need
472 * to be changed, the view will call {@link #requestLayout()}.</li>
473 * <li>Similarly, if in the course of processing the event the view's appearance
474 * may need to be changed, the view will call {@link #invalidate()}.</li>
475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
476 * the framework will take care of measuring, laying out, and drawing the tree
477 * as appropriate.</li>
478 * </ol>
479 * </p>
480 *
481 * <p><em>Note: The entire view tree is single threaded. You must always be on
482 * the UI thread when calling any method on any view.</em>
483 * If you are doing work on other threads and want to update the state of a view
484 * from that thread, you should use a {@link Handler}.
485 * </p>
486 *
487 * <a name="FocusHandling"></a>
488 * <h3>Focus Handling</h3>
489 * <p>
490 * The framework will handle routine focus movement in response to user input.
491 * This includes changing the focus as views are removed or hidden, or as new
492 * views become available. Views indicate their willingness to take focus
493 * through the {@link #isFocusable} method. To change whether a view can take
494 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
496 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
497 * </p>
498 * <p>
499 * Focus movement is based on an algorithm which finds the nearest neighbor in a
500 * given direction. In rare cases, the default algorithm may not match the
501 * intended behavior of the developer. In these situations, you can provide
502 * explicit overrides by using these XML attributes in the layout file:
503 * <pre>
504 * nextFocusDown
505 * nextFocusLeft
506 * nextFocusRight
507 * nextFocusUp
508 * </pre>
509 * </p>
510 *
511 *
512 * <p>
513 * To get a particular view to take focus, call {@link #requestFocus()}.
514 * </p>
515 *
516 * <a name="TouchMode"></a>
517 * <h3>Touch Mode</h3>
518 * <p>
519 * When a user is navigating a user interface via directional keys such as a D-pad, it is
520 * necessary to give focus to actionable items such as buttons so the user can see
521 * what will take input.  If the device has touch capabilities, however, and the user
522 * begins interacting with the interface by touching it, it is no longer necessary to
523 * always highlight, or give focus to, a particular view.  This motivates a mode
524 * for interaction named 'touch mode'.
525 * </p>
526 * <p>
527 * For a touch capable device, once the user touches the screen, the device
528 * will enter touch mode.  From this point onward, only views for which
529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
530 * Other views that are touchable, like buttons, will not take focus when touched; they will
531 * only fire the on click listeners.
532 * </p>
533 * <p>
534 * Any time a user hits a directional key, such as a D-pad direction, the view device will
535 * exit touch mode, and find a view to take focus, so that the user may resume interacting
536 * with the user interface without touching the screen again.
537 * </p>
538 * <p>
539 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
540 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
541 * </p>
542 *
543 * <a name="Scrolling"></a>
544 * <h3>Scrolling</h3>
545 * <p>
546 * The framework provides basic support for views that wish to internally
547 * scroll their content. This includes keeping track of the X and Y scroll
548 * offset as well as mechanisms for drawing scrollbars. See
549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
550 * {@link #awakenScrollBars()} for more details.
551 * </p>
552 *
553 * <a name="Tags"></a>
554 * <h3>Tags</h3>
555 * <p>
556 * Unlike IDs, tags are not used to identify views. Tags are essentially an
557 * extra piece of information that can be associated with a view. They are most
558 * often used as a convenience to store data related to views in the views
559 * themselves rather than by putting them in a separate structure.
560 * </p>
561 *
562 * <a name="Properties"></a>
563 * <h3>Properties</h3>
564 * <p>
565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
567 * available both in the {@link Property} form as well as in similarly-named setter/getter
568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
569 * be used to set persistent state associated with these rendering-related properties on the view.
570 * The properties and methods can also be used in conjunction with
571 * {@link android.animation.Animator Animator}-based animations, described more in the
572 * <a href="#Animation">Animation</a> section.
573 * </p>
574 *
575 * <a name="Animation"></a>
576 * <h3>Animation</h3>
577 * <p>
578 * Starting with Android 3.0, the preferred way of animating views is to use the
579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
584 * makes animating these View properties particularly easy and efficient.
585 * </p>
586 * <p>
587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
588 * You can attach an {@link Animation} object to a view using
589 * {@link #setAnimation(Animation)} or
590 * {@link #startAnimation(Animation)}. The animation can alter the scale,
591 * rotation, translation and alpha of a view over time. If the animation is
592 * attached to a view that has children, the animation will affect the entire
593 * subtree rooted by that node. When an animation is started, the framework will
594 * take care of redrawing the appropriate views until the animation completes.
595 * </p>
596 *
597 * <a name="Security"></a>
598 * <h3>Security</h3>
599 * <p>
600 * Sometimes it is essential that an application be able to verify that an action
601 * is being performed with the full knowledge and consent of the user, such as
602 * granting a permission request, making a purchase or clicking on an advertisement.
603 * Unfortunately, a malicious application could try to spoof the user into
604 * performing these actions, unaware, by concealing the intended purpose of the view.
605 * As a remedy, the framework offers a touch filtering mechanism that can be used to
606 * improve the security of views that provide access to sensitive functionality.
607 * </p><p>
608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
609 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
610 * will discard touches that are received whenever the view's window is obscured by
611 * another visible window.  As a result, the view will not receive touches whenever a
612 * toast, dialog or other window appears above the view's window.
613 * </p><p>
614 * For more fine-grained control over security, consider overriding the
615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
617 * </p>
618 *
619 * @attr ref android.R.styleable#View_alpha
620 * @attr ref android.R.styleable#View_background
621 * @attr ref android.R.styleable#View_clickable
622 * @attr ref android.R.styleable#View_contentDescription
623 * @attr ref android.R.styleable#View_drawingCacheQuality
624 * @attr ref android.R.styleable#View_duplicateParentState
625 * @attr ref android.R.styleable#View_id
626 * @attr ref android.R.styleable#View_requiresFadingEdge
627 * @attr ref android.R.styleable#View_fadeScrollbars
628 * @attr ref android.R.styleable#View_fadingEdgeLength
629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
630 * @attr ref android.R.styleable#View_fitsSystemWindows
631 * @attr ref android.R.styleable#View_isScrollContainer
632 * @attr ref android.R.styleable#View_focusable
633 * @attr ref android.R.styleable#View_focusableInTouchMode
634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
635 * @attr ref android.R.styleable#View_keepScreenOn
636 * @attr ref android.R.styleable#View_layerType
637 * @attr ref android.R.styleable#View_layoutDirection
638 * @attr ref android.R.styleable#View_longClickable
639 * @attr ref android.R.styleable#View_minHeight
640 * @attr ref android.R.styleable#View_minWidth
641 * @attr ref android.R.styleable#View_nextFocusDown
642 * @attr ref android.R.styleable#View_nextFocusLeft
643 * @attr ref android.R.styleable#View_nextFocusRight
644 * @attr ref android.R.styleable#View_nextFocusUp
645 * @attr ref android.R.styleable#View_onClick
646 * @attr ref android.R.styleable#View_padding
647 * @attr ref android.R.styleable#View_paddingBottom
648 * @attr ref android.R.styleable#View_paddingLeft
649 * @attr ref android.R.styleable#View_paddingRight
650 * @attr ref android.R.styleable#View_paddingTop
651 * @attr ref android.R.styleable#View_paddingStart
652 * @attr ref android.R.styleable#View_paddingEnd
653 * @attr ref android.R.styleable#View_saveEnabled
654 * @attr ref android.R.styleable#View_rotation
655 * @attr ref android.R.styleable#View_rotationX
656 * @attr ref android.R.styleable#View_rotationY
657 * @attr ref android.R.styleable#View_scaleX
658 * @attr ref android.R.styleable#View_scaleY
659 * @attr ref android.R.styleable#View_scrollX
660 * @attr ref android.R.styleable#View_scrollY
661 * @attr ref android.R.styleable#View_scrollbarSize
662 * @attr ref android.R.styleable#View_scrollbarStyle
663 * @attr ref android.R.styleable#View_scrollbars
664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
665 * @attr ref android.R.styleable#View_scrollbarFadeDuration
666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
668 * @attr ref android.R.styleable#View_scrollbarThumbVertical
669 * @attr ref android.R.styleable#View_scrollbarTrackVertical
670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
672 * @attr ref android.R.styleable#View_stateListAnimator
673 * @attr ref android.R.styleable#View_transitionName
674 * @attr ref android.R.styleable#View_soundEffectsEnabled
675 * @attr ref android.R.styleable#View_tag
676 * @attr ref android.R.styleable#View_textAlignment
677 * @attr ref android.R.styleable#View_textDirection
678 * @attr ref android.R.styleable#View_transformPivotX
679 * @attr ref android.R.styleable#View_transformPivotY
680 * @attr ref android.R.styleable#View_translationX
681 * @attr ref android.R.styleable#View_translationY
682 * @attr ref android.R.styleable#View_translationZ
683 * @attr ref android.R.styleable#View_visibility
684 *
685 * @see android.view.ViewGroup
686 */
687public class View implements Drawable.Callback, KeyEvent.Callback,
688        AccessibilityEventSource {
689    private static final boolean DBG = false;
690
691    /**
692     * The logging tag used by this class with android.util.Log.
693     */
694    protected static final String VIEW_LOG_TAG = "View";
695
696    /**
697     * When set to true, apps will draw debugging information about their layouts.
698     *
699     * @hide
700     */
701    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
702
703    /**
704     * Used to mark a View that has no ID.
705     */
706    public static final int NO_ID = -1;
707
708    /**
709     * Signals that compatibility booleans have been initialized according to
710     * target SDK versions.
711     */
712    private static boolean sCompatibilityDone = false;
713
714    /**
715     * Use the old (broken) way of building MeasureSpecs.
716     */
717    private static boolean sUseBrokenMakeMeasureSpec = false;
718
719    /**
720     * Ignore any optimizations using the measure cache.
721     */
722    private static boolean sIgnoreMeasureCache = false;
723
724    /**
725     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
726     * calling setFlags.
727     */
728    private static final int NOT_FOCUSABLE = 0x00000000;
729
730    /**
731     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
732     * setFlags.
733     */
734    private static final int FOCUSABLE = 0x00000001;
735
736    /**
737     * Mask for use with setFlags indicating bits used for focus.
738     */
739    private static final int FOCUSABLE_MASK = 0x00000001;
740
741    /**
742     * This view will adjust its padding to fit sytem windows (e.g. status bar)
743     */
744    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
745
746    /** @hide */
747    @IntDef({VISIBLE, INVISIBLE, GONE})
748    @Retention(RetentionPolicy.SOURCE)
749    public @interface Visibility {}
750
751    /**
752     * This view is visible.
753     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
754     * android:visibility}.
755     */
756    public static final int VISIBLE = 0x00000000;
757
758    /**
759     * This view is invisible, but it still takes up space for layout purposes.
760     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
761     * android:visibility}.
762     */
763    public static final int INVISIBLE = 0x00000004;
764
765    /**
766     * This view is invisible, and it doesn't take any space for layout
767     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
768     * android:visibility}.
769     */
770    public static final int GONE = 0x00000008;
771
772    /**
773     * Mask for use with setFlags indicating bits used for visibility.
774     * {@hide}
775     */
776    static final int VISIBILITY_MASK = 0x0000000C;
777
778    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
779
780    /**
781     * This view is enabled. Interpretation varies by subclass.
782     * Use with ENABLED_MASK when calling setFlags.
783     * {@hide}
784     */
785    static final int ENABLED = 0x00000000;
786
787    /**
788     * This view is disabled. Interpretation varies by subclass.
789     * Use with ENABLED_MASK when calling setFlags.
790     * {@hide}
791     */
792    static final int DISABLED = 0x00000020;
793
794   /**
795    * Mask for use with setFlags indicating bits used for indicating whether
796    * this view is enabled
797    * {@hide}
798    */
799    static final int ENABLED_MASK = 0x00000020;
800
801    /**
802     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
803     * called and further optimizations will be performed. It is okay to have
804     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
805     * {@hide}
806     */
807    static final int WILL_NOT_DRAW = 0x00000080;
808
809    /**
810     * Mask for use with setFlags indicating bits used for indicating whether
811     * this view is will draw
812     * {@hide}
813     */
814    static final int DRAW_MASK = 0x00000080;
815
816    /**
817     * <p>This view doesn't show scrollbars.</p>
818     * {@hide}
819     */
820    static final int SCROLLBARS_NONE = 0x00000000;
821
822    /**
823     * <p>This view shows horizontal scrollbars.</p>
824     * {@hide}
825     */
826    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
827
828    /**
829     * <p>This view shows vertical scrollbars.</p>
830     * {@hide}
831     */
832    static final int SCROLLBARS_VERTICAL = 0x00000200;
833
834    /**
835     * <p>Mask for use with setFlags indicating bits used for indicating which
836     * scrollbars are enabled.</p>
837     * {@hide}
838     */
839    static final int SCROLLBARS_MASK = 0x00000300;
840
841    /**
842     * Indicates that the view should filter touches when its window is obscured.
843     * Refer to the class comments for more information about this security feature.
844     * {@hide}
845     */
846    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
847
848    /**
849     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
850     * that they are optional and should be skipped if the window has
851     * requested system UI flags that ignore those insets for layout.
852     */
853    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
854
855    /**
856     * <p>This view doesn't show fading edges.</p>
857     * {@hide}
858     */
859    static final int FADING_EDGE_NONE = 0x00000000;
860
861    /**
862     * <p>This view shows horizontal fading edges.</p>
863     * {@hide}
864     */
865    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
866
867    /**
868     * <p>This view shows vertical fading edges.</p>
869     * {@hide}
870     */
871    static final int FADING_EDGE_VERTICAL = 0x00002000;
872
873    /**
874     * <p>Mask for use with setFlags indicating bits used for indicating which
875     * fading edges are enabled.</p>
876     * {@hide}
877     */
878    static final int FADING_EDGE_MASK = 0x00003000;
879
880    /**
881     * <p>Indicates this view can be clicked. When clickable, a View reacts
882     * to clicks by notifying the OnClickListener.<p>
883     * {@hide}
884     */
885    static final int CLICKABLE = 0x00004000;
886
887    /**
888     * <p>Indicates this view is caching its drawing into a bitmap.</p>
889     * {@hide}
890     */
891    static final int DRAWING_CACHE_ENABLED = 0x00008000;
892
893    /**
894     * <p>Indicates that no icicle should be saved for this view.<p>
895     * {@hide}
896     */
897    static final int SAVE_DISABLED = 0x000010000;
898
899    /**
900     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
901     * property.</p>
902     * {@hide}
903     */
904    static final int SAVE_DISABLED_MASK = 0x000010000;
905
906    /**
907     * <p>Indicates that no drawing cache should ever be created for this view.<p>
908     * {@hide}
909     */
910    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
911
912    /**
913     * <p>Indicates this view can take / keep focus when int touch mode.</p>
914     * {@hide}
915     */
916    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
917
918    /** @hide */
919    @Retention(RetentionPolicy.SOURCE)
920    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
921    public @interface DrawingCacheQuality {}
922
923    /**
924     * <p>Enables low quality mode for the drawing cache.</p>
925     */
926    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
927
928    /**
929     * <p>Enables high quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
932
933    /**
934     * <p>Enables automatic quality mode for the drawing cache.</p>
935     */
936    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
937
938    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
939            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
940    };
941
942    /**
943     * <p>Mask for use with setFlags indicating bits used for the cache
944     * quality property.</p>
945     * {@hide}
946     */
947    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
948
949    /**
950     * <p>
951     * Indicates this view can be long clicked. When long clickable, a View
952     * reacts to long clicks by notifying the OnLongClickListener or showing a
953     * context menu.
954     * </p>
955     * {@hide}
956     */
957    static final int LONG_CLICKABLE = 0x00200000;
958
959    /**
960     * <p>Indicates that this view gets its drawable states from its direct parent
961     * and ignores its original internal states.</p>
962     *
963     * @hide
964     */
965    static final int DUPLICATE_PARENT_STATE = 0x00400000;
966
967    /** @hide */
968    @IntDef({
969        SCROLLBARS_INSIDE_OVERLAY,
970        SCROLLBARS_INSIDE_INSET,
971        SCROLLBARS_OUTSIDE_OVERLAY,
972        SCROLLBARS_OUTSIDE_INSET
973    })
974    @Retention(RetentionPolicy.SOURCE)
975    public @interface ScrollBarStyle {}
976
977    /**
978     * The scrollbar style to display the scrollbars inside the content area,
979     * without increasing the padding. The scrollbars will be overlaid with
980     * translucency on the view's content.
981     */
982    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
983
984    /**
985     * The scrollbar style to display the scrollbars inside the padded area,
986     * increasing the padding of the view. The scrollbars will not overlap the
987     * content area of the view.
988     */
989    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
990
991    /**
992     * The scrollbar style to display the scrollbars at the edge of the view,
993     * without increasing the padding. The scrollbars will be overlaid with
994     * translucency.
995     */
996    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
997
998    /**
999     * The scrollbar style to display the scrollbars at the edge of the view,
1000     * increasing the padding of the view. The scrollbars will only overlap the
1001     * background, if any.
1002     */
1003    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1004
1005    /**
1006     * Mask to check if the scrollbar style is overlay or inset.
1007     * {@hide}
1008     */
1009    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1010
1011    /**
1012     * Mask to check if the scrollbar style is inside or outside.
1013     * {@hide}
1014     */
1015    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1016
1017    /**
1018     * Mask for scrollbar style.
1019     * {@hide}
1020     */
1021    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1022
1023    /**
1024     * View flag indicating that the screen should remain on while the
1025     * window containing this view is visible to the user.  This effectively
1026     * takes care of automatically setting the WindowManager's
1027     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1028     */
1029    public static final int KEEP_SCREEN_ON = 0x04000000;
1030
1031    /**
1032     * View flag indicating whether this view should have sound effects enabled
1033     * for events such as clicking and touching.
1034     */
1035    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1036
1037    /**
1038     * View flag indicating whether this view should have haptic feedback
1039     * enabled for events such as long presses.
1040     */
1041    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1042
1043    /**
1044     * <p>Indicates that the view hierarchy should stop saving state when
1045     * it reaches this view.  If state saving is initiated immediately at
1046     * the view, it will be allowed.
1047     * {@hide}
1048     */
1049    static final int PARENT_SAVE_DISABLED = 0x20000000;
1050
1051    /**
1052     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1053     * {@hide}
1054     */
1055    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1056
1057    /** @hide */
1058    @IntDef(flag = true,
1059            value = {
1060                FOCUSABLES_ALL,
1061                FOCUSABLES_TOUCH_MODE
1062            })
1063    @Retention(RetentionPolicy.SOURCE)
1064    public @interface FocusableMode {}
1065
1066    /**
1067     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1068     * should add all focusable Views regardless if they are focusable in touch mode.
1069     */
1070    public static final int FOCUSABLES_ALL = 0x00000000;
1071
1072    /**
1073     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1074     * should add only Views focusable in touch mode.
1075     */
1076    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1077
1078    /** @hide */
1079    @IntDef({
1080            FOCUS_BACKWARD,
1081            FOCUS_FORWARD,
1082            FOCUS_LEFT,
1083            FOCUS_UP,
1084            FOCUS_RIGHT,
1085            FOCUS_DOWN
1086    })
1087    @Retention(RetentionPolicy.SOURCE)
1088    public @interface FocusDirection {}
1089
1090    /** @hide */
1091    @IntDef({
1092            FOCUS_LEFT,
1093            FOCUS_UP,
1094            FOCUS_RIGHT,
1095            FOCUS_DOWN
1096    })
1097    @Retention(RetentionPolicy.SOURCE)
1098    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1099
1100    /**
1101     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1102     * item.
1103     */
1104    public static final int FOCUS_BACKWARD = 0x00000001;
1105
1106    /**
1107     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1108     * item.
1109     */
1110    public static final int FOCUS_FORWARD = 0x00000002;
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus to the left.
1114     */
1115    public static final int FOCUS_LEFT = 0x00000011;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus up.
1119     */
1120    public static final int FOCUS_UP = 0x00000021;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus to the right.
1124     */
1125    public static final int FOCUS_RIGHT = 0x00000042;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus down.
1129     */
1130    public static final int FOCUS_DOWN = 0x00000082;
1131
1132    /**
1133     * Bits of {@link #getMeasuredWidthAndState()} and
1134     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1135     */
1136    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1137
1138    /**
1139     * Bits of {@link #getMeasuredWidthAndState()} and
1140     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1141     */
1142    public static final int MEASURED_STATE_MASK = 0xff000000;
1143
1144    /**
1145     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1146     * for functions that combine both width and height into a single int,
1147     * such as {@link #getMeasuredState()} and the childState argument of
1148     * {@link #resolveSizeAndState(int, int, int)}.
1149     */
1150    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1151
1152    /**
1153     * Bit of {@link #getMeasuredWidthAndState()} and
1154     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1155     * is smaller that the space the view would like to have.
1156     */
1157    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1158
1159    /**
1160     * Base View state sets
1161     */
1162    // Singles
1163    /**
1164     * Indicates the view has no states set. States are used with
1165     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1166     * view depending on its state.
1167     *
1168     * @see android.graphics.drawable.Drawable
1169     * @see #getDrawableState()
1170     */
1171    protected static final int[] EMPTY_STATE_SET;
1172    /**
1173     * Indicates the view is enabled. States are used with
1174     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1175     * view depending on its state.
1176     *
1177     * @see android.graphics.drawable.Drawable
1178     * @see #getDrawableState()
1179     */
1180    protected static final int[] ENABLED_STATE_SET;
1181    /**
1182     * Indicates the view is focused. States are used with
1183     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1184     * view depending on its state.
1185     *
1186     * @see android.graphics.drawable.Drawable
1187     * @see #getDrawableState()
1188     */
1189    protected static final int[] FOCUSED_STATE_SET;
1190    /**
1191     * Indicates the view is selected. States are used with
1192     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1193     * view depending on its state.
1194     *
1195     * @see android.graphics.drawable.Drawable
1196     * @see #getDrawableState()
1197     */
1198    protected static final int[] SELECTED_STATE_SET;
1199    /**
1200     * Indicates the view is pressed. States are used with
1201     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1202     * view depending on its state.
1203     *
1204     * @see android.graphics.drawable.Drawable
1205     * @see #getDrawableState()
1206     */
1207    protected static final int[] PRESSED_STATE_SET;
1208    /**
1209     * Indicates the view's window has focus. States are used with
1210     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1211     * view depending on its state.
1212     *
1213     * @see android.graphics.drawable.Drawable
1214     * @see #getDrawableState()
1215     */
1216    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1217    // Doubles
1218    /**
1219     * Indicates the view is enabled and has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled and selected.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #SELECTED_STATE_SET
1230     */
1231    protected static final int[] ENABLED_SELECTED_STATE_SET;
1232    /**
1233     * Indicates the view is enabled and that its window has focus.
1234     *
1235     * @see #ENABLED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is focused and selected.
1241     *
1242     * @see #FOCUSED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     */
1245    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1246    /**
1247     * Indicates the view has the focus and that its window has the focus.
1248     *
1249     * @see #FOCUSED_STATE_SET
1250     * @see #WINDOW_FOCUSED_STATE_SET
1251     */
1252    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is selected and that its window has the focus.
1255     *
1256     * @see #SELECTED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1260    // Triples
1261    /**
1262     * Indicates the view is enabled, focused and selected.
1263     *
1264     * @see #ENABLED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is enabled, focused and its window has the focus.
1271     *
1272     * @see #ENABLED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is enabled, selected and its window has the focus.
1279     *
1280     * @see #ENABLED_STATE_SET
1281     * @see #SELECTED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is focused, selected and its window has the focus.
1287     *
1288     * @see #FOCUSED_STATE_SET
1289     * @see #SELECTED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is enabled, focused, selected and its window
1295     * has the focus.
1296     *
1297     * @see #ENABLED_STATE_SET
1298     * @see #FOCUSED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    /**
1304     * Indicates the view is pressed and its window has the focus.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and selected.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #SELECTED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_SELECTED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed, selected and its window has the focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed and focused.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, focused and its window has the focus.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #FOCUSED_STATE_SET
1337     * @see #WINDOW_FOCUSED_STATE_SET
1338     */
1339    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1340    /**
1341     * Indicates the view is pressed, focused and selected.
1342     *
1343     * @see #PRESSED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1348    /**
1349     * Indicates the view is pressed, focused, selected and its window has the focus.
1350     *
1351     * @see #PRESSED_STATE_SET
1352     * @see #FOCUSED_STATE_SET
1353     * @see #SELECTED_STATE_SET
1354     * @see #WINDOW_FOCUSED_STATE_SET
1355     */
1356    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1357    /**
1358     * Indicates the view is pressed and enabled.
1359     *
1360     * @see #PRESSED_STATE_SET
1361     * @see #ENABLED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled and its window has the focus.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #WINDOW_FOCUSED_STATE_SET
1370     */
1371    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1372    /**
1373     * Indicates the view is pressed, enabled and selected.
1374     *
1375     * @see #PRESSED_STATE_SET
1376     * @see #ENABLED_STATE_SET
1377     * @see #SELECTED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1380    /**
1381     * Indicates the view is pressed, enabled, selected and its window has the
1382     * focus.
1383     *
1384     * @see #PRESSED_STATE_SET
1385     * @see #ENABLED_STATE_SET
1386     * @see #SELECTED_STATE_SET
1387     * @see #WINDOW_FOCUSED_STATE_SET
1388     */
1389    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1390    /**
1391     * Indicates the view is pressed, enabled and focused.
1392     *
1393     * @see #PRESSED_STATE_SET
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     */
1397    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is pressed, enabled, focused and its window has the
1400     * focus.
1401     *
1402     * @see #PRESSED_STATE_SET
1403     * @see #ENABLED_STATE_SET
1404     * @see #FOCUSED_STATE_SET
1405     * @see #WINDOW_FOCUSED_STATE_SET
1406     */
1407    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1408    /**
1409     * Indicates the view is pressed, enabled, focused and selected.
1410     *
1411     * @see #PRESSED_STATE_SET
1412     * @see #ENABLED_STATE_SET
1413     * @see #SELECTED_STATE_SET
1414     * @see #FOCUSED_STATE_SET
1415     */
1416    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1417    /**
1418     * Indicates the view is pressed, enabled, focused, selected and its window
1419     * has the focus.
1420     *
1421     * @see #PRESSED_STATE_SET
1422     * @see #ENABLED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     * @see #FOCUSED_STATE_SET
1425     * @see #WINDOW_FOCUSED_STATE_SET
1426     */
1427    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1428
1429    /**
1430     * The order here is very important to {@link #getDrawableState()}
1431     */
1432    private static final int[][] VIEW_STATE_SETS;
1433
1434    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1435    static final int VIEW_STATE_SELECTED = 1 << 1;
1436    static final int VIEW_STATE_FOCUSED = 1 << 2;
1437    static final int VIEW_STATE_ENABLED = 1 << 3;
1438    static final int VIEW_STATE_PRESSED = 1 << 4;
1439    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1440    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1441    static final int VIEW_STATE_HOVERED = 1 << 7;
1442    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1443    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1444
1445    static final int[] VIEW_STATE_IDS = new int[] {
1446        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1447        R.attr.state_selected,          VIEW_STATE_SELECTED,
1448        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1449        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1450        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1451        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1452        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1453        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1454        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1455        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1456    };
1457
1458    static {
1459        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1460            throw new IllegalStateException(
1461                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1462        }
1463        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1464        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1465            int viewState = R.styleable.ViewDrawableStates[i];
1466            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1467                if (VIEW_STATE_IDS[j] == viewState) {
1468                    orderedIds[i * 2] = viewState;
1469                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1470                }
1471            }
1472        }
1473        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1474        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1475        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1476            int numBits = Integer.bitCount(i);
1477            int[] set = new int[numBits];
1478            int pos = 0;
1479            for (int j = 0; j < orderedIds.length; j += 2) {
1480                if ((i & orderedIds[j+1]) != 0) {
1481                    set[pos++] = orderedIds[j];
1482                }
1483            }
1484            VIEW_STATE_SETS[i] = set;
1485        }
1486
1487        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1488        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1489        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1490        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1492        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1493        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1495        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1497        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1499                | VIEW_STATE_FOCUSED];
1500        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1501        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1503        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1505        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1507                | VIEW_STATE_ENABLED];
1508        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1510        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1515                | VIEW_STATE_ENABLED];
1516        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1518                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1519
1520        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1521        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1523        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1525        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1527                | VIEW_STATE_PRESSED];
1528        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1530        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1535                | VIEW_STATE_PRESSED];
1536        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1538                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1539        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1541        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1543                | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1546                | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1549                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1552                | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1555                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1558                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1559        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1560                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1561                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1562                | VIEW_STATE_PRESSED];
1563    }
1564
1565    /**
1566     * Accessibility event types that are dispatched for text population.
1567     */
1568    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1569            AccessibilityEvent.TYPE_VIEW_CLICKED
1570            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1571            | AccessibilityEvent.TYPE_VIEW_SELECTED
1572            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1573            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1574            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1575            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1576            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1577            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1578            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1579            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1580
1581    /**
1582     * Temporary Rect currently for use in setBackground().  This will probably
1583     * be extended in the future to hold our own class with more than just
1584     * a Rect. :)
1585     */
1586    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1587
1588    /**
1589     * Map used to store views' tags.
1590     */
1591    private SparseArray<Object> mKeyedTags;
1592
1593    /**
1594     * The next available accessibility id.
1595     */
1596    private static int sNextAccessibilityViewId;
1597
1598    /**
1599     * The animation currently associated with this view.
1600     * @hide
1601     */
1602    protected Animation mCurrentAnimation = null;
1603
1604    /**
1605     * Width as measured during measure pass.
1606     * {@hide}
1607     */
1608    @ViewDebug.ExportedProperty(category = "measurement")
1609    int mMeasuredWidth;
1610
1611    /**
1612     * Height as measured during measure pass.
1613     * {@hide}
1614     */
1615    @ViewDebug.ExportedProperty(category = "measurement")
1616    int mMeasuredHeight;
1617
1618    /**
1619     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1620     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1621     * its display list. This flag, used only when hw accelerated, allows us to clear the
1622     * flag while retaining this information until it's needed (at getDisplayList() time and
1623     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1624     *
1625     * {@hide}
1626     */
1627    boolean mRecreateDisplayList = false;
1628
1629    /**
1630     * The view's identifier.
1631     * {@hide}
1632     *
1633     * @see #setId(int)
1634     * @see #getId()
1635     */
1636    @ViewDebug.ExportedProperty(resolveId = true)
1637    int mID = NO_ID;
1638
1639    /**
1640     * The stable ID of this view for accessibility purposes.
1641     */
1642    int mAccessibilityViewId = NO_ID;
1643
1644    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1645
1646    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1647
1648    /**
1649     * The view's tag.
1650     * {@hide}
1651     *
1652     * @see #setTag(Object)
1653     * @see #getTag()
1654     */
1655    protected Object mTag = null;
1656
1657    // for mPrivateFlags:
1658    /** {@hide} */
1659    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1660    /** {@hide} */
1661    static final int PFLAG_FOCUSED                     = 0x00000002;
1662    /** {@hide} */
1663    static final int PFLAG_SELECTED                    = 0x00000004;
1664    /** {@hide} */
1665    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1666    /** {@hide} */
1667    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1668    /** {@hide} */
1669    static final int PFLAG_DRAWN                       = 0x00000020;
1670    /**
1671     * When this flag is set, this view is running an animation on behalf of its
1672     * children and should therefore not cancel invalidate requests, even if they
1673     * lie outside of this view's bounds.
1674     *
1675     * {@hide}
1676     */
1677    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1678    /** {@hide} */
1679    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1680    /** {@hide} */
1681    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1682    /** {@hide} */
1683    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1684    /** {@hide} */
1685    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1686    /** {@hide} */
1687    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1688    /** {@hide} */
1689    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1690    /** {@hide} */
1691    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1692
1693    private static final int PFLAG_PRESSED             = 0x00004000;
1694
1695    /** {@hide} */
1696    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1697    /**
1698     * Flag used to indicate that this view should be drawn once more (and only once
1699     * more) after its animation has completed.
1700     * {@hide}
1701     */
1702    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1703
1704    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1705
1706    /**
1707     * Indicates that the View returned true when onSetAlpha() was called and that
1708     * the alpha must be restored.
1709     * {@hide}
1710     */
1711    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1712
1713    /**
1714     * Set by {@link #setScrollContainer(boolean)}.
1715     */
1716    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1717
1718    /**
1719     * Set by {@link #setScrollContainer(boolean)}.
1720     */
1721    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1722
1723    /**
1724     * View flag indicating whether this view was invalidated (fully or partially.)
1725     *
1726     * @hide
1727     */
1728    static final int PFLAG_DIRTY                       = 0x00200000;
1729
1730    /**
1731     * View flag indicating whether this view was invalidated by an opaque
1732     * invalidate request.
1733     *
1734     * @hide
1735     */
1736    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1737
1738    /**
1739     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1740     *
1741     * @hide
1742     */
1743    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1744
1745    /**
1746     * Indicates whether the background is opaque.
1747     *
1748     * @hide
1749     */
1750    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1751
1752    /**
1753     * Indicates whether the scrollbars are opaque.
1754     *
1755     * @hide
1756     */
1757    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1758
1759    /**
1760     * Indicates whether the view is opaque.
1761     *
1762     * @hide
1763     */
1764    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1765
1766    /**
1767     * Indicates a prepressed state;
1768     * the short time between ACTION_DOWN and recognizing
1769     * a 'real' press. Prepressed is used to recognize quick taps
1770     * even when they are shorter than ViewConfiguration.getTapTimeout().
1771     *
1772     * @hide
1773     */
1774    private static final int PFLAG_PREPRESSED          = 0x02000000;
1775
1776    /**
1777     * Indicates whether the view is temporarily detached.
1778     *
1779     * @hide
1780     */
1781    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1782
1783    /**
1784     * Indicates that we should awaken scroll bars once attached
1785     *
1786     * @hide
1787     */
1788    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1789
1790    /**
1791     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1792     * @hide
1793     */
1794    private static final int PFLAG_HOVERED             = 0x10000000;
1795
1796    /**
1797     * no longer needed, should be reused
1798     */
1799    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1800
1801    /** {@hide} */
1802    static final int PFLAG_ACTIVATED                   = 0x40000000;
1803
1804    /**
1805     * Indicates that this view was specifically invalidated, not just dirtied because some
1806     * child view was invalidated. The flag is used to determine when we need to recreate
1807     * a view's display list (as opposed to just returning a reference to its existing
1808     * display list).
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_INVALIDATED                 = 0x80000000;
1813
1814    /**
1815     * Masks for mPrivateFlags2, as generated by dumpFlags():
1816     *
1817     * |-------|-------|-------|-------|
1818     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1819     *                                1  PFLAG2_DRAG_HOVERED
1820     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1821     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1822     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1823     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1824     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1825     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1826     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1827     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1828     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1829     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1830     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1831     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1832     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1833     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1834     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1835     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1836     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1837     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1838     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1839     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1840     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1841     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1842     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1843     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1844     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1845     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1846     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1847     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1848     *    1                              PFLAG2_PADDING_RESOLVED
1849     *   1                               PFLAG2_DRAWABLE_RESOLVED
1850     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1851     * |-------|-------|-------|-------|
1852     */
1853
1854    /**
1855     * Indicates that this view has reported that it can accept the current drag's content.
1856     * Cleared when the drag operation concludes.
1857     * @hide
1858     */
1859    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1860
1861    /**
1862     * Indicates that this view is currently directly under the drag location in a
1863     * drag-and-drop operation involving content that it can accept.  Cleared when
1864     * the drag exits the view, or when the drag operation concludes.
1865     * @hide
1866     */
1867    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1868
1869    /** @hide */
1870    @IntDef({
1871        LAYOUT_DIRECTION_LTR,
1872        LAYOUT_DIRECTION_RTL,
1873        LAYOUT_DIRECTION_INHERIT,
1874        LAYOUT_DIRECTION_LOCALE
1875    })
1876    @Retention(RetentionPolicy.SOURCE)
1877    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1878    public @interface LayoutDir {}
1879
1880    /** @hide */
1881    @IntDef({
1882        LAYOUT_DIRECTION_LTR,
1883        LAYOUT_DIRECTION_RTL
1884    })
1885    @Retention(RetentionPolicy.SOURCE)
1886    public @interface ResolvedLayoutDir {}
1887
1888    /**
1889     * Horizontal layout direction of this view is from Left to Right.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1893
1894    /**
1895     * Horizontal layout direction of this view is from Right to Left.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1899
1900    /**
1901     * Horizontal layout direction of this view is inherited from its parent.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1905
1906    /**
1907     * Horizontal layout direction of this view is from deduced from the default language
1908     * script for the locale. Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1911
1912    /**
1913     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1917
1918    /**
1919     * Mask for use with private flags indicating bits used for horizontal layout direction.
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1923
1924    /**
1925     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1926     * right-to-left direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1942            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /*
1945     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1946     * flag value.
1947     * @hide
1948     */
1949    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1950            LAYOUT_DIRECTION_LTR,
1951            LAYOUT_DIRECTION_RTL,
1952            LAYOUT_DIRECTION_INHERIT,
1953            LAYOUT_DIRECTION_LOCALE
1954    };
1955
1956    /**
1957     * Default horizontal layout direction.
1958     */
1959    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1960
1961    /**
1962     * Default horizontal layout direction.
1963     * @hide
1964     */
1965    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1966
1967    /**
1968     * Text direction is inherited thru {@link ViewGroup}
1969     */
1970    public static final int TEXT_DIRECTION_INHERIT = 0;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is the view's resolved layout direction.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1978
1979    /**
1980     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1981     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1982     * If there are neither, the paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1985
1986    /**
1987     * Text direction is forced to LTR.
1988     */
1989    public static final int TEXT_DIRECTION_LTR = 3;
1990
1991    /**
1992     * Text direction is forced to RTL.
1993     */
1994    public static final int TEXT_DIRECTION_RTL = 4;
1995
1996    /**
1997     * Text direction is coming from the system Locale.
1998     */
1999    public static final int TEXT_DIRECTION_LOCALE = 5;
2000
2001    /**
2002     * Default text direction is inherited
2003     */
2004    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2005
2006    /**
2007     * Default resolved text direction
2008     * @hide
2009     */
2010    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2011
2012    /**
2013     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2017
2018    /**
2019     * Mask for use with private flags indicating bits used for text direction.
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2023            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2024
2025    /**
2026     * Array of text direction flags for mapping attribute "textDirection" to correct
2027     * flag value.
2028     * @hide
2029     */
2030    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2031            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2036            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2037    };
2038
2039    /**
2040     * Indicates whether the view text direction has been resolved.
2041     * @hide
2042     */
2043    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2044            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for resolved text direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2057            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2058
2059    /**
2060     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2061     * @hide
2062     */
2063    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2064            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2065
2066    /** @hide */
2067    @IntDef({
2068        TEXT_ALIGNMENT_INHERIT,
2069        TEXT_ALIGNMENT_GRAVITY,
2070        TEXT_ALIGNMENT_CENTER,
2071        TEXT_ALIGNMENT_TEXT_START,
2072        TEXT_ALIGNMENT_TEXT_END,
2073        TEXT_ALIGNMENT_VIEW_START,
2074        TEXT_ALIGNMENT_VIEW_END
2075    })
2076    @Retention(RetentionPolicy.SOURCE)
2077    public @interface TextAlignment {}
2078
2079    /**
2080     * Default text alignment. The text alignment of this View is inherited from its parent.
2081     * Use with {@link #setTextAlignment(int)}
2082     */
2083    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2084
2085    /**
2086     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2087     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2088     *
2089     * Use with {@link #setTextAlignment(int)}
2090     */
2091    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2092
2093    /**
2094     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2095     *
2096     * Use with {@link #setTextAlignment(int)}
2097     */
2098    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2099
2100    /**
2101     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2102     *
2103     * Use with {@link #setTextAlignment(int)}
2104     */
2105    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2106
2107    /**
2108     * Center the paragraph, e.g. ALIGN_CENTER.
2109     *
2110     * Use with {@link #setTextAlignment(int)}
2111     */
2112    public static final int TEXT_ALIGNMENT_CENTER = 4;
2113
2114    /**
2115     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2116     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2117     *
2118     * Use with {@link #setTextAlignment(int)}
2119     */
2120    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2121
2122    /**
2123     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2124     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2125     *
2126     * Use with {@link #setTextAlignment(int)}
2127     */
2128    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2129
2130    /**
2131     * Default text alignment is inherited
2132     */
2133    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2134
2135    /**
2136     * Default resolved text alignment
2137     * @hide
2138     */
2139    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2140
2141    /**
2142      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2143      * @hide
2144      */
2145    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2146
2147    /**
2148      * Mask for use with private flags indicating bits used for text alignment.
2149      * @hide
2150      */
2151    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2152
2153    /**
2154     * Array of text direction flags for mapping attribute "textAlignment" to correct
2155     * flag value.
2156     * @hide
2157     */
2158    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2159            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2166    };
2167
2168    /**
2169     * Indicates whether the view text alignment has been resolved.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2173
2174    /**
2175     * Bit shift to get the resolved text alignment.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2179
2180    /**
2181     * Mask for use with private flags indicating bits used for text alignment.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2185            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2186
2187    /**
2188     * Indicates whether if the view text alignment has been resolved to gravity
2189     */
2190    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2191            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2192
2193    // Accessiblity constants for mPrivateFlags2
2194
2195    /**
2196     * Shift for the bits in {@link #mPrivateFlags2} related to the
2197     * "importantForAccessibility" attribute.
2198     */
2199    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2200
2201    /**
2202     * Automatically determine whether a view is important for accessibility.
2203     */
2204    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2205
2206    /**
2207     * The view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2210
2211    /**
2212     * The view is not important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2215
2216    /**
2217     * The view is not important for accessibility, nor are any of its
2218     * descendant views.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2221
2222    /**
2223     * The default whether the view is important for accessibility.
2224     */
2225    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2226
2227    /**
2228     * Mask for obtainig the bits which specify how to determine
2229     * whether a view is important for accessibility.
2230     */
2231    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2232        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2233        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2234        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2235
2236    /**
2237     * Shift for the bits in {@link #mPrivateFlags2} related to the
2238     * "accessibilityLiveRegion" attribute.
2239     */
2240    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2241
2242    /**
2243     * Live region mode specifying that accessibility services should not
2244     * automatically announce changes to this view. This is the default live
2245     * region mode for most views.
2246     * <p>
2247     * Use with {@link #setAccessibilityLiveRegion(int)}.
2248     */
2249    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2250
2251    /**
2252     * Live region mode specifying that accessibility services should announce
2253     * changes to this view.
2254     * <p>
2255     * Use with {@link #setAccessibilityLiveRegion(int)}.
2256     */
2257    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2258
2259    /**
2260     * Live region mode specifying that accessibility services should interrupt
2261     * ongoing speech to immediately announce changes to this view.
2262     * <p>
2263     * Use with {@link #setAccessibilityLiveRegion(int)}.
2264     */
2265    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2266
2267    /**
2268     * The default whether the view is important for accessibility.
2269     */
2270    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2271
2272    /**
2273     * Mask for obtaining the bits which specify a view's accessibility live
2274     * region mode.
2275     */
2276    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2277            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2278            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2279
2280    /**
2281     * Flag indicating whether a view has accessibility focus.
2282     */
2283    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2284
2285    /**
2286     * Flag whether the accessibility state of the subtree rooted at this view changed.
2287     */
2288    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2289
2290    /**
2291     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2292     * is used to check whether later changes to the view's transform should invalidate the
2293     * view to force the quickReject test to run again.
2294     */
2295    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2296
2297    /**
2298     * Flag indicating that start/end padding has been resolved into left/right padding
2299     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2300     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2301     * during measurement. In some special cases this is required such as when an adapter-based
2302     * view measures prospective children without attaching them to a window.
2303     */
2304    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2305
2306    /**
2307     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2308     */
2309    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2310
2311    /**
2312     * Indicates that the view is tracking some sort of transient state
2313     * that the app should not need to be aware of, but that the framework
2314     * should take special care to preserve.
2315     */
2316    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2317
2318    /**
2319     * Group of bits indicating that RTL properties resolution is done.
2320     */
2321    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2322            PFLAG2_TEXT_DIRECTION_RESOLVED |
2323            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2324            PFLAG2_PADDING_RESOLVED |
2325            PFLAG2_DRAWABLE_RESOLVED;
2326
2327    // There are a couple of flags left in mPrivateFlags2
2328
2329    /* End of masks for mPrivateFlags2 */
2330
2331    /**
2332     * Masks for mPrivateFlags3, as generated by dumpFlags():
2333     *
2334     * |-------|-------|-------|-------|
2335     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2336     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2337     *                               1   PFLAG3_IS_LAID_OUT
2338     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2339     *                             1     PFLAG3_CALLED_SUPER
2340     * |-------|-------|-------|-------|
2341     */
2342
2343    /**
2344     * Flag indicating that view has a transform animation set on it. This is used to track whether
2345     * an animation is cleared between successive frames, in order to tell the associated
2346     * DisplayList to clear its animation matrix.
2347     */
2348    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2349
2350    /**
2351     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2352     * animation is cleared between successive frames, in order to tell the associated
2353     * DisplayList to restore its alpha value.
2354     */
2355    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2356
2357    /**
2358     * Flag indicating that the view has been through at least one layout since it
2359     * was last attached to a window.
2360     */
2361    static final int PFLAG3_IS_LAID_OUT = 0x4;
2362
2363    /**
2364     * Flag indicating that a call to measure() was skipped and should be done
2365     * instead when layout() is invoked.
2366     */
2367    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2368
2369    /**
2370     * Flag indicating that an overridden method correctly called down to
2371     * the superclass implementation as required by the API spec.
2372     */
2373    static final int PFLAG3_CALLED_SUPER = 0x10;
2374
2375    /**
2376     * Flag indicating that we're in the process of applying window insets.
2377     */
2378    static final int PFLAG3_APPLYING_INSETS = 0x20;
2379
2380    /**
2381     * Flag indicating that we're in the process of fitting system windows using the old method.
2382     */
2383    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2384
2385    /**
2386     * Flag indicating that nested scrolling is enabled for this view.
2387     * The view will optionally cooperate with views up its parent chain to allow for
2388     * integrated nested scrolling along the same axis.
2389     */
2390    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2391
2392    /* End of masks for mPrivateFlags3 */
2393
2394    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2395
2396    /**
2397     * Always allow a user to over-scroll this view, provided it is a
2398     * view that can scroll.
2399     *
2400     * @see #getOverScrollMode()
2401     * @see #setOverScrollMode(int)
2402     */
2403    public static final int OVER_SCROLL_ALWAYS = 0;
2404
2405    /**
2406     * Allow a user to over-scroll this view only if the content is large
2407     * enough to meaningfully scroll, provided it is a view that can scroll.
2408     *
2409     * @see #getOverScrollMode()
2410     * @see #setOverScrollMode(int)
2411     */
2412    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2413
2414    /**
2415     * Never allow a user to over-scroll this view.
2416     *
2417     * @see #getOverScrollMode()
2418     * @see #setOverScrollMode(int)
2419     */
2420    public static final int OVER_SCROLL_NEVER = 2;
2421
2422    /**
2423     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2424     * requested the system UI (status bar) to be visible (the default).
2425     *
2426     * @see #setSystemUiVisibility(int)
2427     */
2428    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2429
2430    /**
2431     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2432     * system UI to enter an unobtrusive "low profile" mode.
2433     *
2434     * <p>This is for use in games, book readers, video players, or any other
2435     * "immersive" application where the usual system chrome is deemed too distracting.
2436     *
2437     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2438     *
2439     * @see #setSystemUiVisibility(int)
2440     */
2441    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2442
2443    /**
2444     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2445     * system navigation be temporarily hidden.
2446     *
2447     * <p>This is an even less obtrusive state than that called for by
2448     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2449     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2450     * those to disappear. This is useful (in conjunction with the
2451     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2452     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2453     * window flags) for displaying content using every last pixel on the display.
2454     *
2455     * <p>There is a limitation: because navigation controls are so important, the least user
2456     * interaction will cause them to reappear immediately.  When this happens, both
2457     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2458     * so that both elements reappear at the same time.
2459     *
2460     * @see #setSystemUiVisibility(int)
2461     */
2462    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2463
2464    /**
2465     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2466     * into the normal fullscreen mode so that its content can take over the screen
2467     * while still allowing the user to interact with the application.
2468     *
2469     * <p>This has the same visual effect as
2470     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2471     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2472     * meaning that non-critical screen decorations (such as the status bar) will be
2473     * hidden while the user is in the View's window, focusing the experience on
2474     * that content.  Unlike the window flag, if you are using ActionBar in
2475     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2476     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2477     * hide the action bar.
2478     *
2479     * <p>This approach to going fullscreen is best used over the window flag when
2480     * it is a transient state -- that is, the application does this at certain
2481     * points in its user interaction where it wants to allow the user to focus
2482     * on content, but not as a continuous state.  For situations where the application
2483     * would like to simply stay full screen the entire time (such as a game that
2484     * wants to take over the screen), the
2485     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2486     * is usually a better approach.  The state set here will be removed by the system
2487     * in various situations (such as the user moving to another application) like
2488     * the other system UI states.
2489     *
2490     * <p>When using this flag, the application should provide some easy facility
2491     * for the user to go out of it.  A common example would be in an e-book
2492     * reader, where tapping on the screen brings back whatever screen and UI
2493     * decorations that had been hidden while the user was immersed in reading
2494     * the book.
2495     *
2496     * @see #setSystemUiVisibility(int)
2497     */
2498    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2499
2500    /**
2501     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2502     * flags, we would like a stable view of the content insets given to
2503     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2504     * will always represent the worst case that the application can expect
2505     * as a continuous state.  In the stock Android UI this is the space for
2506     * the system bar, nav bar, and status bar, but not more transient elements
2507     * such as an input method.
2508     *
2509     * The stable layout your UI sees is based on the system UI modes you can
2510     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2511     * then you will get a stable layout for changes of the
2512     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2513     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2514     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2515     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2516     * with a stable layout.  (Note that you should avoid using
2517     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2518     *
2519     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2520     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2521     * then a hidden status bar will be considered a "stable" state for purposes
2522     * here.  This allows your UI to continually hide the status bar, while still
2523     * using the system UI flags to hide the action bar while still retaining
2524     * a stable layout.  Note that changing the window fullscreen flag will never
2525     * provide a stable layout for a clean transition.
2526     *
2527     * <p>If you are using ActionBar in
2528     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2529     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2530     * insets it adds to those given to the application.
2531     */
2532    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2533
2534    /**
2535     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2536     * to be layed out as if it has requested
2537     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2538     * allows it to avoid artifacts when switching in and out of that mode, at
2539     * the expense that some of its user interface may be covered by screen
2540     * decorations when they are shown.  You can perform layout of your inner
2541     * UI elements to account for the navigation system UI through the
2542     * {@link #fitSystemWindows(Rect)} method.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2545
2546    /**
2547     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2548     * to be layed out as if it has requested
2549     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2550     * allows it to avoid artifacts when switching in and out of that mode, at
2551     * the expense that some of its user interface may be covered by screen
2552     * decorations when they are shown.  You can perform layout of your inner
2553     * UI elements to account for non-fullscreen system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2560     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2561     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2562     * user interaction.
2563     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2564     * has an effect when used in combination with that flag.</p>
2565     */
2566    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2571     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2572     * experience while also hiding the system bars.  If this flag is not set,
2573     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2574     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2575     * if the user swipes from the top of the screen.
2576     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2577     * system gestures, such as swiping from the top of the screen.  These transient system bars
2578     * will overlay app’s content, may have some degree of transparency, and will automatically
2579     * hide after a short timeout.
2580     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2581     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2582     * with one or both of those flags.</p>
2583     */
2584    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2585
2586    /**
2587     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2588     */
2589    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2590
2591    /**
2592     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2593     */
2594    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2595
2596    /**
2597     * @hide
2598     *
2599     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2600     * out of the public fields to keep the undefined bits out of the developer's way.
2601     *
2602     * Flag to make the status bar not expandable.  Unless you also
2603     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2604     */
2605    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2606
2607    /**
2608     * @hide
2609     *
2610     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2611     * out of the public fields to keep the undefined bits out of the developer's way.
2612     *
2613     * Flag to hide notification icons and scrolling ticker text.
2614     */
2615    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2616
2617    /**
2618     * @hide
2619     *
2620     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2621     * out of the public fields to keep the undefined bits out of the developer's way.
2622     *
2623     * Flag to disable incoming notification alerts.  This will not block
2624     * icons, but it will block sound, vibrating and other visual or aural notifications.
2625     */
2626    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2627
2628    /**
2629     * @hide
2630     *
2631     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2632     * out of the public fields to keep the undefined bits out of the developer's way.
2633     *
2634     * Flag to hide only the scrolling ticker.  Note that
2635     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2636     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2639
2640    /**
2641     * @hide
2642     *
2643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2644     * out of the public fields to keep the undefined bits out of the developer's way.
2645     *
2646     * Flag to hide the center system info area.
2647     */
2648    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2649
2650    /**
2651     * @hide
2652     *
2653     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2654     * out of the public fields to keep the undefined bits out of the developer's way.
2655     *
2656     * Flag to hide only the home button.  Don't use this
2657     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2658     */
2659    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2660
2661    /**
2662     * @hide
2663     *
2664     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2665     * out of the public fields to keep the undefined bits out of the developer's way.
2666     *
2667     * Flag to hide only the back button. Don't use this
2668     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2669     */
2670    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2671
2672    /**
2673     * @hide
2674     *
2675     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2676     * out of the public fields to keep the undefined bits out of the developer's way.
2677     *
2678     * Flag to hide only the clock.  You might use this if your activity has
2679     * its own clock making the status bar's clock redundant.
2680     */
2681    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to hide only the recent apps button. Don't use this
2690     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2691     */
2692    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2693
2694    /**
2695     * @hide
2696     *
2697     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2698     * out of the public fields to keep the undefined bits out of the developer's way.
2699     *
2700     * Flag to disable the global search gesture. Don't use this
2701     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2702     */
2703    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2704
2705    /**
2706     * @hide
2707     *
2708     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2709     * out of the public fields to keep the undefined bits out of the developer's way.
2710     *
2711     * Flag to specify that the status bar is displayed in transient mode.
2712     */
2713    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2714
2715    /**
2716     * @hide
2717     *
2718     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2719     * out of the public fields to keep the undefined bits out of the developer's way.
2720     *
2721     * Flag to specify that the navigation bar is displayed in transient mode.
2722     */
2723    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2724
2725    /**
2726     * @hide
2727     *
2728     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2729     * out of the public fields to keep the undefined bits out of the developer's way.
2730     *
2731     * Flag to specify that the hidden status bar would like to be shown.
2732     */
2733    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2734
2735    /**
2736     * @hide
2737     *
2738     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2739     * out of the public fields to keep the undefined bits out of the developer's way.
2740     *
2741     * Flag to specify that the hidden navigation bar would like to be shown.
2742     */
2743    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2744
2745    /**
2746     * @hide
2747     *
2748     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2749     * out of the public fields to keep the undefined bits out of the developer's way.
2750     *
2751     * Flag to specify that the status bar is displayed in translucent mode.
2752     */
2753    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2754
2755    /**
2756     * @hide
2757     *
2758     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2759     * out of the public fields to keep the undefined bits out of the developer's way.
2760     *
2761     * Flag to specify that the navigation bar is displayed in translucent mode.
2762     */
2763    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * Whether Recents is visible or not.
2769     */
2770    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2771
2772    /**
2773     * @hide
2774     *
2775     * Makes system ui transparent.
2776     */
2777    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2778
2779    /**
2780     * @hide
2781     */
2782    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2783
2784    /**
2785     * These are the system UI flags that can be cleared by events outside
2786     * of an application.  Currently this is just the ability to tap on the
2787     * screen while hiding the navigation bar to have it return.
2788     * @hide
2789     */
2790    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2791            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2792            | SYSTEM_UI_FLAG_FULLSCREEN;
2793
2794    /**
2795     * Flags that can impact the layout in relation to system UI.
2796     */
2797    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2798            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2799            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2800
2801    /** @hide */
2802    @IntDef(flag = true,
2803            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2804    @Retention(RetentionPolicy.SOURCE)
2805    public @interface FindViewFlags {}
2806
2807    /**
2808     * Find views that render the specified text.
2809     *
2810     * @see #findViewsWithText(ArrayList, CharSequence, int)
2811     */
2812    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2813
2814    /**
2815     * Find find views that contain the specified content description.
2816     *
2817     * @see #findViewsWithText(ArrayList, CharSequence, int)
2818     */
2819    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2820
2821    /**
2822     * Find views that contain {@link AccessibilityNodeProvider}. Such
2823     * a View is a root of virtual view hierarchy and may contain the searched
2824     * text. If this flag is set Views with providers are automatically
2825     * added and it is a responsibility of the client to call the APIs of
2826     * the provider to determine whether the virtual tree rooted at this View
2827     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2828     * representing the virtual views with this text.
2829     *
2830     * @see #findViewsWithText(ArrayList, CharSequence, int)
2831     *
2832     * @hide
2833     */
2834    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2835
2836    /**
2837     * The undefined cursor position.
2838     *
2839     * @hide
2840     */
2841    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2842
2843    /**
2844     * Indicates that the screen has changed state and is now off.
2845     *
2846     * @see #onScreenStateChanged(int)
2847     */
2848    public static final int SCREEN_STATE_OFF = 0x0;
2849
2850    /**
2851     * Indicates that the screen has changed state and is now on.
2852     *
2853     * @see #onScreenStateChanged(int)
2854     */
2855    public static final int SCREEN_STATE_ON = 0x1;
2856
2857    /**
2858     * Indicates no axis of view scrolling.
2859     */
2860    public static final int SCROLL_AXIS_NONE = 0;
2861
2862    /**
2863     * Indicates scrolling along the horizontal axis.
2864     */
2865    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2866
2867    /**
2868     * Indicates scrolling along the vertical axis.
2869     */
2870    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2871
2872    /**
2873     * Controls the over-scroll mode for this view.
2874     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2875     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2876     * and {@link #OVER_SCROLL_NEVER}.
2877     */
2878    private int mOverScrollMode;
2879
2880    /**
2881     * The parent this view is attached to.
2882     * {@hide}
2883     *
2884     * @see #getParent()
2885     */
2886    protected ViewParent mParent;
2887
2888    /**
2889     * {@hide}
2890     */
2891    AttachInfo mAttachInfo;
2892
2893    /**
2894     * {@hide}
2895     */
2896    @ViewDebug.ExportedProperty(flagMapping = {
2897        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2898                name = "FORCE_LAYOUT"),
2899        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2900                name = "LAYOUT_REQUIRED"),
2901        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2902            name = "DRAWING_CACHE_INVALID", outputIf = false),
2903        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2904        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2905        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2906        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2907    }, formatToHexString = true)
2908    int mPrivateFlags;
2909    int mPrivateFlags2;
2910    int mPrivateFlags3;
2911
2912    /**
2913     * This view's request for the visibility of the status bar.
2914     * @hide
2915     */
2916    @ViewDebug.ExportedProperty(flagMapping = {
2917        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2918                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2919                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2920        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2921                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2922                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2923        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2924                                equals = SYSTEM_UI_FLAG_VISIBLE,
2925                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2926    }, formatToHexString = true)
2927    int mSystemUiVisibility;
2928
2929    /**
2930     * Reference count for transient state.
2931     * @see #setHasTransientState(boolean)
2932     */
2933    int mTransientStateCount = 0;
2934
2935    /**
2936     * Count of how many windows this view has been attached to.
2937     */
2938    int mWindowAttachCount;
2939
2940    /**
2941     * The layout parameters associated with this view and used by the parent
2942     * {@link android.view.ViewGroup} to determine how this view should be
2943     * laid out.
2944     * {@hide}
2945     */
2946    protected ViewGroup.LayoutParams mLayoutParams;
2947
2948    /**
2949     * The view flags hold various views states.
2950     * {@hide}
2951     */
2952    @ViewDebug.ExportedProperty(formatToHexString = true)
2953    int mViewFlags;
2954
2955    static class TransformationInfo {
2956        /**
2957         * The transform matrix for the View. This transform is calculated internally
2958         * based on the translation, rotation, and scale properties.
2959         *
2960         * Do *not* use this variable directly; instead call getMatrix(), which will
2961         * load the value from the View's RenderNode.
2962         */
2963        private final Matrix mMatrix = new Matrix();
2964
2965        /**
2966         * The inverse transform matrix for the View. This transform is calculated
2967         * internally based on the translation, rotation, and scale properties.
2968         *
2969         * Do *not* use this variable directly; instead call getInverseMatrix(),
2970         * which will load the value from the View's RenderNode.
2971         */
2972        private Matrix mInverseMatrix;
2973
2974        /**
2975         * The opacity of the View. This is a value from 0 to 1, where 0 means
2976         * completely transparent and 1 means completely opaque.
2977         */
2978        @ViewDebug.ExportedProperty
2979        float mAlpha = 1f;
2980
2981        /**
2982         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2983         * property only used by transitions, which is composited with the other alpha
2984         * values to calculate the final visual alpha value.
2985         */
2986        float mTransitionAlpha = 1f;
2987    }
2988
2989    TransformationInfo mTransformationInfo;
2990
2991    /**
2992     * Current clip bounds. to which all drawing of this view are constrained.
2993     */
2994    Rect mClipBounds = null;
2995
2996    private boolean mLastIsOpaque;
2997
2998    /**
2999     * The distance in pixels from the left edge of this view's parent
3000     * to the left edge of this view.
3001     * {@hide}
3002     */
3003    @ViewDebug.ExportedProperty(category = "layout")
3004    protected int mLeft;
3005    /**
3006     * The distance in pixels from the left edge of this view's parent
3007     * to the right edge of this view.
3008     * {@hide}
3009     */
3010    @ViewDebug.ExportedProperty(category = "layout")
3011    protected int mRight;
3012    /**
3013     * The distance in pixels from the top edge of this view's parent
3014     * to the top edge of this view.
3015     * {@hide}
3016     */
3017    @ViewDebug.ExportedProperty(category = "layout")
3018    protected int mTop;
3019    /**
3020     * The distance in pixels from the top edge of this view's parent
3021     * to the bottom edge of this view.
3022     * {@hide}
3023     */
3024    @ViewDebug.ExportedProperty(category = "layout")
3025    protected int mBottom;
3026
3027    /**
3028     * The offset, in pixels, by which the content of this view is scrolled
3029     * horizontally.
3030     * {@hide}
3031     */
3032    @ViewDebug.ExportedProperty(category = "scrolling")
3033    protected int mScrollX;
3034    /**
3035     * The offset, in pixels, by which the content of this view is scrolled
3036     * vertically.
3037     * {@hide}
3038     */
3039    @ViewDebug.ExportedProperty(category = "scrolling")
3040    protected int mScrollY;
3041
3042    /**
3043     * The left padding in pixels, that is the distance in pixels between the
3044     * left edge of this view and the left edge of its content.
3045     * {@hide}
3046     */
3047    @ViewDebug.ExportedProperty(category = "padding")
3048    protected int mPaddingLeft = 0;
3049    /**
3050     * The right padding in pixels, that is the distance in pixels between the
3051     * right edge of this view and the right edge of its content.
3052     * {@hide}
3053     */
3054    @ViewDebug.ExportedProperty(category = "padding")
3055    protected int mPaddingRight = 0;
3056    /**
3057     * The top padding in pixels, that is the distance in pixels between the
3058     * top edge of this view and the top edge of its content.
3059     * {@hide}
3060     */
3061    @ViewDebug.ExportedProperty(category = "padding")
3062    protected int mPaddingTop;
3063    /**
3064     * The bottom padding in pixels, that is the distance in pixels between the
3065     * bottom edge of this view and the bottom edge of its content.
3066     * {@hide}
3067     */
3068    @ViewDebug.ExportedProperty(category = "padding")
3069    protected int mPaddingBottom;
3070
3071    /**
3072     * The layout insets in pixels, that is the distance in pixels between the
3073     * visible edges of this view its bounds.
3074     */
3075    private Insets mLayoutInsets;
3076
3077    /**
3078     * Briefly describes the view and is primarily used for accessibility support.
3079     */
3080    private CharSequence mContentDescription;
3081
3082    /**
3083     * Specifies the id of a view for which this view serves as a label for
3084     * accessibility purposes.
3085     */
3086    private int mLabelForId = View.NO_ID;
3087
3088    /**
3089     * Predicate for matching labeled view id with its label for
3090     * accessibility purposes.
3091     */
3092    private MatchLabelForPredicate mMatchLabelForPredicate;
3093
3094    /**
3095     * Predicate for matching a view by its id.
3096     */
3097    private MatchIdPredicate mMatchIdPredicate;
3098
3099    /**
3100     * Cache the paddingRight set by the user to append to the scrollbar's size.
3101     *
3102     * @hide
3103     */
3104    @ViewDebug.ExportedProperty(category = "padding")
3105    protected int mUserPaddingRight;
3106
3107    /**
3108     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3109     *
3110     * @hide
3111     */
3112    @ViewDebug.ExportedProperty(category = "padding")
3113    protected int mUserPaddingBottom;
3114
3115    /**
3116     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3117     *
3118     * @hide
3119     */
3120    @ViewDebug.ExportedProperty(category = "padding")
3121    protected int mUserPaddingLeft;
3122
3123    /**
3124     * Cache the paddingStart set by the user to append to the scrollbar's size.
3125     *
3126     */
3127    @ViewDebug.ExportedProperty(category = "padding")
3128    int mUserPaddingStart;
3129
3130    /**
3131     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3132     *
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    int mUserPaddingEnd;
3136
3137    /**
3138     * Cache initial left padding.
3139     *
3140     * @hide
3141     */
3142    int mUserPaddingLeftInitial;
3143
3144    /**
3145     * Cache initial right padding.
3146     *
3147     * @hide
3148     */
3149    int mUserPaddingRightInitial;
3150
3151    /**
3152     * Default undefined padding
3153     */
3154    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3155
3156    /**
3157     * Cache if a left padding has been defined
3158     */
3159    private boolean mLeftPaddingDefined = false;
3160
3161    /**
3162     * Cache if a right padding has been defined
3163     */
3164    private boolean mRightPaddingDefined = false;
3165
3166    /**
3167     * @hide
3168     */
3169    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3170    /**
3171     * @hide
3172     */
3173    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3174
3175    private LongSparseLongArray mMeasureCache;
3176
3177    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3178    private Drawable mBackground;
3179    private ColorStateList mBackgroundTintList = null;
3180    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3181    private boolean mHasBackgroundTint = false;
3182
3183    /**
3184     * RenderNode used for backgrounds.
3185     * <p>
3186     * When non-null and valid, this is expected to contain an up-to-date copy
3187     * of the background drawable. It is cleared on temporary detach, and reset
3188     * on cleanup.
3189     */
3190    private RenderNode mBackgroundRenderNode;
3191
3192    private int mBackgroundResource;
3193    private boolean mBackgroundSizeChanged;
3194
3195    private String mTransitionName;
3196
3197    static class ListenerInfo {
3198        /**
3199         * Listener used to dispatch focus change events.
3200         * This field should be made private, so it is hidden from the SDK.
3201         * {@hide}
3202         */
3203        protected OnFocusChangeListener mOnFocusChangeListener;
3204
3205        /**
3206         * Listeners for layout change events.
3207         */
3208        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3209
3210        /**
3211         * Listeners for attach events.
3212         */
3213        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3214
3215        /**
3216         * Listener used to dispatch click events.
3217         * This field should be made private, so it is hidden from the SDK.
3218         * {@hide}
3219         */
3220        public OnClickListener mOnClickListener;
3221
3222        /**
3223         * Listener used to dispatch long click events.
3224         * This field should be made private, so it is hidden from the SDK.
3225         * {@hide}
3226         */
3227        protected OnLongClickListener mOnLongClickListener;
3228
3229        /**
3230         * Listener used to build the context menu.
3231         * This field should be made private, so it is hidden from the SDK.
3232         * {@hide}
3233         */
3234        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3235
3236        private OnKeyListener mOnKeyListener;
3237
3238        private OnTouchListener mOnTouchListener;
3239
3240        private OnHoverListener mOnHoverListener;
3241
3242        private OnGenericMotionListener mOnGenericMotionListener;
3243
3244        private OnDragListener mOnDragListener;
3245
3246        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3247
3248        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3249    }
3250
3251    ListenerInfo mListenerInfo;
3252
3253    /**
3254     * The application environment this view lives in.
3255     * This field should be made private, so it is hidden from the SDK.
3256     * {@hide}
3257     */
3258    protected Context mContext;
3259
3260    private final Resources mResources;
3261
3262    private ScrollabilityCache mScrollCache;
3263
3264    private int[] mDrawableState = null;
3265
3266    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3267
3268    /**
3269     * Animator that automatically runs based on state changes.
3270     */
3271    private StateListAnimator mStateListAnimator;
3272
3273    /**
3274     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3275     * the user may specify which view to go to next.
3276     */
3277    private int mNextFocusLeftId = View.NO_ID;
3278
3279    /**
3280     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3281     * the user may specify which view to go to next.
3282     */
3283    private int mNextFocusRightId = View.NO_ID;
3284
3285    /**
3286     * When this view has focus and the next focus is {@link #FOCUS_UP},
3287     * the user may specify which view to go to next.
3288     */
3289    private int mNextFocusUpId = View.NO_ID;
3290
3291    /**
3292     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3293     * the user may specify which view to go to next.
3294     */
3295    private int mNextFocusDownId = View.NO_ID;
3296
3297    /**
3298     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3299     * the user may specify which view to go to next.
3300     */
3301    int mNextFocusForwardId = View.NO_ID;
3302
3303    private CheckForLongPress mPendingCheckForLongPress;
3304    private CheckForTap mPendingCheckForTap = null;
3305    private PerformClick mPerformClick;
3306    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3307
3308    private UnsetPressedState mUnsetPressedState;
3309
3310    /**
3311     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3312     * up event while a long press is invoked as soon as the long press duration is reached, so
3313     * a long press could be performed before the tap is checked, in which case the tap's action
3314     * should not be invoked.
3315     */
3316    private boolean mHasPerformedLongPress;
3317
3318    /**
3319     * The minimum height of the view. We'll try our best to have the height
3320     * of this view to at least this amount.
3321     */
3322    @ViewDebug.ExportedProperty(category = "measurement")
3323    private int mMinHeight;
3324
3325    /**
3326     * The minimum width of the view. We'll try our best to have the width
3327     * of this view to at least this amount.
3328     */
3329    @ViewDebug.ExportedProperty(category = "measurement")
3330    private int mMinWidth;
3331
3332    /**
3333     * The delegate to handle touch events that are physically in this view
3334     * but should be handled by another view.
3335     */
3336    private TouchDelegate mTouchDelegate = null;
3337
3338    /**
3339     * Solid color to use as a background when creating the drawing cache. Enables
3340     * the cache to use 16 bit bitmaps instead of 32 bit.
3341     */
3342    private int mDrawingCacheBackgroundColor = 0;
3343
3344    /**
3345     * Special tree observer used when mAttachInfo is null.
3346     */
3347    private ViewTreeObserver mFloatingTreeObserver;
3348
3349    /**
3350     * Cache the touch slop from the context that created the view.
3351     */
3352    private int mTouchSlop;
3353
3354    /**
3355     * Object that handles automatic animation of view properties.
3356     */
3357    private ViewPropertyAnimator mAnimator = null;
3358
3359    /**
3360     * Flag indicating that a drag can cross window boundaries.  When
3361     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3362     * with this flag set, all visible applications will be able to participate
3363     * in the drag operation and receive the dragged content.
3364     *
3365     * @hide
3366     */
3367    public static final int DRAG_FLAG_GLOBAL = 1;
3368
3369    /**
3370     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3371     */
3372    private float mVerticalScrollFactor;
3373
3374    /**
3375     * Position of the vertical scroll bar.
3376     */
3377    private int mVerticalScrollbarPosition;
3378
3379    /**
3380     * Position the scroll bar at the default position as determined by the system.
3381     */
3382    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3383
3384    /**
3385     * Position the scroll bar along the left edge.
3386     */
3387    public static final int SCROLLBAR_POSITION_LEFT = 1;
3388
3389    /**
3390     * Position the scroll bar along the right edge.
3391     */
3392    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3393
3394    /**
3395     * Indicates that the view does not have a layer.
3396     *
3397     * @see #getLayerType()
3398     * @see #setLayerType(int, android.graphics.Paint)
3399     * @see #LAYER_TYPE_SOFTWARE
3400     * @see #LAYER_TYPE_HARDWARE
3401     */
3402    public static final int LAYER_TYPE_NONE = 0;
3403
3404    /**
3405     * <p>Indicates that the view has a software layer. A software layer is backed
3406     * by a bitmap and causes the view to be rendered using Android's software
3407     * rendering pipeline, even if hardware acceleration is enabled.</p>
3408     *
3409     * <p>Software layers have various usages:</p>
3410     * <p>When the application is not using hardware acceleration, a software layer
3411     * is useful to apply a specific color filter and/or blending mode and/or
3412     * translucency to a view and all its children.</p>
3413     * <p>When the application is using hardware acceleration, a software layer
3414     * is useful to render drawing primitives not supported by the hardware
3415     * accelerated pipeline. It can also be used to cache a complex view tree
3416     * into a texture and reduce the complexity of drawing operations. For instance,
3417     * when animating a complex view tree with a translation, a software layer can
3418     * be used to render the view tree only once.</p>
3419     * <p>Software layers should be avoided when the affected view tree updates
3420     * often. Every update will require to re-render the software layer, which can
3421     * potentially be slow (particularly when hardware acceleration is turned on
3422     * since the layer will have to be uploaded into a hardware texture after every
3423     * update.)</p>
3424     *
3425     * @see #getLayerType()
3426     * @see #setLayerType(int, android.graphics.Paint)
3427     * @see #LAYER_TYPE_NONE
3428     * @see #LAYER_TYPE_HARDWARE
3429     */
3430    public static final int LAYER_TYPE_SOFTWARE = 1;
3431
3432    /**
3433     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3434     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3435     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3436     * rendering pipeline, but only if hardware acceleration is turned on for the
3437     * view hierarchy. When hardware acceleration is turned off, hardware layers
3438     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3439     *
3440     * <p>A hardware layer is useful to apply a specific color filter and/or
3441     * blending mode and/or translucency to a view and all its children.</p>
3442     * <p>A hardware layer can be used to cache a complex view tree into a
3443     * texture and reduce the complexity of drawing operations. For instance,
3444     * when animating a complex view tree with a translation, a hardware layer can
3445     * be used to render the view tree only once.</p>
3446     * <p>A hardware layer can also be used to increase the rendering quality when
3447     * rotation transformations are applied on a view. It can also be used to
3448     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3449     *
3450     * @see #getLayerType()
3451     * @see #setLayerType(int, android.graphics.Paint)
3452     * @see #LAYER_TYPE_NONE
3453     * @see #LAYER_TYPE_SOFTWARE
3454     */
3455    public static final int LAYER_TYPE_HARDWARE = 2;
3456
3457    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3458            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3459            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3460            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3461    })
3462    int mLayerType = LAYER_TYPE_NONE;
3463    Paint mLayerPaint;
3464
3465    /**
3466     * Set to true when drawing cache is enabled and cannot be created.
3467     *
3468     * @hide
3469     */
3470    public boolean mCachingFailed;
3471    private Bitmap mDrawingCache;
3472    private Bitmap mUnscaledDrawingCache;
3473
3474    /**
3475     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3476     * <p>
3477     * When non-null and valid, this is expected to contain an up-to-date copy
3478     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3479     * cleanup.
3480     */
3481    final RenderNode mRenderNode;
3482
3483    /**
3484     * Set to true when the view is sending hover accessibility events because it
3485     * is the innermost hovered view.
3486     */
3487    private boolean mSendingHoverAccessibilityEvents;
3488
3489    /**
3490     * Delegate for injecting accessibility functionality.
3491     */
3492    AccessibilityDelegate mAccessibilityDelegate;
3493
3494    /**
3495     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3496     * and add/remove objects to/from the overlay directly through the Overlay methods.
3497     */
3498    ViewOverlay mOverlay;
3499
3500    /**
3501     * The currently active parent view for receiving delegated nested scrolling events.
3502     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3503     * by {@link #stopNestedScroll()} at the same point where we clear
3504     * requestDisallowInterceptTouchEvent.
3505     */
3506    private ViewParent mNestedScrollingParent;
3507
3508    /**
3509     * Consistency verifier for debugging purposes.
3510     * @hide
3511     */
3512    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3513            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3514                    new InputEventConsistencyVerifier(this, 0) : null;
3515
3516    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3517
3518    private int[] mTempNestedScrollConsumed;
3519
3520    /**
3521     * An overlay is going to draw this View instead of being drawn as part of this
3522     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3523     * when this view is invalidated.
3524     */
3525    GhostView mGhostView;
3526
3527    /**
3528     * Simple constructor to use when creating a view from code.
3529     *
3530     * @param context The Context the view is running in, through which it can
3531     *        access the current theme, resources, etc.
3532     */
3533    public View(Context context) {
3534        mContext = context;
3535        mResources = context != null ? context.getResources() : null;
3536        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3537        // Set some flags defaults
3538        mPrivateFlags2 =
3539                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3540                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3541                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3542                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3543                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3544                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3545        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3546        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3547        mUserPaddingStart = UNDEFINED_PADDING;
3548        mUserPaddingEnd = UNDEFINED_PADDING;
3549        mRenderNode = RenderNode.create(getClass().getName());
3550
3551        if (!sCompatibilityDone && context != null) {
3552            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3553
3554            // Older apps may need this compatibility hack for measurement.
3555            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3556
3557            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3558            // of whether a layout was requested on that View.
3559            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3560
3561            sCompatibilityDone = true;
3562        }
3563    }
3564
3565    /**
3566     * Constructor that is called when inflating a view from XML. This is called
3567     * when a view is being constructed from an XML file, supplying attributes
3568     * that were specified in the XML file. This version uses a default style of
3569     * 0, so the only attribute values applied are those in the Context's Theme
3570     * and the given AttributeSet.
3571     *
3572     * <p>
3573     * The method onFinishInflate() will be called after all children have been
3574     * added.
3575     *
3576     * @param context The Context the view is running in, through which it can
3577     *        access the current theme, resources, etc.
3578     * @param attrs The attributes of the XML tag that is inflating the view.
3579     * @see #View(Context, AttributeSet, int)
3580     */
3581    public View(Context context, AttributeSet attrs) {
3582        this(context, attrs, 0);
3583    }
3584
3585    /**
3586     * Perform inflation from XML and apply a class-specific base style from a
3587     * theme attribute. This constructor of View allows subclasses to use their
3588     * own base style when they are inflating. For example, a Button class's
3589     * constructor would call this version of the super class constructor and
3590     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3591     * allows the theme's button style to modify all of the base view attributes
3592     * (in particular its background) as well as the Button class's attributes.
3593     *
3594     * @param context The Context the view is running in, through which it can
3595     *        access the current theme, resources, etc.
3596     * @param attrs The attributes of the XML tag that is inflating the view.
3597     * @param defStyleAttr An attribute in the current theme that contains a
3598     *        reference to a style resource that supplies default values for
3599     *        the view. Can be 0 to not look for defaults.
3600     * @see #View(Context, AttributeSet)
3601     */
3602    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3603        this(context, attrs, defStyleAttr, 0);
3604    }
3605
3606    /**
3607     * Perform inflation from XML and apply a class-specific base style from a
3608     * theme attribute or style resource. This constructor of View allows
3609     * subclasses to use their own base style when they are inflating.
3610     * <p>
3611     * When determining the final value of a particular attribute, there are
3612     * four inputs that come into play:
3613     * <ol>
3614     * <li>Any attribute values in the given AttributeSet.
3615     * <li>The style resource specified in the AttributeSet (named "style").
3616     * <li>The default style specified by <var>defStyleAttr</var>.
3617     * <li>The default style specified by <var>defStyleRes</var>.
3618     * <li>The base values in this theme.
3619     * </ol>
3620     * <p>
3621     * Each of these inputs is considered in-order, with the first listed taking
3622     * precedence over the following ones. In other words, if in the
3623     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3624     * , then the button's text will <em>always</em> be black, regardless of
3625     * what is specified in any of the styles.
3626     *
3627     * @param context The Context the view is running in, through which it can
3628     *        access the current theme, resources, etc.
3629     * @param attrs The attributes of the XML tag that is inflating the view.
3630     * @param defStyleAttr An attribute in the current theme that contains a
3631     *        reference to a style resource that supplies default values for
3632     *        the view. Can be 0 to not look for defaults.
3633     * @param defStyleRes A resource identifier of a style resource that
3634     *        supplies default values for the view, used only if
3635     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3636     *        to not look for defaults.
3637     * @see #View(Context, AttributeSet, int)
3638     */
3639    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3640        this(context);
3641
3642        final TypedArray a = context.obtainStyledAttributes(
3643                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3644
3645        Drawable background = null;
3646
3647        int leftPadding = -1;
3648        int topPadding = -1;
3649        int rightPadding = -1;
3650        int bottomPadding = -1;
3651        int startPadding = UNDEFINED_PADDING;
3652        int endPadding = UNDEFINED_PADDING;
3653
3654        int padding = -1;
3655
3656        int viewFlagValues = 0;
3657        int viewFlagMasks = 0;
3658
3659        boolean setScrollContainer = false;
3660
3661        int x = 0;
3662        int y = 0;
3663
3664        float tx = 0;
3665        float ty = 0;
3666        float tz = 0;
3667        float elevation = 0;
3668        float rotation = 0;
3669        float rotationX = 0;
3670        float rotationY = 0;
3671        float sx = 1f;
3672        float sy = 1f;
3673        boolean transformSet = false;
3674
3675        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3676        int overScrollMode = mOverScrollMode;
3677        boolean initializeScrollbars = false;
3678
3679        boolean startPaddingDefined = false;
3680        boolean endPaddingDefined = false;
3681        boolean leftPaddingDefined = false;
3682        boolean rightPaddingDefined = false;
3683
3684        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3685
3686        final int N = a.getIndexCount();
3687        for (int i = 0; i < N; i++) {
3688            int attr = a.getIndex(i);
3689            switch (attr) {
3690                case com.android.internal.R.styleable.View_background:
3691                    background = a.getDrawable(attr);
3692                    break;
3693                case com.android.internal.R.styleable.View_padding:
3694                    padding = a.getDimensionPixelSize(attr, -1);
3695                    mUserPaddingLeftInitial = padding;
3696                    mUserPaddingRightInitial = padding;
3697                    leftPaddingDefined = true;
3698                    rightPaddingDefined = true;
3699                    break;
3700                 case com.android.internal.R.styleable.View_paddingLeft:
3701                    leftPadding = a.getDimensionPixelSize(attr, -1);
3702                    mUserPaddingLeftInitial = leftPadding;
3703                    leftPaddingDefined = true;
3704                    break;
3705                case com.android.internal.R.styleable.View_paddingTop:
3706                    topPadding = a.getDimensionPixelSize(attr, -1);
3707                    break;
3708                case com.android.internal.R.styleable.View_paddingRight:
3709                    rightPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingRightInitial = rightPadding;
3711                    rightPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingBottom:
3714                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingStart:
3717                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3718                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3719                    break;
3720                case com.android.internal.R.styleable.View_paddingEnd:
3721                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3722                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3723                    break;
3724                case com.android.internal.R.styleable.View_scrollX:
3725                    x = a.getDimensionPixelOffset(attr, 0);
3726                    break;
3727                case com.android.internal.R.styleable.View_scrollY:
3728                    y = a.getDimensionPixelOffset(attr, 0);
3729                    break;
3730                case com.android.internal.R.styleable.View_alpha:
3731                    setAlpha(a.getFloat(attr, 1f));
3732                    break;
3733                case com.android.internal.R.styleable.View_transformPivotX:
3734                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3735                    break;
3736                case com.android.internal.R.styleable.View_transformPivotY:
3737                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3738                    break;
3739                case com.android.internal.R.styleable.View_translationX:
3740                    tx = a.getDimensionPixelOffset(attr, 0);
3741                    transformSet = true;
3742                    break;
3743                case com.android.internal.R.styleable.View_translationY:
3744                    ty = a.getDimensionPixelOffset(attr, 0);
3745                    transformSet = true;
3746                    break;
3747                case com.android.internal.R.styleable.View_translationZ:
3748                    tz = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_elevation:
3752                    elevation = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_rotation:
3756                    rotation = a.getFloat(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_rotationX:
3760                    rotationX = a.getFloat(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotationY:
3764                    rotationY = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_scaleX:
3768                    sx = a.getFloat(attr, 1f);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_scaleY:
3772                    sy = a.getFloat(attr, 1f);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_id:
3776                    mID = a.getResourceId(attr, NO_ID);
3777                    break;
3778                case com.android.internal.R.styleable.View_tag:
3779                    mTag = a.getText(attr);
3780                    break;
3781                case com.android.internal.R.styleable.View_fitsSystemWindows:
3782                    if (a.getBoolean(attr, false)) {
3783                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3784                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3785                    }
3786                    break;
3787                case com.android.internal.R.styleable.View_focusable:
3788                    if (a.getBoolean(attr, false)) {
3789                        viewFlagValues |= FOCUSABLE;
3790                        viewFlagMasks |= FOCUSABLE_MASK;
3791                    }
3792                    break;
3793                case com.android.internal.R.styleable.View_focusableInTouchMode:
3794                    if (a.getBoolean(attr, false)) {
3795                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3796                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3797                    }
3798                    break;
3799                case com.android.internal.R.styleable.View_clickable:
3800                    if (a.getBoolean(attr, false)) {
3801                        viewFlagValues |= CLICKABLE;
3802                        viewFlagMasks |= CLICKABLE;
3803                    }
3804                    break;
3805                case com.android.internal.R.styleable.View_longClickable:
3806                    if (a.getBoolean(attr, false)) {
3807                        viewFlagValues |= LONG_CLICKABLE;
3808                        viewFlagMasks |= LONG_CLICKABLE;
3809                    }
3810                    break;
3811                case com.android.internal.R.styleable.View_saveEnabled:
3812                    if (!a.getBoolean(attr, true)) {
3813                        viewFlagValues |= SAVE_DISABLED;
3814                        viewFlagMasks |= SAVE_DISABLED_MASK;
3815                    }
3816                    break;
3817                case com.android.internal.R.styleable.View_duplicateParentState:
3818                    if (a.getBoolean(attr, false)) {
3819                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3820                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3821                    }
3822                    break;
3823                case com.android.internal.R.styleable.View_visibility:
3824                    final int visibility = a.getInt(attr, 0);
3825                    if (visibility != 0) {
3826                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3827                        viewFlagMasks |= VISIBILITY_MASK;
3828                    }
3829                    break;
3830                case com.android.internal.R.styleable.View_layoutDirection:
3831                    // Clear any layout direction flags (included resolved bits) already set
3832                    mPrivateFlags2 &=
3833                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3834                    // Set the layout direction flags depending on the value of the attribute
3835                    final int layoutDirection = a.getInt(attr, -1);
3836                    final int value = (layoutDirection != -1) ?
3837                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3838                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3839                    break;
3840                case com.android.internal.R.styleable.View_drawingCacheQuality:
3841                    final int cacheQuality = a.getInt(attr, 0);
3842                    if (cacheQuality != 0) {
3843                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3844                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3845                    }
3846                    break;
3847                case com.android.internal.R.styleable.View_contentDescription:
3848                    setContentDescription(a.getString(attr));
3849                    break;
3850                case com.android.internal.R.styleable.View_labelFor:
3851                    setLabelFor(a.getResourceId(attr, NO_ID));
3852                    break;
3853                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3854                    if (!a.getBoolean(attr, true)) {
3855                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3856                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3860                    if (!a.getBoolean(attr, true)) {
3861                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3862                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3863                    }
3864                    break;
3865                case R.styleable.View_scrollbars:
3866                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3867                    if (scrollbars != SCROLLBARS_NONE) {
3868                        viewFlagValues |= scrollbars;
3869                        viewFlagMasks |= SCROLLBARS_MASK;
3870                        initializeScrollbars = true;
3871                    }
3872                    break;
3873                //noinspection deprecation
3874                case R.styleable.View_fadingEdge:
3875                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3876                        // Ignore the attribute starting with ICS
3877                        break;
3878                    }
3879                    // With builds < ICS, fall through and apply fading edges
3880                case R.styleable.View_requiresFadingEdge:
3881                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3882                    if (fadingEdge != FADING_EDGE_NONE) {
3883                        viewFlagValues |= fadingEdge;
3884                        viewFlagMasks |= FADING_EDGE_MASK;
3885                        initializeFadingEdgeInternal(a);
3886                    }
3887                    break;
3888                case R.styleable.View_scrollbarStyle:
3889                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3890                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3891                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3892                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3893                    }
3894                    break;
3895                case R.styleable.View_isScrollContainer:
3896                    setScrollContainer = true;
3897                    if (a.getBoolean(attr, false)) {
3898                        setScrollContainer(true);
3899                    }
3900                    break;
3901                case com.android.internal.R.styleable.View_keepScreenOn:
3902                    if (a.getBoolean(attr, false)) {
3903                        viewFlagValues |= KEEP_SCREEN_ON;
3904                        viewFlagMasks |= KEEP_SCREEN_ON;
3905                    }
3906                    break;
3907                case R.styleable.View_filterTouchesWhenObscured:
3908                    if (a.getBoolean(attr, false)) {
3909                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3910                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3911                    }
3912                    break;
3913                case R.styleable.View_nextFocusLeft:
3914                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3915                    break;
3916                case R.styleable.View_nextFocusRight:
3917                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3918                    break;
3919                case R.styleable.View_nextFocusUp:
3920                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3921                    break;
3922                case R.styleable.View_nextFocusDown:
3923                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3924                    break;
3925                case R.styleable.View_nextFocusForward:
3926                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3927                    break;
3928                case R.styleable.View_minWidth:
3929                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3930                    break;
3931                case R.styleable.View_minHeight:
3932                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3933                    break;
3934                case R.styleable.View_onClick:
3935                    if (context.isRestricted()) {
3936                        throw new IllegalStateException("The android:onClick attribute cannot "
3937                                + "be used within a restricted context");
3938                    }
3939
3940                    final String handlerName = a.getString(attr);
3941                    if (handlerName != null) {
3942                        setOnClickListener(new OnClickListener() {
3943                            private Method mHandler;
3944
3945                            public void onClick(View v) {
3946                                if (mHandler == null) {
3947                                    try {
3948                                        mHandler = getContext().getClass().getMethod(handlerName,
3949                                                View.class);
3950                                    } catch (NoSuchMethodException e) {
3951                                        int id = getId();
3952                                        String idText = id == NO_ID ? "" : " with id '"
3953                                                + getContext().getResources().getResourceEntryName(
3954                                                    id) + "'";
3955                                        throw new IllegalStateException("Could not find a method " +
3956                                                handlerName + "(View) in the activity "
3957                                                + getContext().getClass() + " for onClick handler"
3958                                                + " on view " + View.this.getClass() + idText, e);
3959                                    }
3960                                }
3961
3962                                try {
3963                                    mHandler.invoke(getContext(), View.this);
3964                                } catch (IllegalAccessException e) {
3965                                    throw new IllegalStateException("Could not execute non "
3966                                            + "public method of the activity", e);
3967                                } catch (InvocationTargetException e) {
3968                                    throw new IllegalStateException("Could not execute "
3969                                            + "method of the activity", e);
3970                                }
3971                            }
3972                        });
3973                    }
3974                    break;
3975                case R.styleable.View_overScrollMode:
3976                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3977                    break;
3978                case R.styleable.View_verticalScrollbarPosition:
3979                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3980                    break;
3981                case R.styleable.View_layerType:
3982                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3983                    break;
3984                case R.styleable.View_textDirection:
3985                    // Clear any text direction flag already set
3986                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3987                    // Set the text direction flags depending on the value of the attribute
3988                    final int textDirection = a.getInt(attr, -1);
3989                    if (textDirection != -1) {
3990                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3991                    }
3992                    break;
3993                case R.styleable.View_textAlignment:
3994                    // Clear any text alignment flag already set
3995                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3996                    // Set the text alignment flag depending on the value of the attribute
3997                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3998                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3999                    break;
4000                case R.styleable.View_importantForAccessibility:
4001                    setImportantForAccessibility(a.getInt(attr,
4002                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4003                    break;
4004                case R.styleable.View_accessibilityLiveRegion:
4005                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4006                    break;
4007                case R.styleable.View_transitionName:
4008                    setTransitionName(a.getString(attr));
4009                    break;
4010                case R.styleable.View_nestedScrollingEnabled:
4011                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4012                    break;
4013                case R.styleable.View_stateListAnimator:
4014                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4015                            a.getResourceId(attr, 0)));
4016                    break;
4017                case R.styleable.View_backgroundTint:
4018                    // This will get applied later during setBackground().
4019                    mBackgroundTintList = a.getColorStateList(R.styleable.View_backgroundTint);
4020                    mHasBackgroundTint = true;
4021                    break;
4022                case R.styleable.View_backgroundTintMode:
4023                    // This will get applied later during setBackground().
4024                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4025                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4026                    break;
4027            }
4028        }
4029
4030        setOverScrollMode(overScrollMode);
4031
4032        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4033        // the resolved layout direction). Those cached values will be used later during padding
4034        // resolution.
4035        mUserPaddingStart = startPadding;
4036        mUserPaddingEnd = endPadding;
4037
4038        if (background != null) {
4039            setBackground(background);
4040        }
4041
4042        // setBackground above will record that padding is currently provided by the background.
4043        // If we have padding specified via xml, record that here instead and use it.
4044        mLeftPaddingDefined = leftPaddingDefined;
4045        mRightPaddingDefined = rightPaddingDefined;
4046
4047        if (padding >= 0) {
4048            leftPadding = padding;
4049            topPadding = padding;
4050            rightPadding = padding;
4051            bottomPadding = padding;
4052            mUserPaddingLeftInitial = padding;
4053            mUserPaddingRightInitial = padding;
4054        }
4055
4056        if (isRtlCompatibilityMode()) {
4057            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4058            // left / right padding are used if defined (meaning here nothing to do). If they are not
4059            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4060            // start / end and resolve them as left / right (layout direction is not taken into account).
4061            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4062            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4063            // defined.
4064            if (!mLeftPaddingDefined && startPaddingDefined) {
4065                leftPadding = startPadding;
4066            }
4067            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4068            if (!mRightPaddingDefined && endPaddingDefined) {
4069                rightPadding = endPadding;
4070            }
4071            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4072        } else {
4073            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4074            // values defined. Otherwise, left /right values are used.
4075            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4076            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4077            // defined.
4078            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4079
4080            if (mLeftPaddingDefined && !hasRelativePadding) {
4081                mUserPaddingLeftInitial = leftPadding;
4082            }
4083            if (mRightPaddingDefined && !hasRelativePadding) {
4084                mUserPaddingRightInitial = rightPadding;
4085            }
4086        }
4087
4088        internalSetPadding(
4089                mUserPaddingLeftInitial,
4090                topPadding >= 0 ? topPadding : mPaddingTop,
4091                mUserPaddingRightInitial,
4092                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4093
4094        if (viewFlagMasks != 0) {
4095            setFlags(viewFlagValues, viewFlagMasks);
4096        }
4097
4098        if (initializeScrollbars) {
4099            initializeScrollbarsInternal(a);
4100        }
4101
4102        a.recycle();
4103
4104        // Needs to be called after mViewFlags is set
4105        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4106            recomputePadding();
4107        }
4108
4109        if (x != 0 || y != 0) {
4110            scrollTo(x, y);
4111        }
4112
4113        if (transformSet) {
4114            setTranslationX(tx);
4115            setTranslationY(ty);
4116            setTranslationZ(tz);
4117            setElevation(elevation);
4118            setRotation(rotation);
4119            setRotationX(rotationX);
4120            setRotationY(rotationY);
4121            setScaleX(sx);
4122            setScaleY(sy);
4123        }
4124
4125        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4126            setScrollContainer(true);
4127        }
4128
4129        computeOpaqueFlags();
4130    }
4131
4132    /**
4133     * Non-public constructor for use in testing
4134     */
4135    View() {
4136        mResources = null;
4137        mRenderNode = RenderNode.create(getClass().getName());
4138    }
4139
4140    public String toString() {
4141        StringBuilder out = new StringBuilder(128);
4142        out.append(getClass().getName());
4143        out.append('{');
4144        out.append(Integer.toHexString(System.identityHashCode(this)));
4145        out.append(' ');
4146        switch (mViewFlags&VISIBILITY_MASK) {
4147            case VISIBLE: out.append('V'); break;
4148            case INVISIBLE: out.append('I'); break;
4149            case GONE: out.append('G'); break;
4150            default: out.append('.'); break;
4151        }
4152        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4153        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4154        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4155        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4156        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4157        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4158        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4159        out.append(' ');
4160        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4161        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4162        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4163        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4164            out.append('p');
4165        } else {
4166            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4167        }
4168        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4169        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4170        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4171        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4172        out.append(' ');
4173        out.append(mLeft);
4174        out.append(',');
4175        out.append(mTop);
4176        out.append('-');
4177        out.append(mRight);
4178        out.append(',');
4179        out.append(mBottom);
4180        final int id = getId();
4181        if (id != NO_ID) {
4182            out.append(" #");
4183            out.append(Integer.toHexString(id));
4184            final Resources r = mResources;
4185            if (Resources.resourceHasPackage(id) && r != null) {
4186                try {
4187                    String pkgname;
4188                    switch (id&0xff000000) {
4189                        case 0x7f000000:
4190                            pkgname="app";
4191                            break;
4192                        case 0x01000000:
4193                            pkgname="android";
4194                            break;
4195                        default:
4196                            pkgname = r.getResourcePackageName(id);
4197                            break;
4198                    }
4199                    String typename = r.getResourceTypeName(id);
4200                    String entryname = r.getResourceEntryName(id);
4201                    out.append(" ");
4202                    out.append(pkgname);
4203                    out.append(":");
4204                    out.append(typename);
4205                    out.append("/");
4206                    out.append(entryname);
4207                } catch (Resources.NotFoundException e) {
4208                }
4209            }
4210        }
4211        out.append("}");
4212        return out.toString();
4213    }
4214
4215    /**
4216     * <p>
4217     * Initializes the fading edges from a given set of styled attributes. This
4218     * method should be called by subclasses that need fading edges and when an
4219     * instance of these subclasses is created programmatically rather than
4220     * being inflated from XML. This method is automatically called when the XML
4221     * is inflated.
4222     * </p>
4223     *
4224     * @param a the styled attributes set to initialize the fading edges from
4225     */
4226    protected void initializeFadingEdge(TypedArray a) {
4227        // This method probably shouldn't have been included in the SDK to begin with.
4228        // It relies on 'a' having been initialized using an attribute filter array that is
4229        // not publicly available to the SDK. The old method has been renamed
4230        // to initializeFadingEdgeInternal and hidden for framework use only;
4231        // this one initializes using defaults to make it safe to call for apps.
4232
4233        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4234
4235        initializeFadingEdgeInternal(arr);
4236
4237        arr.recycle();
4238    }
4239
4240    /**
4241     * <p>
4242     * Initializes the fading edges from a given set of styled attributes. This
4243     * method should be called by subclasses that need fading edges and when an
4244     * instance of these subclasses is created programmatically rather than
4245     * being inflated from XML. This method is automatically called when the XML
4246     * is inflated.
4247     * </p>
4248     *
4249     * @param a the styled attributes set to initialize the fading edges from
4250     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4251     */
4252    protected void initializeFadingEdgeInternal(TypedArray a) {
4253        initScrollCache();
4254
4255        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4256                R.styleable.View_fadingEdgeLength,
4257                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4258    }
4259
4260    /**
4261     * Returns the size of the vertical faded edges used to indicate that more
4262     * content in this view is visible.
4263     *
4264     * @return The size in pixels of the vertical faded edge or 0 if vertical
4265     *         faded edges are not enabled for this view.
4266     * @attr ref android.R.styleable#View_fadingEdgeLength
4267     */
4268    public int getVerticalFadingEdgeLength() {
4269        if (isVerticalFadingEdgeEnabled()) {
4270            ScrollabilityCache cache = mScrollCache;
4271            if (cache != null) {
4272                return cache.fadingEdgeLength;
4273            }
4274        }
4275        return 0;
4276    }
4277
4278    /**
4279     * Set the size of the faded edge used to indicate that more content in this
4280     * view is available.  Will not change whether the fading edge is enabled; use
4281     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4282     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4283     * for the vertical or horizontal fading edges.
4284     *
4285     * @param length The size in pixels of the faded edge used to indicate that more
4286     *        content in this view is visible.
4287     */
4288    public void setFadingEdgeLength(int length) {
4289        initScrollCache();
4290        mScrollCache.fadingEdgeLength = length;
4291    }
4292
4293    /**
4294     * Returns the size of the horizontal faded edges used to indicate that more
4295     * content in this view is visible.
4296     *
4297     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4298     *         faded edges are not enabled for this view.
4299     * @attr ref android.R.styleable#View_fadingEdgeLength
4300     */
4301    public int getHorizontalFadingEdgeLength() {
4302        if (isHorizontalFadingEdgeEnabled()) {
4303            ScrollabilityCache cache = mScrollCache;
4304            if (cache != null) {
4305                return cache.fadingEdgeLength;
4306            }
4307        }
4308        return 0;
4309    }
4310
4311    /**
4312     * Returns the width of the vertical scrollbar.
4313     *
4314     * @return The width in pixels of the vertical scrollbar or 0 if there
4315     *         is no vertical scrollbar.
4316     */
4317    public int getVerticalScrollbarWidth() {
4318        ScrollabilityCache cache = mScrollCache;
4319        if (cache != null) {
4320            ScrollBarDrawable scrollBar = cache.scrollBar;
4321            if (scrollBar != null) {
4322                int size = scrollBar.getSize(true);
4323                if (size <= 0) {
4324                    size = cache.scrollBarSize;
4325                }
4326                return size;
4327            }
4328            return 0;
4329        }
4330        return 0;
4331    }
4332
4333    /**
4334     * Returns the height of the horizontal scrollbar.
4335     *
4336     * @return The height in pixels of the horizontal scrollbar or 0 if
4337     *         there is no horizontal scrollbar.
4338     */
4339    protected int getHorizontalScrollbarHeight() {
4340        ScrollabilityCache cache = mScrollCache;
4341        if (cache != null) {
4342            ScrollBarDrawable scrollBar = cache.scrollBar;
4343            if (scrollBar != null) {
4344                int size = scrollBar.getSize(false);
4345                if (size <= 0) {
4346                    size = cache.scrollBarSize;
4347                }
4348                return size;
4349            }
4350            return 0;
4351        }
4352        return 0;
4353    }
4354
4355    /**
4356     * <p>
4357     * Initializes the scrollbars from a given set of styled attributes. This
4358     * method should be called by subclasses that need scrollbars and when an
4359     * instance of these subclasses is created programmatically rather than
4360     * being inflated from XML. This method is automatically called when the XML
4361     * is inflated.
4362     * </p>
4363     *
4364     * @param a the styled attributes set to initialize the scrollbars from
4365     */
4366    protected void initializeScrollbars(TypedArray a) {
4367        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4368        // using the View filter array which is not available to the SDK. As such, internal
4369        // framework usage now uses initializeScrollbarsInternal and we grab a default
4370        // TypedArray with the right filter instead here.
4371        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4372
4373        initializeScrollbarsInternal(arr);
4374
4375        // We ignored the method parameter. Recycle the one we actually did use.
4376        arr.recycle();
4377    }
4378
4379    /**
4380     * <p>
4381     * Initializes the scrollbars from a given set of styled attributes. This
4382     * method should be called by subclasses that need scrollbars and when an
4383     * instance of these subclasses is created programmatically rather than
4384     * being inflated from XML. This method is automatically called when the XML
4385     * is inflated.
4386     * </p>
4387     *
4388     * @param a the styled attributes set to initialize the scrollbars from
4389     * @hide
4390     */
4391    protected void initializeScrollbarsInternal(TypedArray a) {
4392        initScrollCache();
4393
4394        final ScrollabilityCache scrollabilityCache = mScrollCache;
4395
4396        if (scrollabilityCache.scrollBar == null) {
4397            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4398        }
4399
4400        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4401
4402        if (!fadeScrollbars) {
4403            scrollabilityCache.state = ScrollabilityCache.ON;
4404        }
4405        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4406
4407
4408        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4409                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4410                        .getScrollBarFadeDuration());
4411        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4412                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4413                ViewConfiguration.getScrollDefaultDelay());
4414
4415
4416        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4417                com.android.internal.R.styleable.View_scrollbarSize,
4418                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4419
4420        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4421        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4422
4423        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4424        if (thumb != null) {
4425            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4426        }
4427
4428        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4429                false);
4430        if (alwaysDraw) {
4431            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4432        }
4433
4434        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4435        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4436
4437        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4438        if (thumb != null) {
4439            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4440        }
4441
4442        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4443                false);
4444        if (alwaysDraw) {
4445            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4446        }
4447
4448        // Apply layout direction to the new Drawables if needed
4449        final int layoutDirection = getLayoutDirection();
4450        if (track != null) {
4451            track.setLayoutDirection(layoutDirection);
4452        }
4453        if (thumb != null) {
4454            thumb.setLayoutDirection(layoutDirection);
4455        }
4456
4457        // Re-apply user/background padding so that scrollbar(s) get added
4458        resolvePadding();
4459    }
4460
4461    /**
4462     * <p>
4463     * Initalizes the scrollability cache if necessary.
4464     * </p>
4465     */
4466    private void initScrollCache() {
4467        if (mScrollCache == null) {
4468            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4469        }
4470    }
4471
4472    private ScrollabilityCache getScrollCache() {
4473        initScrollCache();
4474        return mScrollCache;
4475    }
4476
4477    /**
4478     * Set the position of the vertical scroll bar. Should be one of
4479     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4480     * {@link #SCROLLBAR_POSITION_RIGHT}.
4481     *
4482     * @param position Where the vertical scroll bar should be positioned.
4483     */
4484    public void setVerticalScrollbarPosition(int position) {
4485        if (mVerticalScrollbarPosition != position) {
4486            mVerticalScrollbarPosition = position;
4487            computeOpaqueFlags();
4488            resolvePadding();
4489        }
4490    }
4491
4492    /**
4493     * @return The position where the vertical scroll bar will show, if applicable.
4494     * @see #setVerticalScrollbarPosition(int)
4495     */
4496    public int getVerticalScrollbarPosition() {
4497        return mVerticalScrollbarPosition;
4498    }
4499
4500    ListenerInfo getListenerInfo() {
4501        if (mListenerInfo != null) {
4502            return mListenerInfo;
4503        }
4504        mListenerInfo = new ListenerInfo();
4505        return mListenerInfo;
4506    }
4507
4508    /**
4509     * Register a callback to be invoked when focus of this view changed.
4510     *
4511     * @param l The callback that will run.
4512     */
4513    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4514        getListenerInfo().mOnFocusChangeListener = l;
4515    }
4516
4517    /**
4518     * Add a listener that will be called when the bounds of the view change due to
4519     * layout processing.
4520     *
4521     * @param listener The listener that will be called when layout bounds change.
4522     */
4523    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4524        ListenerInfo li = getListenerInfo();
4525        if (li.mOnLayoutChangeListeners == null) {
4526            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4527        }
4528        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4529            li.mOnLayoutChangeListeners.add(listener);
4530        }
4531    }
4532
4533    /**
4534     * Remove a listener for layout changes.
4535     *
4536     * @param listener The listener for layout bounds change.
4537     */
4538    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4539        ListenerInfo li = mListenerInfo;
4540        if (li == null || li.mOnLayoutChangeListeners == null) {
4541            return;
4542        }
4543        li.mOnLayoutChangeListeners.remove(listener);
4544    }
4545
4546    /**
4547     * Add a listener for attach state changes.
4548     *
4549     * This listener will be called whenever this view is attached or detached
4550     * from a window. Remove the listener using
4551     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4552     *
4553     * @param listener Listener to attach
4554     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4555     */
4556    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4557        ListenerInfo li = getListenerInfo();
4558        if (li.mOnAttachStateChangeListeners == null) {
4559            li.mOnAttachStateChangeListeners
4560                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4561        }
4562        li.mOnAttachStateChangeListeners.add(listener);
4563    }
4564
4565    /**
4566     * Remove a listener for attach state changes. The listener will receive no further
4567     * notification of window attach/detach events.
4568     *
4569     * @param listener Listener to remove
4570     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4571     */
4572    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4573        ListenerInfo li = mListenerInfo;
4574        if (li == null || li.mOnAttachStateChangeListeners == null) {
4575            return;
4576        }
4577        li.mOnAttachStateChangeListeners.remove(listener);
4578    }
4579
4580    /**
4581     * Returns the focus-change callback registered for this view.
4582     *
4583     * @return The callback, or null if one is not registered.
4584     */
4585    public OnFocusChangeListener getOnFocusChangeListener() {
4586        ListenerInfo li = mListenerInfo;
4587        return li != null ? li.mOnFocusChangeListener : null;
4588    }
4589
4590    /**
4591     * Register a callback to be invoked when this view is clicked. If this view is not
4592     * clickable, it becomes clickable.
4593     *
4594     * @param l The callback that will run
4595     *
4596     * @see #setClickable(boolean)
4597     */
4598    public void setOnClickListener(OnClickListener l) {
4599        if (!isClickable()) {
4600            setClickable(true);
4601        }
4602        getListenerInfo().mOnClickListener = l;
4603    }
4604
4605    /**
4606     * Return whether this view has an attached OnClickListener.  Returns
4607     * true if there is a listener, false if there is none.
4608     */
4609    public boolean hasOnClickListeners() {
4610        ListenerInfo li = mListenerInfo;
4611        return (li != null && li.mOnClickListener != null);
4612    }
4613
4614    /**
4615     * Register a callback to be invoked when this view is clicked and held. If this view is not
4616     * long clickable, it becomes long clickable.
4617     *
4618     * @param l The callback that will run
4619     *
4620     * @see #setLongClickable(boolean)
4621     */
4622    public void setOnLongClickListener(OnLongClickListener l) {
4623        if (!isLongClickable()) {
4624            setLongClickable(true);
4625        }
4626        getListenerInfo().mOnLongClickListener = l;
4627    }
4628
4629    /**
4630     * Register a callback to be invoked when the context menu for this view is
4631     * being built. If this view is not long clickable, it becomes long clickable.
4632     *
4633     * @param l The callback that will run
4634     *
4635     */
4636    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4637        if (!isLongClickable()) {
4638            setLongClickable(true);
4639        }
4640        getListenerInfo().mOnCreateContextMenuListener = l;
4641    }
4642
4643    /**
4644     * Call this view's OnClickListener, if it is defined.  Performs all normal
4645     * actions associated with clicking: reporting accessibility event, playing
4646     * a sound, etc.
4647     *
4648     * @return True there was an assigned OnClickListener that was called, false
4649     *         otherwise is returned.
4650     */
4651    public boolean performClick() {
4652        final boolean result;
4653        final ListenerInfo li = mListenerInfo;
4654        if (li != null && li.mOnClickListener != null) {
4655            playSoundEffect(SoundEffectConstants.CLICK);
4656            li.mOnClickListener.onClick(this);
4657            result = true;
4658        } else {
4659            result = false;
4660        }
4661
4662        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4663        return result;
4664    }
4665
4666    /**
4667     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4668     * this only calls the listener, and does not do any associated clicking
4669     * actions like reporting an accessibility event.
4670     *
4671     * @return True there was an assigned OnClickListener that was called, false
4672     *         otherwise is returned.
4673     */
4674    public boolean callOnClick() {
4675        ListenerInfo li = mListenerInfo;
4676        if (li != null && li.mOnClickListener != null) {
4677            li.mOnClickListener.onClick(this);
4678            return true;
4679        }
4680        return false;
4681    }
4682
4683    /**
4684     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4685     * OnLongClickListener did not consume the event.
4686     *
4687     * @return True if one of the above receivers consumed the event, false otherwise.
4688     */
4689    public boolean performLongClick() {
4690        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4691
4692        boolean handled = false;
4693        ListenerInfo li = mListenerInfo;
4694        if (li != null && li.mOnLongClickListener != null) {
4695            handled = li.mOnLongClickListener.onLongClick(View.this);
4696        }
4697        if (!handled) {
4698            handled = showContextMenu();
4699        }
4700        if (handled) {
4701            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4702        }
4703        return handled;
4704    }
4705
4706    /**
4707     * Performs button-related actions during a touch down event.
4708     *
4709     * @param event The event.
4710     * @return True if the down was consumed.
4711     *
4712     * @hide
4713     */
4714    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4715        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4716            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4717                return true;
4718            }
4719        }
4720        return false;
4721    }
4722
4723    /**
4724     * Bring up the context menu for this view.
4725     *
4726     * @return Whether a context menu was displayed.
4727     */
4728    public boolean showContextMenu() {
4729        return getParent().showContextMenuForChild(this);
4730    }
4731
4732    /**
4733     * Bring up the context menu for this view, referring to the item under the specified point.
4734     *
4735     * @param x The referenced x coordinate.
4736     * @param y The referenced y coordinate.
4737     * @param metaState The keyboard modifiers that were pressed.
4738     * @return Whether a context menu was displayed.
4739     *
4740     * @hide
4741     */
4742    public boolean showContextMenu(float x, float y, int metaState) {
4743        return showContextMenu();
4744    }
4745
4746    /**
4747     * Start an action mode.
4748     *
4749     * @param callback Callback that will control the lifecycle of the action mode
4750     * @return The new action mode if it is started, null otherwise
4751     *
4752     * @see ActionMode
4753     */
4754    public ActionMode startActionMode(ActionMode.Callback callback) {
4755        ViewParent parent = getParent();
4756        if (parent == null) return null;
4757        return parent.startActionModeForChild(this, callback);
4758    }
4759
4760    /**
4761     * Register a callback to be invoked when a hardware key is pressed in this view.
4762     * Key presses in software input methods will generally not trigger the methods of
4763     * this listener.
4764     * @param l the key listener to attach to this view
4765     */
4766    public void setOnKeyListener(OnKeyListener l) {
4767        getListenerInfo().mOnKeyListener = l;
4768    }
4769
4770    /**
4771     * Register a callback to be invoked when a touch event is sent to this view.
4772     * @param l the touch listener to attach to this view
4773     */
4774    public void setOnTouchListener(OnTouchListener l) {
4775        getListenerInfo().mOnTouchListener = l;
4776    }
4777
4778    /**
4779     * Register a callback to be invoked when a generic motion event is sent to this view.
4780     * @param l the generic motion listener to attach to this view
4781     */
4782    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4783        getListenerInfo().mOnGenericMotionListener = l;
4784    }
4785
4786    /**
4787     * Register a callback to be invoked when a hover event is sent to this view.
4788     * @param l the hover listener to attach to this view
4789     */
4790    public void setOnHoverListener(OnHoverListener l) {
4791        getListenerInfo().mOnHoverListener = l;
4792    }
4793
4794    /**
4795     * Register a drag event listener callback object for this View. The parameter is
4796     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4797     * View, the system calls the
4798     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4799     * @param l An implementation of {@link android.view.View.OnDragListener}.
4800     */
4801    public void setOnDragListener(OnDragListener l) {
4802        getListenerInfo().mOnDragListener = l;
4803    }
4804
4805    /**
4806     * Give this view focus. This will cause
4807     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4808     *
4809     * Note: this does not check whether this {@link View} should get focus, it just
4810     * gives it focus no matter what.  It should only be called internally by framework
4811     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4812     *
4813     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4814     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4815     *        focus moved when requestFocus() is called. It may not always
4816     *        apply, in which case use the default View.FOCUS_DOWN.
4817     * @param previouslyFocusedRect The rectangle of the view that had focus
4818     *        prior in this View's coordinate system.
4819     */
4820    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4821        if (DBG) {
4822            System.out.println(this + " requestFocus()");
4823        }
4824
4825        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4826            mPrivateFlags |= PFLAG_FOCUSED;
4827
4828            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4829
4830            if (mParent != null) {
4831                mParent.requestChildFocus(this, this);
4832            }
4833
4834            if (mAttachInfo != null) {
4835                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4836            }
4837
4838            onFocusChanged(true, direction, previouslyFocusedRect);
4839            manageFocusHotspot(true, oldFocus);
4840            refreshDrawableState();
4841        }
4842    }
4843
4844    /**
4845     * Forwards focus information to the background drawable, if necessary. When
4846     * the view is gaining focus, <code>v</code> is the previous focus holder.
4847     * When the view is losing focus, <code>v</code> is the next focus holder.
4848     *
4849     * @param focused whether this view is focused
4850     * @param v previous or the next focus holder, or null if none
4851     */
4852    private void manageFocusHotspot(boolean focused, View v) {
4853        final Rect r = new Rect();
4854        if (v != null && mAttachInfo != null) {
4855            v.getHotspotBounds(r);
4856            final int[] location = mAttachInfo.mTmpLocation;
4857            getLocationOnScreen(location);
4858            r.offset(-location[0], -location[1]);
4859        } else {
4860            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4861        }
4862
4863        final float x = r.exactCenterX();
4864        final float y = r.exactCenterY();
4865        drawableHotspotChanged(x, y);
4866    }
4867
4868    /**
4869     * Populates <code>outRect</code> with the hotspot bounds. By default,
4870     * the hotspot bounds are identical to the screen bounds.
4871     *
4872     * @param outRect rect to populate with hotspot bounds
4873     * @hide Only for internal use by views and widgets.
4874     */
4875    public void getHotspotBounds(Rect outRect) {
4876        final Drawable background = getBackground();
4877        if (background != null) {
4878            background.getHotspotBounds(outRect);
4879        } else {
4880            getBoundsOnScreen(outRect);
4881        }
4882    }
4883
4884    /**
4885     * Request that a rectangle of this view be visible on the screen,
4886     * scrolling if necessary just enough.
4887     *
4888     * <p>A View should call this if it maintains some notion of which part
4889     * of its content is interesting.  For example, a text editing view
4890     * should call this when its cursor moves.
4891     *
4892     * @param rectangle The rectangle.
4893     * @return Whether any parent scrolled.
4894     */
4895    public boolean requestRectangleOnScreen(Rect rectangle) {
4896        return requestRectangleOnScreen(rectangle, false);
4897    }
4898
4899    /**
4900     * Request that a rectangle of this view be visible on the screen,
4901     * scrolling if necessary just enough.
4902     *
4903     * <p>A View should call this if it maintains some notion of which part
4904     * of its content is interesting.  For example, a text editing view
4905     * should call this when its cursor moves.
4906     *
4907     * <p>When <code>immediate</code> is set to true, scrolling will not be
4908     * animated.
4909     *
4910     * @param rectangle The rectangle.
4911     * @param immediate True to forbid animated scrolling, false otherwise
4912     * @return Whether any parent scrolled.
4913     */
4914    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4915        if (mParent == null) {
4916            return false;
4917        }
4918
4919        View child = this;
4920
4921        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4922        position.set(rectangle);
4923
4924        ViewParent parent = mParent;
4925        boolean scrolled = false;
4926        while (parent != null) {
4927            rectangle.set((int) position.left, (int) position.top,
4928                    (int) position.right, (int) position.bottom);
4929
4930            scrolled |= parent.requestChildRectangleOnScreen(child,
4931                    rectangle, immediate);
4932
4933            if (!child.hasIdentityMatrix()) {
4934                child.getMatrix().mapRect(position);
4935            }
4936
4937            position.offset(child.mLeft, child.mTop);
4938
4939            if (!(parent instanceof View)) {
4940                break;
4941            }
4942
4943            View parentView = (View) parent;
4944
4945            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4946
4947            child = parentView;
4948            parent = child.getParent();
4949        }
4950
4951        return scrolled;
4952    }
4953
4954    /**
4955     * Called when this view wants to give up focus. If focus is cleared
4956     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4957     * <p>
4958     * <strong>Note:</strong> When a View clears focus the framework is trying
4959     * to give focus to the first focusable View from the top. Hence, if this
4960     * View is the first from the top that can take focus, then all callbacks
4961     * related to clearing focus will be invoked after wich the framework will
4962     * give focus to this view.
4963     * </p>
4964     */
4965    public void clearFocus() {
4966        if (DBG) {
4967            System.out.println(this + " clearFocus()");
4968        }
4969
4970        clearFocusInternal(null, true, true);
4971    }
4972
4973    /**
4974     * Clears focus from the view, optionally propagating the change up through
4975     * the parent hierarchy and requesting that the root view place new focus.
4976     *
4977     * @param propagate whether to propagate the change up through the parent
4978     *            hierarchy
4979     * @param refocus when propagate is true, specifies whether to request the
4980     *            root view place new focus
4981     */
4982    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4983        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4984            mPrivateFlags &= ~PFLAG_FOCUSED;
4985
4986            if (propagate && mParent != null) {
4987                mParent.clearChildFocus(this);
4988            }
4989
4990            onFocusChanged(false, 0, null);
4991
4992            manageFocusHotspot(false, focused);
4993            refreshDrawableState();
4994
4995            if (propagate && (!refocus || !rootViewRequestFocus())) {
4996                notifyGlobalFocusCleared(this);
4997            }
4998        }
4999    }
5000
5001    void notifyGlobalFocusCleared(View oldFocus) {
5002        if (oldFocus != null && mAttachInfo != null) {
5003            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5004        }
5005    }
5006
5007    boolean rootViewRequestFocus() {
5008        final View root = getRootView();
5009        return root != null && root.requestFocus();
5010    }
5011
5012    /**
5013     * Called internally by the view system when a new view is getting focus.
5014     * This is what clears the old focus.
5015     * <p>
5016     * <b>NOTE:</b> The parent view's focused child must be updated manually
5017     * after calling this method. Otherwise, the view hierarchy may be left in
5018     * an inconstent state.
5019     */
5020    void unFocus(View focused) {
5021        if (DBG) {
5022            System.out.println(this + " unFocus()");
5023        }
5024
5025        clearFocusInternal(focused, false, false);
5026    }
5027
5028    /**
5029     * Returns true if this view has focus iteself, or is the ancestor of the
5030     * view that has focus.
5031     *
5032     * @return True if this view has or contains focus, false otherwise.
5033     */
5034    @ViewDebug.ExportedProperty(category = "focus")
5035    public boolean hasFocus() {
5036        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5037    }
5038
5039    /**
5040     * Returns true if this view is focusable or if it contains a reachable View
5041     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5042     * is a View whose parents do not block descendants focus.
5043     *
5044     * Only {@link #VISIBLE} views are considered focusable.
5045     *
5046     * @return True if the view is focusable or if the view contains a focusable
5047     *         View, false otherwise.
5048     *
5049     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5050     * @see ViewGroup#getTouchscreenBlocksFocus()
5051     */
5052    public boolean hasFocusable() {
5053        if (!isFocusableInTouchMode()) {
5054            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5055                final ViewGroup g = (ViewGroup) p;
5056                if (g.shouldBlockFocusForTouchscreen()) {
5057                    return false;
5058                }
5059            }
5060        }
5061        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5062    }
5063
5064    /**
5065     * Called by the view system when the focus state of this view changes.
5066     * When the focus change event is caused by directional navigation, direction
5067     * and previouslyFocusedRect provide insight into where the focus is coming from.
5068     * When overriding, be sure to call up through to the super class so that
5069     * the standard focus handling will occur.
5070     *
5071     * @param gainFocus True if the View has focus; false otherwise.
5072     * @param direction The direction focus has moved when requestFocus()
5073     *                  is called to give this view focus. Values are
5074     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5075     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5076     *                  It may not always apply, in which case use the default.
5077     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5078     *        system, of the previously focused view.  If applicable, this will be
5079     *        passed in as finer grained information about where the focus is coming
5080     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5081     */
5082    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5083            @Nullable Rect previouslyFocusedRect) {
5084        if (gainFocus) {
5085            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5086        } else {
5087            notifyViewAccessibilityStateChangedIfNeeded(
5088                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5089        }
5090
5091        InputMethodManager imm = InputMethodManager.peekInstance();
5092        if (!gainFocus) {
5093            if (isPressed()) {
5094                setPressed(false);
5095            }
5096            if (imm != null && mAttachInfo != null
5097                    && mAttachInfo.mHasWindowFocus) {
5098                imm.focusOut(this);
5099            }
5100            onFocusLost();
5101        } else if (imm != null && mAttachInfo != null
5102                && mAttachInfo.mHasWindowFocus) {
5103            imm.focusIn(this);
5104        }
5105
5106        invalidate(true);
5107        ListenerInfo li = mListenerInfo;
5108        if (li != null && li.mOnFocusChangeListener != null) {
5109            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5110        }
5111
5112        if (mAttachInfo != null) {
5113            mAttachInfo.mKeyDispatchState.reset(this);
5114        }
5115    }
5116
5117    /**
5118     * Sends an accessibility event of the given type. If accessibility is
5119     * not enabled this method has no effect. The default implementation calls
5120     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5121     * to populate information about the event source (this View), then calls
5122     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5123     * populate the text content of the event source including its descendants,
5124     * and last calls
5125     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5126     * on its parent to resuest sending of the event to interested parties.
5127     * <p>
5128     * If an {@link AccessibilityDelegate} has been specified via calling
5129     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5130     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5131     * responsible for handling this call.
5132     * </p>
5133     *
5134     * @param eventType The type of the event to send, as defined by several types from
5135     * {@link android.view.accessibility.AccessibilityEvent}, such as
5136     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5137     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5138     *
5139     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5140     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5141     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5142     * @see AccessibilityDelegate
5143     */
5144    public void sendAccessibilityEvent(int eventType) {
5145        if (mAccessibilityDelegate != null) {
5146            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5147        } else {
5148            sendAccessibilityEventInternal(eventType);
5149        }
5150    }
5151
5152    /**
5153     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5154     * {@link AccessibilityEvent} to make an announcement which is related to some
5155     * sort of a context change for which none of the events representing UI transitions
5156     * is a good fit. For example, announcing a new page in a book. If accessibility
5157     * is not enabled this method does nothing.
5158     *
5159     * @param text The announcement text.
5160     */
5161    public void announceForAccessibility(CharSequence text) {
5162        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5163            AccessibilityEvent event = AccessibilityEvent.obtain(
5164                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5165            onInitializeAccessibilityEvent(event);
5166            event.getText().add(text);
5167            event.setContentDescription(null);
5168            mParent.requestSendAccessibilityEvent(this, event);
5169        }
5170    }
5171
5172    /**
5173     * @see #sendAccessibilityEvent(int)
5174     *
5175     * Note: Called from the default {@link AccessibilityDelegate}.
5176     */
5177    void sendAccessibilityEventInternal(int eventType) {
5178        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5179            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5180        }
5181    }
5182
5183    /**
5184     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5185     * takes as an argument an empty {@link AccessibilityEvent} and does not
5186     * perform a check whether accessibility is enabled.
5187     * <p>
5188     * If an {@link AccessibilityDelegate} has been specified via calling
5189     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5190     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5191     * is responsible for handling this call.
5192     * </p>
5193     *
5194     * @param event The event to send.
5195     *
5196     * @see #sendAccessibilityEvent(int)
5197     */
5198    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5199        if (mAccessibilityDelegate != null) {
5200            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5201        } else {
5202            sendAccessibilityEventUncheckedInternal(event);
5203        }
5204    }
5205
5206    /**
5207     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5208     *
5209     * Note: Called from the default {@link AccessibilityDelegate}.
5210     */
5211    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5212        if (!isShown()) {
5213            return;
5214        }
5215        onInitializeAccessibilityEvent(event);
5216        // Only a subset of accessibility events populates text content.
5217        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5218            dispatchPopulateAccessibilityEvent(event);
5219        }
5220        // In the beginning we called #isShown(), so we know that getParent() is not null.
5221        getParent().requestSendAccessibilityEvent(this, event);
5222    }
5223
5224    /**
5225     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5226     * to its children for adding their text content to the event. Note that the
5227     * event text is populated in a separate dispatch path since we add to the
5228     * event not only the text of the source but also the text of all its descendants.
5229     * A typical implementation will call
5230     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5231     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5232     * on each child. Override this method if custom population of the event text
5233     * content is required.
5234     * <p>
5235     * If an {@link AccessibilityDelegate} has been specified via calling
5236     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5237     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5238     * is responsible for handling this call.
5239     * </p>
5240     * <p>
5241     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5242     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5243     * </p>
5244     *
5245     * @param event The event.
5246     *
5247     * @return True if the event population was completed.
5248     */
5249    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5250        if (mAccessibilityDelegate != null) {
5251            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5252        } else {
5253            return dispatchPopulateAccessibilityEventInternal(event);
5254        }
5255    }
5256
5257    /**
5258     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5259     *
5260     * Note: Called from the default {@link AccessibilityDelegate}.
5261     */
5262    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5263        onPopulateAccessibilityEvent(event);
5264        return false;
5265    }
5266
5267    /**
5268     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5269     * giving a chance to this View to populate the accessibility event with its
5270     * text content. While this method is free to modify event
5271     * attributes other than text content, doing so should normally be performed in
5272     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5273     * <p>
5274     * Example: Adding formatted date string to an accessibility event in addition
5275     *          to the text added by the super implementation:
5276     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5277     *     super.onPopulateAccessibilityEvent(event);
5278     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5279     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5280     *         mCurrentDate.getTimeInMillis(), flags);
5281     *     event.getText().add(selectedDateUtterance);
5282     * }</pre>
5283     * <p>
5284     * If an {@link AccessibilityDelegate} has been specified via calling
5285     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5286     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5287     * is responsible for handling this call.
5288     * </p>
5289     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5290     * information to the event, in case the default implementation has basic information to add.
5291     * </p>
5292     *
5293     * @param event The accessibility event which to populate.
5294     *
5295     * @see #sendAccessibilityEvent(int)
5296     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5297     */
5298    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5299        if (mAccessibilityDelegate != null) {
5300            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5301        } else {
5302            onPopulateAccessibilityEventInternal(event);
5303        }
5304    }
5305
5306    /**
5307     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5308     *
5309     * Note: Called from the default {@link AccessibilityDelegate}.
5310     */
5311    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5312    }
5313
5314    /**
5315     * Initializes an {@link AccessibilityEvent} with information about
5316     * this View which is the event source. In other words, the source of
5317     * an accessibility event is the view whose state change triggered firing
5318     * the event.
5319     * <p>
5320     * Example: Setting the password property of an event in addition
5321     *          to properties set by the super implementation:
5322     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5323     *     super.onInitializeAccessibilityEvent(event);
5324     *     event.setPassword(true);
5325     * }</pre>
5326     * <p>
5327     * If an {@link AccessibilityDelegate} has been specified via calling
5328     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5329     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5330     * is responsible for handling this call.
5331     * </p>
5332     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5333     * information to the event, in case the default implementation has basic information to add.
5334     * </p>
5335     * @param event The event to initialize.
5336     *
5337     * @see #sendAccessibilityEvent(int)
5338     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5339     */
5340    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5341        if (mAccessibilityDelegate != null) {
5342            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5343        } else {
5344            onInitializeAccessibilityEventInternal(event);
5345        }
5346    }
5347
5348    /**
5349     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5350     *
5351     * Note: Called from the default {@link AccessibilityDelegate}.
5352     */
5353    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5354        event.setSource(this);
5355        event.setClassName(View.class.getName());
5356        event.setPackageName(getContext().getPackageName());
5357        event.setEnabled(isEnabled());
5358        event.setContentDescription(mContentDescription);
5359
5360        switch (event.getEventType()) {
5361            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5362                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5363                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5364                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5365                event.setItemCount(focusablesTempList.size());
5366                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5367                if (mAttachInfo != null) {
5368                    focusablesTempList.clear();
5369                }
5370            } break;
5371            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5372                CharSequence text = getIterableTextForAccessibility();
5373                if (text != null && text.length() > 0) {
5374                    event.setFromIndex(getAccessibilitySelectionStart());
5375                    event.setToIndex(getAccessibilitySelectionEnd());
5376                    event.setItemCount(text.length());
5377                }
5378            } break;
5379        }
5380    }
5381
5382    /**
5383     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5384     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5385     * This method is responsible for obtaining an accessibility node info from a
5386     * pool of reusable instances and calling
5387     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5388     * initialize the former.
5389     * <p>
5390     * Note: The client is responsible for recycling the obtained instance by calling
5391     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5392     * </p>
5393     *
5394     * @return A populated {@link AccessibilityNodeInfo}.
5395     *
5396     * @see AccessibilityNodeInfo
5397     */
5398    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5399        if (mAccessibilityDelegate != null) {
5400            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5401        } else {
5402            return createAccessibilityNodeInfoInternal();
5403        }
5404    }
5405
5406    /**
5407     * @see #createAccessibilityNodeInfo()
5408     */
5409    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5410        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5411        if (provider != null) {
5412            return provider.createAccessibilityNodeInfo(View.NO_ID);
5413        } else {
5414            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5415            onInitializeAccessibilityNodeInfo(info);
5416            return info;
5417        }
5418    }
5419
5420    /**
5421     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5422     * The base implementation sets:
5423     * <ul>
5424     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5425     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5426     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5427     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5428     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5429     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5430     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5431     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5432     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5433     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5434     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5435     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5436     * </ul>
5437     * <p>
5438     * Subclasses should override this method, call the super implementation,
5439     * and set additional attributes.
5440     * </p>
5441     * <p>
5442     * If an {@link AccessibilityDelegate} has been specified via calling
5443     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5444     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5445     * is responsible for handling this call.
5446     * </p>
5447     *
5448     * @param info The instance to initialize.
5449     */
5450    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5451        if (mAccessibilityDelegate != null) {
5452            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5453        } else {
5454            onInitializeAccessibilityNodeInfoInternal(info);
5455        }
5456    }
5457
5458    /**
5459     * Gets the location of this view in screen coordintates.
5460     *
5461     * @param outRect The output location
5462     * @hide
5463     */
5464    public void getBoundsOnScreen(Rect outRect) {
5465        if (mAttachInfo == null) {
5466            return;
5467        }
5468
5469        RectF position = mAttachInfo.mTmpTransformRect;
5470        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5471
5472        if (!hasIdentityMatrix()) {
5473            getMatrix().mapRect(position);
5474        }
5475
5476        position.offset(mLeft, mTop);
5477
5478        ViewParent parent = mParent;
5479        while (parent instanceof View) {
5480            View parentView = (View) parent;
5481
5482            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5483
5484            if (!parentView.hasIdentityMatrix()) {
5485                parentView.getMatrix().mapRect(position);
5486            }
5487
5488            position.offset(parentView.mLeft, parentView.mTop);
5489
5490            parent = parentView.mParent;
5491        }
5492
5493        if (parent instanceof ViewRootImpl) {
5494            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5495            position.offset(0, -viewRootImpl.mCurScrollY);
5496        }
5497
5498        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5499
5500        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5501                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5502    }
5503
5504    /**
5505     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5506     *
5507     * Note: Called from the default {@link AccessibilityDelegate}.
5508     */
5509    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5510        Rect bounds = mAttachInfo.mTmpInvalRect;
5511
5512        getDrawingRect(bounds);
5513        info.setBoundsInParent(bounds);
5514
5515        getBoundsOnScreen(bounds);
5516        info.setBoundsInScreen(bounds);
5517
5518        ViewParent parent = getParentForAccessibility();
5519        if (parent instanceof View) {
5520            info.setParent((View) parent);
5521        }
5522
5523        if (mID != View.NO_ID) {
5524            View rootView = getRootView();
5525            if (rootView == null) {
5526                rootView = this;
5527            }
5528            View label = rootView.findLabelForView(this, mID);
5529            if (label != null) {
5530                info.setLabeledBy(label);
5531            }
5532
5533            if ((mAttachInfo.mAccessibilityFetchFlags
5534                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5535                    && Resources.resourceHasPackage(mID)) {
5536                try {
5537                    String viewId = getResources().getResourceName(mID);
5538                    info.setViewIdResourceName(viewId);
5539                } catch (Resources.NotFoundException nfe) {
5540                    /* ignore */
5541                }
5542            }
5543        }
5544
5545        if (mLabelForId != View.NO_ID) {
5546            View rootView = getRootView();
5547            if (rootView == null) {
5548                rootView = this;
5549            }
5550            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5551            if (labeled != null) {
5552                info.setLabelFor(labeled);
5553            }
5554        }
5555
5556        info.setVisibleToUser(isVisibleToUser());
5557
5558        info.setPackageName(mContext.getPackageName());
5559        info.setClassName(View.class.getName());
5560        info.setContentDescription(getContentDescription());
5561
5562        info.setEnabled(isEnabled());
5563        info.setClickable(isClickable());
5564        info.setFocusable(isFocusable());
5565        info.setFocused(isFocused());
5566        info.setAccessibilityFocused(isAccessibilityFocused());
5567        info.setSelected(isSelected());
5568        info.setLongClickable(isLongClickable());
5569        info.setLiveRegion(getAccessibilityLiveRegion());
5570
5571        // TODO: These make sense only if we are in an AdapterView but all
5572        // views can be selected. Maybe from accessibility perspective
5573        // we should report as selectable view in an AdapterView.
5574        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5575        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5576
5577        if (isFocusable()) {
5578            if (isFocused()) {
5579                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5580            } else {
5581                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5582            }
5583        }
5584
5585        if (!isAccessibilityFocused()) {
5586            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5587        } else {
5588            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5589        }
5590
5591        if (isClickable() && isEnabled()) {
5592            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5593        }
5594
5595        if (isLongClickable() && isEnabled()) {
5596            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5597        }
5598
5599        CharSequence text = getIterableTextForAccessibility();
5600        if (text != null && text.length() > 0) {
5601            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5602
5603            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5604            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5605            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5606            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5607                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5608                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5609        }
5610    }
5611
5612    private View findLabelForView(View view, int labeledId) {
5613        if (mMatchLabelForPredicate == null) {
5614            mMatchLabelForPredicate = new MatchLabelForPredicate();
5615        }
5616        mMatchLabelForPredicate.mLabeledId = labeledId;
5617        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5618    }
5619
5620    /**
5621     * Computes whether this view is visible to the user. Such a view is
5622     * attached, visible, all its predecessors are visible, it is not clipped
5623     * entirely by its predecessors, and has an alpha greater than zero.
5624     *
5625     * @return Whether the view is visible on the screen.
5626     *
5627     * @hide
5628     */
5629    protected boolean isVisibleToUser() {
5630        return isVisibleToUser(null);
5631    }
5632
5633    /**
5634     * Computes whether the given portion of this view is visible to the user.
5635     * Such a view is attached, visible, all its predecessors are visible,
5636     * has an alpha greater than zero, and the specified portion is not
5637     * clipped entirely by its predecessors.
5638     *
5639     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5640     *                    <code>null</code>, and the entire view will be tested in this case.
5641     *                    When <code>true</code> is returned by the function, the actual visible
5642     *                    region will be stored in this parameter; that is, if boundInView is fully
5643     *                    contained within the view, no modification will be made, otherwise regions
5644     *                    outside of the visible area of the view will be clipped.
5645     *
5646     * @return Whether the specified portion of the view is visible on the screen.
5647     *
5648     * @hide
5649     */
5650    protected boolean isVisibleToUser(Rect boundInView) {
5651        if (mAttachInfo != null) {
5652            // Attached to invisible window means this view is not visible.
5653            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5654                return false;
5655            }
5656            // An invisible predecessor or one with alpha zero means
5657            // that this view is not visible to the user.
5658            Object current = this;
5659            while (current instanceof View) {
5660                View view = (View) current;
5661                // We have attach info so this view is attached and there is no
5662                // need to check whether we reach to ViewRootImpl on the way up.
5663                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5664                        view.getVisibility() != VISIBLE) {
5665                    return false;
5666                }
5667                current = view.mParent;
5668            }
5669            // Check if the view is entirely covered by its predecessors.
5670            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5671            Point offset = mAttachInfo.mPoint;
5672            if (!getGlobalVisibleRect(visibleRect, offset)) {
5673                return false;
5674            }
5675            // Check if the visible portion intersects the rectangle of interest.
5676            if (boundInView != null) {
5677                visibleRect.offset(-offset.x, -offset.y);
5678                return boundInView.intersect(visibleRect);
5679            }
5680            return true;
5681        }
5682        return false;
5683    }
5684
5685    /**
5686     * Returns the delegate for implementing accessibility support via
5687     * composition. For more details see {@link AccessibilityDelegate}.
5688     *
5689     * @return The delegate, or null if none set.
5690     *
5691     * @hide
5692     */
5693    public AccessibilityDelegate getAccessibilityDelegate() {
5694        return mAccessibilityDelegate;
5695    }
5696
5697    /**
5698     * Sets a delegate for implementing accessibility support via composition as
5699     * opposed to inheritance. The delegate's primary use is for implementing
5700     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5701     *
5702     * @param delegate The delegate instance.
5703     *
5704     * @see AccessibilityDelegate
5705     */
5706    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5707        mAccessibilityDelegate = delegate;
5708    }
5709
5710    /**
5711     * Gets the provider for managing a virtual view hierarchy rooted at this View
5712     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5713     * that explore the window content.
5714     * <p>
5715     * If this method returns an instance, this instance is responsible for managing
5716     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5717     * View including the one representing the View itself. Similarly the returned
5718     * instance is responsible for performing accessibility actions on any virtual
5719     * view or the root view itself.
5720     * </p>
5721     * <p>
5722     * If an {@link AccessibilityDelegate} has been specified via calling
5723     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5724     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5725     * is responsible for handling this call.
5726     * </p>
5727     *
5728     * @return The provider.
5729     *
5730     * @see AccessibilityNodeProvider
5731     */
5732    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5733        if (mAccessibilityDelegate != null) {
5734            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5735        } else {
5736            return null;
5737        }
5738    }
5739
5740    /**
5741     * Gets the unique identifier of this view on the screen for accessibility purposes.
5742     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5743     *
5744     * @return The view accessibility id.
5745     *
5746     * @hide
5747     */
5748    public int getAccessibilityViewId() {
5749        if (mAccessibilityViewId == NO_ID) {
5750            mAccessibilityViewId = sNextAccessibilityViewId++;
5751        }
5752        return mAccessibilityViewId;
5753    }
5754
5755    /**
5756     * Gets the unique identifier of the window in which this View reseides.
5757     *
5758     * @return The window accessibility id.
5759     *
5760     * @hide
5761     */
5762    public int getAccessibilityWindowId() {
5763        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5764                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5765    }
5766
5767    /**
5768     * Gets the {@link View} description. It briefly describes the view and is
5769     * primarily used for accessibility support. Set this property to enable
5770     * better accessibility support for your application. This is especially
5771     * true for views that do not have textual representation (For example,
5772     * ImageButton).
5773     *
5774     * @return The content description.
5775     *
5776     * @attr ref android.R.styleable#View_contentDescription
5777     */
5778    @ViewDebug.ExportedProperty(category = "accessibility")
5779    public CharSequence getContentDescription() {
5780        return mContentDescription;
5781    }
5782
5783    /**
5784     * Sets the {@link View} description. It briefly describes the view and is
5785     * primarily used for accessibility support. Set this property to enable
5786     * better accessibility support for your application. This is especially
5787     * true for views that do not have textual representation (For example,
5788     * ImageButton).
5789     *
5790     * @param contentDescription The content description.
5791     *
5792     * @attr ref android.R.styleable#View_contentDescription
5793     */
5794    @RemotableViewMethod
5795    public void setContentDescription(CharSequence contentDescription) {
5796        if (mContentDescription == null) {
5797            if (contentDescription == null) {
5798                return;
5799            }
5800        } else if (mContentDescription.equals(contentDescription)) {
5801            return;
5802        }
5803        mContentDescription = contentDescription;
5804        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5805        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5806            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5807            notifySubtreeAccessibilityStateChangedIfNeeded();
5808        } else {
5809            notifyViewAccessibilityStateChangedIfNeeded(
5810                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5811        }
5812    }
5813
5814    /**
5815     * Gets the id of a view for which this view serves as a label for
5816     * accessibility purposes.
5817     *
5818     * @return The labeled view id.
5819     */
5820    @ViewDebug.ExportedProperty(category = "accessibility")
5821    public int getLabelFor() {
5822        return mLabelForId;
5823    }
5824
5825    /**
5826     * Sets the id of a view for which this view serves as a label for
5827     * accessibility purposes.
5828     *
5829     * @param id The labeled view id.
5830     */
5831    @RemotableViewMethod
5832    public void setLabelFor(int id) {
5833        mLabelForId = id;
5834        if (mLabelForId != View.NO_ID
5835                && mID == View.NO_ID) {
5836            mID = generateViewId();
5837        }
5838    }
5839
5840    /**
5841     * Invoked whenever this view loses focus, either by losing window focus or by losing
5842     * focus within its window. This method can be used to clear any state tied to the
5843     * focus. For instance, if a button is held pressed with the trackball and the window
5844     * loses focus, this method can be used to cancel the press.
5845     *
5846     * Subclasses of View overriding this method should always call super.onFocusLost().
5847     *
5848     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5849     * @see #onWindowFocusChanged(boolean)
5850     *
5851     * @hide pending API council approval
5852     */
5853    protected void onFocusLost() {
5854        resetPressedState();
5855    }
5856
5857    private void resetPressedState() {
5858        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5859            return;
5860        }
5861
5862        if (isPressed()) {
5863            setPressed(false);
5864
5865            if (!mHasPerformedLongPress) {
5866                removeLongPressCallback();
5867            }
5868        }
5869    }
5870
5871    /**
5872     * Returns true if this view has focus
5873     *
5874     * @return True if this view has focus, false otherwise.
5875     */
5876    @ViewDebug.ExportedProperty(category = "focus")
5877    public boolean isFocused() {
5878        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5879    }
5880
5881    /**
5882     * Find the view in the hierarchy rooted at this view that currently has
5883     * focus.
5884     *
5885     * @return The view that currently has focus, or null if no focused view can
5886     *         be found.
5887     */
5888    public View findFocus() {
5889        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5890    }
5891
5892    /**
5893     * Indicates whether this view is one of the set of scrollable containers in
5894     * its window.
5895     *
5896     * @return whether this view is one of the set of scrollable containers in
5897     * its window
5898     *
5899     * @attr ref android.R.styleable#View_isScrollContainer
5900     */
5901    public boolean isScrollContainer() {
5902        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5903    }
5904
5905    /**
5906     * Change whether this view is one of the set of scrollable containers in
5907     * its window.  This will be used to determine whether the window can
5908     * resize or must pan when a soft input area is open -- scrollable
5909     * containers allow the window to use resize mode since the container
5910     * will appropriately shrink.
5911     *
5912     * @attr ref android.R.styleable#View_isScrollContainer
5913     */
5914    public void setScrollContainer(boolean isScrollContainer) {
5915        if (isScrollContainer) {
5916            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5917                mAttachInfo.mScrollContainers.add(this);
5918                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5919            }
5920            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5921        } else {
5922            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5923                mAttachInfo.mScrollContainers.remove(this);
5924            }
5925            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5926        }
5927    }
5928
5929    /**
5930     * Returns the quality of the drawing cache.
5931     *
5932     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5933     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5934     *
5935     * @see #setDrawingCacheQuality(int)
5936     * @see #setDrawingCacheEnabled(boolean)
5937     * @see #isDrawingCacheEnabled()
5938     *
5939     * @attr ref android.R.styleable#View_drawingCacheQuality
5940     */
5941    @DrawingCacheQuality
5942    public int getDrawingCacheQuality() {
5943        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5944    }
5945
5946    /**
5947     * Set the drawing cache quality of this view. This value is used only when the
5948     * drawing cache is enabled
5949     *
5950     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5951     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5952     *
5953     * @see #getDrawingCacheQuality()
5954     * @see #setDrawingCacheEnabled(boolean)
5955     * @see #isDrawingCacheEnabled()
5956     *
5957     * @attr ref android.R.styleable#View_drawingCacheQuality
5958     */
5959    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5960        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5961    }
5962
5963    /**
5964     * Returns whether the screen should remain on, corresponding to the current
5965     * value of {@link #KEEP_SCREEN_ON}.
5966     *
5967     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5968     *
5969     * @see #setKeepScreenOn(boolean)
5970     *
5971     * @attr ref android.R.styleable#View_keepScreenOn
5972     */
5973    public boolean getKeepScreenOn() {
5974        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5975    }
5976
5977    /**
5978     * Controls whether the screen should remain on, modifying the
5979     * value of {@link #KEEP_SCREEN_ON}.
5980     *
5981     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5982     *
5983     * @see #getKeepScreenOn()
5984     *
5985     * @attr ref android.R.styleable#View_keepScreenOn
5986     */
5987    public void setKeepScreenOn(boolean keepScreenOn) {
5988        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5989    }
5990
5991    /**
5992     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5993     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5994     *
5995     * @attr ref android.R.styleable#View_nextFocusLeft
5996     */
5997    public int getNextFocusLeftId() {
5998        return mNextFocusLeftId;
5999    }
6000
6001    /**
6002     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6003     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6004     * decide automatically.
6005     *
6006     * @attr ref android.R.styleable#View_nextFocusLeft
6007     */
6008    public void setNextFocusLeftId(int nextFocusLeftId) {
6009        mNextFocusLeftId = nextFocusLeftId;
6010    }
6011
6012    /**
6013     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6014     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6015     *
6016     * @attr ref android.R.styleable#View_nextFocusRight
6017     */
6018    public int getNextFocusRightId() {
6019        return mNextFocusRightId;
6020    }
6021
6022    /**
6023     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6024     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6025     * decide automatically.
6026     *
6027     * @attr ref android.R.styleable#View_nextFocusRight
6028     */
6029    public void setNextFocusRightId(int nextFocusRightId) {
6030        mNextFocusRightId = nextFocusRightId;
6031    }
6032
6033    /**
6034     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6035     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6036     *
6037     * @attr ref android.R.styleable#View_nextFocusUp
6038     */
6039    public int getNextFocusUpId() {
6040        return mNextFocusUpId;
6041    }
6042
6043    /**
6044     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6045     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6046     * decide automatically.
6047     *
6048     * @attr ref android.R.styleable#View_nextFocusUp
6049     */
6050    public void setNextFocusUpId(int nextFocusUpId) {
6051        mNextFocusUpId = nextFocusUpId;
6052    }
6053
6054    /**
6055     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6056     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6057     *
6058     * @attr ref android.R.styleable#View_nextFocusDown
6059     */
6060    public int getNextFocusDownId() {
6061        return mNextFocusDownId;
6062    }
6063
6064    /**
6065     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6066     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6067     * decide automatically.
6068     *
6069     * @attr ref android.R.styleable#View_nextFocusDown
6070     */
6071    public void setNextFocusDownId(int nextFocusDownId) {
6072        mNextFocusDownId = nextFocusDownId;
6073    }
6074
6075    /**
6076     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6077     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6078     *
6079     * @attr ref android.R.styleable#View_nextFocusForward
6080     */
6081    public int getNextFocusForwardId() {
6082        return mNextFocusForwardId;
6083    }
6084
6085    /**
6086     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6087     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6088     * decide automatically.
6089     *
6090     * @attr ref android.R.styleable#View_nextFocusForward
6091     */
6092    public void setNextFocusForwardId(int nextFocusForwardId) {
6093        mNextFocusForwardId = nextFocusForwardId;
6094    }
6095
6096    /**
6097     * Returns the visibility of this view and all of its ancestors
6098     *
6099     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6100     */
6101    public boolean isShown() {
6102        View current = this;
6103        //noinspection ConstantConditions
6104        do {
6105            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6106                return false;
6107            }
6108            ViewParent parent = current.mParent;
6109            if (parent == null) {
6110                return false; // We are not attached to the view root
6111            }
6112            if (!(parent instanceof View)) {
6113                return true;
6114            }
6115            current = (View) parent;
6116        } while (current != null);
6117
6118        return false;
6119    }
6120
6121    /**
6122     * Called by the view hierarchy when the content insets for a window have
6123     * changed, to allow it to adjust its content to fit within those windows.
6124     * The content insets tell you the space that the status bar, input method,
6125     * and other system windows infringe on the application's window.
6126     *
6127     * <p>You do not normally need to deal with this function, since the default
6128     * window decoration given to applications takes care of applying it to the
6129     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6130     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6131     * and your content can be placed under those system elements.  You can then
6132     * use this method within your view hierarchy if you have parts of your UI
6133     * which you would like to ensure are not being covered.
6134     *
6135     * <p>The default implementation of this method simply applies the content
6136     * insets to the view's padding, consuming that content (modifying the
6137     * insets to be 0), and returning true.  This behavior is off by default, but can
6138     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6139     *
6140     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6141     * insets object is propagated down the hierarchy, so any changes made to it will
6142     * be seen by all following views (including potentially ones above in
6143     * the hierarchy since this is a depth-first traversal).  The first view
6144     * that returns true will abort the entire traversal.
6145     *
6146     * <p>The default implementation works well for a situation where it is
6147     * used with a container that covers the entire window, allowing it to
6148     * apply the appropriate insets to its content on all edges.  If you need
6149     * a more complicated layout (such as two different views fitting system
6150     * windows, one on the top of the window, and one on the bottom),
6151     * you can override the method and handle the insets however you would like.
6152     * Note that the insets provided by the framework are always relative to the
6153     * far edges of the window, not accounting for the location of the called view
6154     * within that window.  (In fact when this method is called you do not yet know
6155     * where the layout will place the view, as it is done before layout happens.)
6156     *
6157     * <p>Note: unlike many View methods, there is no dispatch phase to this
6158     * call.  If you are overriding it in a ViewGroup and want to allow the
6159     * call to continue to your children, you must be sure to call the super
6160     * implementation.
6161     *
6162     * <p>Here is a sample layout that makes use of fitting system windows
6163     * to have controls for a video view placed inside of the window decorations
6164     * that it hides and shows.  This can be used with code like the second
6165     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6166     *
6167     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6168     *
6169     * @param insets Current content insets of the window.  Prior to
6170     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6171     * the insets or else you and Android will be unhappy.
6172     *
6173     * @return {@code true} if this view applied the insets and it should not
6174     * continue propagating further down the hierarchy, {@code false} otherwise.
6175     * @see #getFitsSystemWindows()
6176     * @see #setFitsSystemWindows(boolean)
6177     * @see #setSystemUiVisibility(int)
6178     *
6179     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6180     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6181     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6182     * to implement handling their own insets.
6183     */
6184    protected boolean fitSystemWindows(Rect insets) {
6185        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6186            if (insets == null) {
6187                // Null insets by definition have already been consumed.
6188                // This call cannot apply insets since there are none to apply,
6189                // so return false.
6190                return false;
6191            }
6192            // If we're not in the process of dispatching the newer apply insets call,
6193            // that means we're not in the compatibility path. Dispatch into the newer
6194            // apply insets path and take things from there.
6195            try {
6196                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6197                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6198            } finally {
6199                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6200            }
6201        } else {
6202            // We're being called from the newer apply insets path.
6203            // Perform the standard fallback behavior.
6204            return fitSystemWindowsInt(insets);
6205        }
6206    }
6207
6208    private boolean fitSystemWindowsInt(Rect insets) {
6209        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6210            mUserPaddingStart = UNDEFINED_PADDING;
6211            mUserPaddingEnd = UNDEFINED_PADDING;
6212            Rect localInsets = sThreadLocal.get();
6213            if (localInsets == null) {
6214                localInsets = new Rect();
6215                sThreadLocal.set(localInsets);
6216            }
6217            boolean res = computeFitSystemWindows(insets, localInsets);
6218            mUserPaddingLeftInitial = localInsets.left;
6219            mUserPaddingRightInitial = localInsets.right;
6220            internalSetPadding(localInsets.left, localInsets.top,
6221                    localInsets.right, localInsets.bottom);
6222            return res;
6223        }
6224        return false;
6225    }
6226
6227    /**
6228     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6229     *
6230     * <p>This method should be overridden by views that wish to apply a policy different from or
6231     * in addition to the default behavior. Clients that wish to force a view subtree
6232     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6233     *
6234     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6235     * it will be called during dispatch instead of this method. The listener may optionally
6236     * call this method from its own implementation if it wishes to apply the view's default
6237     * insets policy in addition to its own.</p>
6238     *
6239     * <p>Implementations of this method should either return the insets parameter unchanged
6240     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6241     * that this view applied itself. This allows new inset types added in future platform
6242     * versions to pass through existing implementations unchanged without being erroneously
6243     * consumed.</p>
6244     *
6245     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6246     * property is set then the view will consume the system window insets and apply them
6247     * as padding for the view.</p>
6248     *
6249     * @param insets Insets to apply
6250     * @return The supplied insets with any applied insets consumed
6251     */
6252    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6253        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6254            // We weren't called from within a direct call to fitSystemWindows,
6255            // call into it as a fallback in case we're in a class that overrides it
6256            // and has logic to perform.
6257            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6258                return insets.consumeSystemWindowInsets();
6259            }
6260        } else {
6261            // We were called from within a direct call to fitSystemWindows.
6262            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6263                return insets.consumeSystemWindowInsets();
6264            }
6265        }
6266        return insets;
6267    }
6268
6269    /**
6270     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6271     * window insets to this view. The listener's
6272     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6273     * method will be called instead of the view's
6274     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6275     *
6276     * @param listener Listener to set
6277     *
6278     * @see #onApplyWindowInsets(WindowInsets)
6279     */
6280    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6281        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6282    }
6283
6284    /**
6285     * Request to apply the given window insets to this view or another view in its subtree.
6286     *
6287     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6288     * obscured by window decorations or overlays. This can include the status and navigation bars,
6289     * action bars, input methods and more. New inset categories may be added in the future.
6290     * The method returns the insets provided minus any that were applied by this view or its
6291     * children.</p>
6292     *
6293     * <p>Clients wishing to provide custom behavior should override the
6294     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6295     * {@link OnApplyWindowInsetsListener} via the
6296     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6297     * method.</p>
6298     *
6299     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6300     * </p>
6301     *
6302     * @param insets Insets to apply
6303     * @return The provided insets minus the insets that were consumed
6304     */
6305    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6306        try {
6307            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6308            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6309                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6310            } else {
6311                return onApplyWindowInsets(insets);
6312            }
6313        } finally {
6314            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6315        }
6316    }
6317
6318    /**
6319     * @hide Compute the insets that should be consumed by this view and the ones
6320     * that should propagate to those under it.
6321     */
6322    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6323        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6324                || mAttachInfo == null
6325                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6326                        && !mAttachInfo.mOverscanRequested)) {
6327            outLocalInsets.set(inoutInsets);
6328            inoutInsets.set(0, 0, 0, 0);
6329            return true;
6330        } else {
6331            // The application wants to take care of fitting system window for
6332            // the content...  however we still need to take care of any overscan here.
6333            final Rect overscan = mAttachInfo.mOverscanInsets;
6334            outLocalInsets.set(overscan);
6335            inoutInsets.left -= overscan.left;
6336            inoutInsets.top -= overscan.top;
6337            inoutInsets.right -= overscan.right;
6338            inoutInsets.bottom -= overscan.bottom;
6339            return false;
6340        }
6341    }
6342
6343    /**
6344     * Sets whether or not this view should account for system screen decorations
6345     * such as the status bar and inset its content; that is, controlling whether
6346     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6347     * executed.  See that method for more details.
6348     *
6349     * <p>Note that if you are providing your own implementation of
6350     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6351     * flag to true -- your implementation will be overriding the default
6352     * implementation that checks this flag.
6353     *
6354     * @param fitSystemWindows If true, then the default implementation of
6355     * {@link #fitSystemWindows(Rect)} will be executed.
6356     *
6357     * @attr ref android.R.styleable#View_fitsSystemWindows
6358     * @see #getFitsSystemWindows()
6359     * @see #fitSystemWindows(Rect)
6360     * @see #setSystemUiVisibility(int)
6361     */
6362    public void setFitsSystemWindows(boolean fitSystemWindows) {
6363        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6364    }
6365
6366    /**
6367     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6368     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6369     * will be executed.
6370     *
6371     * @return {@code true} if the default implementation of
6372     * {@link #fitSystemWindows(Rect)} will be executed.
6373     *
6374     * @attr ref android.R.styleable#View_fitsSystemWindows
6375     * @see #setFitsSystemWindows(boolean)
6376     * @see #fitSystemWindows(Rect)
6377     * @see #setSystemUiVisibility(int)
6378     */
6379    public boolean getFitsSystemWindows() {
6380        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6381    }
6382
6383    /** @hide */
6384    public boolean fitsSystemWindows() {
6385        return getFitsSystemWindows();
6386    }
6387
6388    /**
6389     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6390     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6391     */
6392    public void requestFitSystemWindows() {
6393        if (mParent != null) {
6394            mParent.requestFitSystemWindows();
6395        }
6396    }
6397
6398    /**
6399     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6400     */
6401    public void requestApplyInsets() {
6402        requestFitSystemWindows();
6403    }
6404
6405    /**
6406     * For use by PhoneWindow to make its own system window fitting optional.
6407     * @hide
6408     */
6409    public void makeOptionalFitsSystemWindows() {
6410        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6411    }
6412
6413    /**
6414     * Returns the visibility status for this view.
6415     *
6416     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6417     * @attr ref android.R.styleable#View_visibility
6418     */
6419    @ViewDebug.ExportedProperty(mapping = {
6420        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6421        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6422        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6423    })
6424    @Visibility
6425    public int getVisibility() {
6426        return mViewFlags & VISIBILITY_MASK;
6427    }
6428
6429    /**
6430     * Set the enabled state of this view.
6431     *
6432     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6433     * @attr ref android.R.styleable#View_visibility
6434     */
6435    @RemotableViewMethod
6436    public void setVisibility(@Visibility int visibility) {
6437        setFlags(visibility, VISIBILITY_MASK);
6438        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6439    }
6440
6441    /**
6442     * Returns the enabled status for this view. The interpretation of the
6443     * enabled state varies by subclass.
6444     *
6445     * @return True if this view is enabled, false otherwise.
6446     */
6447    @ViewDebug.ExportedProperty
6448    public boolean isEnabled() {
6449        return (mViewFlags & ENABLED_MASK) == ENABLED;
6450    }
6451
6452    /**
6453     * Set the enabled state of this view. The interpretation of the enabled
6454     * state varies by subclass.
6455     *
6456     * @param enabled True if this view is enabled, false otherwise.
6457     */
6458    @RemotableViewMethod
6459    public void setEnabled(boolean enabled) {
6460        if (enabled == isEnabled()) return;
6461
6462        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6463
6464        /*
6465         * The View most likely has to change its appearance, so refresh
6466         * the drawable state.
6467         */
6468        refreshDrawableState();
6469
6470        // Invalidate too, since the default behavior for views is to be
6471        // be drawn at 50% alpha rather than to change the drawable.
6472        invalidate(true);
6473
6474        if (!enabled) {
6475            cancelPendingInputEvents();
6476        }
6477    }
6478
6479    /**
6480     * Set whether this view can receive the focus.
6481     *
6482     * Setting this to false will also ensure that this view is not focusable
6483     * in touch mode.
6484     *
6485     * @param focusable If true, this view can receive the focus.
6486     *
6487     * @see #setFocusableInTouchMode(boolean)
6488     * @attr ref android.R.styleable#View_focusable
6489     */
6490    public void setFocusable(boolean focusable) {
6491        if (!focusable) {
6492            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6493        }
6494        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6495    }
6496
6497    /**
6498     * Set whether this view can receive focus while in touch mode.
6499     *
6500     * Setting this to true will also ensure that this view is focusable.
6501     *
6502     * @param focusableInTouchMode If true, this view can receive the focus while
6503     *   in touch mode.
6504     *
6505     * @see #setFocusable(boolean)
6506     * @attr ref android.R.styleable#View_focusableInTouchMode
6507     */
6508    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6509        // Focusable in touch mode should always be set before the focusable flag
6510        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6511        // which, in touch mode, will not successfully request focus on this view
6512        // because the focusable in touch mode flag is not set
6513        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6514        if (focusableInTouchMode) {
6515            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6516        }
6517    }
6518
6519    /**
6520     * Set whether this view should have sound effects enabled for events such as
6521     * clicking and touching.
6522     *
6523     * <p>You may wish to disable sound effects for a view if you already play sounds,
6524     * for instance, a dial key that plays dtmf tones.
6525     *
6526     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6527     * @see #isSoundEffectsEnabled()
6528     * @see #playSoundEffect(int)
6529     * @attr ref android.R.styleable#View_soundEffectsEnabled
6530     */
6531    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6532        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6533    }
6534
6535    /**
6536     * @return whether this view should have sound effects enabled for events such as
6537     *     clicking and touching.
6538     *
6539     * @see #setSoundEffectsEnabled(boolean)
6540     * @see #playSoundEffect(int)
6541     * @attr ref android.R.styleable#View_soundEffectsEnabled
6542     */
6543    @ViewDebug.ExportedProperty
6544    public boolean isSoundEffectsEnabled() {
6545        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6546    }
6547
6548    /**
6549     * Set whether this view should have haptic feedback for events such as
6550     * long presses.
6551     *
6552     * <p>You may wish to disable haptic feedback if your view already controls
6553     * its own haptic feedback.
6554     *
6555     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6556     * @see #isHapticFeedbackEnabled()
6557     * @see #performHapticFeedback(int)
6558     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6559     */
6560    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6561        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6562    }
6563
6564    /**
6565     * @return whether this view should have haptic feedback enabled for events
6566     * long presses.
6567     *
6568     * @see #setHapticFeedbackEnabled(boolean)
6569     * @see #performHapticFeedback(int)
6570     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6571     */
6572    @ViewDebug.ExportedProperty
6573    public boolean isHapticFeedbackEnabled() {
6574        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6575    }
6576
6577    /**
6578     * Returns the layout direction for this view.
6579     *
6580     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6581     *   {@link #LAYOUT_DIRECTION_RTL},
6582     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6583     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6584     *
6585     * @attr ref android.R.styleable#View_layoutDirection
6586     *
6587     * @hide
6588     */
6589    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6590        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6591        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6592        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6593        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6594    })
6595    @LayoutDir
6596    public int getRawLayoutDirection() {
6597        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6598    }
6599
6600    /**
6601     * Set the layout direction for this view. This will propagate a reset of layout direction
6602     * resolution to the view's children and resolve layout direction for this view.
6603     *
6604     * @param layoutDirection the layout direction to set. Should be one of:
6605     *
6606     * {@link #LAYOUT_DIRECTION_LTR},
6607     * {@link #LAYOUT_DIRECTION_RTL},
6608     * {@link #LAYOUT_DIRECTION_INHERIT},
6609     * {@link #LAYOUT_DIRECTION_LOCALE}.
6610     *
6611     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6612     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6613     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6614     *
6615     * @attr ref android.R.styleable#View_layoutDirection
6616     */
6617    @RemotableViewMethod
6618    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6619        if (getRawLayoutDirection() != layoutDirection) {
6620            // Reset the current layout direction and the resolved one
6621            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6622            resetRtlProperties();
6623            // Set the new layout direction (filtered)
6624            mPrivateFlags2 |=
6625                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6626            // We need to resolve all RTL properties as they all depend on layout direction
6627            resolveRtlPropertiesIfNeeded();
6628            requestLayout();
6629            invalidate(true);
6630        }
6631    }
6632
6633    /**
6634     * Returns the resolved layout direction for this view.
6635     *
6636     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6637     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6638     *
6639     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6640     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6641     *
6642     * @attr ref android.R.styleable#View_layoutDirection
6643     */
6644    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6645        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6646        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6647    })
6648    @ResolvedLayoutDir
6649    public int getLayoutDirection() {
6650        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6651        if (targetSdkVersion < JELLY_BEAN_MR1) {
6652            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6653            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6654        }
6655        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6656                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6657    }
6658
6659    /**
6660     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6661     * layout attribute and/or the inherited value from the parent
6662     *
6663     * @return true if the layout is right-to-left.
6664     *
6665     * @hide
6666     */
6667    @ViewDebug.ExportedProperty(category = "layout")
6668    public boolean isLayoutRtl() {
6669        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6670    }
6671
6672    /**
6673     * Indicates whether the view is currently tracking transient state that the
6674     * app should not need to concern itself with saving and restoring, but that
6675     * the framework should take special note to preserve when possible.
6676     *
6677     * <p>A view with transient state cannot be trivially rebound from an external
6678     * data source, such as an adapter binding item views in a list. This may be
6679     * because the view is performing an animation, tracking user selection
6680     * of content, or similar.</p>
6681     *
6682     * @return true if the view has transient state
6683     */
6684    @ViewDebug.ExportedProperty(category = "layout")
6685    public boolean hasTransientState() {
6686        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6687    }
6688
6689    /**
6690     * Set whether this view is currently tracking transient state that the
6691     * framework should attempt to preserve when possible. This flag is reference counted,
6692     * so every call to setHasTransientState(true) should be paired with a later call
6693     * to setHasTransientState(false).
6694     *
6695     * <p>A view with transient state cannot be trivially rebound from an external
6696     * data source, such as an adapter binding item views in a list. This may be
6697     * because the view is performing an animation, tracking user selection
6698     * of content, or similar.</p>
6699     *
6700     * @param hasTransientState true if this view has transient state
6701     */
6702    public void setHasTransientState(boolean hasTransientState) {
6703        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6704                mTransientStateCount - 1;
6705        if (mTransientStateCount < 0) {
6706            mTransientStateCount = 0;
6707            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6708                    "unmatched pair of setHasTransientState calls");
6709        } else if ((hasTransientState && mTransientStateCount == 1) ||
6710                (!hasTransientState && mTransientStateCount == 0)) {
6711            // update flag if we've just incremented up from 0 or decremented down to 0
6712            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6713                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6714            if (mParent != null) {
6715                try {
6716                    mParent.childHasTransientStateChanged(this, hasTransientState);
6717                } catch (AbstractMethodError e) {
6718                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6719                            " does not fully implement ViewParent", e);
6720                }
6721            }
6722        }
6723    }
6724
6725    /**
6726     * Returns true if this view is currently attached to a window.
6727     */
6728    public boolean isAttachedToWindow() {
6729        return mAttachInfo != null;
6730    }
6731
6732    /**
6733     * Returns true if this view has been through at least one layout since it
6734     * was last attached to or detached from a window.
6735     */
6736    public boolean isLaidOut() {
6737        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6738    }
6739
6740    /**
6741     * If this view doesn't do any drawing on its own, set this flag to
6742     * allow further optimizations. By default, this flag is not set on
6743     * View, but could be set on some View subclasses such as ViewGroup.
6744     *
6745     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6746     * you should clear this flag.
6747     *
6748     * @param willNotDraw whether or not this View draw on its own
6749     */
6750    public void setWillNotDraw(boolean willNotDraw) {
6751        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6752    }
6753
6754    /**
6755     * Returns whether or not this View draws on its own.
6756     *
6757     * @return true if this view has nothing to draw, false otherwise
6758     */
6759    @ViewDebug.ExportedProperty(category = "drawing")
6760    public boolean willNotDraw() {
6761        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6762    }
6763
6764    /**
6765     * When a View's drawing cache is enabled, drawing is redirected to an
6766     * offscreen bitmap. Some views, like an ImageView, must be able to
6767     * bypass this mechanism if they already draw a single bitmap, to avoid
6768     * unnecessary usage of the memory.
6769     *
6770     * @param willNotCacheDrawing true if this view does not cache its
6771     *        drawing, false otherwise
6772     */
6773    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6774        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6775    }
6776
6777    /**
6778     * Returns whether or not this View can cache its drawing or not.
6779     *
6780     * @return true if this view does not cache its drawing, false otherwise
6781     */
6782    @ViewDebug.ExportedProperty(category = "drawing")
6783    public boolean willNotCacheDrawing() {
6784        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6785    }
6786
6787    /**
6788     * Indicates whether this view reacts to click events or not.
6789     *
6790     * @return true if the view is clickable, false otherwise
6791     *
6792     * @see #setClickable(boolean)
6793     * @attr ref android.R.styleable#View_clickable
6794     */
6795    @ViewDebug.ExportedProperty
6796    public boolean isClickable() {
6797        return (mViewFlags & CLICKABLE) == CLICKABLE;
6798    }
6799
6800    /**
6801     * Enables or disables click events for this view. When a view
6802     * is clickable it will change its state to "pressed" on every click.
6803     * Subclasses should set the view clickable to visually react to
6804     * user's clicks.
6805     *
6806     * @param clickable true to make the view clickable, false otherwise
6807     *
6808     * @see #isClickable()
6809     * @attr ref android.R.styleable#View_clickable
6810     */
6811    public void setClickable(boolean clickable) {
6812        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6813    }
6814
6815    /**
6816     * Indicates whether this view reacts to long click events or not.
6817     *
6818     * @return true if the view is long clickable, false otherwise
6819     *
6820     * @see #setLongClickable(boolean)
6821     * @attr ref android.R.styleable#View_longClickable
6822     */
6823    public boolean isLongClickable() {
6824        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6825    }
6826
6827    /**
6828     * Enables or disables long click events for this view. When a view is long
6829     * clickable it reacts to the user holding down the button for a longer
6830     * duration than a tap. This event can either launch the listener or a
6831     * context menu.
6832     *
6833     * @param longClickable true to make the view long clickable, false otherwise
6834     * @see #isLongClickable()
6835     * @attr ref android.R.styleable#View_longClickable
6836     */
6837    public void setLongClickable(boolean longClickable) {
6838        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6839    }
6840
6841    /**
6842     * Sets the pressed state for this view and provides a touch coordinate for
6843     * animation hinting.
6844     *
6845     * @param pressed Pass true to set the View's internal state to "pressed",
6846     *            or false to reverts the View's internal state from a
6847     *            previously set "pressed" state.
6848     * @param x The x coordinate of the touch that caused the press
6849     * @param y The y coordinate of the touch that caused the press
6850     */
6851    private void setPressed(boolean pressed, float x, float y) {
6852        if (pressed) {
6853            drawableHotspotChanged(x, y);
6854        }
6855
6856        setPressed(pressed);
6857    }
6858
6859    /**
6860     * Sets the pressed state for this view.
6861     *
6862     * @see #isClickable()
6863     * @see #setClickable(boolean)
6864     *
6865     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6866     *        the View's internal state from a previously set "pressed" state.
6867     */
6868    public void setPressed(boolean pressed) {
6869        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6870
6871        if (pressed) {
6872            mPrivateFlags |= PFLAG_PRESSED;
6873        } else {
6874            mPrivateFlags &= ~PFLAG_PRESSED;
6875        }
6876
6877        if (needsRefresh) {
6878            refreshDrawableState();
6879        }
6880        dispatchSetPressed(pressed);
6881    }
6882
6883    /**
6884     * Dispatch setPressed to all of this View's children.
6885     *
6886     * @see #setPressed(boolean)
6887     *
6888     * @param pressed The new pressed state
6889     */
6890    protected void dispatchSetPressed(boolean pressed) {
6891    }
6892
6893    /**
6894     * Indicates whether the view is currently in pressed state. Unless
6895     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6896     * the pressed state.
6897     *
6898     * @see #setPressed(boolean)
6899     * @see #isClickable()
6900     * @see #setClickable(boolean)
6901     *
6902     * @return true if the view is currently pressed, false otherwise
6903     */
6904    public boolean isPressed() {
6905        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6906    }
6907
6908    /**
6909     * Indicates whether this view will save its state (that is,
6910     * whether its {@link #onSaveInstanceState} method will be called).
6911     *
6912     * @return Returns true if the view state saving is enabled, else false.
6913     *
6914     * @see #setSaveEnabled(boolean)
6915     * @attr ref android.R.styleable#View_saveEnabled
6916     */
6917    public boolean isSaveEnabled() {
6918        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6919    }
6920
6921    /**
6922     * Controls whether the saving of this view's state is
6923     * enabled (that is, whether its {@link #onSaveInstanceState} method
6924     * will be called).  Note that even if freezing is enabled, the
6925     * view still must have an id assigned to it (via {@link #setId(int)})
6926     * for its state to be saved.  This flag can only disable the
6927     * saving of this view; any child views may still have their state saved.
6928     *
6929     * @param enabled Set to false to <em>disable</em> state saving, or true
6930     * (the default) to allow it.
6931     *
6932     * @see #isSaveEnabled()
6933     * @see #setId(int)
6934     * @see #onSaveInstanceState()
6935     * @attr ref android.R.styleable#View_saveEnabled
6936     */
6937    public void setSaveEnabled(boolean enabled) {
6938        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6939    }
6940
6941    /**
6942     * Gets whether the framework should discard touches when the view's
6943     * window is obscured by another visible window.
6944     * Refer to the {@link View} security documentation for more details.
6945     *
6946     * @return True if touch filtering is enabled.
6947     *
6948     * @see #setFilterTouchesWhenObscured(boolean)
6949     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6950     */
6951    @ViewDebug.ExportedProperty
6952    public boolean getFilterTouchesWhenObscured() {
6953        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6954    }
6955
6956    /**
6957     * Sets whether the framework should discard touches when the view's
6958     * window is obscured by another visible window.
6959     * Refer to the {@link View} security documentation for more details.
6960     *
6961     * @param enabled True if touch filtering should be enabled.
6962     *
6963     * @see #getFilterTouchesWhenObscured
6964     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6965     */
6966    public void setFilterTouchesWhenObscured(boolean enabled) {
6967        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6968                FILTER_TOUCHES_WHEN_OBSCURED);
6969    }
6970
6971    /**
6972     * Indicates whether the entire hierarchy under this view will save its
6973     * state when a state saving traversal occurs from its parent.  The default
6974     * is true; if false, these views will not be saved unless
6975     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6976     *
6977     * @return Returns true if the view state saving from parent is enabled, else false.
6978     *
6979     * @see #setSaveFromParentEnabled(boolean)
6980     */
6981    public boolean isSaveFromParentEnabled() {
6982        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6983    }
6984
6985    /**
6986     * Controls whether the entire hierarchy under this view will save its
6987     * state when a state saving traversal occurs from its parent.  The default
6988     * is true; if false, these views will not be saved unless
6989     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6990     *
6991     * @param enabled Set to false to <em>disable</em> state saving, or true
6992     * (the default) to allow it.
6993     *
6994     * @see #isSaveFromParentEnabled()
6995     * @see #setId(int)
6996     * @see #onSaveInstanceState()
6997     */
6998    public void setSaveFromParentEnabled(boolean enabled) {
6999        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7000    }
7001
7002
7003    /**
7004     * Returns whether this View is able to take focus.
7005     *
7006     * @return True if this view can take focus, or false otherwise.
7007     * @attr ref android.R.styleable#View_focusable
7008     */
7009    @ViewDebug.ExportedProperty(category = "focus")
7010    public final boolean isFocusable() {
7011        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7012    }
7013
7014    /**
7015     * When a view is focusable, it may not want to take focus when in touch mode.
7016     * For example, a button would like focus when the user is navigating via a D-pad
7017     * so that the user can click on it, but once the user starts touching the screen,
7018     * the button shouldn't take focus
7019     * @return Whether the view is focusable in touch mode.
7020     * @attr ref android.R.styleable#View_focusableInTouchMode
7021     */
7022    @ViewDebug.ExportedProperty
7023    public final boolean isFocusableInTouchMode() {
7024        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7025    }
7026
7027    /**
7028     * Find the nearest view in the specified direction that can take focus.
7029     * This does not actually give focus to that view.
7030     *
7031     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7032     *
7033     * @return The nearest focusable in the specified direction, or null if none
7034     *         can be found.
7035     */
7036    public View focusSearch(@FocusRealDirection int direction) {
7037        if (mParent != null) {
7038            return mParent.focusSearch(this, direction);
7039        } else {
7040            return null;
7041        }
7042    }
7043
7044    /**
7045     * This method is the last chance for the focused view and its ancestors to
7046     * respond to an arrow key. This is called when the focused view did not
7047     * consume the key internally, nor could the view system find a new view in
7048     * the requested direction to give focus to.
7049     *
7050     * @param focused The currently focused view.
7051     * @param direction The direction focus wants to move. One of FOCUS_UP,
7052     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7053     * @return True if the this view consumed this unhandled move.
7054     */
7055    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7056        return false;
7057    }
7058
7059    /**
7060     * If a user manually specified the next view id for a particular direction,
7061     * use the root to look up the view.
7062     * @param root The root view of the hierarchy containing this view.
7063     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7064     * or FOCUS_BACKWARD.
7065     * @return The user specified next view, or null if there is none.
7066     */
7067    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7068        switch (direction) {
7069            case FOCUS_LEFT:
7070                if (mNextFocusLeftId == View.NO_ID) return null;
7071                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7072            case FOCUS_RIGHT:
7073                if (mNextFocusRightId == View.NO_ID) return null;
7074                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7075            case FOCUS_UP:
7076                if (mNextFocusUpId == View.NO_ID) return null;
7077                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7078            case FOCUS_DOWN:
7079                if (mNextFocusDownId == View.NO_ID) return null;
7080                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7081            case FOCUS_FORWARD:
7082                if (mNextFocusForwardId == View.NO_ID) return null;
7083                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7084            case FOCUS_BACKWARD: {
7085                if (mID == View.NO_ID) return null;
7086                final int id = mID;
7087                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7088                    @Override
7089                    public boolean apply(View t) {
7090                        return t.mNextFocusForwardId == id;
7091                    }
7092                });
7093            }
7094        }
7095        return null;
7096    }
7097
7098    private View findViewInsideOutShouldExist(View root, int id) {
7099        if (mMatchIdPredicate == null) {
7100            mMatchIdPredicate = new MatchIdPredicate();
7101        }
7102        mMatchIdPredicate.mId = id;
7103        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7104        if (result == null) {
7105            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7106        }
7107        return result;
7108    }
7109
7110    /**
7111     * Find and return all focusable views that are descendants of this view,
7112     * possibly including this view if it is focusable itself.
7113     *
7114     * @param direction The direction of the focus
7115     * @return A list of focusable views
7116     */
7117    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7118        ArrayList<View> result = new ArrayList<View>(24);
7119        addFocusables(result, direction);
7120        return result;
7121    }
7122
7123    /**
7124     * Add any focusable views that are descendants of this view (possibly
7125     * including this view if it is focusable itself) to views.  If we are in touch mode,
7126     * only add views that are also focusable in touch mode.
7127     *
7128     * @param views Focusable views found so far
7129     * @param direction The direction of the focus
7130     */
7131    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7132        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7133    }
7134
7135    /**
7136     * Adds any focusable views that are descendants of this view (possibly
7137     * including this view if it is focusable itself) to views. This method
7138     * adds all focusable views regardless if we are in touch mode or
7139     * only views focusable in touch mode if we are in touch mode or
7140     * only views that can take accessibility focus if accessibility is enabeld
7141     * depending on the focusable mode paramater.
7142     *
7143     * @param views Focusable views found so far or null if all we are interested is
7144     *        the number of focusables.
7145     * @param direction The direction of the focus.
7146     * @param focusableMode The type of focusables to be added.
7147     *
7148     * @see #FOCUSABLES_ALL
7149     * @see #FOCUSABLES_TOUCH_MODE
7150     */
7151    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7152            @FocusableMode int focusableMode) {
7153        if (views == null) {
7154            return;
7155        }
7156        if (!isFocusable()) {
7157            return;
7158        }
7159        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7160                && isInTouchMode() && !isFocusableInTouchMode()) {
7161            return;
7162        }
7163        views.add(this);
7164    }
7165
7166    /**
7167     * Finds the Views that contain given text. The containment is case insensitive.
7168     * The search is performed by either the text that the View renders or the content
7169     * description that describes the view for accessibility purposes and the view does
7170     * not render or both. Clients can specify how the search is to be performed via
7171     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7172     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7173     *
7174     * @param outViews The output list of matching Views.
7175     * @param searched The text to match against.
7176     *
7177     * @see #FIND_VIEWS_WITH_TEXT
7178     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7179     * @see #setContentDescription(CharSequence)
7180     */
7181    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7182            @FindViewFlags int flags) {
7183        if (getAccessibilityNodeProvider() != null) {
7184            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7185                outViews.add(this);
7186            }
7187        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7188                && (searched != null && searched.length() > 0)
7189                && (mContentDescription != null && mContentDescription.length() > 0)) {
7190            String searchedLowerCase = searched.toString().toLowerCase();
7191            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7192            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7193                outViews.add(this);
7194            }
7195        }
7196    }
7197
7198    /**
7199     * Find and return all touchable views that are descendants of this view,
7200     * possibly including this view if it is touchable itself.
7201     *
7202     * @return A list of touchable views
7203     */
7204    public ArrayList<View> getTouchables() {
7205        ArrayList<View> result = new ArrayList<View>();
7206        addTouchables(result);
7207        return result;
7208    }
7209
7210    /**
7211     * Add any touchable views that are descendants of this view (possibly
7212     * including this view if it is touchable itself) to views.
7213     *
7214     * @param views Touchable views found so far
7215     */
7216    public void addTouchables(ArrayList<View> views) {
7217        final int viewFlags = mViewFlags;
7218
7219        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7220                && (viewFlags & ENABLED_MASK) == ENABLED) {
7221            views.add(this);
7222        }
7223    }
7224
7225    /**
7226     * Returns whether this View is accessibility focused.
7227     *
7228     * @return True if this View is accessibility focused.
7229     */
7230    public boolean isAccessibilityFocused() {
7231        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7232    }
7233
7234    /**
7235     * Call this to try to give accessibility focus to this view.
7236     *
7237     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7238     * returns false or the view is no visible or the view already has accessibility
7239     * focus.
7240     *
7241     * See also {@link #focusSearch(int)}, which is what you call to say that you
7242     * have focus, and you want your parent to look for the next one.
7243     *
7244     * @return Whether this view actually took accessibility focus.
7245     *
7246     * @hide
7247     */
7248    public boolean requestAccessibilityFocus() {
7249        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7250        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7251            return false;
7252        }
7253        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7254            return false;
7255        }
7256        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7257            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7258            ViewRootImpl viewRootImpl = getViewRootImpl();
7259            if (viewRootImpl != null) {
7260                viewRootImpl.setAccessibilityFocus(this, null);
7261            }
7262            invalidate();
7263            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7264            return true;
7265        }
7266        return false;
7267    }
7268
7269    /**
7270     * Call this to try to clear accessibility focus of this view.
7271     *
7272     * See also {@link #focusSearch(int)}, which is what you call to say that you
7273     * have focus, and you want your parent to look for the next one.
7274     *
7275     * @hide
7276     */
7277    public void clearAccessibilityFocus() {
7278        clearAccessibilityFocusNoCallbacks();
7279        // Clear the global reference of accessibility focus if this
7280        // view or any of its descendants had accessibility focus.
7281        ViewRootImpl viewRootImpl = getViewRootImpl();
7282        if (viewRootImpl != null) {
7283            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7284            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7285                viewRootImpl.setAccessibilityFocus(null, null);
7286            }
7287        }
7288    }
7289
7290    private void sendAccessibilityHoverEvent(int eventType) {
7291        // Since we are not delivering to a client accessibility events from not
7292        // important views (unless the clinet request that) we need to fire the
7293        // event from the deepest view exposed to the client. As a consequence if
7294        // the user crosses a not exposed view the client will see enter and exit
7295        // of the exposed predecessor followed by and enter and exit of that same
7296        // predecessor when entering and exiting the not exposed descendant. This
7297        // is fine since the client has a clear idea which view is hovered at the
7298        // price of a couple more events being sent. This is a simple and
7299        // working solution.
7300        View source = this;
7301        while (true) {
7302            if (source.includeForAccessibility()) {
7303                source.sendAccessibilityEvent(eventType);
7304                return;
7305            }
7306            ViewParent parent = source.getParent();
7307            if (parent instanceof View) {
7308                source = (View) parent;
7309            } else {
7310                return;
7311            }
7312        }
7313    }
7314
7315    /**
7316     * Clears accessibility focus without calling any callback methods
7317     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7318     * is used for clearing accessibility focus when giving this focus to
7319     * another view.
7320     */
7321    void clearAccessibilityFocusNoCallbacks() {
7322        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7323            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7324            invalidate();
7325            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7326        }
7327    }
7328
7329    /**
7330     * Call this to try to give focus to a specific view or to one of its
7331     * descendants.
7332     *
7333     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7334     * false), or if it is focusable and it is not focusable in touch mode
7335     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7336     *
7337     * See also {@link #focusSearch(int)}, which is what you call to say that you
7338     * have focus, and you want your parent to look for the next one.
7339     *
7340     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7341     * {@link #FOCUS_DOWN} and <code>null</code>.
7342     *
7343     * @return Whether this view or one of its descendants actually took focus.
7344     */
7345    public final boolean requestFocus() {
7346        return requestFocus(View.FOCUS_DOWN);
7347    }
7348
7349    /**
7350     * Call this to try to give focus to a specific view or to one of its
7351     * descendants and give it a hint about what direction focus is heading.
7352     *
7353     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7354     * false), or if it is focusable and it is not focusable in touch mode
7355     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7356     *
7357     * See also {@link #focusSearch(int)}, which is what you call to say that you
7358     * have focus, and you want your parent to look for the next one.
7359     *
7360     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7361     * <code>null</code> set for the previously focused rectangle.
7362     *
7363     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7364     * @return Whether this view or one of its descendants actually took focus.
7365     */
7366    public final boolean requestFocus(int direction) {
7367        return requestFocus(direction, null);
7368    }
7369
7370    /**
7371     * Call this to try to give focus to a specific view or to one of its descendants
7372     * and give it hints about the direction and a specific rectangle that the focus
7373     * is coming from.  The rectangle can help give larger views a finer grained hint
7374     * about where focus is coming from, and therefore, where to show selection, or
7375     * forward focus change internally.
7376     *
7377     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7378     * false), or if it is focusable and it is not focusable in touch mode
7379     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7380     *
7381     * A View will not take focus if it is not visible.
7382     *
7383     * A View will not take focus if one of its parents has
7384     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7385     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7386     *
7387     * See also {@link #focusSearch(int)}, which is what you call to say that you
7388     * have focus, and you want your parent to look for the next one.
7389     *
7390     * You may wish to override this method if your custom {@link View} has an internal
7391     * {@link View} that it wishes to forward the request to.
7392     *
7393     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7394     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7395     *        to give a finer grained hint about where focus is coming from.  May be null
7396     *        if there is no hint.
7397     * @return Whether this view or one of its descendants actually took focus.
7398     */
7399    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7400        return requestFocusNoSearch(direction, previouslyFocusedRect);
7401    }
7402
7403    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7404        // need to be focusable
7405        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7406                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7407            return false;
7408        }
7409
7410        // need to be focusable in touch mode if in touch mode
7411        if (isInTouchMode() &&
7412            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7413               return false;
7414        }
7415
7416        // need to not have any parents blocking us
7417        if (hasAncestorThatBlocksDescendantFocus()) {
7418            return false;
7419        }
7420
7421        handleFocusGainInternal(direction, previouslyFocusedRect);
7422        return true;
7423    }
7424
7425    /**
7426     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7427     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7428     * touch mode to request focus when they are touched.
7429     *
7430     * @return Whether this view or one of its descendants actually took focus.
7431     *
7432     * @see #isInTouchMode()
7433     *
7434     */
7435    public final boolean requestFocusFromTouch() {
7436        // Leave touch mode if we need to
7437        if (isInTouchMode()) {
7438            ViewRootImpl viewRoot = getViewRootImpl();
7439            if (viewRoot != null) {
7440                viewRoot.ensureTouchMode(false);
7441            }
7442        }
7443        return requestFocus(View.FOCUS_DOWN);
7444    }
7445
7446    /**
7447     * @return Whether any ancestor of this view blocks descendant focus.
7448     */
7449    private boolean hasAncestorThatBlocksDescendantFocus() {
7450        final boolean focusableInTouchMode = isFocusableInTouchMode();
7451        ViewParent ancestor = mParent;
7452        while (ancestor instanceof ViewGroup) {
7453            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7454            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7455                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7456                return true;
7457            } else {
7458                ancestor = vgAncestor.getParent();
7459            }
7460        }
7461        return false;
7462    }
7463
7464    /**
7465     * Gets the mode for determining whether this View is important for accessibility
7466     * which is if it fires accessibility events and if it is reported to
7467     * accessibility services that query the screen.
7468     *
7469     * @return The mode for determining whether a View is important for accessibility.
7470     *
7471     * @attr ref android.R.styleable#View_importantForAccessibility
7472     *
7473     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7474     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7475     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7476     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7477     */
7478    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7479            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7480            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7481            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7482            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7483                    to = "noHideDescendants")
7484        })
7485    public int getImportantForAccessibility() {
7486        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7487                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7488    }
7489
7490    /**
7491     * Sets the live region mode for this view. This indicates to accessibility
7492     * services whether they should automatically notify the user about changes
7493     * to the view's content description or text, or to the content descriptions
7494     * or text of the view's children (where applicable).
7495     * <p>
7496     * For example, in a login screen with a TextView that displays an "incorrect
7497     * password" notification, that view should be marked as a live region with
7498     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7499     * <p>
7500     * To disable change notifications for this view, use
7501     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7502     * mode for most views.
7503     * <p>
7504     * To indicate that the user should be notified of changes, use
7505     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7506     * <p>
7507     * If the view's changes should interrupt ongoing speech and notify the user
7508     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7509     *
7510     * @param mode The live region mode for this view, one of:
7511     *        <ul>
7512     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7513     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7514     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7515     *        </ul>
7516     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7517     */
7518    public void setAccessibilityLiveRegion(int mode) {
7519        if (mode != getAccessibilityLiveRegion()) {
7520            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7521            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7522                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7523            notifyViewAccessibilityStateChangedIfNeeded(
7524                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7525        }
7526    }
7527
7528    /**
7529     * Gets the live region mode for this View.
7530     *
7531     * @return The live region mode for the view.
7532     *
7533     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7534     *
7535     * @see #setAccessibilityLiveRegion(int)
7536     */
7537    public int getAccessibilityLiveRegion() {
7538        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7539                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7540    }
7541
7542    /**
7543     * Sets how to determine whether this view is important for accessibility
7544     * which is if it fires accessibility events and if it is reported to
7545     * accessibility services that query the screen.
7546     *
7547     * @param mode How to determine whether this view is important for accessibility.
7548     *
7549     * @attr ref android.R.styleable#View_importantForAccessibility
7550     *
7551     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7552     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7553     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7554     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7555     */
7556    public void setImportantForAccessibility(int mode) {
7557        final int oldMode = getImportantForAccessibility();
7558        if (mode != oldMode) {
7559            // If we're moving between AUTO and another state, we might not need
7560            // to send a subtree changed notification. We'll store the computed
7561            // importance, since we'll need to check it later to make sure.
7562            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7563                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7564            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7565            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7566            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7567                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7568            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7569                notifySubtreeAccessibilityStateChangedIfNeeded();
7570            } else {
7571                notifyViewAccessibilityStateChangedIfNeeded(
7572                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7573            }
7574        }
7575    }
7576
7577    /**
7578     * Computes whether this view should be exposed for accessibility. In
7579     * general, views that are interactive or provide information are exposed
7580     * while views that serve only as containers are hidden.
7581     * <p>
7582     * If an ancestor of this view has importance
7583     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7584     * returns <code>false</code>.
7585     * <p>
7586     * Otherwise, the value is computed according to the view's
7587     * {@link #getImportantForAccessibility()} value:
7588     * <ol>
7589     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7590     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7591     * </code>
7592     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7593     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7594     * view satisfies any of the following:
7595     * <ul>
7596     * <li>Is actionable, e.g. {@link #isClickable()},
7597     * {@link #isLongClickable()}, or {@link #isFocusable()}
7598     * <li>Has an {@link AccessibilityDelegate}
7599     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7600     * {@link OnKeyListener}, etc.
7601     * <li>Is an accessibility live region, e.g.
7602     * {@link #getAccessibilityLiveRegion()} is not
7603     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7604     * </ul>
7605     * </ol>
7606     *
7607     * @return Whether the view is exposed for accessibility.
7608     * @see #setImportantForAccessibility(int)
7609     * @see #getImportantForAccessibility()
7610     */
7611    public boolean isImportantForAccessibility() {
7612        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7613                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7614        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7615                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7616            return false;
7617        }
7618
7619        // Check parent mode to ensure we're not hidden.
7620        ViewParent parent = mParent;
7621        while (parent instanceof View) {
7622            if (((View) parent).getImportantForAccessibility()
7623                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7624                return false;
7625            }
7626            parent = parent.getParent();
7627        }
7628
7629        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7630                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7631                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7632    }
7633
7634    /**
7635     * Gets the parent for accessibility purposes. Note that the parent for
7636     * accessibility is not necessary the immediate parent. It is the first
7637     * predecessor that is important for accessibility.
7638     *
7639     * @return The parent for accessibility purposes.
7640     */
7641    public ViewParent getParentForAccessibility() {
7642        if (mParent instanceof View) {
7643            View parentView = (View) mParent;
7644            if (parentView.includeForAccessibility()) {
7645                return mParent;
7646            } else {
7647                return mParent.getParentForAccessibility();
7648            }
7649        }
7650        return null;
7651    }
7652
7653    /**
7654     * Adds the children of a given View for accessibility. Since some Views are
7655     * not important for accessibility the children for accessibility are not
7656     * necessarily direct children of the view, rather they are the first level of
7657     * descendants important for accessibility.
7658     *
7659     * @param children The list of children for accessibility.
7660     */
7661    public void addChildrenForAccessibility(ArrayList<View> children) {
7662
7663    }
7664
7665    /**
7666     * Whether to regard this view for accessibility. A view is regarded for
7667     * accessibility if it is important for accessibility or the querying
7668     * accessibility service has explicitly requested that view not
7669     * important for accessibility are regarded.
7670     *
7671     * @return Whether to regard the view for accessibility.
7672     *
7673     * @hide
7674     */
7675    public boolean includeForAccessibility() {
7676        if (mAttachInfo != null) {
7677            return (mAttachInfo.mAccessibilityFetchFlags
7678                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7679                    || isImportantForAccessibility();
7680        }
7681        return false;
7682    }
7683
7684    /**
7685     * Returns whether the View is considered actionable from
7686     * accessibility perspective. Such view are important for
7687     * accessibility.
7688     *
7689     * @return True if the view is actionable for accessibility.
7690     *
7691     * @hide
7692     */
7693    public boolean isActionableForAccessibility() {
7694        return (isClickable() || isLongClickable() || isFocusable());
7695    }
7696
7697    /**
7698     * Returns whether the View has registered callbacks which makes it
7699     * important for accessibility.
7700     *
7701     * @return True if the view is actionable for accessibility.
7702     */
7703    private boolean hasListenersForAccessibility() {
7704        ListenerInfo info = getListenerInfo();
7705        return mTouchDelegate != null || info.mOnKeyListener != null
7706                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7707                || info.mOnHoverListener != null || info.mOnDragListener != null;
7708    }
7709
7710    /**
7711     * Notifies that the accessibility state of this view changed. The change
7712     * is local to this view and does not represent structural changes such
7713     * as children and parent. For example, the view became focusable. The
7714     * notification is at at most once every
7715     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7716     * to avoid unnecessary load to the system. Also once a view has a pending
7717     * notification this method is a NOP until the notification has been sent.
7718     *
7719     * @hide
7720     */
7721    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7722        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7723            return;
7724        }
7725        if (mSendViewStateChangedAccessibilityEvent == null) {
7726            mSendViewStateChangedAccessibilityEvent =
7727                    new SendViewStateChangedAccessibilityEvent();
7728        }
7729        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7730    }
7731
7732    /**
7733     * Notifies that the accessibility state of this view changed. The change
7734     * is *not* local to this view and does represent structural changes such
7735     * as children and parent. For example, the view size changed. The
7736     * notification is at at most once every
7737     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7738     * to avoid unnecessary load to the system. Also once a view has a pending
7739     * notification this method is a NOP until the notification has been sent.
7740     *
7741     * @hide
7742     */
7743    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7744        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7745            return;
7746        }
7747        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7748            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7749            if (mParent != null) {
7750                try {
7751                    mParent.notifySubtreeAccessibilityStateChanged(
7752                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7753                } catch (AbstractMethodError e) {
7754                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7755                            " does not fully implement ViewParent", e);
7756                }
7757            }
7758        }
7759    }
7760
7761    /**
7762     * Reset the flag indicating the accessibility state of the subtree rooted
7763     * at this view changed.
7764     */
7765    void resetSubtreeAccessibilityStateChanged() {
7766        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7767    }
7768
7769    /**
7770     * Performs the specified accessibility action on the view. For
7771     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7772     * <p>
7773     * If an {@link AccessibilityDelegate} has been specified via calling
7774     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7775     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7776     * is responsible for handling this call.
7777     * </p>
7778     *
7779     * @param action The action to perform.
7780     * @param arguments Optional action arguments.
7781     * @return Whether the action was performed.
7782     */
7783    public boolean performAccessibilityAction(int action, Bundle arguments) {
7784      if (mAccessibilityDelegate != null) {
7785          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7786      } else {
7787          return performAccessibilityActionInternal(action, arguments);
7788      }
7789    }
7790
7791   /**
7792    * @see #performAccessibilityAction(int, Bundle)
7793    *
7794    * Note: Called from the default {@link AccessibilityDelegate}.
7795    */
7796    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7797        switch (action) {
7798            case AccessibilityNodeInfo.ACTION_CLICK: {
7799                if (isClickable()) {
7800                    performClick();
7801                    return true;
7802                }
7803            } break;
7804            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7805                if (isLongClickable()) {
7806                    performLongClick();
7807                    return true;
7808                }
7809            } break;
7810            case AccessibilityNodeInfo.ACTION_FOCUS: {
7811                if (!hasFocus()) {
7812                    // Get out of touch mode since accessibility
7813                    // wants to move focus around.
7814                    getViewRootImpl().ensureTouchMode(false);
7815                    return requestFocus();
7816                }
7817            } break;
7818            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7819                if (hasFocus()) {
7820                    clearFocus();
7821                    return !isFocused();
7822                }
7823            } break;
7824            case AccessibilityNodeInfo.ACTION_SELECT: {
7825                if (!isSelected()) {
7826                    setSelected(true);
7827                    return isSelected();
7828                }
7829            } break;
7830            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7831                if (isSelected()) {
7832                    setSelected(false);
7833                    return !isSelected();
7834                }
7835            } break;
7836            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7837                if (!isAccessibilityFocused()) {
7838                    return requestAccessibilityFocus();
7839                }
7840            } break;
7841            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7842                if (isAccessibilityFocused()) {
7843                    clearAccessibilityFocus();
7844                    return true;
7845                }
7846            } break;
7847            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7848                if (arguments != null) {
7849                    final int granularity = arguments.getInt(
7850                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7851                    final boolean extendSelection = arguments.getBoolean(
7852                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7853                    return traverseAtGranularity(granularity, true, extendSelection);
7854                }
7855            } break;
7856            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7857                if (arguments != null) {
7858                    final int granularity = arguments.getInt(
7859                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7860                    final boolean extendSelection = arguments.getBoolean(
7861                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7862                    return traverseAtGranularity(granularity, false, extendSelection);
7863                }
7864            } break;
7865            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7866                CharSequence text = getIterableTextForAccessibility();
7867                if (text == null) {
7868                    return false;
7869                }
7870                final int start = (arguments != null) ? arguments.getInt(
7871                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7872                final int end = (arguments != null) ? arguments.getInt(
7873                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7874                // Only cursor position can be specified (selection length == 0)
7875                if ((getAccessibilitySelectionStart() != start
7876                        || getAccessibilitySelectionEnd() != end)
7877                        && (start == end)) {
7878                    setAccessibilitySelection(start, end);
7879                    notifyViewAccessibilityStateChangedIfNeeded(
7880                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7881                    return true;
7882                }
7883            } break;
7884        }
7885        return false;
7886    }
7887
7888    private boolean traverseAtGranularity(int granularity, boolean forward,
7889            boolean extendSelection) {
7890        CharSequence text = getIterableTextForAccessibility();
7891        if (text == null || text.length() == 0) {
7892            return false;
7893        }
7894        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7895        if (iterator == null) {
7896            return false;
7897        }
7898        int current = getAccessibilitySelectionEnd();
7899        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7900            current = forward ? 0 : text.length();
7901        }
7902        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7903        if (range == null) {
7904            return false;
7905        }
7906        final int segmentStart = range[0];
7907        final int segmentEnd = range[1];
7908        int selectionStart;
7909        int selectionEnd;
7910        if (extendSelection && isAccessibilitySelectionExtendable()) {
7911            selectionStart = getAccessibilitySelectionStart();
7912            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7913                selectionStart = forward ? segmentStart : segmentEnd;
7914            }
7915            selectionEnd = forward ? segmentEnd : segmentStart;
7916        } else {
7917            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7918        }
7919        setAccessibilitySelection(selectionStart, selectionEnd);
7920        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7921                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7922        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7923        return true;
7924    }
7925
7926    /**
7927     * Gets the text reported for accessibility purposes.
7928     *
7929     * @return The accessibility text.
7930     *
7931     * @hide
7932     */
7933    public CharSequence getIterableTextForAccessibility() {
7934        return getContentDescription();
7935    }
7936
7937    /**
7938     * Gets whether accessibility selection can be extended.
7939     *
7940     * @return If selection is extensible.
7941     *
7942     * @hide
7943     */
7944    public boolean isAccessibilitySelectionExtendable() {
7945        return false;
7946    }
7947
7948    /**
7949     * @hide
7950     */
7951    public int getAccessibilitySelectionStart() {
7952        return mAccessibilityCursorPosition;
7953    }
7954
7955    /**
7956     * @hide
7957     */
7958    public int getAccessibilitySelectionEnd() {
7959        return getAccessibilitySelectionStart();
7960    }
7961
7962    /**
7963     * @hide
7964     */
7965    public void setAccessibilitySelection(int start, int end) {
7966        if (start ==  end && end == mAccessibilityCursorPosition) {
7967            return;
7968        }
7969        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7970            mAccessibilityCursorPosition = start;
7971        } else {
7972            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7973        }
7974        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7975    }
7976
7977    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7978            int fromIndex, int toIndex) {
7979        if (mParent == null) {
7980            return;
7981        }
7982        AccessibilityEvent event = AccessibilityEvent.obtain(
7983                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7984        onInitializeAccessibilityEvent(event);
7985        onPopulateAccessibilityEvent(event);
7986        event.setFromIndex(fromIndex);
7987        event.setToIndex(toIndex);
7988        event.setAction(action);
7989        event.setMovementGranularity(granularity);
7990        mParent.requestSendAccessibilityEvent(this, event);
7991    }
7992
7993    /**
7994     * @hide
7995     */
7996    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7997        switch (granularity) {
7998            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7999                CharSequence text = getIterableTextForAccessibility();
8000                if (text != null && text.length() > 0) {
8001                    CharacterTextSegmentIterator iterator =
8002                        CharacterTextSegmentIterator.getInstance(
8003                                mContext.getResources().getConfiguration().locale);
8004                    iterator.initialize(text.toString());
8005                    return iterator;
8006                }
8007            } break;
8008            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8009                CharSequence text = getIterableTextForAccessibility();
8010                if (text != null && text.length() > 0) {
8011                    WordTextSegmentIterator iterator =
8012                        WordTextSegmentIterator.getInstance(
8013                                mContext.getResources().getConfiguration().locale);
8014                    iterator.initialize(text.toString());
8015                    return iterator;
8016                }
8017            } break;
8018            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8019                CharSequence text = getIterableTextForAccessibility();
8020                if (text != null && text.length() > 0) {
8021                    ParagraphTextSegmentIterator iterator =
8022                        ParagraphTextSegmentIterator.getInstance();
8023                    iterator.initialize(text.toString());
8024                    return iterator;
8025                }
8026            } break;
8027        }
8028        return null;
8029    }
8030
8031    /**
8032     * @hide
8033     */
8034    public void dispatchStartTemporaryDetach() {
8035        onStartTemporaryDetach();
8036    }
8037
8038    /**
8039     * This is called when a container is going to temporarily detach a child, with
8040     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8041     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8042     * {@link #onDetachedFromWindow()} when the container is done.
8043     */
8044    public void onStartTemporaryDetach() {
8045        removeUnsetPressCallback();
8046        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8047    }
8048
8049    /**
8050     * @hide
8051     */
8052    public void dispatchFinishTemporaryDetach() {
8053        onFinishTemporaryDetach();
8054    }
8055
8056    /**
8057     * Called after {@link #onStartTemporaryDetach} when the container is done
8058     * changing the view.
8059     */
8060    public void onFinishTemporaryDetach() {
8061    }
8062
8063    /**
8064     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8065     * for this view's window.  Returns null if the view is not currently attached
8066     * to the window.  Normally you will not need to use this directly, but
8067     * just use the standard high-level event callbacks like
8068     * {@link #onKeyDown(int, KeyEvent)}.
8069     */
8070    public KeyEvent.DispatcherState getKeyDispatcherState() {
8071        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8072    }
8073
8074    /**
8075     * Dispatch a key event before it is processed by any input method
8076     * associated with the view hierarchy.  This can be used to intercept
8077     * key events in special situations before the IME consumes them; a
8078     * typical example would be handling the BACK key to update the application's
8079     * UI instead of allowing the IME to see it and close itself.
8080     *
8081     * @param event The key event to be dispatched.
8082     * @return True if the event was handled, false otherwise.
8083     */
8084    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8085        return onKeyPreIme(event.getKeyCode(), event);
8086    }
8087
8088    /**
8089     * Dispatch a key event to the next view on the focus path. This path runs
8090     * from the top of the view tree down to the currently focused view. If this
8091     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8092     * the next node down the focus path. This method also fires any key
8093     * listeners.
8094     *
8095     * @param event The key event to be dispatched.
8096     * @return True if the event was handled, false otherwise.
8097     */
8098    public boolean dispatchKeyEvent(KeyEvent event) {
8099        if (mInputEventConsistencyVerifier != null) {
8100            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8101        }
8102
8103        // Give any attached key listener a first crack at the event.
8104        //noinspection SimplifiableIfStatement
8105        ListenerInfo li = mListenerInfo;
8106        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8107                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8108            return true;
8109        }
8110
8111        if (event.dispatch(this, mAttachInfo != null
8112                ? mAttachInfo.mKeyDispatchState : null, this)) {
8113            return true;
8114        }
8115
8116        if (mInputEventConsistencyVerifier != null) {
8117            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8118        }
8119        return false;
8120    }
8121
8122    /**
8123     * Dispatches a key shortcut event.
8124     *
8125     * @param event The key event to be dispatched.
8126     * @return True if the event was handled by the view, false otherwise.
8127     */
8128    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8129        return onKeyShortcut(event.getKeyCode(), event);
8130    }
8131
8132    /**
8133     * Pass the touch screen motion event down to the target view, or this
8134     * view if it is the target.
8135     *
8136     * @param event The motion event to be dispatched.
8137     * @return True if the event was handled by the view, false otherwise.
8138     */
8139    public boolean dispatchTouchEvent(MotionEvent event) {
8140        boolean result = false;
8141
8142        if (mInputEventConsistencyVerifier != null) {
8143            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8144        }
8145
8146        final int actionMasked = event.getActionMasked();
8147        if (actionMasked == MotionEvent.ACTION_DOWN) {
8148            // Defensive cleanup for new gesture
8149            stopNestedScroll();
8150        }
8151
8152        if (onFilterTouchEventForSecurity(event)) {
8153            //noinspection SimplifiableIfStatement
8154            ListenerInfo li = mListenerInfo;
8155            if (li != null && li.mOnTouchListener != null
8156                    && (mViewFlags & ENABLED_MASK) == ENABLED
8157                    && li.mOnTouchListener.onTouch(this, event)) {
8158                result = true;
8159            }
8160
8161            if (!result && onTouchEvent(event)) {
8162                result = true;
8163            }
8164        }
8165
8166        if (!result && mInputEventConsistencyVerifier != null) {
8167            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8168        }
8169
8170        // Clean up after nested scrolls if this is the end of a gesture;
8171        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8172        // of the gesture.
8173        if (actionMasked == MotionEvent.ACTION_UP ||
8174                actionMasked == MotionEvent.ACTION_CANCEL ||
8175                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8176            stopNestedScroll();
8177        }
8178
8179        return result;
8180    }
8181
8182    /**
8183     * Filter the touch event to apply security policies.
8184     *
8185     * @param event The motion event to be filtered.
8186     * @return True if the event should be dispatched, false if the event should be dropped.
8187     *
8188     * @see #getFilterTouchesWhenObscured
8189     */
8190    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8191        //noinspection RedundantIfStatement
8192        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8193                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8194            // Window is obscured, drop this touch.
8195            return false;
8196        }
8197        return true;
8198    }
8199
8200    /**
8201     * Pass a trackball motion event down to the focused view.
8202     *
8203     * @param event The motion event to be dispatched.
8204     * @return True if the event was handled by the view, false otherwise.
8205     */
8206    public boolean dispatchTrackballEvent(MotionEvent event) {
8207        if (mInputEventConsistencyVerifier != null) {
8208            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8209        }
8210
8211        return onTrackballEvent(event);
8212    }
8213
8214    /**
8215     * Dispatch a generic motion event.
8216     * <p>
8217     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8218     * are delivered to the view under the pointer.  All other generic motion events are
8219     * delivered to the focused view.  Hover events are handled specially and are delivered
8220     * to {@link #onHoverEvent(MotionEvent)}.
8221     * </p>
8222     *
8223     * @param event The motion event to be dispatched.
8224     * @return True if the event was handled by the view, false otherwise.
8225     */
8226    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8227        if (mInputEventConsistencyVerifier != null) {
8228            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8229        }
8230
8231        final int source = event.getSource();
8232        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8233            final int action = event.getAction();
8234            if (action == MotionEvent.ACTION_HOVER_ENTER
8235                    || action == MotionEvent.ACTION_HOVER_MOVE
8236                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8237                if (dispatchHoverEvent(event)) {
8238                    return true;
8239                }
8240            } else if (dispatchGenericPointerEvent(event)) {
8241                return true;
8242            }
8243        } else if (dispatchGenericFocusedEvent(event)) {
8244            return true;
8245        }
8246
8247        if (dispatchGenericMotionEventInternal(event)) {
8248            return true;
8249        }
8250
8251        if (mInputEventConsistencyVerifier != null) {
8252            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8253        }
8254        return false;
8255    }
8256
8257    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8258        //noinspection SimplifiableIfStatement
8259        ListenerInfo li = mListenerInfo;
8260        if (li != null && li.mOnGenericMotionListener != null
8261                && (mViewFlags & ENABLED_MASK) == ENABLED
8262                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8263            return true;
8264        }
8265
8266        if (onGenericMotionEvent(event)) {
8267            return true;
8268        }
8269
8270        if (mInputEventConsistencyVerifier != null) {
8271            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8272        }
8273        return false;
8274    }
8275
8276    /**
8277     * Dispatch a hover event.
8278     * <p>
8279     * Do not call this method directly.
8280     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8281     * </p>
8282     *
8283     * @param event The motion event to be dispatched.
8284     * @return True if the event was handled by the view, false otherwise.
8285     */
8286    protected boolean dispatchHoverEvent(MotionEvent event) {
8287        ListenerInfo li = mListenerInfo;
8288        //noinspection SimplifiableIfStatement
8289        if (li != null && li.mOnHoverListener != null
8290                && (mViewFlags & ENABLED_MASK) == ENABLED
8291                && li.mOnHoverListener.onHover(this, event)) {
8292            return true;
8293        }
8294
8295        return onHoverEvent(event);
8296    }
8297
8298    /**
8299     * Returns true if the view has a child to which it has recently sent
8300     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8301     * it does not have a hovered child, then it must be the innermost hovered view.
8302     * @hide
8303     */
8304    protected boolean hasHoveredChild() {
8305        return false;
8306    }
8307
8308    /**
8309     * Dispatch a generic motion event to the view under the first pointer.
8310     * <p>
8311     * Do not call this method directly.
8312     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8313     * </p>
8314     *
8315     * @param event The motion event to be dispatched.
8316     * @return True if the event was handled by the view, false otherwise.
8317     */
8318    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8319        return false;
8320    }
8321
8322    /**
8323     * Dispatch a generic motion event to the currently focused view.
8324     * <p>
8325     * Do not call this method directly.
8326     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8327     * </p>
8328     *
8329     * @param event The motion event to be dispatched.
8330     * @return True if the event was handled by the view, false otherwise.
8331     */
8332    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8333        return false;
8334    }
8335
8336    /**
8337     * Dispatch a pointer event.
8338     * <p>
8339     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8340     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8341     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8342     * and should not be expected to handle other pointing device features.
8343     * </p>
8344     *
8345     * @param event The motion event to be dispatched.
8346     * @return True if the event was handled by the view, false otherwise.
8347     * @hide
8348     */
8349    public final boolean dispatchPointerEvent(MotionEvent event) {
8350        if (event.isTouchEvent()) {
8351            return dispatchTouchEvent(event);
8352        } else {
8353            return dispatchGenericMotionEvent(event);
8354        }
8355    }
8356
8357    /**
8358     * Called when the window containing this view gains or loses window focus.
8359     * ViewGroups should override to route to their children.
8360     *
8361     * @param hasFocus True if the window containing this view now has focus,
8362     *        false otherwise.
8363     */
8364    public void dispatchWindowFocusChanged(boolean hasFocus) {
8365        onWindowFocusChanged(hasFocus);
8366    }
8367
8368    /**
8369     * Called when the window containing this view gains or loses focus.  Note
8370     * that this is separate from view focus: to receive key events, both
8371     * your view and its window must have focus.  If a window is displayed
8372     * on top of yours that takes input focus, then your own window will lose
8373     * focus but the view focus will remain unchanged.
8374     *
8375     * @param hasWindowFocus True if the window containing this view now has
8376     *        focus, false otherwise.
8377     */
8378    public void onWindowFocusChanged(boolean hasWindowFocus) {
8379        InputMethodManager imm = InputMethodManager.peekInstance();
8380        if (!hasWindowFocus) {
8381            if (isPressed()) {
8382                setPressed(false);
8383            }
8384            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8385                imm.focusOut(this);
8386            }
8387            removeLongPressCallback();
8388            removeTapCallback();
8389            onFocusLost();
8390        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8391            imm.focusIn(this);
8392        }
8393        refreshDrawableState();
8394    }
8395
8396    /**
8397     * Returns true if this view is in a window that currently has window focus.
8398     * Note that this is not the same as the view itself having focus.
8399     *
8400     * @return True if this view is in a window that currently has window focus.
8401     */
8402    public boolean hasWindowFocus() {
8403        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8404    }
8405
8406    /**
8407     * Dispatch a view visibility change down the view hierarchy.
8408     * ViewGroups should override to route to their children.
8409     * @param changedView The view whose visibility changed. Could be 'this' or
8410     * an ancestor view.
8411     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8412     * {@link #INVISIBLE} or {@link #GONE}.
8413     */
8414    protected void dispatchVisibilityChanged(@NonNull View changedView,
8415            @Visibility int visibility) {
8416        onVisibilityChanged(changedView, visibility);
8417    }
8418
8419    /**
8420     * Called when the visibility of the view or an ancestor of the view is changed.
8421     * @param changedView The view whose visibility changed. Could be 'this' or
8422     * an ancestor view.
8423     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8424     * {@link #INVISIBLE} or {@link #GONE}.
8425     */
8426    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8427        if (visibility == VISIBLE) {
8428            if (mAttachInfo != null) {
8429                initialAwakenScrollBars();
8430            } else {
8431                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8432            }
8433        }
8434    }
8435
8436    /**
8437     * Dispatch a hint about whether this view is displayed. For instance, when
8438     * a View moves out of the screen, it might receives a display hint indicating
8439     * the view is not displayed. Applications should not <em>rely</em> on this hint
8440     * as there is no guarantee that they will receive one.
8441     *
8442     * @param hint A hint about whether or not this view is displayed:
8443     * {@link #VISIBLE} or {@link #INVISIBLE}.
8444     */
8445    public void dispatchDisplayHint(@Visibility int hint) {
8446        onDisplayHint(hint);
8447    }
8448
8449    /**
8450     * Gives this view a hint about whether is displayed or not. For instance, when
8451     * a View moves out of the screen, it might receives a display hint indicating
8452     * the view is not displayed. Applications should not <em>rely</em> on this hint
8453     * as there is no guarantee that they will receive one.
8454     *
8455     * @param hint A hint about whether or not this view is displayed:
8456     * {@link #VISIBLE} or {@link #INVISIBLE}.
8457     */
8458    protected void onDisplayHint(@Visibility int hint) {
8459    }
8460
8461    /**
8462     * Dispatch a window visibility change down the view hierarchy.
8463     * ViewGroups should override to route to their children.
8464     *
8465     * @param visibility The new visibility of the window.
8466     *
8467     * @see #onWindowVisibilityChanged(int)
8468     */
8469    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8470        onWindowVisibilityChanged(visibility);
8471    }
8472
8473    /**
8474     * Called when the window containing has change its visibility
8475     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8476     * that this tells you whether or not your window is being made visible
8477     * to the window manager; this does <em>not</em> tell you whether or not
8478     * your window is obscured by other windows on the screen, even if it
8479     * is itself visible.
8480     *
8481     * @param visibility The new visibility of the window.
8482     */
8483    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8484        if (visibility == VISIBLE) {
8485            initialAwakenScrollBars();
8486        }
8487    }
8488
8489    /**
8490     * Returns the current visibility of the window this view is attached to
8491     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8492     *
8493     * @return Returns the current visibility of the view's window.
8494     */
8495    @Visibility
8496    public int getWindowVisibility() {
8497        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8498    }
8499
8500    /**
8501     * Retrieve the overall visible display size in which the window this view is
8502     * attached to has been positioned in.  This takes into account screen
8503     * decorations above the window, for both cases where the window itself
8504     * is being position inside of them or the window is being placed under
8505     * then and covered insets are used for the window to position its content
8506     * inside.  In effect, this tells you the available area where content can
8507     * be placed and remain visible to users.
8508     *
8509     * <p>This function requires an IPC back to the window manager to retrieve
8510     * the requested information, so should not be used in performance critical
8511     * code like drawing.
8512     *
8513     * @param outRect Filled in with the visible display frame.  If the view
8514     * is not attached to a window, this is simply the raw display size.
8515     */
8516    public void getWindowVisibleDisplayFrame(Rect outRect) {
8517        if (mAttachInfo != null) {
8518            try {
8519                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8520            } catch (RemoteException e) {
8521                return;
8522            }
8523            // XXX This is really broken, and probably all needs to be done
8524            // in the window manager, and we need to know more about whether
8525            // we want the area behind or in front of the IME.
8526            final Rect insets = mAttachInfo.mVisibleInsets;
8527            outRect.left += insets.left;
8528            outRect.top += insets.top;
8529            outRect.right -= insets.right;
8530            outRect.bottom -= insets.bottom;
8531            return;
8532        }
8533        // The view is not attached to a display so we don't have a context.
8534        // Make a best guess about the display size.
8535        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8536        d.getRectSize(outRect);
8537    }
8538
8539    /**
8540     * Dispatch a notification about a resource configuration change down
8541     * the view hierarchy.
8542     * ViewGroups should override to route to their children.
8543     *
8544     * @param newConfig The new resource configuration.
8545     *
8546     * @see #onConfigurationChanged(android.content.res.Configuration)
8547     */
8548    public void dispatchConfigurationChanged(Configuration newConfig) {
8549        onConfigurationChanged(newConfig);
8550    }
8551
8552    /**
8553     * Called when the current configuration of the resources being used
8554     * by the application have changed.  You can use this to decide when
8555     * to reload resources that can changed based on orientation and other
8556     * configuration characterstics.  You only need to use this if you are
8557     * not relying on the normal {@link android.app.Activity} mechanism of
8558     * recreating the activity instance upon a configuration change.
8559     *
8560     * @param newConfig The new resource configuration.
8561     */
8562    protected void onConfigurationChanged(Configuration newConfig) {
8563    }
8564
8565    /**
8566     * Private function to aggregate all per-view attributes in to the view
8567     * root.
8568     */
8569    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8570        performCollectViewAttributes(attachInfo, visibility);
8571    }
8572
8573    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8574        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8575            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8576                attachInfo.mKeepScreenOn = true;
8577            }
8578            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8579            ListenerInfo li = mListenerInfo;
8580            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8581                attachInfo.mHasSystemUiListeners = true;
8582            }
8583        }
8584    }
8585
8586    void needGlobalAttributesUpdate(boolean force) {
8587        final AttachInfo ai = mAttachInfo;
8588        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8589            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8590                    || ai.mHasSystemUiListeners) {
8591                ai.mRecomputeGlobalAttributes = true;
8592            }
8593        }
8594    }
8595
8596    /**
8597     * Returns whether the device is currently in touch mode.  Touch mode is entered
8598     * once the user begins interacting with the device by touch, and affects various
8599     * things like whether focus is always visible to the user.
8600     *
8601     * @return Whether the device is in touch mode.
8602     */
8603    @ViewDebug.ExportedProperty
8604    public boolean isInTouchMode() {
8605        if (mAttachInfo != null) {
8606            return mAttachInfo.mInTouchMode;
8607        } else {
8608            return ViewRootImpl.isInTouchMode();
8609        }
8610    }
8611
8612    /**
8613     * Returns the context the view is running in, through which it can
8614     * access the current theme, resources, etc.
8615     *
8616     * @return The view's Context.
8617     */
8618    @ViewDebug.CapturedViewProperty
8619    public final Context getContext() {
8620        return mContext;
8621    }
8622
8623    /**
8624     * Handle a key event before it is processed by any input method
8625     * associated with the view hierarchy.  This can be used to intercept
8626     * key events in special situations before the IME consumes them; a
8627     * typical example would be handling the BACK key to update the application's
8628     * UI instead of allowing the IME to see it and close itself.
8629     *
8630     * @param keyCode The value in event.getKeyCode().
8631     * @param event Description of the key event.
8632     * @return If you handled the event, return true. If you want to allow the
8633     *         event to be handled by the next receiver, return false.
8634     */
8635    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8636        return false;
8637    }
8638
8639    /**
8640     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8641     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8642     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8643     * is released, if the view is enabled and clickable.
8644     *
8645     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8646     * although some may elect to do so in some situations. Do not rely on this to
8647     * catch software key presses.
8648     *
8649     * @param keyCode A key code that represents the button pressed, from
8650     *                {@link android.view.KeyEvent}.
8651     * @param event   The KeyEvent object that defines the button action.
8652     */
8653    public boolean onKeyDown(int keyCode, KeyEvent event) {
8654        boolean result = false;
8655
8656        if (KeyEvent.isConfirmKey(keyCode)) {
8657            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8658                return true;
8659            }
8660            // Long clickable items don't necessarily have to be clickable
8661            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8662                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8663                    (event.getRepeatCount() == 0)) {
8664                setPressed(true);
8665                checkForLongClick(0);
8666                return true;
8667            }
8668        }
8669        return result;
8670    }
8671
8672    /**
8673     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8674     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8675     * the event).
8676     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8677     * although some may elect to do so in some situations. Do not rely on this to
8678     * catch software key presses.
8679     */
8680    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8681        return false;
8682    }
8683
8684    /**
8685     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8686     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8687     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8688     * {@link KeyEvent#KEYCODE_ENTER} is released.
8689     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8690     * although some may elect to do so in some situations. Do not rely on this to
8691     * catch software key presses.
8692     *
8693     * @param keyCode A key code that represents the button pressed, from
8694     *                {@link android.view.KeyEvent}.
8695     * @param event   The KeyEvent object that defines the button action.
8696     */
8697    public boolean onKeyUp(int keyCode, KeyEvent event) {
8698        if (KeyEvent.isConfirmKey(keyCode)) {
8699            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8700                return true;
8701            }
8702            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8703                setPressed(false);
8704
8705                if (!mHasPerformedLongPress) {
8706                    // This is a tap, so remove the longpress check
8707                    removeLongPressCallback();
8708                    return performClick();
8709                }
8710            }
8711        }
8712        return false;
8713    }
8714
8715    /**
8716     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8717     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8718     * the event).
8719     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8720     * although some may elect to do so in some situations. Do not rely on this to
8721     * catch software key presses.
8722     *
8723     * @param keyCode     A key code that represents the button pressed, from
8724     *                    {@link android.view.KeyEvent}.
8725     * @param repeatCount The number of times the action was made.
8726     * @param event       The KeyEvent object that defines the button action.
8727     */
8728    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8729        return false;
8730    }
8731
8732    /**
8733     * Called on the focused view when a key shortcut event is not handled.
8734     * Override this method to implement local key shortcuts for the View.
8735     * Key shortcuts can also be implemented by setting the
8736     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8737     *
8738     * @param keyCode The value in event.getKeyCode().
8739     * @param event Description of the key event.
8740     * @return If you handled the event, return true. If you want to allow the
8741     *         event to be handled by the next receiver, return false.
8742     */
8743    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8744        return false;
8745    }
8746
8747    /**
8748     * Check whether the called view is a text editor, in which case it
8749     * would make sense to automatically display a soft input window for
8750     * it.  Subclasses should override this if they implement
8751     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8752     * a call on that method would return a non-null InputConnection, and
8753     * they are really a first-class editor that the user would normally
8754     * start typing on when the go into a window containing your view.
8755     *
8756     * <p>The default implementation always returns false.  This does
8757     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8758     * will not be called or the user can not otherwise perform edits on your
8759     * view; it is just a hint to the system that this is not the primary
8760     * purpose of this view.
8761     *
8762     * @return Returns true if this view is a text editor, else false.
8763     */
8764    public boolean onCheckIsTextEditor() {
8765        return false;
8766    }
8767
8768    /**
8769     * Create a new InputConnection for an InputMethod to interact
8770     * with the view.  The default implementation returns null, since it doesn't
8771     * support input methods.  You can override this to implement such support.
8772     * This is only needed for views that take focus and text input.
8773     *
8774     * <p>When implementing this, you probably also want to implement
8775     * {@link #onCheckIsTextEditor()} to indicate you will return a
8776     * non-null InputConnection.</p>
8777     *
8778     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8779     * object correctly and in its entirety, so that the connected IME can rely
8780     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8781     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8782     * must be filled in with the correct cursor position for IMEs to work correctly
8783     * with your application.</p>
8784     *
8785     * @param outAttrs Fill in with attribute information about the connection.
8786     */
8787    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8788        return null;
8789    }
8790
8791    /**
8792     * Called by the {@link android.view.inputmethod.InputMethodManager}
8793     * when a view who is not the current
8794     * input connection target is trying to make a call on the manager.  The
8795     * default implementation returns false; you can override this to return
8796     * true for certain views if you are performing InputConnection proxying
8797     * to them.
8798     * @param view The View that is making the InputMethodManager call.
8799     * @return Return true to allow the call, false to reject.
8800     */
8801    public boolean checkInputConnectionProxy(View view) {
8802        return false;
8803    }
8804
8805    /**
8806     * Show the context menu for this view. It is not safe to hold on to the
8807     * menu after returning from this method.
8808     *
8809     * You should normally not overload this method. Overload
8810     * {@link #onCreateContextMenu(ContextMenu)} or define an
8811     * {@link OnCreateContextMenuListener} to add items to the context menu.
8812     *
8813     * @param menu The context menu to populate
8814     */
8815    public void createContextMenu(ContextMenu menu) {
8816        ContextMenuInfo menuInfo = getContextMenuInfo();
8817
8818        // Sets the current menu info so all items added to menu will have
8819        // my extra info set.
8820        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8821
8822        onCreateContextMenu(menu);
8823        ListenerInfo li = mListenerInfo;
8824        if (li != null && li.mOnCreateContextMenuListener != null) {
8825            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8826        }
8827
8828        // Clear the extra information so subsequent items that aren't mine don't
8829        // have my extra info.
8830        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8831
8832        if (mParent != null) {
8833            mParent.createContextMenu(menu);
8834        }
8835    }
8836
8837    /**
8838     * Views should implement this if they have extra information to associate
8839     * with the context menu. The return result is supplied as a parameter to
8840     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8841     * callback.
8842     *
8843     * @return Extra information about the item for which the context menu
8844     *         should be shown. This information will vary across different
8845     *         subclasses of View.
8846     */
8847    protected ContextMenuInfo getContextMenuInfo() {
8848        return null;
8849    }
8850
8851    /**
8852     * Views should implement this if the view itself is going to add items to
8853     * the context menu.
8854     *
8855     * @param menu the context menu to populate
8856     */
8857    protected void onCreateContextMenu(ContextMenu menu) {
8858    }
8859
8860    /**
8861     * Implement this method to handle trackball motion events.  The
8862     * <em>relative</em> movement of the trackball since the last event
8863     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8864     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8865     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8866     * they will often be fractional values, representing the more fine-grained
8867     * movement information available from a trackball).
8868     *
8869     * @param event The motion event.
8870     * @return True if the event was handled, false otherwise.
8871     */
8872    public boolean onTrackballEvent(MotionEvent event) {
8873        return false;
8874    }
8875
8876    /**
8877     * Implement this method to handle generic motion events.
8878     * <p>
8879     * Generic motion events describe joystick movements, mouse hovers, track pad
8880     * touches, scroll wheel movements and other input events.  The
8881     * {@link MotionEvent#getSource() source} of the motion event specifies
8882     * the class of input that was received.  Implementations of this method
8883     * must examine the bits in the source before processing the event.
8884     * The following code example shows how this is done.
8885     * </p><p>
8886     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8887     * are delivered to the view under the pointer.  All other generic motion events are
8888     * delivered to the focused view.
8889     * </p>
8890     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8891     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8892     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8893     *             // process the joystick movement...
8894     *             return true;
8895     *         }
8896     *     }
8897     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8898     *         switch (event.getAction()) {
8899     *             case MotionEvent.ACTION_HOVER_MOVE:
8900     *                 // process the mouse hover movement...
8901     *                 return true;
8902     *             case MotionEvent.ACTION_SCROLL:
8903     *                 // process the scroll wheel movement...
8904     *                 return true;
8905     *         }
8906     *     }
8907     *     return super.onGenericMotionEvent(event);
8908     * }</pre>
8909     *
8910     * @param event The generic motion event being processed.
8911     * @return True if the event was handled, false otherwise.
8912     */
8913    public boolean onGenericMotionEvent(MotionEvent event) {
8914        return false;
8915    }
8916
8917    /**
8918     * Implement this method to handle hover events.
8919     * <p>
8920     * This method is called whenever a pointer is hovering into, over, or out of the
8921     * bounds of a view and the view is not currently being touched.
8922     * Hover events are represented as pointer events with action
8923     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8924     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8925     * </p>
8926     * <ul>
8927     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8928     * when the pointer enters the bounds of the view.</li>
8929     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8930     * when the pointer has already entered the bounds of the view and has moved.</li>
8931     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8932     * when the pointer has exited the bounds of the view or when the pointer is
8933     * about to go down due to a button click, tap, or similar user action that
8934     * causes the view to be touched.</li>
8935     * </ul>
8936     * <p>
8937     * The view should implement this method to return true to indicate that it is
8938     * handling the hover event, such as by changing its drawable state.
8939     * </p><p>
8940     * The default implementation calls {@link #setHovered} to update the hovered state
8941     * of the view when a hover enter or hover exit event is received, if the view
8942     * is enabled and is clickable.  The default implementation also sends hover
8943     * accessibility events.
8944     * </p>
8945     *
8946     * @param event The motion event that describes the hover.
8947     * @return True if the view handled the hover event.
8948     *
8949     * @see #isHovered
8950     * @see #setHovered
8951     * @see #onHoverChanged
8952     */
8953    public boolean onHoverEvent(MotionEvent event) {
8954        // The root view may receive hover (or touch) events that are outside the bounds of
8955        // the window.  This code ensures that we only send accessibility events for
8956        // hovers that are actually within the bounds of the root view.
8957        final int action = event.getActionMasked();
8958        if (!mSendingHoverAccessibilityEvents) {
8959            if ((action == MotionEvent.ACTION_HOVER_ENTER
8960                    || action == MotionEvent.ACTION_HOVER_MOVE)
8961                    && !hasHoveredChild()
8962                    && pointInView(event.getX(), event.getY())) {
8963                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8964                mSendingHoverAccessibilityEvents = true;
8965            }
8966        } else {
8967            if (action == MotionEvent.ACTION_HOVER_EXIT
8968                    || (action == MotionEvent.ACTION_MOVE
8969                            && !pointInView(event.getX(), event.getY()))) {
8970                mSendingHoverAccessibilityEvents = false;
8971                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8972            }
8973        }
8974
8975        if (isHoverable()) {
8976            switch (action) {
8977                case MotionEvent.ACTION_HOVER_ENTER:
8978                    setHovered(true);
8979                    break;
8980                case MotionEvent.ACTION_HOVER_EXIT:
8981                    setHovered(false);
8982                    break;
8983            }
8984
8985            // Dispatch the event to onGenericMotionEvent before returning true.
8986            // This is to provide compatibility with existing applications that
8987            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8988            // break because of the new default handling for hoverable views
8989            // in onHoverEvent.
8990            // Note that onGenericMotionEvent will be called by default when
8991            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8992            dispatchGenericMotionEventInternal(event);
8993            // The event was already handled by calling setHovered(), so always
8994            // return true.
8995            return true;
8996        }
8997
8998        return false;
8999    }
9000
9001    /**
9002     * Returns true if the view should handle {@link #onHoverEvent}
9003     * by calling {@link #setHovered} to change its hovered state.
9004     *
9005     * @return True if the view is hoverable.
9006     */
9007    private boolean isHoverable() {
9008        final int viewFlags = mViewFlags;
9009        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9010            return false;
9011        }
9012
9013        return (viewFlags & CLICKABLE) == CLICKABLE
9014                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9015    }
9016
9017    /**
9018     * Returns true if the view is currently hovered.
9019     *
9020     * @return True if the view is currently hovered.
9021     *
9022     * @see #setHovered
9023     * @see #onHoverChanged
9024     */
9025    @ViewDebug.ExportedProperty
9026    public boolean isHovered() {
9027        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9028    }
9029
9030    /**
9031     * Sets whether the view is currently hovered.
9032     * <p>
9033     * Calling this method also changes the drawable state of the view.  This
9034     * enables the view to react to hover by using different drawable resources
9035     * to change its appearance.
9036     * </p><p>
9037     * The {@link #onHoverChanged} method is called when the hovered state changes.
9038     * </p>
9039     *
9040     * @param hovered True if the view is hovered.
9041     *
9042     * @see #isHovered
9043     * @see #onHoverChanged
9044     */
9045    public void setHovered(boolean hovered) {
9046        if (hovered) {
9047            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9048                mPrivateFlags |= PFLAG_HOVERED;
9049                refreshDrawableState();
9050                onHoverChanged(true);
9051            }
9052        } else {
9053            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9054                mPrivateFlags &= ~PFLAG_HOVERED;
9055                refreshDrawableState();
9056                onHoverChanged(false);
9057            }
9058        }
9059    }
9060
9061    /**
9062     * Implement this method to handle hover state changes.
9063     * <p>
9064     * This method is called whenever the hover state changes as a result of a
9065     * call to {@link #setHovered}.
9066     * </p>
9067     *
9068     * @param hovered The current hover state, as returned by {@link #isHovered}.
9069     *
9070     * @see #isHovered
9071     * @see #setHovered
9072     */
9073    public void onHoverChanged(boolean hovered) {
9074    }
9075
9076    /**
9077     * Implement this method to handle touch screen motion events.
9078     * <p>
9079     * If this method is used to detect click actions, it is recommended that
9080     * the actions be performed by implementing and calling
9081     * {@link #performClick()}. This will ensure consistent system behavior,
9082     * including:
9083     * <ul>
9084     * <li>obeying click sound preferences
9085     * <li>dispatching OnClickListener calls
9086     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9087     * accessibility features are enabled
9088     * </ul>
9089     *
9090     * @param event The motion event.
9091     * @return True if the event was handled, false otherwise.
9092     */
9093    public boolean onTouchEvent(MotionEvent event) {
9094        final float x = event.getX();
9095        final float y = event.getY();
9096        final int viewFlags = mViewFlags;
9097
9098        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9099            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9100                setPressed(false);
9101            }
9102            // A disabled view that is clickable still consumes the touch
9103            // events, it just doesn't respond to them.
9104            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9105                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9106        }
9107
9108        if (mTouchDelegate != null) {
9109            if (mTouchDelegate.onTouchEvent(event)) {
9110                return true;
9111            }
9112        }
9113
9114        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9115                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9116            switch (event.getAction()) {
9117                case MotionEvent.ACTION_UP:
9118                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9119                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9120                        // take focus if we don't have it already and we should in
9121                        // touch mode.
9122                        boolean focusTaken = false;
9123                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9124                            focusTaken = requestFocus();
9125                        }
9126
9127                        if (prepressed) {
9128                            // The button is being released before we actually
9129                            // showed it as pressed.  Make it show the pressed
9130                            // state now (before scheduling the click) to ensure
9131                            // the user sees it.
9132                            setPressed(true, x, y);
9133                       }
9134
9135                        if (!mHasPerformedLongPress) {
9136                            // This is a tap, so remove the longpress check
9137                            removeLongPressCallback();
9138
9139                            // Only perform take click actions if we were in the pressed state
9140                            if (!focusTaken) {
9141                                // Use a Runnable and post this rather than calling
9142                                // performClick directly. This lets other visual state
9143                                // of the view update before click actions start.
9144                                if (mPerformClick == null) {
9145                                    mPerformClick = new PerformClick();
9146                                }
9147                                if (!post(mPerformClick)) {
9148                                    performClick();
9149                                }
9150                            }
9151                        }
9152
9153                        if (mUnsetPressedState == null) {
9154                            mUnsetPressedState = new UnsetPressedState();
9155                        }
9156
9157                        if (prepressed) {
9158                            postDelayed(mUnsetPressedState,
9159                                    ViewConfiguration.getPressedStateDuration());
9160                        } else if (!post(mUnsetPressedState)) {
9161                            // If the post failed, unpress right now
9162                            mUnsetPressedState.run();
9163                        }
9164
9165                        removeTapCallback();
9166                    }
9167                    break;
9168
9169                case MotionEvent.ACTION_DOWN:
9170                    mHasPerformedLongPress = false;
9171
9172                    if (performButtonActionOnTouchDown(event)) {
9173                        break;
9174                    }
9175
9176                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9177                    boolean isInScrollingContainer = isInScrollingContainer();
9178
9179                    // For views inside a scrolling container, delay the pressed feedback for
9180                    // a short period in case this is a scroll.
9181                    if (isInScrollingContainer) {
9182                        mPrivateFlags |= PFLAG_PREPRESSED;
9183                        if (mPendingCheckForTap == null) {
9184                            mPendingCheckForTap = new CheckForTap();
9185                        }
9186                        mPendingCheckForTap.x = event.getX();
9187                        mPendingCheckForTap.y = event.getY();
9188                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9189                    } else {
9190                        // Not inside a scrolling container, so show the feedback right away
9191                        setPressed(true, x, y);
9192                        checkForLongClick(0);
9193                    }
9194                    break;
9195
9196                case MotionEvent.ACTION_CANCEL:
9197                    setPressed(false);
9198                    removeTapCallback();
9199                    removeLongPressCallback();
9200                    break;
9201
9202                case MotionEvent.ACTION_MOVE:
9203                    drawableHotspotChanged(x, y);
9204
9205                    // Be lenient about moving outside of buttons
9206                    if (!pointInView(x, y, mTouchSlop)) {
9207                        // Outside button
9208                        removeTapCallback();
9209                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9210                            // Remove any future long press/tap checks
9211                            removeLongPressCallback();
9212
9213                            setPressed(false);
9214                        }
9215                    }
9216                    break;
9217            }
9218
9219            return true;
9220        }
9221
9222        return false;
9223    }
9224
9225    /**
9226     * @hide
9227     */
9228    public boolean isInScrollingContainer() {
9229        ViewParent p = getParent();
9230        while (p != null && p instanceof ViewGroup) {
9231            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9232                return true;
9233            }
9234            p = p.getParent();
9235        }
9236        return false;
9237    }
9238
9239    /**
9240     * Remove the longpress detection timer.
9241     */
9242    private void removeLongPressCallback() {
9243        if (mPendingCheckForLongPress != null) {
9244          removeCallbacks(mPendingCheckForLongPress);
9245        }
9246    }
9247
9248    /**
9249     * Remove the pending click action
9250     */
9251    private void removePerformClickCallback() {
9252        if (mPerformClick != null) {
9253            removeCallbacks(mPerformClick);
9254        }
9255    }
9256
9257    /**
9258     * Remove the prepress detection timer.
9259     */
9260    private void removeUnsetPressCallback() {
9261        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9262            setPressed(false);
9263            removeCallbacks(mUnsetPressedState);
9264        }
9265    }
9266
9267    /**
9268     * Remove the tap detection timer.
9269     */
9270    private void removeTapCallback() {
9271        if (mPendingCheckForTap != null) {
9272            mPrivateFlags &= ~PFLAG_PREPRESSED;
9273            removeCallbacks(mPendingCheckForTap);
9274        }
9275    }
9276
9277    /**
9278     * Cancels a pending long press.  Your subclass can use this if you
9279     * want the context menu to come up if the user presses and holds
9280     * at the same place, but you don't want it to come up if they press
9281     * and then move around enough to cause scrolling.
9282     */
9283    public void cancelLongPress() {
9284        removeLongPressCallback();
9285
9286        /*
9287         * The prepressed state handled by the tap callback is a display
9288         * construct, but the tap callback will post a long press callback
9289         * less its own timeout. Remove it here.
9290         */
9291        removeTapCallback();
9292    }
9293
9294    /**
9295     * Remove the pending callback for sending a
9296     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9297     */
9298    private void removeSendViewScrolledAccessibilityEventCallback() {
9299        if (mSendViewScrolledAccessibilityEvent != null) {
9300            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9301            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9302        }
9303    }
9304
9305    /**
9306     * Sets the TouchDelegate for this View.
9307     */
9308    public void setTouchDelegate(TouchDelegate delegate) {
9309        mTouchDelegate = delegate;
9310    }
9311
9312    /**
9313     * Gets the TouchDelegate for this View.
9314     */
9315    public TouchDelegate getTouchDelegate() {
9316        return mTouchDelegate;
9317    }
9318
9319    /**
9320     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9321     *
9322     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9323     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9324     * available. This method should only be called for touch events.
9325     *
9326     * <p class="note">This api is not intended for most applications. Buffered dispatch
9327     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9328     * streams will not improve your input latency. Side effects include: increased latency,
9329     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9330     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9331     * you.</p>
9332     */
9333    public final void requestUnbufferedDispatch(MotionEvent event) {
9334        final int action = event.getAction();
9335        if (mAttachInfo == null
9336                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9337                || !event.isTouchEvent()) {
9338            return;
9339        }
9340        mAttachInfo.mUnbufferedDispatchRequested = true;
9341    }
9342
9343    /**
9344     * Set flags controlling behavior of this view.
9345     *
9346     * @param flags Constant indicating the value which should be set
9347     * @param mask Constant indicating the bit range that should be changed
9348     */
9349    void setFlags(int flags, int mask) {
9350        final boolean accessibilityEnabled =
9351                AccessibilityManager.getInstance(mContext).isEnabled();
9352        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9353
9354        int old = mViewFlags;
9355        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9356
9357        int changed = mViewFlags ^ old;
9358        if (changed == 0) {
9359            return;
9360        }
9361        int privateFlags = mPrivateFlags;
9362
9363        /* Check if the FOCUSABLE bit has changed */
9364        if (((changed & FOCUSABLE_MASK) != 0) &&
9365                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9366            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9367                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9368                /* Give up focus if we are no longer focusable */
9369                clearFocus();
9370            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9371                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9372                /*
9373                 * Tell the view system that we are now available to take focus
9374                 * if no one else already has it.
9375                 */
9376                if (mParent != null) mParent.focusableViewAvailable(this);
9377            }
9378        }
9379
9380        final int newVisibility = flags & VISIBILITY_MASK;
9381        if (newVisibility == VISIBLE) {
9382            if ((changed & VISIBILITY_MASK) != 0) {
9383                /*
9384                 * If this view is becoming visible, invalidate it in case it changed while
9385                 * it was not visible. Marking it drawn ensures that the invalidation will
9386                 * go through.
9387                 */
9388                mPrivateFlags |= PFLAG_DRAWN;
9389                invalidate(true);
9390
9391                needGlobalAttributesUpdate(true);
9392
9393                // a view becoming visible is worth notifying the parent
9394                // about in case nothing has focus.  even if this specific view
9395                // isn't focusable, it may contain something that is, so let
9396                // the root view try to give this focus if nothing else does.
9397                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9398                    mParent.focusableViewAvailable(this);
9399                }
9400            }
9401        }
9402
9403        /* Check if the GONE bit has changed */
9404        if ((changed & GONE) != 0) {
9405            needGlobalAttributesUpdate(false);
9406            requestLayout();
9407
9408            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9409                if (hasFocus()) clearFocus();
9410                clearAccessibilityFocus();
9411                destroyDrawingCache();
9412                if (mParent instanceof View) {
9413                    // GONE views noop invalidation, so invalidate the parent
9414                    ((View) mParent).invalidate(true);
9415                }
9416                // Mark the view drawn to ensure that it gets invalidated properly the next
9417                // time it is visible and gets invalidated
9418                mPrivateFlags |= PFLAG_DRAWN;
9419            }
9420            if (mAttachInfo != null) {
9421                mAttachInfo.mViewVisibilityChanged = true;
9422            }
9423        }
9424
9425        /* Check if the VISIBLE bit has changed */
9426        if ((changed & INVISIBLE) != 0) {
9427            needGlobalAttributesUpdate(false);
9428            /*
9429             * If this view is becoming invisible, set the DRAWN flag so that
9430             * the next invalidate() will not be skipped.
9431             */
9432            mPrivateFlags |= PFLAG_DRAWN;
9433
9434            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9435                // root view becoming invisible shouldn't clear focus and accessibility focus
9436                if (getRootView() != this) {
9437                    if (hasFocus()) clearFocus();
9438                    clearAccessibilityFocus();
9439                }
9440            }
9441            if (mAttachInfo != null) {
9442                mAttachInfo.mViewVisibilityChanged = true;
9443            }
9444        }
9445
9446        if ((changed & VISIBILITY_MASK) != 0) {
9447            // If the view is invisible, cleanup its display list to free up resources
9448            if (newVisibility != VISIBLE && mAttachInfo != null) {
9449                cleanupDraw();
9450            }
9451
9452            if (mParent instanceof ViewGroup) {
9453                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9454                        (changed & VISIBILITY_MASK), newVisibility);
9455                ((View) mParent).invalidate(true);
9456            } else if (mParent != null) {
9457                mParent.invalidateChild(this, null);
9458            }
9459            dispatchVisibilityChanged(this, newVisibility);
9460
9461            notifySubtreeAccessibilityStateChangedIfNeeded();
9462        }
9463
9464        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9465            destroyDrawingCache();
9466        }
9467
9468        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9469            destroyDrawingCache();
9470            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9471            invalidateParentCaches();
9472        }
9473
9474        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9475            destroyDrawingCache();
9476            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9477        }
9478
9479        if ((changed & DRAW_MASK) != 0) {
9480            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9481                if (mBackground != null) {
9482                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9483                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9484                } else {
9485                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9486                }
9487            } else {
9488                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9489            }
9490            requestLayout();
9491            invalidate(true);
9492        }
9493
9494        if ((changed & KEEP_SCREEN_ON) != 0) {
9495            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9496                mParent.recomputeViewAttributes(this);
9497            }
9498        }
9499
9500        if (accessibilityEnabled) {
9501            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9502                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9503                if (oldIncludeForAccessibility != includeForAccessibility()) {
9504                    notifySubtreeAccessibilityStateChangedIfNeeded();
9505                } else {
9506                    notifyViewAccessibilityStateChangedIfNeeded(
9507                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9508                }
9509            } else if ((changed & ENABLED_MASK) != 0) {
9510                notifyViewAccessibilityStateChangedIfNeeded(
9511                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9512            }
9513        }
9514    }
9515
9516    /**
9517     * Change the view's z order in the tree, so it's on top of other sibling
9518     * views. This ordering change may affect layout, if the parent container
9519     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9520     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9521     * method should be followed by calls to {@link #requestLayout()} and
9522     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9523     * with the new child ordering.
9524     *
9525     * @see ViewGroup#bringChildToFront(View)
9526     */
9527    public void bringToFront() {
9528        if (mParent != null) {
9529            mParent.bringChildToFront(this);
9530        }
9531    }
9532
9533    /**
9534     * This is called in response to an internal scroll in this view (i.e., the
9535     * view scrolled its own contents). This is typically as a result of
9536     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9537     * called.
9538     *
9539     * @param l Current horizontal scroll origin.
9540     * @param t Current vertical scroll origin.
9541     * @param oldl Previous horizontal scroll origin.
9542     * @param oldt Previous vertical scroll origin.
9543     */
9544    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9545        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9546            postSendViewScrolledAccessibilityEventCallback();
9547        }
9548
9549        mBackgroundSizeChanged = true;
9550
9551        final AttachInfo ai = mAttachInfo;
9552        if (ai != null) {
9553            ai.mViewScrollChanged = true;
9554        }
9555    }
9556
9557    /**
9558     * Interface definition for a callback to be invoked when the layout bounds of a view
9559     * changes due to layout processing.
9560     */
9561    public interface OnLayoutChangeListener {
9562        /**
9563         * Called when the layout bounds of a view changes due to layout processing.
9564         *
9565         * @param v The view whose bounds have changed.
9566         * @param left The new value of the view's left property.
9567         * @param top The new value of the view's top property.
9568         * @param right The new value of the view's right property.
9569         * @param bottom The new value of the view's bottom property.
9570         * @param oldLeft The previous value of the view's left property.
9571         * @param oldTop The previous value of the view's top property.
9572         * @param oldRight The previous value of the view's right property.
9573         * @param oldBottom The previous value of the view's bottom property.
9574         */
9575        void onLayoutChange(View v, int left, int top, int right, int bottom,
9576            int oldLeft, int oldTop, int oldRight, int oldBottom);
9577    }
9578
9579    /**
9580     * This is called during layout when the size of this view has changed. If
9581     * you were just added to the view hierarchy, you're called with the old
9582     * values of 0.
9583     *
9584     * @param w Current width of this view.
9585     * @param h Current height of this view.
9586     * @param oldw Old width of this view.
9587     * @param oldh Old height of this view.
9588     */
9589    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9590    }
9591
9592    /**
9593     * Called by draw to draw the child views. This may be overridden
9594     * by derived classes to gain control just before its children are drawn
9595     * (but after its own view has been drawn).
9596     * @param canvas the canvas on which to draw the view
9597     */
9598    protected void dispatchDraw(Canvas canvas) {
9599
9600    }
9601
9602    /**
9603     * Gets the parent of this view. Note that the parent is a
9604     * ViewParent and not necessarily a View.
9605     *
9606     * @return Parent of this view.
9607     */
9608    public final ViewParent getParent() {
9609        return mParent;
9610    }
9611
9612    /**
9613     * Set the horizontal scrolled position of your view. This will cause a call to
9614     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9615     * invalidated.
9616     * @param value the x position to scroll to
9617     */
9618    public void setScrollX(int value) {
9619        scrollTo(value, mScrollY);
9620    }
9621
9622    /**
9623     * Set the vertical scrolled position of your view. This will cause a call to
9624     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9625     * invalidated.
9626     * @param value the y position to scroll to
9627     */
9628    public void setScrollY(int value) {
9629        scrollTo(mScrollX, value);
9630    }
9631
9632    /**
9633     * Return the scrolled left position of this view. This is the left edge of
9634     * the displayed part of your view. You do not need to draw any pixels
9635     * farther left, since those are outside of the frame of your view on
9636     * screen.
9637     *
9638     * @return The left edge of the displayed part of your view, in pixels.
9639     */
9640    public final int getScrollX() {
9641        return mScrollX;
9642    }
9643
9644    /**
9645     * Return the scrolled top position of this view. This is the top edge of
9646     * the displayed part of your view. You do not need to draw any pixels above
9647     * it, since those are outside of the frame of your view on screen.
9648     *
9649     * @return The top edge of the displayed part of your view, in pixels.
9650     */
9651    public final int getScrollY() {
9652        return mScrollY;
9653    }
9654
9655    /**
9656     * Return the width of the your view.
9657     *
9658     * @return The width of your view, in pixels.
9659     */
9660    @ViewDebug.ExportedProperty(category = "layout")
9661    public final int getWidth() {
9662        return mRight - mLeft;
9663    }
9664
9665    /**
9666     * Return the height of your view.
9667     *
9668     * @return The height of your view, in pixels.
9669     */
9670    @ViewDebug.ExportedProperty(category = "layout")
9671    public final int getHeight() {
9672        return mBottom - mTop;
9673    }
9674
9675    /**
9676     * Return the visible drawing bounds of your view. Fills in the output
9677     * rectangle with the values from getScrollX(), getScrollY(),
9678     * getWidth(), and getHeight(). These bounds do not account for any
9679     * transformation properties currently set on the view, such as
9680     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9681     *
9682     * @param outRect The (scrolled) drawing bounds of the view.
9683     */
9684    public void getDrawingRect(Rect outRect) {
9685        outRect.left = mScrollX;
9686        outRect.top = mScrollY;
9687        outRect.right = mScrollX + (mRight - mLeft);
9688        outRect.bottom = mScrollY + (mBottom - mTop);
9689    }
9690
9691    /**
9692     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9693     * raw width component (that is the result is masked by
9694     * {@link #MEASURED_SIZE_MASK}).
9695     *
9696     * @return The raw measured width of this view.
9697     */
9698    public final int getMeasuredWidth() {
9699        return mMeasuredWidth & MEASURED_SIZE_MASK;
9700    }
9701
9702    /**
9703     * Return the full width measurement information for this view as computed
9704     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9705     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9706     * This should be used during measurement and layout calculations only. Use
9707     * {@link #getWidth()} to see how wide a view is after layout.
9708     *
9709     * @return The measured width of this view as a bit mask.
9710     */
9711    public final int getMeasuredWidthAndState() {
9712        return mMeasuredWidth;
9713    }
9714
9715    /**
9716     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9717     * raw width component (that is the result is masked by
9718     * {@link #MEASURED_SIZE_MASK}).
9719     *
9720     * @return The raw measured height of this view.
9721     */
9722    public final int getMeasuredHeight() {
9723        return mMeasuredHeight & MEASURED_SIZE_MASK;
9724    }
9725
9726    /**
9727     * Return the full height measurement information for this view as computed
9728     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9729     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9730     * This should be used during measurement and layout calculations only. Use
9731     * {@link #getHeight()} to see how wide a view is after layout.
9732     *
9733     * @return The measured width of this view as a bit mask.
9734     */
9735    public final int getMeasuredHeightAndState() {
9736        return mMeasuredHeight;
9737    }
9738
9739    /**
9740     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9741     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9742     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9743     * and the height component is at the shifted bits
9744     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9745     */
9746    public final int getMeasuredState() {
9747        return (mMeasuredWidth&MEASURED_STATE_MASK)
9748                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9749                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9750    }
9751
9752    /**
9753     * The transform matrix of this view, which is calculated based on the current
9754     * rotation, scale, and pivot properties.
9755     *
9756     * @see #getRotation()
9757     * @see #getScaleX()
9758     * @see #getScaleY()
9759     * @see #getPivotX()
9760     * @see #getPivotY()
9761     * @return The current transform matrix for the view
9762     */
9763    public Matrix getMatrix() {
9764        ensureTransformationInfo();
9765        final Matrix matrix = mTransformationInfo.mMatrix;
9766        mRenderNode.getMatrix(matrix);
9767        return matrix;
9768    }
9769
9770    /**
9771     * Returns true if the transform matrix is the identity matrix.
9772     * Recomputes the matrix if necessary.
9773     *
9774     * @return True if the transform matrix is the identity matrix, false otherwise.
9775     */
9776    final boolean hasIdentityMatrix() {
9777        return mRenderNode.hasIdentityMatrix();
9778    }
9779
9780    void ensureTransformationInfo() {
9781        if (mTransformationInfo == null) {
9782            mTransformationInfo = new TransformationInfo();
9783        }
9784    }
9785
9786   /**
9787     * Utility method to retrieve the inverse of the current mMatrix property.
9788     * We cache the matrix to avoid recalculating it when transform properties
9789     * have not changed.
9790     *
9791     * @return The inverse of the current matrix of this view.
9792     * @hide
9793     */
9794    public final Matrix getInverseMatrix() {
9795        ensureTransformationInfo();
9796        if (mTransformationInfo.mInverseMatrix == null) {
9797            mTransformationInfo.mInverseMatrix = new Matrix();
9798        }
9799        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9800        mRenderNode.getInverseMatrix(matrix);
9801        return matrix;
9802    }
9803
9804    /**
9805     * Gets the distance along the Z axis from the camera to this view.
9806     *
9807     * @see #setCameraDistance(float)
9808     *
9809     * @return The distance along the Z axis.
9810     */
9811    public float getCameraDistance() {
9812        final float dpi = mResources.getDisplayMetrics().densityDpi;
9813        return -(mRenderNode.getCameraDistance() * dpi);
9814    }
9815
9816    /**
9817     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9818     * views are drawn) from the camera to this view. The camera's distance
9819     * affects 3D transformations, for instance rotations around the X and Y
9820     * axis. If the rotationX or rotationY properties are changed and this view is
9821     * large (more than half the size of the screen), it is recommended to always
9822     * use a camera distance that's greater than the height (X axis rotation) or
9823     * the width (Y axis rotation) of this view.</p>
9824     *
9825     * <p>The distance of the camera from the view plane can have an affect on the
9826     * perspective distortion of the view when it is rotated around the x or y axis.
9827     * For example, a large distance will result in a large viewing angle, and there
9828     * will not be much perspective distortion of the view as it rotates. A short
9829     * distance may cause much more perspective distortion upon rotation, and can
9830     * also result in some drawing artifacts if the rotated view ends up partially
9831     * behind the camera (which is why the recommendation is to use a distance at
9832     * least as far as the size of the view, if the view is to be rotated.)</p>
9833     *
9834     * <p>The distance is expressed in "depth pixels." The default distance depends
9835     * on the screen density. For instance, on a medium density display, the
9836     * default distance is 1280. On a high density display, the default distance
9837     * is 1920.</p>
9838     *
9839     * <p>If you want to specify a distance that leads to visually consistent
9840     * results across various densities, use the following formula:</p>
9841     * <pre>
9842     * float scale = context.getResources().getDisplayMetrics().density;
9843     * view.setCameraDistance(distance * scale);
9844     * </pre>
9845     *
9846     * <p>The density scale factor of a high density display is 1.5,
9847     * and 1920 = 1280 * 1.5.</p>
9848     *
9849     * @param distance The distance in "depth pixels", if negative the opposite
9850     *        value is used
9851     *
9852     * @see #setRotationX(float)
9853     * @see #setRotationY(float)
9854     */
9855    public void setCameraDistance(float distance) {
9856        final float dpi = mResources.getDisplayMetrics().densityDpi;
9857
9858        invalidateViewProperty(true, false);
9859        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9860        invalidateViewProperty(false, false);
9861
9862        invalidateParentIfNeededAndWasQuickRejected();
9863    }
9864
9865    /**
9866     * The degrees that the view is rotated around the pivot point.
9867     *
9868     * @see #setRotation(float)
9869     * @see #getPivotX()
9870     * @see #getPivotY()
9871     *
9872     * @return The degrees of rotation.
9873     */
9874    @ViewDebug.ExportedProperty(category = "drawing")
9875    public float getRotation() {
9876        return mRenderNode.getRotation();
9877    }
9878
9879    /**
9880     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9881     * result in clockwise rotation.
9882     *
9883     * @param rotation The degrees of rotation.
9884     *
9885     * @see #getRotation()
9886     * @see #getPivotX()
9887     * @see #getPivotY()
9888     * @see #setRotationX(float)
9889     * @see #setRotationY(float)
9890     *
9891     * @attr ref android.R.styleable#View_rotation
9892     */
9893    public void setRotation(float rotation) {
9894        if (rotation != getRotation()) {
9895            // Double-invalidation is necessary to capture view's old and new areas
9896            invalidateViewProperty(true, false);
9897            mRenderNode.setRotation(rotation);
9898            invalidateViewProperty(false, true);
9899
9900            invalidateParentIfNeededAndWasQuickRejected();
9901            notifySubtreeAccessibilityStateChangedIfNeeded();
9902        }
9903    }
9904
9905    /**
9906     * The degrees that the view is rotated around the vertical axis through the pivot point.
9907     *
9908     * @see #getPivotX()
9909     * @see #getPivotY()
9910     * @see #setRotationY(float)
9911     *
9912     * @return The degrees of Y rotation.
9913     */
9914    @ViewDebug.ExportedProperty(category = "drawing")
9915    public float getRotationY() {
9916        return mRenderNode.getRotationY();
9917    }
9918
9919    /**
9920     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9921     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9922     * down the y axis.
9923     *
9924     * When rotating large views, it is recommended to adjust the camera distance
9925     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9926     *
9927     * @param rotationY The degrees of Y rotation.
9928     *
9929     * @see #getRotationY()
9930     * @see #getPivotX()
9931     * @see #getPivotY()
9932     * @see #setRotation(float)
9933     * @see #setRotationX(float)
9934     * @see #setCameraDistance(float)
9935     *
9936     * @attr ref android.R.styleable#View_rotationY
9937     */
9938    public void setRotationY(float rotationY) {
9939        if (rotationY != getRotationY()) {
9940            invalidateViewProperty(true, false);
9941            mRenderNode.setRotationY(rotationY);
9942            invalidateViewProperty(false, true);
9943
9944            invalidateParentIfNeededAndWasQuickRejected();
9945            notifySubtreeAccessibilityStateChangedIfNeeded();
9946        }
9947    }
9948
9949    /**
9950     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9951     *
9952     * @see #getPivotX()
9953     * @see #getPivotY()
9954     * @see #setRotationX(float)
9955     *
9956     * @return The degrees of X rotation.
9957     */
9958    @ViewDebug.ExportedProperty(category = "drawing")
9959    public float getRotationX() {
9960        return mRenderNode.getRotationX();
9961    }
9962
9963    /**
9964     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9965     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9966     * x axis.
9967     *
9968     * When rotating large views, it is recommended to adjust the camera distance
9969     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9970     *
9971     * @param rotationX The degrees of X rotation.
9972     *
9973     * @see #getRotationX()
9974     * @see #getPivotX()
9975     * @see #getPivotY()
9976     * @see #setRotation(float)
9977     * @see #setRotationY(float)
9978     * @see #setCameraDistance(float)
9979     *
9980     * @attr ref android.R.styleable#View_rotationX
9981     */
9982    public void setRotationX(float rotationX) {
9983        if (rotationX != getRotationX()) {
9984            invalidateViewProperty(true, false);
9985            mRenderNode.setRotationX(rotationX);
9986            invalidateViewProperty(false, true);
9987
9988            invalidateParentIfNeededAndWasQuickRejected();
9989            notifySubtreeAccessibilityStateChangedIfNeeded();
9990        }
9991    }
9992
9993    /**
9994     * The amount that the view is scaled in x around the pivot point, as a proportion of
9995     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9996     *
9997     * <p>By default, this is 1.0f.
9998     *
9999     * @see #getPivotX()
10000     * @see #getPivotY()
10001     * @return The scaling factor.
10002     */
10003    @ViewDebug.ExportedProperty(category = "drawing")
10004    public float getScaleX() {
10005        return mRenderNode.getScaleX();
10006    }
10007
10008    /**
10009     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10010     * the view's unscaled width. A value of 1 means that no scaling is applied.
10011     *
10012     * @param scaleX The scaling factor.
10013     * @see #getPivotX()
10014     * @see #getPivotY()
10015     *
10016     * @attr ref android.R.styleable#View_scaleX
10017     */
10018    public void setScaleX(float scaleX) {
10019        if (scaleX != getScaleX()) {
10020            invalidateViewProperty(true, false);
10021            mRenderNode.setScaleX(scaleX);
10022            invalidateViewProperty(false, true);
10023
10024            invalidateParentIfNeededAndWasQuickRejected();
10025            notifySubtreeAccessibilityStateChangedIfNeeded();
10026        }
10027    }
10028
10029    /**
10030     * The amount that the view is scaled in y around the pivot point, as a proportion of
10031     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10032     *
10033     * <p>By default, this is 1.0f.
10034     *
10035     * @see #getPivotX()
10036     * @see #getPivotY()
10037     * @return The scaling factor.
10038     */
10039    @ViewDebug.ExportedProperty(category = "drawing")
10040    public float getScaleY() {
10041        return mRenderNode.getScaleY();
10042    }
10043
10044    /**
10045     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10046     * the view's unscaled width. A value of 1 means that no scaling is applied.
10047     *
10048     * @param scaleY The scaling factor.
10049     * @see #getPivotX()
10050     * @see #getPivotY()
10051     *
10052     * @attr ref android.R.styleable#View_scaleY
10053     */
10054    public void setScaleY(float scaleY) {
10055        if (scaleY != getScaleY()) {
10056            invalidateViewProperty(true, false);
10057            mRenderNode.setScaleY(scaleY);
10058            invalidateViewProperty(false, true);
10059
10060            invalidateParentIfNeededAndWasQuickRejected();
10061            notifySubtreeAccessibilityStateChangedIfNeeded();
10062        }
10063    }
10064
10065    /**
10066     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10067     * and {@link #setScaleX(float) scaled}.
10068     *
10069     * @see #getRotation()
10070     * @see #getScaleX()
10071     * @see #getScaleY()
10072     * @see #getPivotY()
10073     * @return The x location of the pivot point.
10074     *
10075     * @attr ref android.R.styleable#View_transformPivotX
10076     */
10077    @ViewDebug.ExportedProperty(category = "drawing")
10078    public float getPivotX() {
10079        return mRenderNode.getPivotX();
10080    }
10081
10082    /**
10083     * Sets the x location of the point around which the view is
10084     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10085     * By default, the pivot point is centered on the object.
10086     * Setting this property disables this behavior and causes the view to use only the
10087     * explicitly set pivotX and pivotY values.
10088     *
10089     * @param pivotX The x location of the pivot point.
10090     * @see #getRotation()
10091     * @see #getScaleX()
10092     * @see #getScaleY()
10093     * @see #getPivotY()
10094     *
10095     * @attr ref android.R.styleable#View_transformPivotX
10096     */
10097    public void setPivotX(float pivotX) {
10098        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10099            invalidateViewProperty(true, false);
10100            mRenderNode.setPivotX(pivotX);
10101            invalidateViewProperty(false, true);
10102
10103            invalidateParentIfNeededAndWasQuickRejected();
10104        }
10105    }
10106
10107    /**
10108     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10109     * and {@link #setScaleY(float) scaled}.
10110     *
10111     * @see #getRotation()
10112     * @see #getScaleX()
10113     * @see #getScaleY()
10114     * @see #getPivotY()
10115     * @return The y location of the pivot point.
10116     *
10117     * @attr ref android.R.styleable#View_transformPivotY
10118     */
10119    @ViewDebug.ExportedProperty(category = "drawing")
10120    public float getPivotY() {
10121        return mRenderNode.getPivotY();
10122    }
10123
10124    /**
10125     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10126     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10127     * Setting this property disables this behavior and causes the view to use only the
10128     * explicitly set pivotX and pivotY values.
10129     *
10130     * @param pivotY The y location of the pivot point.
10131     * @see #getRotation()
10132     * @see #getScaleX()
10133     * @see #getScaleY()
10134     * @see #getPivotY()
10135     *
10136     * @attr ref android.R.styleable#View_transformPivotY
10137     */
10138    public void setPivotY(float pivotY) {
10139        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10140            invalidateViewProperty(true, false);
10141            mRenderNode.setPivotY(pivotY);
10142            invalidateViewProperty(false, true);
10143
10144            invalidateParentIfNeededAndWasQuickRejected();
10145        }
10146    }
10147
10148    /**
10149     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10150     * completely transparent and 1 means the view is completely opaque.
10151     *
10152     * <p>By default this is 1.0f.
10153     * @return The opacity of the view.
10154     */
10155    @ViewDebug.ExportedProperty(category = "drawing")
10156    public float getAlpha() {
10157        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10158    }
10159
10160    /**
10161     * Returns whether this View has content which overlaps.
10162     *
10163     * <p>This function, intended to be overridden by specific View types, is an optimization when
10164     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10165     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10166     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10167     * directly. An example of overlapping rendering is a TextView with a background image, such as
10168     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10169     * ImageView with only the foreground image. The default implementation returns true; subclasses
10170     * should override if they have cases which can be optimized.</p>
10171     *
10172     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10173     * necessitates that a View return true if it uses the methods internally without passing the
10174     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10175     *
10176     * @return true if the content in this view might overlap, false otherwise.
10177     */
10178    public boolean hasOverlappingRendering() {
10179        return true;
10180    }
10181
10182    /**
10183     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10184     * completely transparent and 1 means the view is completely opaque.</p>
10185     *
10186     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10187     * performance implications, especially for large views. It is best to use the alpha property
10188     * sparingly and transiently, as in the case of fading animations.</p>
10189     *
10190     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10191     * strongly recommended for performance reasons to either override
10192     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10193     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10194     *
10195     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10196     * responsible for applying the opacity itself.</p>
10197     *
10198     * <p>Note that if the view is backed by a
10199     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10200     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10201     * 1.0 will supercede the alpha of the layer paint.</p>
10202     *
10203     * @param alpha The opacity of the view.
10204     *
10205     * @see #hasOverlappingRendering()
10206     * @see #setLayerType(int, android.graphics.Paint)
10207     *
10208     * @attr ref android.R.styleable#View_alpha
10209     */
10210    public void setAlpha(float alpha) {
10211        ensureTransformationInfo();
10212        if (mTransformationInfo.mAlpha != alpha) {
10213            mTransformationInfo.mAlpha = alpha;
10214            if (onSetAlpha((int) (alpha * 255))) {
10215                mPrivateFlags |= PFLAG_ALPHA_SET;
10216                // subclass is handling alpha - don't optimize rendering cache invalidation
10217                invalidateParentCaches();
10218                invalidate(true);
10219            } else {
10220                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10221                invalidateViewProperty(true, false);
10222                mRenderNode.setAlpha(getFinalAlpha());
10223                notifyViewAccessibilityStateChangedIfNeeded(
10224                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10225            }
10226        }
10227    }
10228
10229    /**
10230     * Faster version of setAlpha() which performs the same steps except there are
10231     * no calls to invalidate(). The caller of this function should perform proper invalidation
10232     * on the parent and this object. The return value indicates whether the subclass handles
10233     * alpha (the return value for onSetAlpha()).
10234     *
10235     * @param alpha The new value for the alpha property
10236     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10237     *         the new value for the alpha property is different from the old value
10238     */
10239    boolean setAlphaNoInvalidation(float alpha) {
10240        ensureTransformationInfo();
10241        if (mTransformationInfo.mAlpha != alpha) {
10242            mTransformationInfo.mAlpha = alpha;
10243            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10244            if (subclassHandlesAlpha) {
10245                mPrivateFlags |= PFLAG_ALPHA_SET;
10246                return true;
10247            } else {
10248                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10249                mRenderNode.setAlpha(getFinalAlpha());
10250            }
10251        }
10252        return false;
10253    }
10254
10255    /**
10256     * This property is hidden and intended only for use by the Fade transition, which
10257     * animates it to produce a visual translucency that does not side-effect (or get
10258     * affected by) the real alpha property. This value is composited with the other
10259     * alpha value (and the AlphaAnimation value, when that is present) to produce
10260     * a final visual translucency result, which is what is passed into the DisplayList.
10261     *
10262     * @hide
10263     */
10264    public void setTransitionAlpha(float alpha) {
10265        ensureTransformationInfo();
10266        if (mTransformationInfo.mTransitionAlpha != alpha) {
10267            mTransformationInfo.mTransitionAlpha = alpha;
10268            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10269            invalidateViewProperty(true, false);
10270            mRenderNode.setAlpha(getFinalAlpha());
10271        }
10272    }
10273
10274    /**
10275     * Calculates the visual alpha of this view, which is a combination of the actual
10276     * alpha value and the transitionAlpha value (if set).
10277     */
10278    private float getFinalAlpha() {
10279        if (mTransformationInfo != null) {
10280            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10281        }
10282        return 1;
10283    }
10284
10285    /**
10286     * This property is hidden and intended only for use by the Fade transition, which
10287     * animates it to produce a visual translucency that does not side-effect (or get
10288     * affected by) the real alpha property. This value is composited with the other
10289     * alpha value (and the AlphaAnimation value, when that is present) to produce
10290     * a final visual translucency result, which is what is passed into the DisplayList.
10291     *
10292     * @hide
10293     */
10294    @ViewDebug.ExportedProperty(category = "drawing")
10295    public float getTransitionAlpha() {
10296        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10297    }
10298
10299    /**
10300     * Top position of this view relative to its parent.
10301     *
10302     * @return The top of this view, in pixels.
10303     */
10304    @ViewDebug.CapturedViewProperty
10305    public final int getTop() {
10306        return mTop;
10307    }
10308
10309    /**
10310     * Sets the top position of this view relative to its parent. This method is meant to be called
10311     * by the layout system and should not generally be called otherwise, because the property
10312     * may be changed at any time by the layout.
10313     *
10314     * @param top The top of this view, in pixels.
10315     */
10316    public final void setTop(int top) {
10317        if (top != mTop) {
10318            final boolean matrixIsIdentity = hasIdentityMatrix();
10319            if (matrixIsIdentity) {
10320                if (mAttachInfo != null) {
10321                    int minTop;
10322                    int yLoc;
10323                    if (top < mTop) {
10324                        minTop = top;
10325                        yLoc = top - mTop;
10326                    } else {
10327                        minTop = mTop;
10328                        yLoc = 0;
10329                    }
10330                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10331                }
10332            } else {
10333                // Double-invalidation is necessary to capture view's old and new areas
10334                invalidate(true);
10335            }
10336
10337            int width = mRight - mLeft;
10338            int oldHeight = mBottom - mTop;
10339
10340            mTop = top;
10341            mRenderNode.setTop(mTop);
10342
10343            sizeChange(width, mBottom - mTop, width, oldHeight);
10344
10345            if (!matrixIsIdentity) {
10346                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10347                invalidate(true);
10348            }
10349            mBackgroundSizeChanged = true;
10350            invalidateParentIfNeeded();
10351            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10352                // View was rejected last time it was drawn by its parent; this may have changed
10353                invalidateParentIfNeeded();
10354            }
10355        }
10356    }
10357
10358    /**
10359     * Bottom position of this view relative to its parent.
10360     *
10361     * @return The bottom of this view, in pixels.
10362     */
10363    @ViewDebug.CapturedViewProperty
10364    public final int getBottom() {
10365        return mBottom;
10366    }
10367
10368    /**
10369     * True if this view has changed since the last time being drawn.
10370     *
10371     * @return The dirty state of this view.
10372     */
10373    public boolean isDirty() {
10374        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10375    }
10376
10377    /**
10378     * Sets the bottom position of this view relative to its parent. This method is meant to be
10379     * called by the layout system and should not generally be called otherwise, because the
10380     * property may be changed at any time by the layout.
10381     *
10382     * @param bottom The bottom of this view, in pixels.
10383     */
10384    public final void setBottom(int bottom) {
10385        if (bottom != mBottom) {
10386            final boolean matrixIsIdentity = hasIdentityMatrix();
10387            if (matrixIsIdentity) {
10388                if (mAttachInfo != null) {
10389                    int maxBottom;
10390                    if (bottom < mBottom) {
10391                        maxBottom = mBottom;
10392                    } else {
10393                        maxBottom = bottom;
10394                    }
10395                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10396                }
10397            } else {
10398                // Double-invalidation is necessary to capture view's old and new areas
10399                invalidate(true);
10400            }
10401
10402            int width = mRight - mLeft;
10403            int oldHeight = mBottom - mTop;
10404
10405            mBottom = bottom;
10406            mRenderNode.setBottom(mBottom);
10407
10408            sizeChange(width, mBottom - mTop, width, oldHeight);
10409
10410            if (!matrixIsIdentity) {
10411                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10412                invalidate(true);
10413            }
10414            mBackgroundSizeChanged = true;
10415            invalidateParentIfNeeded();
10416            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10417                // View was rejected last time it was drawn by its parent; this may have changed
10418                invalidateParentIfNeeded();
10419            }
10420        }
10421    }
10422
10423    /**
10424     * Left position of this view relative to its parent.
10425     *
10426     * @return The left edge of this view, in pixels.
10427     */
10428    @ViewDebug.CapturedViewProperty
10429    public final int getLeft() {
10430        return mLeft;
10431    }
10432
10433    /**
10434     * Sets the left position of this view relative to its parent. This method is meant to be called
10435     * by the layout system and should not generally be called otherwise, because the property
10436     * may be changed at any time by the layout.
10437     *
10438     * @param left The left of this view, in pixels.
10439     */
10440    public final void setLeft(int left) {
10441        if (left != mLeft) {
10442            final boolean matrixIsIdentity = hasIdentityMatrix();
10443            if (matrixIsIdentity) {
10444                if (mAttachInfo != null) {
10445                    int minLeft;
10446                    int xLoc;
10447                    if (left < mLeft) {
10448                        minLeft = left;
10449                        xLoc = left - mLeft;
10450                    } else {
10451                        minLeft = mLeft;
10452                        xLoc = 0;
10453                    }
10454                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10455                }
10456            } else {
10457                // Double-invalidation is necessary to capture view's old and new areas
10458                invalidate(true);
10459            }
10460
10461            int oldWidth = mRight - mLeft;
10462            int height = mBottom - mTop;
10463
10464            mLeft = left;
10465            mRenderNode.setLeft(left);
10466
10467            sizeChange(mRight - mLeft, height, oldWidth, height);
10468
10469            if (!matrixIsIdentity) {
10470                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10471                invalidate(true);
10472            }
10473            mBackgroundSizeChanged = true;
10474            invalidateParentIfNeeded();
10475            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10476                // View was rejected last time it was drawn by its parent; this may have changed
10477                invalidateParentIfNeeded();
10478            }
10479        }
10480    }
10481
10482    /**
10483     * Right position of this view relative to its parent.
10484     *
10485     * @return The right edge of this view, in pixels.
10486     */
10487    @ViewDebug.CapturedViewProperty
10488    public final int getRight() {
10489        return mRight;
10490    }
10491
10492    /**
10493     * Sets the right position of this view relative to its parent. This method is meant to be called
10494     * by the layout system and should not generally be called otherwise, because the property
10495     * may be changed at any time by the layout.
10496     *
10497     * @param right The right of this view, in pixels.
10498     */
10499    public final void setRight(int right) {
10500        if (right != mRight) {
10501            final boolean matrixIsIdentity = hasIdentityMatrix();
10502            if (matrixIsIdentity) {
10503                if (mAttachInfo != null) {
10504                    int maxRight;
10505                    if (right < mRight) {
10506                        maxRight = mRight;
10507                    } else {
10508                        maxRight = right;
10509                    }
10510                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10511                }
10512            } else {
10513                // Double-invalidation is necessary to capture view's old and new areas
10514                invalidate(true);
10515            }
10516
10517            int oldWidth = mRight - mLeft;
10518            int height = mBottom - mTop;
10519
10520            mRight = right;
10521            mRenderNode.setRight(mRight);
10522
10523            sizeChange(mRight - mLeft, height, oldWidth, height);
10524
10525            if (!matrixIsIdentity) {
10526                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10527                invalidate(true);
10528            }
10529            mBackgroundSizeChanged = true;
10530            invalidateParentIfNeeded();
10531            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10532                // View was rejected last time it was drawn by its parent; this may have changed
10533                invalidateParentIfNeeded();
10534            }
10535        }
10536    }
10537
10538    /**
10539     * The visual x position of this view, in pixels. This is equivalent to the
10540     * {@link #setTranslationX(float) translationX} property plus the current
10541     * {@link #getLeft() left} property.
10542     *
10543     * @return The visual x position of this view, in pixels.
10544     */
10545    @ViewDebug.ExportedProperty(category = "drawing")
10546    public float getX() {
10547        return mLeft + getTranslationX();
10548    }
10549
10550    /**
10551     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10552     * {@link #setTranslationX(float) translationX} property to be the difference between
10553     * the x value passed in and the current {@link #getLeft() left} property.
10554     *
10555     * @param x The visual x position of this view, in pixels.
10556     */
10557    public void setX(float x) {
10558        setTranslationX(x - mLeft);
10559    }
10560
10561    /**
10562     * The visual y position of this view, in pixels. This is equivalent to the
10563     * {@link #setTranslationY(float) translationY} property plus the current
10564     * {@link #getTop() top} property.
10565     *
10566     * @return The visual y position of this view, in pixels.
10567     */
10568    @ViewDebug.ExportedProperty(category = "drawing")
10569    public float getY() {
10570        return mTop + getTranslationY();
10571    }
10572
10573    /**
10574     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10575     * {@link #setTranslationY(float) translationY} property to be the difference between
10576     * the y value passed in and the current {@link #getTop() top} property.
10577     *
10578     * @param y The visual y position of this view, in pixels.
10579     */
10580    public void setY(float y) {
10581        setTranslationY(y - mTop);
10582    }
10583
10584    /**
10585     * The visual z position of this view, in pixels. This is equivalent to the
10586     * {@link #setTranslationZ(float) translationZ} property plus the current
10587     * {@link #getElevation() elevation} property.
10588     *
10589     * @return The visual z position of this view, in pixels.
10590     */
10591    @ViewDebug.ExportedProperty(category = "drawing")
10592    public float getZ() {
10593        return getElevation() + getTranslationZ();
10594    }
10595
10596    /**
10597     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10598     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10599     * the x value passed in and the current {@link #getElevation() elevation} property.
10600     *
10601     * @param z The visual z position of this view, in pixels.
10602     */
10603    public void setZ(float z) {
10604        setTranslationZ(z - getElevation());
10605    }
10606
10607    /**
10608     * The base elevation of this view relative to its parent, in pixels.
10609     *
10610     * @return The base depth position of the view, in pixels.
10611     */
10612    @ViewDebug.ExportedProperty(category = "drawing")
10613    public float getElevation() {
10614        return mRenderNode.getElevation();
10615    }
10616
10617    /**
10618     * Sets the base elevation of this view, in pixels.
10619     *
10620     * @attr ref android.R.styleable#View_elevation
10621     */
10622    public void setElevation(float elevation) {
10623        if (elevation != getElevation()) {
10624            invalidateViewProperty(true, false);
10625            mRenderNode.setElevation(elevation);
10626            invalidateViewProperty(false, true);
10627
10628            invalidateParentIfNeededAndWasQuickRejected();
10629        }
10630    }
10631
10632    /**
10633     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10634     * This position is post-layout, in addition to wherever the object's
10635     * layout placed it.
10636     *
10637     * @return The horizontal position of this view relative to its left position, in pixels.
10638     */
10639    @ViewDebug.ExportedProperty(category = "drawing")
10640    public float getTranslationX() {
10641        return mRenderNode.getTranslationX();
10642    }
10643
10644    /**
10645     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10646     * This effectively positions the object post-layout, in addition to wherever the object's
10647     * layout placed it.
10648     *
10649     * @param translationX The horizontal position of this view relative to its left position,
10650     * in pixels.
10651     *
10652     * @attr ref android.R.styleable#View_translationX
10653     */
10654    public void setTranslationX(float translationX) {
10655        if (translationX != getTranslationX()) {
10656            invalidateViewProperty(true, false);
10657            mRenderNode.setTranslationX(translationX);
10658            invalidateViewProperty(false, true);
10659
10660            invalidateParentIfNeededAndWasQuickRejected();
10661            notifySubtreeAccessibilityStateChangedIfNeeded();
10662        }
10663    }
10664
10665    /**
10666     * The vertical location of this view relative to its {@link #getTop() top} position.
10667     * This position is post-layout, in addition to wherever the object's
10668     * layout placed it.
10669     *
10670     * @return The vertical position of this view relative to its top position,
10671     * in pixels.
10672     */
10673    @ViewDebug.ExportedProperty(category = "drawing")
10674    public float getTranslationY() {
10675        return mRenderNode.getTranslationY();
10676    }
10677
10678    /**
10679     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10680     * This effectively positions the object post-layout, in addition to wherever the object's
10681     * layout placed it.
10682     *
10683     * @param translationY The vertical position of this view relative to its top position,
10684     * in pixels.
10685     *
10686     * @attr ref android.R.styleable#View_translationY
10687     */
10688    public void setTranslationY(float translationY) {
10689        if (translationY != getTranslationY()) {
10690            invalidateViewProperty(true, false);
10691            mRenderNode.setTranslationY(translationY);
10692            invalidateViewProperty(false, true);
10693
10694            invalidateParentIfNeededAndWasQuickRejected();
10695        }
10696    }
10697
10698    /**
10699     * The depth location of this view relative to its {@link #getElevation() elevation}.
10700     *
10701     * @return The depth of this view relative to its elevation.
10702     */
10703    @ViewDebug.ExportedProperty(category = "drawing")
10704    public float getTranslationZ() {
10705        return mRenderNode.getTranslationZ();
10706    }
10707
10708    /**
10709     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10710     *
10711     * @attr ref android.R.styleable#View_translationZ
10712     */
10713    public void setTranslationZ(float translationZ) {
10714        if (translationZ != getTranslationZ()) {
10715            invalidateViewProperty(true, false);
10716            mRenderNode.setTranslationZ(translationZ);
10717            invalidateViewProperty(false, true);
10718
10719            invalidateParentIfNeededAndWasQuickRejected();
10720        }
10721    }
10722
10723    /**
10724     * Returns the current StateListAnimator if exists.
10725     *
10726     * @return StateListAnimator or null if it does not exists
10727     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10728     */
10729    public StateListAnimator getStateListAnimator() {
10730        return mStateListAnimator;
10731    }
10732
10733    /**
10734     * Attaches the provided StateListAnimator to this View.
10735     * <p>
10736     * Any previously attached StateListAnimator will be detached.
10737     *
10738     * @param stateListAnimator The StateListAnimator to update the view
10739     * @see {@link android.animation.StateListAnimator}
10740     */
10741    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10742        if (mStateListAnimator == stateListAnimator) {
10743            return;
10744        }
10745        if (mStateListAnimator != null) {
10746            mStateListAnimator.setTarget(null);
10747        }
10748        mStateListAnimator = stateListAnimator;
10749        if (stateListAnimator != null) {
10750            stateListAnimator.setTarget(this);
10751            if (isAttachedToWindow()) {
10752                stateListAnimator.setState(getDrawableState());
10753            }
10754        }
10755    }
10756
10757    /**
10758     * Deprecated, pending removal
10759     *
10760     * @hide
10761     */
10762    @Deprecated
10763    public void setOutline(@Nullable Outline outline) {}
10764
10765    /**
10766     * Returns whether the Outline should be used to clip the contents of the View.
10767     * <p>
10768     * Note that this flag will only be respected if the View's Outline returns true from
10769     * {@link Outline#canClip()}.
10770     *
10771     * @see #setOutlineProvider(ViewOutlineProvider)
10772     * @see #setClipToOutline(boolean)
10773     */
10774    public final boolean getClipToOutline() {
10775        return mRenderNode.getClipToOutline();
10776    }
10777
10778    /**
10779     * Sets whether the View's Outline should be used to clip the contents of the View.
10780     * <p>
10781     * Note that this flag will only be respected if the View's Outline returns true from
10782     * {@link Outline#canClip()}.
10783     *
10784     * @see #setOutlineProvider(ViewOutlineProvider)
10785     * @see #getClipToOutline()
10786     */
10787    public void setClipToOutline(boolean clipToOutline) {
10788        damageInParent();
10789        if (getClipToOutline() != clipToOutline) {
10790            mRenderNode.setClipToOutline(clipToOutline);
10791        }
10792    }
10793
10794    /**
10795     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10796     * the shape of the shadow it casts, and enables outline clipping.
10797     * <p>
10798     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10799     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10800     * outline provider with this method allows this behavior to be overridden.
10801     * <p>
10802     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10803     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10804     * <p>
10805     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10806     *
10807     * @see #setClipToOutline(boolean)
10808     * @see #getClipToOutline()
10809     * @see #getOutlineProvider()
10810     */
10811    public void setOutlineProvider(ViewOutlineProvider provider) {
10812        mOutlineProvider = provider;
10813        invalidateOutline();
10814    }
10815
10816    /**
10817     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10818     * that defines the shape of the shadow it casts, and enables outline clipping.
10819     *
10820     * @see #setOutlineProvider(ViewOutlineProvider)
10821     */
10822    public ViewOutlineProvider getOutlineProvider() {
10823        return mOutlineProvider;
10824    }
10825
10826    /**
10827     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10828     *
10829     * @see #setOutlineProvider(ViewOutlineProvider)
10830     */
10831    public void invalidateOutline() {
10832        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10833        if (mAttachInfo == null) return;
10834
10835        if (mOutlineProvider == null) {
10836            // no provider, remove outline
10837            mRenderNode.setOutline(null);
10838        } else {
10839            final Outline outline = mAttachInfo.mTmpOutline;
10840            outline.setEmpty();
10841            outline.setAlpha(1.0f);
10842
10843            mOutlineProvider.getOutline(this, outline);
10844            mRenderNode.setOutline(outline);
10845        }
10846
10847        notifySubtreeAccessibilityStateChangedIfNeeded();
10848        invalidateViewProperty(false, false);
10849    }
10850
10851    /** @hide */
10852    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
10853        mRenderNode.setRevealClip(shouldClip, x, y, radius);
10854        invalidateViewProperty(false, false);
10855    }
10856
10857    /**
10858     * Hit rectangle in parent's coordinates
10859     *
10860     * @param outRect The hit rectangle of the view.
10861     */
10862    public void getHitRect(Rect outRect) {
10863        if (hasIdentityMatrix() || mAttachInfo == null) {
10864            outRect.set(mLeft, mTop, mRight, mBottom);
10865        } else {
10866            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10867            tmpRect.set(0, 0, getWidth(), getHeight());
10868            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10869            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10870                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10871        }
10872    }
10873
10874    /**
10875     * Determines whether the given point, in local coordinates is inside the view.
10876     */
10877    /*package*/ final boolean pointInView(float localX, float localY) {
10878        return localX >= 0 && localX < (mRight - mLeft)
10879                && localY >= 0 && localY < (mBottom - mTop);
10880    }
10881
10882    /**
10883     * Utility method to determine whether the given point, in local coordinates,
10884     * is inside the view, where the area of the view is expanded by the slop factor.
10885     * This method is called while processing touch-move events to determine if the event
10886     * is still within the view.
10887     *
10888     * @hide
10889     */
10890    public boolean pointInView(float localX, float localY, float slop) {
10891        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10892                localY < ((mBottom - mTop) + slop);
10893    }
10894
10895    /**
10896     * When a view has focus and the user navigates away from it, the next view is searched for
10897     * starting from the rectangle filled in by this method.
10898     *
10899     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10900     * of the view.  However, if your view maintains some idea of internal selection,
10901     * such as a cursor, or a selected row or column, you should override this method and
10902     * fill in a more specific rectangle.
10903     *
10904     * @param r The rectangle to fill in, in this view's coordinates.
10905     */
10906    public void getFocusedRect(Rect r) {
10907        getDrawingRect(r);
10908    }
10909
10910    /**
10911     * If some part of this view is not clipped by any of its parents, then
10912     * return that area in r in global (root) coordinates. To convert r to local
10913     * coordinates (without taking possible View rotations into account), offset
10914     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10915     * If the view is completely clipped or translated out, return false.
10916     *
10917     * @param r If true is returned, r holds the global coordinates of the
10918     *        visible portion of this view.
10919     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10920     *        between this view and its root. globalOffet may be null.
10921     * @return true if r is non-empty (i.e. part of the view is visible at the
10922     *         root level.
10923     */
10924    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10925        int width = mRight - mLeft;
10926        int height = mBottom - mTop;
10927        if (width > 0 && height > 0) {
10928            r.set(0, 0, width, height);
10929            if (globalOffset != null) {
10930                globalOffset.set(-mScrollX, -mScrollY);
10931            }
10932            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10933        }
10934        return false;
10935    }
10936
10937    public final boolean getGlobalVisibleRect(Rect r) {
10938        return getGlobalVisibleRect(r, null);
10939    }
10940
10941    public final boolean getLocalVisibleRect(Rect r) {
10942        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10943        if (getGlobalVisibleRect(r, offset)) {
10944            r.offset(-offset.x, -offset.y); // make r local
10945            return true;
10946        }
10947        return false;
10948    }
10949
10950    /**
10951     * Offset this view's vertical location by the specified number of pixels.
10952     *
10953     * @param offset the number of pixels to offset the view by
10954     */
10955    public void offsetTopAndBottom(int offset) {
10956        if (offset != 0) {
10957            final boolean matrixIsIdentity = hasIdentityMatrix();
10958            if (matrixIsIdentity) {
10959                if (isHardwareAccelerated()) {
10960                    invalidateViewProperty(false, false);
10961                } else {
10962                    final ViewParent p = mParent;
10963                    if (p != null && mAttachInfo != null) {
10964                        final Rect r = mAttachInfo.mTmpInvalRect;
10965                        int minTop;
10966                        int maxBottom;
10967                        int yLoc;
10968                        if (offset < 0) {
10969                            minTop = mTop + offset;
10970                            maxBottom = mBottom;
10971                            yLoc = offset;
10972                        } else {
10973                            minTop = mTop;
10974                            maxBottom = mBottom + offset;
10975                            yLoc = 0;
10976                        }
10977                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10978                        p.invalidateChild(this, r);
10979                    }
10980                }
10981            } else {
10982                invalidateViewProperty(false, false);
10983            }
10984
10985            mTop += offset;
10986            mBottom += offset;
10987            mRenderNode.offsetTopAndBottom(offset);
10988            if (isHardwareAccelerated()) {
10989                invalidateViewProperty(false, false);
10990            } else {
10991                if (!matrixIsIdentity) {
10992                    invalidateViewProperty(false, true);
10993                }
10994                invalidateParentIfNeeded();
10995            }
10996            notifySubtreeAccessibilityStateChangedIfNeeded();
10997        }
10998    }
10999
11000    /**
11001     * Offset this view's horizontal location by the specified amount of pixels.
11002     *
11003     * @param offset the number of pixels to offset the view by
11004     */
11005    public void offsetLeftAndRight(int offset) {
11006        if (offset != 0) {
11007            final boolean matrixIsIdentity = hasIdentityMatrix();
11008            if (matrixIsIdentity) {
11009                if (isHardwareAccelerated()) {
11010                    invalidateViewProperty(false, false);
11011                } else {
11012                    final ViewParent p = mParent;
11013                    if (p != null && mAttachInfo != null) {
11014                        final Rect r = mAttachInfo.mTmpInvalRect;
11015                        int minLeft;
11016                        int maxRight;
11017                        if (offset < 0) {
11018                            minLeft = mLeft + offset;
11019                            maxRight = mRight;
11020                        } else {
11021                            minLeft = mLeft;
11022                            maxRight = mRight + offset;
11023                        }
11024                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11025                        p.invalidateChild(this, r);
11026                    }
11027                }
11028            } else {
11029                invalidateViewProperty(false, false);
11030            }
11031
11032            mLeft += offset;
11033            mRight += offset;
11034            mRenderNode.offsetLeftAndRight(offset);
11035            if (isHardwareAccelerated()) {
11036                invalidateViewProperty(false, false);
11037            } else {
11038                if (!matrixIsIdentity) {
11039                    invalidateViewProperty(false, true);
11040                }
11041                invalidateParentIfNeeded();
11042            }
11043            notifySubtreeAccessibilityStateChangedIfNeeded();
11044        }
11045    }
11046
11047    /**
11048     * Get the LayoutParams associated with this view. All views should have
11049     * layout parameters. These supply parameters to the <i>parent</i> of this
11050     * view specifying how it should be arranged. There are many subclasses of
11051     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11052     * of ViewGroup that are responsible for arranging their children.
11053     *
11054     * This method may return null if this View is not attached to a parent
11055     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11056     * was not invoked successfully. When a View is attached to a parent
11057     * ViewGroup, this method must not return null.
11058     *
11059     * @return The LayoutParams associated with this view, or null if no
11060     *         parameters have been set yet
11061     */
11062    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11063    public ViewGroup.LayoutParams getLayoutParams() {
11064        return mLayoutParams;
11065    }
11066
11067    /**
11068     * Set the layout parameters associated with this view. These supply
11069     * parameters to the <i>parent</i> of this view specifying how it should be
11070     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11071     * correspond to the different subclasses of ViewGroup that are responsible
11072     * for arranging their children.
11073     *
11074     * @param params The layout parameters for this view, cannot be null
11075     */
11076    public void setLayoutParams(ViewGroup.LayoutParams params) {
11077        if (params == null) {
11078            throw new NullPointerException("Layout parameters cannot be null");
11079        }
11080        mLayoutParams = params;
11081        resolveLayoutParams();
11082        if (mParent instanceof ViewGroup) {
11083            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11084        }
11085        requestLayout();
11086    }
11087
11088    /**
11089     * Resolve the layout parameters depending on the resolved layout direction
11090     *
11091     * @hide
11092     */
11093    public void resolveLayoutParams() {
11094        if (mLayoutParams != null) {
11095            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11096        }
11097    }
11098
11099    /**
11100     * Set the scrolled position of your view. This will cause a call to
11101     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11102     * invalidated.
11103     * @param x the x position to scroll to
11104     * @param y the y position to scroll to
11105     */
11106    public void scrollTo(int x, int y) {
11107        if (mScrollX != x || mScrollY != y) {
11108            int oldX = mScrollX;
11109            int oldY = mScrollY;
11110            mScrollX = x;
11111            mScrollY = y;
11112            invalidateParentCaches();
11113            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11114            if (!awakenScrollBars()) {
11115                postInvalidateOnAnimation();
11116            }
11117        }
11118    }
11119
11120    /**
11121     * Move the scrolled position of your view. This will cause a call to
11122     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11123     * invalidated.
11124     * @param x the amount of pixels to scroll by horizontally
11125     * @param y the amount of pixels to scroll by vertically
11126     */
11127    public void scrollBy(int x, int y) {
11128        scrollTo(mScrollX + x, mScrollY + y);
11129    }
11130
11131    /**
11132     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11133     * animation to fade the scrollbars out after a default delay. If a subclass
11134     * provides animated scrolling, the start delay should equal the duration
11135     * of the scrolling animation.</p>
11136     *
11137     * <p>The animation starts only if at least one of the scrollbars is
11138     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11139     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11140     * this method returns true, and false otherwise. If the animation is
11141     * started, this method calls {@link #invalidate()}; in that case the
11142     * caller should not call {@link #invalidate()}.</p>
11143     *
11144     * <p>This method should be invoked every time a subclass directly updates
11145     * the scroll parameters.</p>
11146     *
11147     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11148     * and {@link #scrollTo(int, int)}.</p>
11149     *
11150     * @return true if the animation is played, false otherwise
11151     *
11152     * @see #awakenScrollBars(int)
11153     * @see #scrollBy(int, int)
11154     * @see #scrollTo(int, int)
11155     * @see #isHorizontalScrollBarEnabled()
11156     * @see #isVerticalScrollBarEnabled()
11157     * @see #setHorizontalScrollBarEnabled(boolean)
11158     * @see #setVerticalScrollBarEnabled(boolean)
11159     */
11160    protected boolean awakenScrollBars() {
11161        return mScrollCache != null &&
11162                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11163    }
11164
11165    /**
11166     * Trigger the scrollbars to draw.
11167     * This method differs from awakenScrollBars() only in its default duration.
11168     * initialAwakenScrollBars() will show the scroll bars for longer than
11169     * usual to give the user more of a chance to notice them.
11170     *
11171     * @return true if the animation is played, false otherwise.
11172     */
11173    private boolean initialAwakenScrollBars() {
11174        return mScrollCache != null &&
11175                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11176    }
11177
11178    /**
11179     * <p>
11180     * Trigger the scrollbars to draw. When invoked this method starts an
11181     * animation to fade the scrollbars out after a fixed delay. If a subclass
11182     * provides animated scrolling, the start delay should equal the duration of
11183     * the scrolling animation.
11184     * </p>
11185     *
11186     * <p>
11187     * The animation starts only if at least one of the scrollbars is enabled,
11188     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11189     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11190     * this method returns true, and false otherwise. If the animation is
11191     * started, this method calls {@link #invalidate()}; in that case the caller
11192     * should not call {@link #invalidate()}.
11193     * </p>
11194     *
11195     * <p>
11196     * This method should be invoked everytime a subclass directly updates the
11197     * scroll parameters.
11198     * </p>
11199     *
11200     * @param startDelay the delay, in milliseconds, after which the animation
11201     *        should start; when the delay is 0, the animation starts
11202     *        immediately
11203     * @return true if the animation is played, false otherwise
11204     *
11205     * @see #scrollBy(int, int)
11206     * @see #scrollTo(int, int)
11207     * @see #isHorizontalScrollBarEnabled()
11208     * @see #isVerticalScrollBarEnabled()
11209     * @see #setHorizontalScrollBarEnabled(boolean)
11210     * @see #setVerticalScrollBarEnabled(boolean)
11211     */
11212    protected boolean awakenScrollBars(int startDelay) {
11213        return awakenScrollBars(startDelay, true);
11214    }
11215
11216    /**
11217     * <p>
11218     * Trigger the scrollbars to draw. When invoked this method starts an
11219     * animation to fade the scrollbars out after a fixed delay. If a subclass
11220     * provides animated scrolling, the start delay should equal the duration of
11221     * the scrolling animation.
11222     * </p>
11223     *
11224     * <p>
11225     * The animation starts only if at least one of the scrollbars is enabled,
11226     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11227     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11228     * this method returns true, and false otherwise. If the animation is
11229     * started, this method calls {@link #invalidate()} if the invalidate parameter
11230     * is set to true; in that case the caller
11231     * should not call {@link #invalidate()}.
11232     * </p>
11233     *
11234     * <p>
11235     * This method should be invoked everytime a subclass directly updates the
11236     * scroll parameters.
11237     * </p>
11238     *
11239     * @param startDelay the delay, in milliseconds, after which the animation
11240     *        should start; when the delay is 0, the animation starts
11241     *        immediately
11242     *
11243     * @param invalidate Wheter this method should call invalidate
11244     *
11245     * @return true if the animation is played, false otherwise
11246     *
11247     * @see #scrollBy(int, int)
11248     * @see #scrollTo(int, int)
11249     * @see #isHorizontalScrollBarEnabled()
11250     * @see #isVerticalScrollBarEnabled()
11251     * @see #setHorizontalScrollBarEnabled(boolean)
11252     * @see #setVerticalScrollBarEnabled(boolean)
11253     */
11254    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11255        final ScrollabilityCache scrollCache = mScrollCache;
11256
11257        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11258            return false;
11259        }
11260
11261        if (scrollCache.scrollBar == null) {
11262            scrollCache.scrollBar = new ScrollBarDrawable();
11263        }
11264
11265        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11266
11267            if (invalidate) {
11268                // Invalidate to show the scrollbars
11269                postInvalidateOnAnimation();
11270            }
11271
11272            if (scrollCache.state == ScrollabilityCache.OFF) {
11273                // FIXME: this is copied from WindowManagerService.
11274                // We should get this value from the system when it
11275                // is possible to do so.
11276                final int KEY_REPEAT_FIRST_DELAY = 750;
11277                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11278            }
11279
11280            // Tell mScrollCache when we should start fading. This may
11281            // extend the fade start time if one was already scheduled
11282            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11283            scrollCache.fadeStartTime = fadeStartTime;
11284            scrollCache.state = ScrollabilityCache.ON;
11285
11286            // Schedule our fader to run, unscheduling any old ones first
11287            if (mAttachInfo != null) {
11288                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11289                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11290            }
11291
11292            return true;
11293        }
11294
11295        return false;
11296    }
11297
11298    /**
11299     * Do not invalidate views which are not visible and which are not running an animation. They
11300     * will not get drawn and they should not set dirty flags as if they will be drawn
11301     */
11302    private boolean skipInvalidate() {
11303        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11304                (!(mParent instanceof ViewGroup) ||
11305                        !((ViewGroup) mParent).isViewTransitioning(this));
11306    }
11307
11308    /**
11309     * Mark the area defined by dirty as needing to be drawn. If the view is
11310     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11311     * point in the future.
11312     * <p>
11313     * This must be called from a UI thread. To call from a non-UI thread, call
11314     * {@link #postInvalidate()}.
11315     * <p>
11316     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11317     * {@code dirty}.
11318     *
11319     * @param dirty the rectangle representing the bounds of the dirty region
11320     */
11321    public void invalidate(Rect dirty) {
11322        final int scrollX = mScrollX;
11323        final int scrollY = mScrollY;
11324        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11325                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11326    }
11327
11328    /**
11329     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11330     * coordinates of the dirty rect are relative to the view. If the view is
11331     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11332     * point in the future.
11333     * <p>
11334     * This must be called from a UI thread. To call from a non-UI thread, call
11335     * {@link #postInvalidate()}.
11336     *
11337     * @param l the left position of the dirty region
11338     * @param t the top position of the dirty region
11339     * @param r the right position of the dirty region
11340     * @param b the bottom position of the dirty region
11341     */
11342    public void invalidate(int l, int t, int r, int b) {
11343        final int scrollX = mScrollX;
11344        final int scrollY = mScrollY;
11345        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11346    }
11347
11348    /**
11349     * Invalidate the whole view. If the view is visible,
11350     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11351     * the future.
11352     * <p>
11353     * This must be called from a UI thread. To call from a non-UI thread, call
11354     * {@link #postInvalidate()}.
11355     */
11356    public void invalidate() {
11357        invalidate(true);
11358    }
11359
11360    /**
11361     * This is where the invalidate() work actually happens. A full invalidate()
11362     * causes the drawing cache to be invalidated, but this function can be
11363     * called with invalidateCache set to false to skip that invalidation step
11364     * for cases that do not need it (for example, a component that remains at
11365     * the same dimensions with the same content).
11366     *
11367     * @param invalidateCache Whether the drawing cache for this view should be
11368     *            invalidated as well. This is usually true for a full
11369     *            invalidate, but may be set to false if the View's contents or
11370     *            dimensions have not changed.
11371     */
11372    void invalidate(boolean invalidateCache) {
11373        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11374    }
11375
11376    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11377            boolean fullInvalidate) {
11378        if (mGhostView != null) {
11379            mGhostView.invalidate(invalidateCache);
11380            return;
11381        }
11382
11383        if (skipInvalidate()) {
11384            return;
11385        }
11386
11387        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11388                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11389                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11390                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11391            if (fullInvalidate) {
11392                mLastIsOpaque = isOpaque();
11393                mPrivateFlags &= ~PFLAG_DRAWN;
11394            }
11395
11396            mPrivateFlags |= PFLAG_DIRTY;
11397
11398            if (invalidateCache) {
11399                mPrivateFlags |= PFLAG_INVALIDATED;
11400                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11401            }
11402
11403            // Propagate the damage rectangle to the parent view.
11404            final AttachInfo ai = mAttachInfo;
11405            final ViewParent p = mParent;
11406            if (p != null && ai != null && l < r && t < b) {
11407                final Rect damage = ai.mTmpInvalRect;
11408                damage.set(l, t, r, b);
11409                p.invalidateChild(this, damage);
11410            }
11411
11412            // Damage the entire projection receiver, if necessary.
11413            if (mBackground != null && mBackground.isProjected()) {
11414                final View receiver = getProjectionReceiver();
11415                if (receiver != null) {
11416                    receiver.damageInParent();
11417                }
11418            }
11419
11420            // Damage the entire IsolatedZVolume receiving this view's shadow.
11421            if (isHardwareAccelerated() && getZ() != 0) {
11422                damageShadowReceiver();
11423            }
11424        }
11425    }
11426
11427    /**
11428     * @return this view's projection receiver, or {@code null} if none exists
11429     */
11430    private View getProjectionReceiver() {
11431        ViewParent p = getParent();
11432        while (p != null && p instanceof View) {
11433            final View v = (View) p;
11434            if (v.isProjectionReceiver()) {
11435                return v;
11436            }
11437            p = p.getParent();
11438        }
11439
11440        return null;
11441    }
11442
11443    /**
11444     * @return whether the view is a projection receiver
11445     */
11446    private boolean isProjectionReceiver() {
11447        return mBackground != null;
11448    }
11449
11450    /**
11451     * Damage area of the screen that can be covered by this View's shadow.
11452     *
11453     * This method will guarantee that any changes to shadows cast by a View
11454     * are damaged on the screen for future redraw.
11455     */
11456    private void damageShadowReceiver() {
11457        final AttachInfo ai = mAttachInfo;
11458        if (ai != null) {
11459            ViewParent p = getParent();
11460            if (p != null && p instanceof ViewGroup) {
11461                final ViewGroup vg = (ViewGroup) p;
11462                vg.damageInParent();
11463            }
11464        }
11465    }
11466
11467    /**
11468     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11469     * set any flags or handle all of the cases handled by the default invalidation methods.
11470     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11471     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11472     * walk up the hierarchy, transforming the dirty rect as necessary.
11473     *
11474     * The method also handles normal invalidation logic if display list properties are not
11475     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11476     * backup approach, to handle these cases used in the various property-setting methods.
11477     *
11478     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11479     * are not being used in this view
11480     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11481     * list properties are not being used in this view
11482     */
11483    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11484        if (!isHardwareAccelerated()
11485                || !mRenderNode.isValid()
11486                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11487            if (invalidateParent) {
11488                invalidateParentCaches();
11489            }
11490            if (forceRedraw) {
11491                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11492            }
11493            invalidate(false);
11494        } else {
11495            damageInParent();
11496        }
11497        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11498            damageShadowReceiver();
11499        }
11500    }
11501
11502    /**
11503     * Tells the parent view to damage this view's bounds.
11504     *
11505     * @hide
11506     */
11507    protected void damageInParent() {
11508        final AttachInfo ai = mAttachInfo;
11509        final ViewParent p = mParent;
11510        if (p != null && ai != null) {
11511            final Rect r = ai.mTmpInvalRect;
11512            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11513            if (mParent instanceof ViewGroup) {
11514                ((ViewGroup) mParent).damageChild(this, r);
11515            } else {
11516                mParent.invalidateChild(this, r);
11517            }
11518        }
11519    }
11520
11521    /**
11522     * Utility method to transform a given Rect by the current matrix of this view.
11523     */
11524    void transformRect(final Rect rect) {
11525        if (!getMatrix().isIdentity()) {
11526            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11527            boundingRect.set(rect);
11528            getMatrix().mapRect(boundingRect);
11529            rect.set((int) Math.floor(boundingRect.left),
11530                    (int) Math.floor(boundingRect.top),
11531                    (int) Math.ceil(boundingRect.right),
11532                    (int) Math.ceil(boundingRect.bottom));
11533        }
11534    }
11535
11536    /**
11537     * Used to indicate that the parent of this view should clear its caches. This functionality
11538     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11539     * which is necessary when various parent-managed properties of the view change, such as
11540     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11541     * clears the parent caches and does not causes an invalidate event.
11542     *
11543     * @hide
11544     */
11545    protected void invalidateParentCaches() {
11546        if (mParent instanceof View) {
11547            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11548        }
11549    }
11550
11551    /**
11552     * Used to indicate that the parent of this view should be invalidated. This functionality
11553     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11554     * which is necessary when various parent-managed properties of the view change, such as
11555     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11556     * an invalidation event to the parent.
11557     *
11558     * @hide
11559     */
11560    protected void invalidateParentIfNeeded() {
11561        if (isHardwareAccelerated() && mParent instanceof View) {
11562            ((View) mParent).invalidate(true);
11563        }
11564    }
11565
11566    /**
11567     * @hide
11568     */
11569    protected void invalidateParentIfNeededAndWasQuickRejected() {
11570        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11571            // View was rejected last time it was drawn by its parent; this may have changed
11572            invalidateParentIfNeeded();
11573        }
11574    }
11575
11576    /**
11577     * Indicates whether this View is opaque. An opaque View guarantees that it will
11578     * draw all the pixels overlapping its bounds using a fully opaque color.
11579     *
11580     * Subclasses of View should override this method whenever possible to indicate
11581     * whether an instance is opaque. Opaque Views are treated in a special way by
11582     * the View hierarchy, possibly allowing it to perform optimizations during
11583     * invalidate/draw passes.
11584     *
11585     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11586     */
11587    @ViewDebug.ExportedProperty(category = "drawing")
11588    public boolean isOpaque() {
11589        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11590                getFinalAlpha() >= 1.0f;
11591    }
11592
11593    /**
11594     * @hide
11595     */
11596    protected void computeOpaqueFlags() {
11597        // Opaque if:
11598        //   - Has a background
11599        //   - Background is opaque
11600        //   - Doesn't have scrollbars or scrollbars overlay
11601
11602        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11603            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11604        } else {
11605            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11606        }
11607
11608        final int flags = mViewFlags;
11609        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11610                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11611                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11612            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11613        } else {
11614            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11615        }
11616    }
11617
11618    /**
11619     * @hide
11620     */
11621    protected boolean hasOpaqueScrollbars() {
11622        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11623    }
11624
11625    /**
11626     * @return A handler associated with the thread running the View. This
11627     * handler can be used to pump events in the UI events queue.
11628     */
11629    public Handler getHandler() {
11630        final AttachInfo attachInfo = mAttachInfo;
11631        if (attachInfo != null) {
11632            return attachInfo.mHandler;
11633        }
11634        return null;
11635    }
11636
11637    /**
11638     * Gets the view root associated with the View.
11639     * @return The view root, or null if none.
11640     * @hide
11641     */
11642    public ViewRootImpl getViewRootImpl() {
11643        if (mAttachInfo != null) {
11644            return mAttachInfo.mViewRootImpl;
11645        }
11646        return null;
11647    }
11648
11649    /**
11650     * @hide
11651     */
11652    public HardwareRenderer getHardwareRenderer() {
11653        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11654    }
11655
11656    /**
11657     * <p>Causes the Runnable to be added to the message queue.
11658     * The runnable will be run on the user interface thread.</p>
11659     *
11660     * @param action The Runnable that will be executed.
11661     *
11662     * @return Returns true if the Runnable was successfully placed in to the
11663     *         message queue.  Returns false on failure, usually because the
11664     *         looper processing the message queue is exiting.
11665     *
11666     * @see #postDelayed
11667     * @see #removeCallbacks
11668     */
11669    public boolean post(Runnable action) {
11670        final AttachInfo attachInfo = mAttachInfo;
11671        if (attachInfo != null) {
11672            return attachInfo.mHandler.post(action);
11673        }
11674        // Assume that post will succeed later
11675        ViewRootImpl.getRunQueue().post(action);
11676        return true;
11677    }
11678
11679    /**
11680     * <p>Causes the Runnable to be added to the message queue, to be run
11681     * after the specified amount of time elapses.
11682     * The runnable will be run on the user interface thread.</p>
11683     *
11684     * @param action The Runnable that will be executed.
11685     * @param delayMillis The delay (in milliseconds) until the Runnable
11686     *        will be executed.
11687     *
11688     * @return true if the Runnable was successfully placed in to the
11689     *         message queue.  Returns false on failure, usually because the
11690     *         looper processing the message queue is exiting.  Note that a
11691     *         result of true does not mean the Runnable will be processed --
11692     *         if the looper is quit before the delivery time of the message
11693     *         occurs then the message will be dropped.
11694     *
11695     * @see #post
11696     * @see #removeCallbacks
11697     */
11698    public boolean postDelayed(Runnable action, long delayMillis) {
11699        final AttachInfo attachInfo = mAttachInfo;
11700        if (attachInfo != null) {
11701            return attachInfo.mHandler.postDelayed(action, delayMillis);
11702        }
11703        // Assume that post will succeed later
11704        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11705        return true;
11706    }
11707
11708    /**
11709     * <p>Causes the Runnable to execute on the next animation time step.
11710     * The runnable will be run on the user interface thread.</p>
11711     *
11712     * @param action The Runnable that will be executed.
11713     *
11714     * @see #postOnAnimationDelayed
11715     * @see #removeCallbacks
11716     */
11717    public void postOnAnimation(Runnable action) {
11718        final AttachInfo attachInfo = mAttachInfo;
11719        if (attachInfo != null) {
11720            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11721                    Choreographer.CALLBACK_ANIMATION, action, null);
11722        } else {
11723            // Assume that post will succeed later
11724            ViewRootImpl.getRunQueue().post(action);
11725        }
11726    }
11727
11728    /**
11729     * <p>Causes the Runnable to execute on the next animation time step,
11730     * after the specified amount of time elapses.
11731     * The runnable will be run on the user interface thread.</p>
11732     *
11733     * @param action The Runnable that will be executed.
11734     * @param delayMillis The delay (in milliseconds) until the Runnable
11735     *        will be executed.
11736     *
11737     * @see #postOnAnimation
11738     * @see #removeCallbacks
11739     */
11740    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11741        final AttachInfo attachInfo = mAttachInfo;
11742        if (attachInfo != null) {
11743            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11744                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11745        } else {
11746            // Assume that post will succeed later
11747            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11748        }
11749    }
11750
11751    /**
11752     * <p>Removes the specified Runnable from the message queue.</p>
11753     *
11754     * @param action The Runnable to remove from the message handling queue
11755     *
11756     * @return true if this view could ask the Handler to remove the Runnable,
11757     *         false otherwise. When the returned value is true, the Runnable
11758     *         may or may not have been actually removed from the message queue
11759     *         (for instance, if the Runnable was not in the queue already.)
11760     *
11761     * @see #post
11762     * @see #postDelayed
11763     * @see #postOnAnimation
11764     * @see #postOnAnimationDelayed
11765     */
11766    public boolean removeCallbacks(Runnable action) {
11767        if (action != null) {
11768            final AttachInfo attachInfo = mAttachInfo;
11769            if (attachInfo != null) {
11770                attachInfo.mHandler.removeCallbacks(action);
11771                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11772                        Choreographer.CALLBACK_ANIMATION, action, null);
11773            }
11774            // Assume that post will succeed later
11775            ViewRootImpl.getRunQueue().removeCallbacks(action);
11776        }
11777        return true;
11778    }
11779
11780    /**
11781     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11782     * Use this to invalidate the View from a non-UI thread.</p>
11783     *
11784     * <p>This method can be invoked from outside of the UI thread
11785     * only when this View is attached to a window.</p>
11786     *
11787     * @see #invalidate()
11788     * @see #postInvalidateDelayed(long)
11789     */
11790    public void postInvalidate() {
11791        postInvalidateDelayed(0);
11792    }
11793
11794    /**
11795     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11796     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11797     *
11798     * <p>This method can be invoked from outside of the UI thread
11799     * only when this View is attached to a window.</p>
11800     *
11801     * @param left The left coordinate of the rectangle to invalidate.
11802     * @param top The top coordinate of the rectangle to invalidate.
11803     * @param right The right coordinate of the rectangle to invalidate.
11804     * @param bottom The bottom coordinate of the rectangle to invalidate.
11805     *
11806     * @see #invalidate(int, int, int, int)
11807     * @see #invalidate(Rect)
11808     * @see #postInvalidateDelayed(long, int, int, int, int)
11809     */
11810    public void postInvalidate(int left, int top, int right, int bottom) {
11811        postInvalidateDelayed(0, left, top, right, bottom);
11812    }
11813
11814    /**
11815     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11816     * loop. Waits for the specified amount of time.</p>
11817     *
11818     * <p>This method can be invoked from outside of the UI thread
11819     * only when this View is attached to a window.</p>
11820     *
11821     * @param delayMilliseconds the duration in milliseconds to delay the
11822     *         invalidation by
11823     *
11824     * @see #invalidate()
11825     * @see #postInvalidate()
11826     */
11827    public void postInvalidateDelayed(long delayMilliseconds) {
11828        // We try only with the AttachInfo because there's no point in invalidating
11829        // if we are not attached to our window
11830        final AttachInfo attachInfo = mAttachInfo;
11831        if (attachInfo != null) {
11832            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11833        }
11834    }
11835
11836    /**
11837     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11838     * through the event loop. Waits for the specified amount of time.</p>
11839     *
11840     * <p>This method can be invoked from outside of the UI thread
11841     * only when this View is attached to a window.</p>
11842     *
11843     * @param delayMilliseconds the duration in milliseconds to delay the
11844     *         invalidation by
11845     * @param left The left coordinate of the rectangle to invalidate.
11846     * @param top The top coordinate of the rectangle to invalidate.
11847     * @param right The right coordinate of the rectangle to invalidate.
11848     * @param bottom The bottom coordinate of the rectangle to invalidate.
11849     *
11850     * @see #invalidate(int, int, int, int)
11851     * @see #invalidate(Rect)
11852     * @see #postInvalidate(int, int, int, int)
11853     */
11854    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11855            int right, int bottom) {
11856
11857        // We try only with the AttachInfo because there's no point in invalidating
11858        // if we are not attached to our window
11859        final AttachInfo attachInfo = mAttachInfo;
11860        if (attachInfo != null) {
11861            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11862            info.target = this;
11863            info.left = left;
11864            info.top = top;
11865            info.right = right;
11866            info.bottom = bottom;
11867
11868            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11869        }
11870    }
11871
11872    /**
11873     * <p>Cause an invalidate to happen on the next animation time step, typically the
11874     * next display frame.</p>
11875     *
11876     * <p>This method can be invoked from outside of the UI thread
11877     * only when this View is attached to a window.</p>
11878     *
11879     * @see #invalidate()
11880     */
11881    public void postInvalidateOnAnimation() {
11882        // We try only with the AttachInfo because there's no point in invalidating
11883        // if we are not attached to our window
11884        final AttachInfo attachInfo = mAttachInfo;
11885        if (attachInfo != null) {
11886            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11887        }
11888    }
11889
11890    /**
11891     * <p>Cause an invalidate of the specified area to happen on the next animation
11892     * time step, typically the next display frame.</p>
11893     *
11894     * <p>This method can be invoked from outside of the UI thread
11895     * only when this View is attached to a window.</p>
11896     *
11897     * @param left The left coordinate of the rectangle to invalidate.
11898     * @param top The top coordinate of the rectangle to invalidate.
11899     * @param right The right coordinate of the rectangle to invalidate.
11900     * @param bottom The bottom coordinate of the rectangle to invalidate.
11901     *
11902     * @see #invalidate(int, int, int, int)
11903     * @see #invalidate(Rect)
11904     */
11905    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11906        // We try only with the AttachInfo because there's no point in invalidating
11907        // if we are not attached to our window
11908        final AttachInfo attachInfo = mAttachInfo;
11909        if (attachInfo != null) {
11910            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11911            info.target = this;
11912            info.left = left;
11913            info.top = top;
11914            info.right = right;
11915            info.bottom = bottom;
11916
11917            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11918        }
11919    }
11920
11921    /**
11922     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11923     * This event is sent at most once every
11924     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11925     */
11926    private void postSendViewScrolledAccessibilityEventCallback() {
11927        if (mSendViewScrolledAccessibilityEvent == null) {
11928            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11929        }
11930        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11931            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11932            postDelayed(mSendViewScrolledAccessibilityEvent,
11933                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11934        }
11935    }
11936
11937    /**
11938     * Called by a parent to request that a child update its values for mScrollX
11939     * and mScrollY if necessary. This will typically be done if the child is
11940     * animating a scroll using a {@link android.widget.Scroller Scroller}
11941     * object.
11942     */
11943    public void computeScroll() {
11944    }
11945
11946    /**
11947     * <p>Indicate whether the horizontal edges are faded when the view is
11948     * scrolled horizontally.</p>
11949     *
11950     * @return true if the horizontal edges should are faded on scroll, false
11951     *         otherwise
11952     *
11953     * @see #setHorizontalFadingEdgeEnabled(boolean)
11954     *
11955     * @attr ref android.R.styleable#View_requiresFadingEdge
11956     */
11957    public boolean isHorizontalFadingEdgeEnabled() {
11958        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11959    }
11960
11961    /**
11962     * <p>Define whether the horizontal edges should be faded when this view
11963     * is scrolled horizontally.</p>
11964     *
11965     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11966     *                                    be faded when the view is scrolled
11967     *                                    horizontally
11968     *
11969     * @see #isHorizontalFadingEdgeEnabled()
11970     *
11971     * @attr ref android.R.styleable#View_requiresFadingEdge
11972     */
11973    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11974        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11975            if (horizontalFadingEdgeEnabled) {
11976                initScrollCache();
11977            }
11978
11979            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11980        }
11981    }
11982
11983    /**
11984     * <p>Indicate whether the vertical edges are faded when the view is
11985     * scrolled horizontally.</p>
11986     *
11987     * @return true if the vertical edges should are faded on scroll, false
11988     *         otherwise
11989     *
11990     * @see #setVerticalFadingEdgeEnabled(boolean)
11991     *
11992     * @attr ref android.R.styleable#View_requiresFadingEdge
11993     */
11994    public boolean isVerticalFadingEdgeEnabled() {
11995        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11996    }
11997
11998    /**
11999     * <p>Define whether the vertical edges should be faded when this view
12000     * is scrolled vertically.</p>
12001     *
12002     * @param verticalFadingEdgeEnabled true if the vertical edges should
12003     *                                  be faded when the view is scrolled
12004     *                                  vertically
12005     *
12006     * @see #isVerticalFadingEdgeEnabled()
12007     *
12008     * @attr ref android.R.styleable#View_requiresFadingEdge
12009     */
12010    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12011        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12012            if (verticalFadingEdgeEnabled) {
12013                initScrollCache();
12014            }
12015
12016            mViewFlags ^= FADING_EDGE_VERTICAL;
12017        }
12018    }
12019
12020    /**
12021     * Returns the strength, or intensity, of the top faded edge. The strength is
12022     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12023     * returns 0.0 or 1.0 but no value in between.
12024     *
12025     * Subclasses should override this method to provide a smoother fade transition
12026     * when scrolling occurs.
12027     *
12028     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12029     */
12030    protected float getTopFadingEdgeStrength() {
12031        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12032    }
12033
12034    /**
12035     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12036     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12037     * returns 0.0 or 1.0 but no value in between.
12038     *
12039     * Subclasses should override this method to provide a smoother fade transition
12040     * when scrolling occurs.
12041     *
12042     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12043     */
12044    protected float getBottomFadingEdgeStrength() {
12045        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12046                computeVerticalScrollRange() ? 1.0f : 0.0f;
12047    }
12048
12049    /**
12050     * Returns the strength, or intensity, of the left faded edge. The strength is
12051     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12052     * returns 0.0 or 1.0 but no value in between.
12053     *
12054     * Subclasses should override this method to provide a smoother fade transition
12055     * when scrolling occurs.
12056     *
12057     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12058     */
12059    protected float getLeftFadingEdgeStrength() {
12060        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12061    }
12062
12063    /**
12064     * Returns the strength, or intensity, of the right faded edge. The strength is
12065     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12066     * returns 0.0 or 1.0 but no value in between.
12067     *
12068     * Subclasses should override this method to provide a smoother fade transition
12069     * when scrolling occurs.
12070     *
12071     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12072     */
12073    protected float getRightFadingEdgeStrength() {
12074        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12075                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12076    }
12077
12078    /**
12079     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12080     * scrollbar is not drawn by default.</p>
12081     *
12082     * @return true if the horizontal scrollbar should be painted, false
12083     *         otherwise
12084     *
12085     * @see #setHorizontalScrollBarEnabled(boolean)
12086     */
12087    public boolean isHorizontalScrollBarEnabled() {
12088        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12089    }
12090
12091    /**
12092     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12093     * scrollbar is not drawn by default.</p>
12094     *
12095     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12096     *                                   be painted
12097     *
12098     * @see #isHorizontalScrollBarEnabled()
12099     */
12100    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12101        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12102            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12103            computeOpaqueFlags();
12104            resolvePadding();
12105        }
12106    }
12107
12108    /**
12109     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12110     * scrollbar is not drawn by default.</p>
12111     *
12112     * @return true if the vertical scrollbar should be painted, false
12113     *         otherwise
12114     *
12115     * @see #setVerticalScrollBarEnabled(boolean)
12116     */
12117    public boolean isVerticalScrollBarEnabled() {
12118        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12119    }
12120
12121    /**
12122     * <p>Define whether the vertical scrollbar should be drawn or not. The
12123     * scrollbar is not drawn by default.</p>
12124     *
12125     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12126     *                                 be painted
12127     *
12128     * @see #isVerticalScrollBarEnabled()
12129     */
12130    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12131        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12132            mViewFlags ^= SCROLLBARS_VERTICAL;
12133            computeOpaqueFlags();
12134            resolvePadding();
12135        }
12136    }
12137
12138    /**
12139     * @hide
12140     */
12141    protected void recomputePadding() {
12142        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12143    }
12144
12145    /**
12146     * Define whether scrollbars will fade when the view is not scrolling.
12147     *
12148     * @param fadeScrollbars wheter to enable fading
12149     *
12150     * @attr ref android.R.styleable#View_fadeScrollbars
12151     */
12152    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12153        initScrollCache();
12154        final ScrollabilityCache scrollabilityCache = mScrollCache;
12155        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12156        if (fadeScrollbars) {
12157            scrollabilityCache.state = ScrollabilityCache.OFF;
12158        } else {
12159            scrollabilityCache.state = ScrollabilityCache.ON;
12160        }
12161    }
12162
12163    /**
12164     *
12165     * Returns true if scrollbars will fade when this view is not scrolling
12166     *
12167     * @return true if scrollbar fading is enabled
12168     *
12169     * @attr ref android.R.styleable#View_fadeScrollbars
12170     */
12171    public boolean isScrollbarFadingEnabled() {
12172        return mScrollCache != null && mScrollCache.fadeScrollBars;
12173    }
12174
12175    /**
12176     *
12177     * Returns the delay before scrollbars fade.
12178     *
12179     * @return the delay before scrollbars fade
12180     *
12181     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12182     */
12183    public int getScrollBarDefaultDelayBeforeFade() {
12184        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12185                mScrollCache.scrollBarDefaultDelayBeforeFade;
12186    }
12187
12188    /**
12189     * Define the delay before scrollbars fade.
12190     *
12191     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12192     *
12193     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12194     */
12195    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12196        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12197    }
12198
12199    /**
12200     *
12201     * Returns the scrollbar fade duration.
12202     *
12203     * @return the scrollbar fade duration
12204     *
12205     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12206     */
12207    public int getScrollBarFadeDuration() {
12208        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12209                mScrollCache.scrollBarFadeDuration;
12210    }
12211
12212    /**
12213     * Define the scrollbar fade duration.
12214     *
12215     * @param scrollBarFadeDuration - the scrollbar fade duration
12216     *
12217     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12218     */
12219    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12220        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12221    }
12222
12223    /**
12224     *
12225     * Returns the scrollbar size.
12226     *
12227     * @return the scrollbar size
12228     *
12229     * @attr ref android.R.styleable#View_scrollbarSize
12230     */
12231    public int getScrollBarSize() {
12232        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12233                mScrollCache.scrollBarSize;
12234    }
12235
12236    /**
12237     * Define the scrollbar size.
12238     *
12239     * @param scrollBarSize - the scrollbar size
12240     *
12241     * @attr ref android.R.styleable#View_scrollbarSize
12242     */
12243    public void setScrollBarSize(int scrollBarSize) {
12244        getScrollCache().scrollBarSize = scrollBarSize;
12245    }
12246
12247    /**
12248     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12249     * inset. When inset, they add to the padding of the view. And the scrollbars
12250     * can be drawn inside the padding area or on the edge of the view. For example,
12251     * if a view has a background drawable and you want to draw the scrollbars
12252     * inside the padding specified by the drawable, you can use
12253     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12254     * appear at the edge of the view, ignoring the padding, then you can use
12255     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12256     * @param style the style of the scrollbars. Should be one of
12257     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12258     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12259     * @see #SCROLLBARS_INSIDE_OVERLAY
12260     * @see #SCROLLBARS_INSIDE_INSET
12261     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12262     * @see #SCROLLBARS_OUTSIDE_INSET
12263     *
12264     * @attr ref android.R.styleable#View_scrollbarStyle
12265     */
12266    public void setScrollBarStyle(@ScrollBarStyle int style) {
12267        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12268            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12269            computeOpaqueFlags();
12270            resolvePadding();
12271        }
12272    }
12273
12274    /**
12275     * <p>Returns the current scrollbar style.</p>
12276     * @return the current scrollbar style
12277     * @see #SCROLLBARS_INSIDE_OVERLAY
12278     * @see #SCROLLBARS_INSIDE_INSET
12279     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12280     * @see #SCROLLBARS_OUTSIDE_INSET
12281     *
12282     * @attr ref android.R.styleable#View_scrollbarStyle
12283     */
12284    @ViewDebug.ExportedProperty(mapping = {
12285            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12286            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12287            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12288            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12289    })
12290    @ScrollBarStyle
12291    public int getScrollBarStyle() {
12292        return mViewFlags & SCROLLBARS_STYLE_MASK;
12293    }
12294
12295    /**
12296     * <p>Compute the horizontal range that the horizontal scrollbar
12297     * represents.</p>
12298     *
12299     * <p>The range is expressed in arbitrary units that must be the same as the
12300     * units used by {@link #computeHorizontalScrollExtent()} and
12301     * {@link #computeHorizontalScrollOffset()}.</p>
12302     *
12303     * <p>The default range is the drawing width of this view.</p>
12304     *
12305     * @return the total horizontal range represented by the horizontal
12306     *         scrollbar
12307     *
12308     * @see #computeHorizontalScrollExtent()
12309     * @see #computeHorizontalScrollOffset()
12310     * @see android.widget.ScrollBarDrawable
12311     */
12312    protected int computeHorizontalScrollRange() {
12313        return getWidth();
12314    }
12315
12316    /**
12317     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12318     * within the horizontal range. This value is used to compute the position
12319     * of the thumb within the scrollbar's track.</p>
12320     *
12321     * <p>The range is expressed in arbitrary units that must be the same as the
12322     * units used by {@link #computeHorizontalScrollRange()} and
12323     * {@link #computeHorizontalScrollExtent()}.</p>
12324     *
12325     * <p>The default offset is the scroll offset of this view.</p>
12326     *
12327     * @return the horizontal offset of the scrollbar's thumb
12328     *
12329     * @see #computeHorizontalScrollRange()
12330     * @see #computeHorizontalScrollExtent()
12331     * @see android.widget.ScrollBarDrawable
12332     */
12333    protected int computeHorizontalScrollOffset() {
12334        return mScrollX;
12335    }
12336
12337    /**
12338     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12339     * within the horizontal range. This value is used to compute the length
12340     * of the thumb within the scrollbar's track.</p>
12341     *
12342     * <p>The range is expressed in arbitrary units that must be the same as the
12343     * units used by {@link #computeHorizontalScrollRange()} and
12344     * {@link #computeHorizontalScrollOffset()}.</p>
12345     *
12346     * <p>The default extent is the drawing width of this view.</p>
12347     *
12348     * @return the horizontal extent of the scrollbar's thumb
12349     *
12350     * @see #computeHorizontalScrollRange()
12351     * @see #computeHorizontalScrollOffset()
12352     * @see android.widget.ScrollBarDrawable
12353     */
12354    protected int computeHorizontalScrollExtent() {
12355        return getWidth();
12356    }
12357
12358    /**
12359     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12360     *
12361     * <p>The range is expressed in arbitrary units that must be the same as the
12362     * units used by {@link #computeVerticalScrollExtent()} and
12363     * {@link #computeVerticalScrollOffset()}.</p>
12364     *
12365     * @return the total vertical range represented by the vertical scrollbar
12366     *
12367     * <p>The default range is the drawing height of this view.</p>
12368     *
12369     * @see #computeVerticalScrollExtent()
12370     * @see #computeVerticalScrollOffset()
12371     * @see android.widget.ScrollBarDrawable
12372     */
12373    protected int computeVerticalScrollRange() {
12374        return getHeight();
12375    }
12376
12377    /**
12378     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12379     * within the horizontal range. This value is used to compute the position
12380     * of the thumb within the scrollbar's track.</p>
12381     *
12382     * <p>The range is expressed in arbitrary units that must be the same as the
12383     * units used by {@link #computeVerticalScrollRange()} and
12384     * {@link #computeVerticalScrollExtent()}.</p>
12385     *
12386     * <p>The default offset is the scroll offset of this view.</p>
12387     *
12388     * @return the vertical offset of the scrollbar's thumb
12389     *
12390     * @see #computeVerticalScrollRange()
12391     * @see #computeVerticalScrollExtent()
12392     * @see android.widget.ScrollBarDrawable
12393     */
12394    protected int computeVerticalScrollOffset() {
12395        return mScrollY;
12396    }
12397
12398    /**
12399     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12400     * within the vertical range. This value is used to compute the length
12401     * of the thumb within the scrollbar's track.</p>
12402     *
12403     * <p>The range is expressed in arbitrary units that must be the same as the
12404     * units used by {@link #computeVerticalScrollRange()} and
12405     * {@link #computeVerticalScrollOffset()}.</p>
12406     *
12407     * <p>The default extent is the drawing height of this view.</p>
12408     *
12409     * @return the vertical extent of the scrollbar's thumb
12410     *
12411     * @see #computeVerticalScrollRange()
12412     * @see #computeVerticalScrollOffset()
12413     * @see android.widget.ScrollBarDrawable
12414     */
12415    protected int computeVerticalScrollExtent() {
12416        return getHeight();
12417    }
12418
12419    /**
12420     * Check if this view can be scrolled horizontally in a certain direction.
12421     *
12422     * @param direction Negative to check scrolling left, positive to check scrolling right.
12423     * @return true if this view can be scrolled in the specified direction, false otherwise.
12424     */
12425    public boolean canScrollHorizontally(int direction) {
12426        final int offset = computeHorizontalScrollOffset();
12427        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12428        if (range == 0) return false;
12429        if (direction < 0) {
12430            return offset > 0;
12431        } else {
12432            return offset < range - 1;
12433        }
12434    }
12435
12436    /**
12437     * Check if this view can be scrolled vertically in a certain direction.
12438     *
12439     * @param direction Negative to check scrolling up, positive to check scrolling down.
12440     * @return true if this view can be scrolled in the specified direction, false otherwise.
12441     */
12442    public boolean canScrollVertically(int direction) {
12443        final int offset = computeVerticalScrollOffset();
12444        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12445        if (range == 0) return false;
12446        if (direction < 0) {
12447            return offset > 0;
12448        } else {
12449            return offset < range - 1;
12450        }
12451    }
12452
12453    /**
12454     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12455     * scrollbars are painted only if they have been awakened first.</p>
12456     *
12457     * @param canvas the canvas on which to draw the scrollbars
12458     *
12459     * @see #awakenScrollBars(int)
12460     */
12461    protected final void onDrawScrollBars(Canvas canvas) {
12462        // scrollbars are drawn only when the animation is running
12463        final ScrollabilityCache cache = mScrollCache;
12464        if (cache != null) {
12465
12466            int state = cache.state;
12467
12468            if (state == ScrollabilityCache.OFF) {
12469                return;
12470            }
12471
12472            boolean invalidate = false;
12473
12474            if (state == ScrollabilityCache.FADING) {
12475                // We're fading -- get our fade interpolation
12476                if (cache.interpolatorValues == null) {
12477                    cache.interpolatorValues = new float[1];
12478                }
12479
12480                float[] values = cache.interpolatorValues;
12481
12482                // Stops the animation if we're done
12483                if (cache.scrollBarInterpolator.timeToValues(values) ==
12484                        Interpolator.Result.FREEZE_END) {
12485                    cache.state = ScrollabilityCache.OFF;
12486                } else {
12487                    cache.scrollBar.setAlpha(Math.round(values[0]));
12488                }
12489
12490                // This will make the scroll bars inval themselves after
12491                // drawing. We only want this when we're fading so that
12492                // we prevent excessive redraws
12493                invalidate = true;
12494            } else {
12495                // We're just on -- but we may have been fading before so
12496                // reset alpha
12497                cache.scrollBar.setAlpha(255);
12498            }
12499
12500
12501            final int viewFlags = mViewFlags;
12502
12503            final boolean drawHorizontalScrollBar =
12504                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12505            final boolean drawVerticalScrollBar =
12506                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12507                && !isVerticalScrollBarHidden();
12508
12509            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12510                final int width = mRight - mLeft;
12511                final int height = mBottom - mTop;
12512
12513                final ScrollBarDrawable scrollBar = cache.scrollBar;
12514
12515                final int scrollX = mScrollX;
12516                final int scrollY = mScrollY;
12517                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12518
12519                int left;
12520                int top;
12521                int right;
12522                int bottom;
12523
12524                if (drawHorizontalScrollBar) {
12525                    int size = scrollBar.getSize(false);
12526                    if (size <= 0) {
12527                        size = cache.scrollBarSize;
12528                    }
12529
12530                    scrollBar.setParameters(computeHorizontalScrollRange(),
12531                                            computeHorizontalScrollOffset(),
12532                                            computeHorizontalScrollExtent(), false);
12533                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12534                            getVerticalScrollbarWidth() : 0;
12535                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12536                    left = scrollX + (mPaddingLeft & inside);
12537                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12538                    bottom = top + size;
12539                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12540                    if (invalidate) {
12541                        invalidate(left, top, right, bottom);
12542                    }
12543                }
12544
12545                if (drawVerticalScrollBar) {
12546                    int size = scrollBar.getSize(true);
12547                    if (size <= 0) {
12548                        size = cache.scrollBarSize;
12549                    }
12550
12551                    scrollBar.setParameters(computeVerticalScrollRange(),
12552                                            computeVerticalScrollOffset(),
12553                                            computeVerticalScrollExtent(), true);
12554                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12555                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12556                        verticalScrollbarPosition = isLayoutRtl() ?
12557                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12558                    }
12559                    switch (verticalScrollbarPosition) {
12560                        default:
12561                        case SCROLLBAR_POSITION_RIGHT:
12562                            left = scrollX + width - size - (mUserPaddingRight & inside);
12563                            break;
12564                        case SCROLLBAR_POSITION_LEFT:
12565                            left = scrollX + (mUserPaddingLeft & inside);
12566                            break;
12567                    }
12568                    top = scrollY + (mPaddingTop & inside);
12569                    right = left + size;
12570                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12571                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12572                    if (invalidate) {
12573                        invalidate(left, top, right, bottom);
12574                    }
12575                }
12576            }
12577        }
12578    }
12579
12580    /**
12581     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12582     * FastScroller is visible.
12583     * @return whether to temporarily hide the vertical scrollbar
12584     * @hide
12585     */
12586    protected boolean isVerticalScrollBarHidden() {
12587        return false;
12588    }
12589
12590    /**
12591     * <p>Draw the horizontal scrollbar if
12592     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12593     *
12594     * @param canvas the canvas on which to draw the scrollbar
12595     * @param scrollBar the scrollbar's drawable
12596     *
12597     * @see #isHorizontalScrollBarEnabled()
12598     * @see #computeHorizontalScrollRange()
12599     * @see #computeHorizontalScrollExtent()
12600     * @see #computeHorizontalScrollOffset()
12601     * @see android.widget.ScrollBarDrawable
12602     * @hide
12603     */
12604    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12605            int l, int t, int r, int b) {
12606        scrollBar.setBounds(l, t, r, b);
12607        scrollBar.draw(canvas);
12608    }
12609
12610    /**
12611     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12612     * returns true.</p>
12613     *
12614     * @param canvas the canvas on which to draw the scrollbar
12615     * @param scrollBar the scrollbar's drawable
12616     *
12617     * @see #isVerticalScrollBarEnabled()
12618     * @see #computeVerticalScrollRange()
12619     * @see #computeVerticalScrollExtent()
12620     * @see #computeVerticalScrollOffset()
12621     * @see android.widget.ScrollBarDrawable
12622     * @hide
12623     */
12624    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12625            int l, int t, int r, int b) {
12626        scrollBar.setBounds(l, t, r, b);
12627        scrollBar.draw(canvas);
12628    }
12629
12630    /**
12631     * Implement this to do your drawing.
12632     *
12633     * @param canvas the canvas on which the background will be drawn
12634     */
12635    protected void onDraw(Canvas canvas) {
12636    }
12637
12638    /*
12639     * Caller is responsible for calling requestLayout if necessary.
12640     * (This allows addViewInLayout to not request a new layout.)
12641     */
12642    void assignParent(ViewParent parent) {
12643        if (mParent == null) {
12644            mParent = parent;
12645        } else if (parent == null) {
12646            mParent = null;
12647        } else {
12648            throw new RuntimeException("view " + this + " being added, but"
12649                    + " it already has a parent");
12650        }
12651    }
12652
12653    /**
12654     * This is called when the view is attached to a window.  At this point it
12655     * has a Surface and will start drawing.  Note that this function is
12656     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12657     * however it may be called any time before the first onDraw -- including
12658     * before or after {@link #onMeasure(int, int)}.
12659     *
12660     * @see #onDetachedFromWindow()
12661     */
12662    protected void onAttachedToWindow() {
12663        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12664            mParent.requestTransparentRegion(this);
12665        }
12666
12667        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12668            initialAwakenScrollBars();
12669            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12670        }
12671
12672        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12673
12674        jumpDrawablesToCurrentState();
12675
12676        resetSubtreeAccessibilityStateChanged();
12677
12678        invalidateOutline();
12679
12680        if (isFocused()) {
12681            InputMethodManager imm = InputMethodManager.peekInstance();
12682            imm.focusIn(this);
12683        }
12684    }
12685
12686    /**
12687     * Resolve all RTL related properties.
12688     *
12689     * @return true if resolution of RTL properties has been done
12690     *
12691     * @hide
12692     */
12693    public boolean resolveRtlPropertiesIfNeeded() {
12694        if (!needRtlPropertiesResolution()) return false;
12695
12696        // Order is important here: LayoutDirection MUST be resolved first
12697        if (!isLayoutDirectionResolved()) {
12698            resolveLayoutDirection();
12699            resolveLayoutParams();
12700        }
12701        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12702        if (!isTextDirectionResolved()) {
12703            resolveTextDirection();
12704        }
12705        if (!isTextAlignmentResolved()) {
12706            resolveTextAlignment();
12707        }
12708        // Should resolve Drawables before Padding because we need the layout direction of the
12709        // Drawable to correctly resolve Padding.
12710        if (!isDrawablesResolved()) {
12711            resolveDrawables();
12712        }
12713        if (!isPaddingResolved()) {
12714            resolvePadding();
12715        }
12716        onRtlPropertiesChanged(getLayoutDirection());
12717        return true;
12718    }
12719
12720    /**
12721     * Reset resolution of all RTL related properties.
12722     *
12723     * @hide
12724     */
12725    public void resetRtlProperties() {
12726        resetResolvedLayoutDirection();
12727        resetResolvedTextDirection();
12728        resetResolvedTextAlignment();
12729        resetResolvedPadding();
12730        resetResolvedDrawables();
12731    }
12732
12733    /**
12734     * @see #onScreenStateChanged(int)
12735     */
12736    void dispatchScreenStateChanged(int screenState) {
12737        onScreenStateChanged(screenState);
12738    }
12739
12740    /**
12741     * This method is called whenever the state of the screen this view is
12742     * attached to changes. A state change will usually occurs when the screen
12743     * turns on or off (whether it happens automatically or the user does it
12744     * manually.)
12745     *
12746     * @param screenState The new state of the screen. Can be either
12747     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12748     */
12749    public void onScreenStateChanged(int screenState) {
12750    }
12751
12752    /**
12753     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12754     */
12755    private boolean hasRtlSupport() {
12756        return mContext.getApplicationInfo().hasRtlSupport();
12757    }
12758
12759    /**
12760     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12761     * RTL not supported)
12762     */
12763    private boolean isRtlCompatibilityMode() {
12764        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12765        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12766    }
12767
12768    /**
12769     * @return true if RTL properties need resolution.
12770     *
12771     */
12772    private boolean needRtlPropertiesResolution() {
12773        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12774    }
12775
12776    /**
12777     * Called when any RTL property (layout direction or text direction or text alignment) has
12778     * been changed.
12779     *
12780     * Subclasses need to override this method to take care of cached information that depends on the
12781     * resolved layout direction, or to inform child views that inherit their layout direction.
12782     *
12783     * The default implementation does nothing.
12784     *
12785     * @param layoutDirection the direction of the layout
12786     *
12787     * @see #LAYOUT_DIRECTION_LTR
12788     * @see #LAYOUT_DIRECTION_RTL
12789     */
12790    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12791    }
12792
12793    /**
12794     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12795     * that the parent directionality can and will be resolved before its children.
12796     *
12797     * @return true if resolution has been done, false otherwise.
12798     *
12799     * @hide
12800     */
12801    public boolean resolveLayoutDirection() {
12802        // Clear any previous layout direction resolution
12803        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12804
12805        if (hasRtlSupport()) {
12806            // Set resolved depending on layout direction
12807            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12808                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12809                case LAYOUT_DIRECTION_INHERIT:
12810                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12811                    // later to get the correct resolved value
12812                    if (!canResolveLayoutDirection()) return false;
12813
12814                    // Parent has not yet resolved, LTR is still the default
12815                    try {
12816                        if (!mParent.isLayoutDirectionResolved()) return false;
12817
12818                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12819                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12820                        }
12821                    } catch (AbstractMethodError e) {
12822                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12823                                " does not fully implement ViewParent", e);
12824                    }
12825                    break;
12826                case LAYOUT_DIRECTION_RTL:
12827                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12828                    break;
12829                case LAYOUT_DIRECTION_LOCALE:
12830                    if((LAYOUT_DIRECTION_RTL ==
12831                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12832                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12833                    }
12834                    break;
12835                default:
12836                    // Nothing to do, LTR by default
12837            }
12838        }
12839
12840        // Set to resolved
12841        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12842        return true;
12843    }
12844
12845    /**
12846     * Check if layout direction resolution can be done.
12847     *
12848     * @return true if layout direction resolution can be done otherwise return false.
12849     */
12850    public boolean canResolveLayoutDirection() {
12851        switch (getRawLayoutDirection()) {
12852            case LAYOUT_DIRECTION_INHERIT:
12853                if (mParent != null) {
12854                    try {
12855                        return mParent.canResolveLayoutDirection();
12856                    } catch (AbstractMethodError e) {
12857                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12858                                " does not fully implement ViewParent", e);
12859                    }
12860                }
12861                return false;
12862
12863            default:
12864                return true;
12865        }
12866    }
12867
12868    /**
12869     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12870     * {@link #onMeasure(int, int)}.
12871     *
12872     * @hide
12873     */
12874    public void resetResolvedLayoutDirection() {
12875        // Reset the current resolved bits
12876        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12877    }
12878
12879    /**
12880     * @return true if the layout direction is inherited.
12881     *
12882     * @hide
12883     */
12884    public boolean isLayoutDirectionInherited() {
12885        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12886    }
12887
12888    /**
12889     * @return true if layout direction has been resolved.
12890     */
12891    public boolean isLayoutDirectionResolved() {
12892        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12893    }
12894
12895    /**
12896     * Return if padding has been resolved
12897     *
12898     * @hide
12899     */
12900    boolean isPaddingResolved() {
12901        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12902    }
12903
12904    /**
12905     * Resolves padding depending on layout direction, if applicable, and
12906     * recomputes internal padding values to adjust for scroll bars.
12907     *
12908     * @hide
12909     */
12910    public void resolvePadding() {
12911        final int resolvedLayoutDirection = getLayoutDirection();
12912
12913        if (!isRtlCompatibilityMode()) {
12914            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12915            // If start / end padding are defined, they will be resolved (hence overriding) to
12916            // left / right or right / left depending on the resolved layout direction.
12917            // If start / end padding are not defined, use the left / right ones.
12918            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12919                Rect padding = sThreadLocal.get();
12920                if (padding == null) {
12921                    padding = new Rect();
12922                    sThreadLocal.set(padding);
12923                }
12924                mBackground.getPadding(padding);
12925                if (!mLeftPaddingDefined) {
12926                    mUserPaddingLeftInitial = padding.left;
12927                }
12928                if (!mRightPaddingDefined) {
12929                    mUserPaddingRightInitial = padding.right;
12930                }
12931            }
12932            switch (resolvedLayoutDirection) {
12933                case LAYOUT_DIRECTION_RTL:
12934                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12935                        mUserPaddingRight = mUserPaddingStart;
12936                    } else {
12937                        mUserPaddingRight = mUserPaddingRightInitial;
12938                    }
12939                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12940                        mUserPaddingLeft = mUserPaddingEnd;
12941                    } else {
12942                        mUserPaddingLeft = mUserPaddingLeftInitial;
12943                    }
12944                    break;
12945                case LAYOUT_DIRECTION_LTR:
12946                default:
12947                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12948                        mUserPaddingLeft = mUserPaddingStart;
12949                    } else {
12950                        mUserPaddingLeft = mUserPaddingLeftInitial;
12951                    }
12952                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12953                        mUserPaddingRight = mUserPaddingEnd;
12954                    } else {
12955                        mUserPaddingRight = mUserPaddingRightInitial;
12956                    }
12957            }
12958
12959            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12960        }
12961
12962        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12963        onRtlPropertiesChanged(resolvedLayoutDirection);
12964
12965        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12966    }
12967
12968    /**
12969     * Reset the resolved layout direction.
12970     *
12971     * @hide
12972     */
12973    public void resetResolvedPadding() {
12974        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12975    }
12976
12977    /**
12978     * This is called when the view is detached from a window.  At this point it
12979     * no longer has a surface for drawing.
12980     *
12981     * @see #onAttachedToWindow()
12982     */
12983    protected void onDetachedFromWindow() {
12984    }
12985
12986    /**
12987     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12988     * after onDetachedFromWindow().
12989     *
12990     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12991     * The super method should be called at the end of the overriden method to ensure
12992     * subclasses are destroyed first
12993     *
12994     * @hide
12995     */
12996    protected void onDetachedFromWindowInternal() {
12997        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12998        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12999
13000        removeUnsetPressCallback();
13001        removeLongPressCallback();
13002        removePerformClickCallback();
13003        removeSendViewScrolledAccessibilityEventCallback();
13004        stopNestedScroll();
13005
13006        destroyDrawingCache();
13007
13008        cleanupDraw();
13009        mCurrentAnimation = null;
13010    }
13011
13012    private void cleanupDraw() {
13013        resetDisplayList();
13014        if (mAttachInfo != null) {
13015            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13016        }
13017    }
13018
13019    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13020    }
13021
13022    /**
13023     * @return The number of times this view has been attached to a window
13024     */
13025    protected int getWindowAttachCount() {
13026        return mWindowAttachCount;
13027    }
13028
13029    /**
13030     * Retrieve a unique token identifying the window this view is attached to.
13031     * @return Return the window's token for use in
13032     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13033     */
13034    public IBinder getWindowToken() {
13035        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13036    }
13037
13038    /**
13039     * Retrieve the {@link WindowId} for the window this view is
13040     * currently attached to.
13041     */
13042    public WindowId getWindowId() {
13043        if (mAttachInfo == null) {
13044            return null;
13045        }
13046        if (mAttachInfo.mWindowId == null) {
13047            try {
13048                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13049                        mAttachInfo.mWindowToken);
13050                mAttachInfo.mWindowId = new WindowId(
13051                        mAttachInfo.mIWindowId);
13052            } catch (RemoteException e) {
13053            }
13054        }
13055        return mAttachInfo.mWindowId;
13056    }
13057
13058    /**
13059     * Retrieve a unique token identifying the top-level "real" window of
13060     * the window that this view is attached to.  That is, this is like
13061     * {@link #getWindowToken}, except if the window this view in is a panel
13062     * window (attached to another containing window), then the token of
13063     * the containing window is returned instead.
13064     *
13065     * @return Returns the associated window token, either
13066     * {@link #getWindowToken()} or the containing window's token.
13067     */
13068    public IBinder getApplicationWindowToken() {
13069        AttachInfo ai = mAttachInfo;
13070        if (ai != null) {
13071            IBinder appWindowToken = ai.mPanelParentWindowToken;
13072            if (appWindowToken == null) {
13073                appWindowToken = ai.mWindowToken;
13074            }
13075            return appWindowToken;
13076        }
13077        return null;
13078    }
13079
13080    /**
13081     * Gets the logical display to which the view's window has been attached.
13082     *
13083     * @return The logical display, or null if the view is not currently attached to a window.
13084     */
13085    public Display getDisplay() {
13086        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13087    }
13088
13089    /**
13090     * Retrieve private session object this view hierarchy is using to
13091     * communicate with the window manager.
13092     * @return the session object to communicate with the window manager
13093     */
13094    /*package*/ IWindowSession getWindowSession() {
13095        return mAttachInfo != null ? mAttachInfo.mSession : null;
13096    }
13097
13098    /**
13099     * @param info the {@link android.view.View.AttachInfo} to associated with
13100     *        this view
13101     */
13102    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13103        //System.out.println("Attached! " + this);
13104        mAttachInfo = info;
13105        if (mOverlay != null) {
13106            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13107        }
13108        mWindowAttachCount++;
13109        // We will need to evaluate the drawable state at least once.
13110        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13111        if (mFloatingTreeObserver != null) {
13112            info.mTreeObserver.merge(mFloatingTreeObserver);
13113            mFloatingTreeObserver = null;
13114        }
13115        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13116            mAttachInfo.mScrollContainers.add(this);
13117            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13118        }
13119        performCollectViewAttributes(mAttachInfo, visibility);
13120        onAttachedToWindow();
13121
13122        ListenerInfo li = mListenerInfo;
13123        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13124                li != null ? li.mOnAttachStateChangeListeners : null;
13125        if (listeners != null && listeners.size() > 0) {
13126            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13127            // perform the dispatching. The iterator is a safe guard against listeners that
13128            // could mutate the list by calling the various add/remove methods. This prevents
13129            // the array from being modified while we iterate it.
13130            for (OnAttachStateChangeListener listener : listeners) {
13131                listener.onViewAttachedToWindow(this);
13132            }
13133        }
13134
13135        int vis = info.mWindowVisibility;
13136        if (vis != GONE) {
13137            onWindowVisibilityChanged(vis);
13138        }
13139        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13140            // If nobody has evaluated the drawable state yet, then do it now.
13141            refreshDrawableState();
13142        }
13143        needGlobalAttributesUpdate(false);
13144    }
13145
13146    void dispatchDetachedFromWindow() {
13147        AttachInfo info = mAttachInfo;
13148        if (info != null) {
13149            int vis = info.mWindowVisibility;
13150            if (vis != GONE) {
13151                onWindowVisibilityChanged(GONE);
13152            }
13153        }
13154
13155        onDetachedFromWindow();
13156        onDetachedFromWindowInternal();
13157
13158        ListenerInfo li = mListenerInfo;
13159        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13160                li != null ? li.mOnAttachStateChangeListeners : null;
13161        if (listeners != null && listeners.size() > 0) {
13162            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13163            // perform the dispatching. The iterator is a safe guard against listeners that
13164            // could mutate the list by calling the various add/remove methods. This prevents
13165            // the array from being modified while we iterate it.
13166            for (OnAttachStateChangeListener listener : listeners) {
13167                listener.onViewDetachedFromWindow(this);
13168            }
13169        }
13170
13171        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13172            mAttachInfo.mScrollContainers.remove(this);
13173            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13174        }
13175
13176        mAttachInfo = null;
13177        if (mOverlay != null) {
13178            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13179        }
13180    }
13181
13182    /**
13183     * Cancel any deferred high-level input events that were previously posted to the event queue.
13184     *
13185     * <p>Many views post high-level events such as click handlers to the event queue
13186     * to run deferred in order to preserve a desired user experience - clearing visible
13187     * pressed states before executing, etc. This method will abort any events of this nature
13188     * that are currently in flight.</p>
13189     *
13190     * <p>Custom views that generate their own high-level deferred input events should override
13191     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13192     *
13193     * <p>This will also cancel pending input events for any child views.</p>
13194     *
13195     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13196     * This will not impact newer events posted after this call that may occur as a result of
13197     * lower-level input events still waiting in the queue. If you are trying to prevent
13198     * double-submitted  events for the duration of some sort of asynchronous transaction
13199     * you should also take other steps to protect against unexpected double inputs e.g. calling
13200     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13201     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13202     */
13203    public final void cancelPendingInputEvents() {
13204        dispatchCancelPendingInputEvents();
13205    }
13206
13207    /**
13208     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13209     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13210     */
13211    void dispatchCancelPendingInputEvents() {
13212        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13213        onCancelPendingInputEvents();
13214        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13215            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13216                    " did not call through to super.onCancelPendingInputEvents()");
13217        }
13218    }
13219
13220    /**
13221     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13222     * a parent view.
13223     *
13224     * <p>This method is responsible for removing any pending high-level input events that were
13225     * posted to the event queue to run later. Custom view classes that post their own deferred
13226     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13227     * {@link android.os.Handler} should override this method, call
13228     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13229     * </p>
13230     */
13231    public void onCancelPendingInputEvents() {
13232        removePerformClickCallback();
13233        cancelLongPress();
13234        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13235    }
13236
13237    /**
13238     * Store this view hierarchy's frozen state into the given container.
13239     *
13240     * @param container The SparseArray in which to save the view's state.
13241     *
13242     * @see #restoreHierarchyState(android.util.SparseArray)
13243     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13244     * @see #onSaveInstanceState()
13245     */
13246    public void saveHierarchyState(SparseArray<Parcelable> container) {
13247        dispatchSaveInstanceState(container);
13248    }
13249
13250    /**
13251     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13252     * this view and its children. May be overridden to modify how freezing happens to a
13253     * view's children; for example, some views may want to not store state for their children.
13254     *
13255     * @param container The SparseArray in which to save the view's state.
13256     *
13257     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13258     * @see #saveHierarchyState(android.util.SparseArray)
13259     * @see #onSaveInstanceState()
13260     */
13261    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13262        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13263            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13264            Parcelable state = onSaveInstanceState();
13265            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13266                throw new IllegalStateException(
13267                        "Derived class did not call super.onSaveInstanceState()");
13268            }
13269            if (state != null) {
13270                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13271                // + ": " + state);
13272                container.put(mID, state);
13273            }
13274        }
13275    }
13276
13277    /**
13278     * Hook allowing a view to generate a representation of its internal state
13279     * that can later be used to create a new instance with that same state.
13280     * This state should only contain information that is not persistent or can
13281     * not be reconstructed later. For example, you will never store your
13282     * current position on screen because that will be computed again when a
13283     * new instance of the view is placed in its view hierarchy.
13284     * <p>
13285     * Some examples of things you may store here: the current cursor position
13286     * in a text view (but usually not the text itself since that is stored in a
13287     * content provider or other persistent storage), the currently selected
13288     * item in a list view.
13289     *
13290     * @return Returns a Parcelable object containing the view's current dynamic
13291     *         state, or null if there is nothing interesting to save. The
13292     *         default implementation returns null.
13293     * @see #onRestoreInstanceState(android.os.Parcelable)
13294     * @see #saveHierarchyState(android.util.SparseArray)
13295     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13296     * @see #setSaveEnabled(boolean)
13297     */
13298    protected Parcelable onSaveInstanceState() {
13299        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13300        return BaseSavedState.EMPTY_STATE;
13301    }
13302
13303    /**
13304     * Restore this view hierarchy's frozen state from the given container.
13305     *
13306     * @param container The SparseArray which holds previously frozen states.
13307     *
13308     * @see #saveHierarchyState(android.util.SparseArray)
13309     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13310     * @see #onRestoreInstanceState(android.os.Parcelable)
13311     */
13312    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13313        dispatchRestoreInstanceState(container);
13314    }
13315
13316    /**
13317     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13318     * state for this view and its children. May be overridden to modify how restoring
13319     * happens to a view's children; for example, some views may want to not store state
13320     * for their children.
13321     *
13322     * @param container The SparseArray which holds previously saved state.
13323     *
13324     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13325     * @see #restoreHierarchyState(android.util.SparseArray)
13326     * @see #onRestoreInstanceState(android.os.Parcelable)
13327     */
13328    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13329        if (mID != NO_ID) {
13330            Parcelable state = container.get(mID);
13331            if (state != null) {
13332                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13333                // + ": " + state);
13334                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13335                onRestoreInstanceState(state);
13336                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13337                    throw new IllegalStateException(
13338                            "Derived class did not call super.onRestoreInstanceState()");
13339                }
13340            }
13341        }
13342    }
13343
13344    /**
13345     * Hook allowing a view to re-apply a representation of its internal state that had previously
13346     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13347     * null state.
13348     *
13349     * @param state The frozen state that had previously been returned by
13350     *        {@link #onSaveInstanceState}.
13351     *
13352     * @see #onSaveInstanceState()
13353     * @see #restoreHierarchyState(android.util.SparseArray)
13354     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13355     */
13356    protected void onRestoreInstanceState(Parcelable state) {
13357        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13358        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13359            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13360                    + "received " + state.getClass().toString() + " instead. This usually happens "
13361                    + "when two views of different type have the same id in the same hierarchy. "
13362                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13363                    + "other views do not use the same id.");
13364        }
13365    }
13366
13367    /**
13368     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13369     *
13370     * @return the drawing start time in milliseconds
13371     */
13372    public long getDrawingTime() {
13373        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13374    }
13375
13376    /**
13377     * <p>Enables or disables the duplication of the parent's state into this view. When
13378     * duplication is enabled, this view gets its drawable state from its parent rather
13379     * than from its own internal properties.</p>
13380     *
13381     * <p>Note: in the current implementation, setting this property to true after the
13382     * view was added to a ViewGroup might have no effect at all. This property should
13383     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13384     *
13385     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13386     * property is enabled, an exception will be thrown.</p>
13387     *
13388     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13389     * parent, these states should not be affected by this method.</p>
13390     *
13391     * @param enabled True to enable duplication of the parent's drawable state, false
13392     *                to disable it.
13393     *
13394     * @see #getDrawableState()
13395     * @see #isDuplicateParentStateEnabled()
13396     */
13397    public void setDuplicateParentStateEnabled(boolean enabled) {
13398        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13399    }
13400
13401    /**
13402     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13403     *
13404     * @return True if this view's drawable state is duplicated from the parent,
13405     *         false otherwise
13406     *
13407     * @see #getDrawableState()
13408     * @see #setDuplicateParentStateEnabled(boolean)
13409     */
13410    public boolean isDuplicateParentStateEnabled() {
13411        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13412    }
13413
13414    /**
13415     * <p>Specifies the type of layer backing this view. The layer can be
13416     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13417     * {@link #LAYER_TYPE_HARDWARE}.</p>
13418     *
13419     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13420     * instance that controls how the layer is composed on screen. The following
13421     * properties of the paint are taken into account when composing the layer:</p>
13422     * <ul>
13423     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13424     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13425     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13426     * </ul>
13427     *
13428     * <p>If this view has an alpha value set to < 1.0 by calling
13429     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13430     * by this view's alpha value.</p>
13431     *
13432     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13433     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13434     * for more information on when and how to use layers.</p>
13435     *
13436     * @param layerType The type of layer to use with this view, must be one of
13437     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13438     *        {@link #LAYER_TYPE_HARDWARE}
13439     * @param paint The paint used to compose the layer. This argument is optional
13440     *        and can be null. It is ignored when the layer type is
13441     *        {@link #LAYER_TYPE_NONE}
13442     *
13443     * @see #getLayerType()
13444     * @see #LAYER_TYPE_NONE
13445     * @see #LAYER_TYPE_SOFTWARE
13446     * @see #LAYER_TYPE_HARDWARE
13447     * @see #setAlpha(float)
13448     *
13449     * @attr ref android.R.styleable#View_layerType
13450     */
13451    public void setLayerType(int layerType, Paint paint) {
13452        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13453            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13454                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13455        }
13456
13457        boolean typeChanged = mRenderNode.setLayerType(layerType);
13458
13459        if (!typeChanged) {
13460            setLayerPaint(paint);
13461            return;
13462        }
13463
13464        // Destroy any previous software drawing cache if needed
13465        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13466            destroyDrawingCache();
13467        }
13468
13469        mLayerType = layerType;
13470        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13471        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13472        mRenderNode.setLayerPaint(mLayerPaint);
13473
13474        // draw() behaves differently if we are on a layer, so we need to
13475        // invalidate() here
13476        invalidateParentCaches();
13477        invalidate(true);
13478    }
13479
13480    /**
13481     * Updates the {@link Paint} object used with the current layer (used only if the current
13482     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13483     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13484     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13485     * ensure that the view gets redrawn immediately.
13486     *
13487     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13488     * instance that controls how the layer is composed on screen. The following
13489     * properties of the paint are taken into account when composing the layer:</p>
13490     * <ul>
13491     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13492     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13493     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13494     * </ul>
13495     *
13496     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13497     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13498     *
13499     * @param paint The paint used to compose the layer. This argument is optional
13500     *        and can be null. It is ignored when the layer type is
13501     *        {@link #LAYER_TYPE_NONE}
13502     *
13503     * @see #setLayerType(int, android.graphics.Paint)
13504     */
13505    public void setLayerPaint(Paint paint) {
13506        int layerType = getLayerType();
13507        if (layerType != LAYER_TYPE_NONE) {
13508            mLayerPaint = paint == null ? new Paint() : paint;
13509            if (layerType == LAYER_TYPE_HARDWARE) {
13510                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13511                    invalidateViewProperty(false, false);
13512                }
13513            } else {
13514                invalidate();
13515            }
13516        }
13517    }
13518
13519    /**
13520     * Indicates whether this view has a static layer. A view with layer type
13521     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13522     * dynamic.
13523     */
13524    boolean hasStaticLayer() {
13525        return true;
13526    }
13527
13528    /**
13529     * Indicates what type of layer is currently associated with this view. By default
13530     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13531     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13532     * for more information on the different types of layers.
13533     *
13534     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13535     *         {@link #LAYER_TYPE_HARDWARE}
13536     *
13537     * @see #setLayerType(int, android.graphics.Paint)
13538     * @see #buildLayer()
13539     * @see #LAYER_TYPE_NONE
13540     * @see #LAYER_TYPE_SOFTWARE
13541     * @see #LAYER_TYPE_HARDWARE
13542     */
13543    public int getLayerType() {
13544        return mLayerType;
13545    }
13546
13547    /**
13548     * Forces this view's layer to be created and this view to be rendered
13549     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13550     * invoking this method will have no effect.
13551     *
13552     * This method can for instance be used to render a view into its layer before
13553     * starting an animation. If this view is complex, rendering into the layer
13554     * before starting the animation will avoid skipping frames.
13555     *
13556     * @throws IllegalStateException If this view is not attached to a window
13557     *
13558     * @see #setLayerType(int, android.graphics.Paint)
13559     */
13560    public void buildLayer() {
13561        if (mLayerType == LAYER_TYPE_NONE) return;
13562
13563        final AttachInfo attachInfo = mAttachInfo;
13564        if (attachInfo == null) {
13565            throw new IllegalStateException("This view must be attached to a window first");
13566        }
13567
13568        if (getWidth() == 0 || getHeight() == 0) {
13569            return;
13570        }
13571
13572        switch (mLayerType) {
13573            case LAYER_TYPE_HARDWARE:
13574                // The only part of a hardware layer we can build in response to
13575                // this call is to ensure the display list is up to date.
13576                // The actual rendering of the display list into the layer must
13577                // be done at playback time
13578                updateDisplayListIfDirty();
13579                break;
13580            case LAYER_TYPE_SOFTWARE:
13581                buildDrawingCache(true);
13582                break;
13583        }
13584    }
13585
13586    /**
13587     * If this View draws with a HardwareLayer, returns it.
13588     * Otherwise returns null
13589     *
13590     * TODO: Only TextureView uses this, can we eliminate it?
13591     */
13592    HardwareLayer getHardwareLayer() {
13593        return null;
13594    }
13595
13596    /**
13597     * Destroys all hardware rendering resources. This method is invoked
13598     * when the system needs to reclaim resources. Upon execution of this
13599     * method, you should free any OpenGL resources created by the view.
13600     *
13601     * Note: you <strong>must</strong> call
13602     * <code>super.destroyHardwareResources()</code> when overriding
13603     * this method.
13604     *
13605     * @hide
13606     */
13607    protected void destroyHardwareResources() {
13608        // Although the Layer will be destroyed by RenderNode, we want to release
13609        // the staging display list, which is also a signal to RenderNode that it's
13610        // safe to free its copy of the display list as it knows that we will
13611        // push an updated DisplayList if we try to draw again
13612        resetDisplayList();
13613    }
13614
13615    /**
13616     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13617     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13618     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13619     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13620     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13621     * null.</p>
13622     *
13623     * <p>Enabling the drawing cache is similar to
13624     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13625     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13626     * drawing cache has no effect on rendering because the system uses a different mechanism
13627     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13628     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13629     * for information on how to enable software and hardware layers.</p>
13630     *
13631     * <p>This API can be used to manually generate
13632     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13633     * {@link #getDrawingCache()}.</p>
13634     *
13635     * @param enabled true to enable the drawing cache, false otherwise
13636     *
13637     * @see #isDrawingCacheEnabled()
13638     * @see #getDrawingCache()
13639     * @see #buildDrawingCache()
13640     * @see #setLayerType(int, android.graphics.Paint)
13641     */
13642    public void setDrawingCacheEnabled(boolean enabled) {
13643        mCachingFailed = false;
13644        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13645    }
13646
13647    /**
13648     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13649     *
13650     * @return true if the drawing cache is enabled
13651     *
13652     * @see #setDrawingCacheEnabled(boolean)
13653     * @see #getDrawingCache()
13654     */
13655    @ViewDebug.ExportedProperty(category = "drawing")
13656    public boolean isDrawingCacheEnabled() {
13657        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13658    }
13659
13660    /**
13661     * Debugging utility which recursively outputs the dirty state of a view and its
13662     * descendants.
13663     *
13664     * @hide
13665     */
13666    @SuppressWarnings({"UnusedDeclaration"})
13667    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13668        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13669                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13670                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13671                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13672        if (clear) {
13673            mPrivateFlags &= clearMask;
13674        }
13675        if (this instanceof ViewGroup) {
13676            ViewGroup parent = (ViewGroup) this;
13677            final int count = parent.getChildCount();
13678            for (int i = 0; i < count; i++) {
13679                final View child = parent.getChildAt(i);
13680                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13681            }
13682        }
13683    }
13684
13685    /**
13686     * This method is used by ViewGroup to cause its children to restore or recreate their
13687     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13688     * to recreate its own display list, which would happen if it went through the normal
13689     * draw/dispatchDraw mechanisms.
13690     *
13691     * @hide
13692     */
13693    protected void dispatchGetDisplayList() {}
13694
13695    /**
13696     * A view that is not attached or hardware accelerated cannot create a display list.
13697     * This method checks these conditions and returns the appropriate result.
13698     *
13699     * @return true if view has the ability to create a display list, false otherwise.
13700     *
13701     * @hide
13702     */
13703    public boolean canHaveDisplayList() {
13704        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13705    }
13706
13707    private void updateDisplayListIfDirty() {
13708        final RenderNode renderNode = mRenderNode;
13709        if (!canHaveDisplayList()) {
13710            // can't populate RenderNode, don't try
13711            return;
13712        }
13713
13714        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13715                || !renderNode.isValid()
13716                || (mRecreateDisplayList)) {
13717            // Don't need to recreate the display list, just need to tell our
13718            // children to restore/recreate theirs
13719            if (renderNode.isValid()
13720                    && !mRecreateDisplayList) {
13721                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13722                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13723                dispatchGetDisplayList();
13724
13725                return; // no work needed
13726            }
13727
13728            // If we got here, we're recreating it. Mark it as such to ensure that
13729            // we copy in child display lists into ours in drawChild()
13730            mRecreateDisplayList = true;
13731
13732            int width = mRight - mLeft;
13733            int height = mBottom - mTop;
13734            int layerType = getLayerType();
13735
13736            final HardwareCanvas canvas = renderNode.start(width, height);
13737            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13738
13739            try {
13740                final HardwareLayer layer = getHardwareLayer();
13741                if (layer != null && layer.isValid()) {
13742                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13743                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13744                    buildDrawingCache(true);
13745                    Bitmap cache = getDrawingCache(true);
13746                    if (cache != null) {
13747                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13748                    }
13749                } else {
13750                    computeScroll();
13751
13752                    canvas.translate(-mScrollX, -mScrollY);
13753                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13754                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13755
13756                    // Fast path for layouts with no backgrounds
13757                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13758                        dispatchDraw(canvas);
13759                        if (mOverlay != null && !mOverlay.isEmpty()) {
13760                            mOverlay.getOverlayView().draw(canvas);
13761                        }
13762                    } else {
13763                        draw(canvas);
13764                    }
13765                }
13766            } finally {
13767                renderNode.end(canvas);
13768                setDisplayListProperties(renderNode);
13769            }
13770        } else {
13771            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13772            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13773        }
13774    }
13775
13776    /**
13777     * Returns a RenderNode with View draw content recorded, which can be
13778     * used to draw this view again without executing its draw method.
13779     *
13780     * @return A RenderNode ready to replay, or null if caching is not enabled.
13781     *
13782     * @hide
13783     */
13784    public RenderNode getDisplayList() {
13785        updateDisplayListIfDirty();
13786        return mRenderNode;
13787    }
13788
13789    private void resetDisplayList() {
13790        if (mRenderNode.isValid()) {
13791            mRenderNode.destroyDisplayListData();
13792        }
13793
13794        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13795            mBackgroundRenderNode.destroyDisplayListData();
13796        }
13797    }
13798
13799    /**
13800     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13801     *
13802     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13803     *
13804     * @see #getDrawingCache(boolean)
13805     */
13806    public Bitmap getDrawingCache() {
13807        return getDrawingCache(false);
13808    }
13809
13810    /**
13811     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13812     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13813     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13814     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13815     * request the drawing cache by calling this method and draw it on screen if the
13816     * returned bitmap is not null.</p>
13817     *
13818     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13819     * this method will create a bitmap of the same size as this view. Because this bitmap
13820     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13821     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13822     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13823     * size than the view. This implies that your application must be able to handle this
13824     * size.</p>
13825     *
13826     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13827     *        the current density of the screen when the application is in compatibility
13828     *        mode.
13829     *
13830     * @return A bitmap representing this view or null if cache is disabled.
13831     *
13832     * @see #setDrawingCacheEnabled(boolean)
13833     * @see #isDrawingCacheEnabled()
13834     * @see #buildDrawingCache(boolean)
13835     * @see #destroyDrawingCache()
13836     */
13837    public Bitmap getDrawingCache(boolean autoScale) {
13838        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13839            return null;
13840        }
13841        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13842            buildDrawingCache(autoScale);
13843        }
13844        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13845    }
13846
13847    /**
13848     * <p>Frees the resources used by the drawing cache. If you call
13849     * {@link #buildDrawingCache()} manually without calling
13850     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13851     * should cleanup the cache with this method afterwards.</p>
13852     *
13853     * @see #setDrawingCacheEnabled(boolean)
13854     * @see #buildDrawingCache()
13855     * @see #getDrawingCache()
13856     */
13857    public void destroyDrawingCache() {
13858        if (mDrawingCache != null) {
13859            mDrawingCache.recycle();
13860            mDrawingCache = null;
13861        }
13862        if (mUnscaledDrawingCache != null) {
13863            mUnscaledDrawingCache.recycle();
13864            mUnscaledDrawingCache = null;
13865        }
13866    }
13867
13868    /**
13869     * Setting a solid background color for the drawing cache's bitmaps will improve
13870     * performance and memory usage. Note, though that this should only be used if this
13871     * view will always be drawn on top of a solid color.
13872     *
13873     * @param color The background color to use for the drawing cache's bitmap
13874     *
13875     * @see #setDrawingCacheEnabled(boolean)
13876     * @see #buildDrawingCache()
13877     * @see #getDrawingCache()
13878     */
13879    public void setDrawingCacheBackgroundColor(int color) {
13880        if (color != mDrawingCacheBackgroundColor) {
13881            mDrawingCacheBackgroundColor = color;
13882            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13883        }
13884    }
13885
13886    /**
13887     * @see #setDrawingCacheBackgroundColor(int)
13888     *
13889     * @return The background color to used for the drawing cache's bitmap
13890     */
13891    public int getDrawingCacheBackgroundColor() {
13892        return mDrawingCacheBackgroundColor;
13893    }
13894
13895    /**
13896     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13897     *
13898     * @see #buildDrawingCache(boolean)
13899     */
13900    public void buildDrawingCache() {
13901        buildDrawingCache(false);
13902    }
13903
13904    /**
13905     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13906     *
13907     * <p>If you call {@link #buildDrawingCache()} manually without calling
13908     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13909     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13910     *
13911     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13912     * this method will create a bitmap of the same size as this view. Because this bitmap
13913     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13914     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13915     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13916     * size than the view. This implies that your application must be able to handle this
13917     * size.</p>
13918     *
13919     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13920     * you do not need the drawing cache bitmap, calling this method will increase memory
13921     * usage and cause the view to be rendered in software once, thus negatively impacting
13922     * performance.</p>
13923     *
13924     * @see #getDrawingCache()
13925     * @see #destroyDrawingCache()
13926     */
13927    public void buildDrawingCache(boolean autoScale) {
13928        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13929                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13930            mCachingFailed = false;
13931
13932            int width = mRight - mLeft;
13933            int height = mBottom - mTop;
13934
13935            final AttachInfo attachInfo = mAttachInfo;
13936            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13937
13938            if (autoScale && scalingRequired) {
13939                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13940                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13941            }
13942
13943            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13944            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13945            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13946
13947            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13948            final long drawingCacheSize =
13949                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13950            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13951                if (width > 0 && height > 0) {
13952                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13953                            + projectedBitmapSize + " bytes, only "
13954                            + drawingCacheSize + " available");
13955                }
13956                destroyDrawingCache();
13957                mCachingFailed = true;
13958                return;
13959            }
13960
13961            boolean clear = true;
13962            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13963
13964            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13965                Bitmap.Config quality;
13966                if (!opaque) {
13967                    // Never pick ARGB_4444 because it looks awful
13968                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13969                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13970                        case DRAWING_CACHE_QUALITY_AUTO:
13971                        case DRAWING_CACHE_QUALITY_LOW:
13972                        case DRAWING_CACHE_QUALITY_HIGH:
13973                        default:
13974                            quality = Bitmap.Config.ARGB_8888;
13975                            break;
13976                    }
13977                } else {
13978                    // Optimization for translucent windows
13979                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13980                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13981                }
13982
13983                // Try to cleanup memory
13984                if (bitmap != null) bitmap.recycle();
13985
13986                try {
13987                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13988                            width, height, quality);
13989                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13990                    if (autoScale) {
13991                        mDrawingCache = bitmap;
13992                    } else {
13993                        mUnscaledDrawingCache = bitmap;
13994                    }
13995                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13996                } catch (OutOfMemoryError e) {
13997                    // If there is not enough memory to create the bitmap cache, just
13998                    // ignore the issue as bitmap caches are not required to draw the
13999                    // view hierarchy
14000                    if (autoScale) {
14001                        mDrawingCache = null;
14002                    } else {
14003                        mUnscaledDrawingCache = null;
14004                    }
14005                    mCachingFailed = true;
14006                    return;
14007                }
14008
14009                clear = drawingCacheBackgroundColor != 0;
14010            }
14011
14012            Canvas canvas;
14013            if (attachInfo != null) {
14014                canvas = attachInfo.mCanvas;
14015                if (canvas == null) {
14016                    canvas = new Canvas();
14017                }
14018                canvas.setBitmap(bitmap);
14019                // Temporarily clobber the cached Canvas in case one of our children
14020                // is also using a drawing cache. Without this, the children would
14021                // steal the canvas by attaching their own bitmap to it and bad, bad
14022                // thing would happen (invisible views, corrupted drawings, etc.)
14023                attachInfo.mCanvas = null;
14024            } else {
14025                // This case should hopefully never or seldom happen
14026                canvas = new Canvas(bitmap);
14027            }
14028
14029            if (clear) {
14030                bitmap.eraseColor(drawingCacheBackgroundColor);
14031            }
14032
14033            computeScroll();
14034            final int restoreCount = canvas.save();
14035
14036            if (autoScale && scalingRequired) {
14037                final float scale = attachInfo.mApplicationScale;
14038                canvas.scale(scale, scale);
14039            }
14040
14041            canvas.translate(-mScrollX, -mScrollY);
14042
14043            mPrivateFlags |= PFLAG_DRAWN;
14044            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14045                    mLayerType != LAYER_TYPE_NONE) {
14046                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14047            }
14048
14049            // Fast path for layouts with no backgrounds
14050            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14051                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14052                dispatchDraw(canvas);
14053                if (mOverlay != null && !mOverlay.isEmpty()) {
14054                    mOverlay.getOverlayView().draw(canvas);
14055                }
14056            } else {
14057                draw(canvas);
14058            }
14059
14060            canvas.restoreToCount(restoreCount);
14061            canvas.setBitmap(null);
14062
14063            if (attachInfo != null) {
14064                // Restore the cached Canvas for our siblings
14065                attachInfo.mCanvas = canvas;
14066            }
14067        }
14068    }
14069
14070    /**
14071     * Create a snapshot of the view into a bitmap.  We should probably make
14072     * some form of this public, but should think about the API.
14073     */
14074    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14075        int width = mRight - mLeft;
14076        int height = mBottom - mTop;
14077
14078        final AttachInfo attachInfo = mAttachInfo;
14079        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14080        width = (int) ((width * scale) + 0.5f);
14081        height = (int) ((height * scale) + 0.5f);
14082
14083        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14084                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14085        if (bitmap == null) {
14086            throw new OutOfMemoryError();
14087        }
14088
14089        Resources resources = getResources();
14090        if (resources != null) {
14091            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14092        }
14093
14094        Canvas canvas;
14095        if (attachInfo != null) {
14096            canvas = attachInfo.mCanvas;
14097            if (canvas == null) {
14098                canvas = new Canvas();
14099            }
14100            canvas.setBitmap(bitmap);
14101            // Temporarily clobber the cached Canvas in case one of our children
14102            // is also using a drawing cache. Without this, the children would
14103            // steal the canvas by attaching their own bitmap to it and bad, bad
14104            // things would happen (invisible views, corrupted drawings, etc.)
14105            attachInfo.mCanvas = null;
14106        } else {
14107            // This case should hopefully never or seldom happen
14108            canvas = new Canvas(bitmap);
14109        }
14110
14111        if ((backgroundColor & 0xff000000) != 0) {
14112            bitmap.eraseColor(backgroundColor);
14113        }
14114
14115        computeScroll();
14116        final int restoreCount = canvas.save();
14117        canvas.scale(scale, scale);
14118        canvas.translate(-mScrollX, -mScrollY);
14119
14120        // Temporarily remove the dirty mask
14121        int flags = mPrivateFlags;
14122        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14123
14124        // Fast path for layouts with no backgrounds
14125        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14126            dispatchDraw(canvas);
14127            if (mOverlay != null && !mOverlay.isEmpty()) {
14128                mOverlay.getOverlayView().draw(canvas);
14129            }
14130        } else {
14131            draw(canvas);
14132        }
14133
14134        mPrivateFlags = flags;
14135
14136        canvas.restoreToCount(restoreCount);
14137        canvas.setBitmap(null);
14138
14139        if (attachInfo != null) {
14140            // Restore the cached Canvas for our siblings
14141            attachInfo.mCanvas = canvas;
14142        }
14143
14144        return bitmap;
14145    }
14146
14147    /**
14148     * Indicates whether this View is currently in edit mode. A View is usually
14149     * in edit mode when displayed within a developer tool. For instance, if
14150     * this View is being drawn by a visual user interface builder, this method
14151     * should return true.
14152     *
14153     * Subclasses should check the return value of this method to provide
14154     * different behaviors if their normal behavior might interfere with the
14155     * host environment. For instance: the class spawns a thread in its
14156     * constructor, the drawing code relies on device-specific features, etc.
14157     *
14158     * This method is usually checked in the drawing code of custom widgets.
14159     *
14160     * @return True if this View is in edit mode, false otherwise.
14161     */
14162    public boolean isInEditMode() {
14163        return false;
14164    }
14165
14166    /**
14167     * If the View draws content inside its padding and enables fading edges,
14168     * it needs to support padding offsets. Padding offsets are added to the
14169     * fading edges to extend the length of the fade so that it covers pixels
14170     * drawn inside the padding.
14171     *
14172     * Subclasses of this class should override this method if they need
14173     * to draw content inside the padding.
14174     *
14175     * @return True if padding offset must be applied, false otherwise.
14176     *
14177     * @see #getLeftPaddingOffset()
14178     * @see #getRightPaddingOffset()
14179     * @see #getTopPaddingOffset()
14180     * @see #getBottomPaddingOffset()
14181     *
14182     * @since CURRENT
14183     */
14184    protected boolean isPaddingOffsetRequired() {
14185        return false;
14186    }
14187
14188    /**
14189     * Amount by which to extend the left fading region. Called only when
14190     * {@link #isPaddingOffsetRequired()} returns true.
14191     *
14192     * @return The left padding offset in pixels.
14193     *
14194     * @see #isPaddingOffsetRequired()
14195     *
14196     * @since CURRENT
14197     */
14198    protected int getLeftPaddingOffset() {
14199        return 0;
14200    }
14201
14202    /**
14203     * Amount by which to extend the right fading region. Called only when
14204     * {@link #isPaddingOffsetRequired()} returns true.
14205     *
14206     * @return The right padding offset in pixels.
14207     *
14208     * @see #isPaddingOffsetRequired()
14209     *
14210     * @since CURRENT
14211     */
14212    protected int getRightPaddingOffset() {
14213        return 0;
14214    }
14215
14216    /**
14217     * Amount by which to extend the top fading region. Called only when
14218     * {@link #isPaddingOffsetRequired()} returns true.
14219     *
14220     * @return The top padding offset in pixels.
14221     *
14222     * @see #isPaddingOffsetRequired()
14223     *
14224     * @since CURRENT
14225     */
14226    protected int getTopPaddingOffset() {
14227        return 0;
14228    }
14229
14230    /**
14231     * Amount by which to extend the bottom fading region. Called only when
14232     * {@link #isPaddingOffsetRequired()} returns true.
14233     *
14234     * @return The bottom padding offset in pixels.
14235     *
14236     * @see #isPaddingOffsetRequired()
14237     *
14238     * @since CURRENT
14239     */
14240    protected int getBottomPaddingOffset() {
14241        return 0;
14242    }
14243
14244    /**
14245     * @hide
14246     * @param offsetRequired
14247     */
14248    protected int getFadeTop(boolean offsetRequired) {
14249        int top = mPaddingTop;
14250        if (offsetRequired) top += getTopPaddingOffset();
14251        return top;
14252    }
14253
14254    /**
14255     * @hide
14256     * @param offsetRequired
14257     */
14258    protected int getFadeHeight(boolean offsetRequired) {
14259        int padding = mPaddingTop;
14260        if (offsetRequired) padding += getTopPaddingOffset();
14261        return mBottom - mTop - mPaddingBottom - padding;
14262    }
14263
14264    /**
14265     * <p>Indicates whether this view is attached to a hardware accelerated
14266     * window or not.</p>
14267     *
14268     * <p>Even if this method returns true, it does not mean that every call
14269     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14270     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14271     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14272     * window is hardware accelerated,
14273     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14274     * return false, and this method will return true.</p>
14275     *
14276     * @return True if the view is attached to a window and the window is
14277     *         hardware accelerated; false in any other case.
14278     */
14279    @ViewDebug.ExportedProperty(category = "drawing")
14280    public boolean isHardwareAccelerated() {
14281        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14282    }
14283
14284    /**
14285     * Sets a rectangular area on this view to which the view will be clipped
14286     * when it is drawn. Setting the value to null will remove the clip bounds
14287     * and the view will draw normally, using its full bounds.
14288     *
14289     * @param clipBounds The rectangular area, in the local coordinates of
14290     * this view, to which future drawing operations will be clipped.
14291     */
14292    public void setClipBounds(Rect clipBounds) {
14293        if (clipBounds != null) {
14294            if (clipBounds.equals(mClipBounds)) {
14295                return;
14296            }
14297            if (mClipBounds == null) {
14298                invalidate();
14299                mClipBounds = new Rect(clipBounds);
14300            } else {
14301                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14302                        Math.min(mClipBounds.top, clipBounds.top),
14303                        Math.max(mClipBounds.right, clipBounds.right),
14304                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14305                mClipBounds.set(clipBounds);
14306            }
14307        } else {
14308            if (mClipBounds != null) {
14309                invalidate();
14310                mClipBounds = null;
14311            }
14312        }
14313        mRenderNode.setClipBounds(mClipBounds);
14314    }
14315
14316    /**
14317     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14318     *
14319     * @return A copy of the current clip bounds if clip bounds are set,
14320     * otherwise null.
14321     */
14322    public Rect getClipBounds() {
14323        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14324    }
14325
14326    /**
14327     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14328     * case of an active Animation being run on the view.
14329     */
14330    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14331            Animation a, boolean scalingRequired) {
14332        Transformation invalidationTransform;
14333        final int flags = parent.mGroupFlags;
14334        final boolean initialized = a.isInitialized();
14335        if (!initialized) {
14336            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14337            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14338            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14339            onAnimationStart();
14340        }
14341
14342        final Transformation t = parent.getChildTransformation();
14343        boolean more = a.getTransformation(drawingTime, t, 1f);
14344        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14345            if (parent.mInvalidationTransformation == null) {
14346                parent.mInvalidationTransformation = new Transformation();
14347            }
14348            invalidationTransform = parent.mInvalidationTransformation;
14349            a.getTransformation(drawingTime, invalidationTransform, 1f);
14350        } else {
14351            invalidationTransform = t;
14352        }
14353
14354        if (more) {
14355            if (!a.willChangeBounds()) {
14356                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14357                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14358                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14359                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14360                    // The child need to draw an animation, potentially offscreen, so
14361                    // make sure we do not cancel invalidate requests
14362                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14363                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14364                }
14365            } else {
14366                if (parent.mInvalidateRegion == null) {
14367                    parent.mInvalidateRegion = new RectF();
14368                }
14369                final RectF region = parent.mInvalidateRegion;
14370                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14371                        invalidationTransform);
14372
14373                // The child need to draw an animation, potentially offscreen, so
14374                // make sure we do not cancel invalidate requests
14375                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14376
14377                final int left = mLeft + (int) region.left;
14378                final int top = mTop + (int) region.top;
14379                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14380                        top + (int) (region.height() + .5f));
14381            }
14382        }
14383        return more;
14384    }
14385
14386    /**
14387     * This method is called by getDisplayList() when a display list is recorded for a View.
14388     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14389     */
14390    void setDisplayListProperties(RenderNode renderNode) {
14391        if (renderNode != null) {
14392            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14393            if (mParent instanceof ViewGroup) {
14394                renderNode.setClipToBounds(
14395                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14396            }
14397            float alpha = 1;
14398            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14399                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14400                ViewGroup parentVG = (ViewGroup) mParent;
14401                final Transformation t = parentVG.getChildTransformation();
14402                if (parentVG.getChildStaticTransformation(this, t)) {
14403                    final int transformType = t.getTransformationType();
14404                    if (transformType != Transformation.TYPE_IDENTITY) {
14405                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14406                            alpha = t.getAlpha();
14407                        }
14408                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14409                            renderNode.setStaticMatrix(t.getMatrix());
14410                        }
14411                    }
14412                }
14413            }
14414            if (mTransformationInfo != null) {
14415                alpha *= getFinalAlpha();
14416                if (alpha < 1) {
14417                    final int multipliedAlpha = (int) (255 * alpha);
14418                    if (onSetAlpha(multipliedAlpha)) {
14419                        alpha = 1;
14420                    }
14421                }
14422                renderNode.setAlpha(alpha);
14423            } else if (alpha < 1) {
14424                renderNode.setAlpha(alpha);
14425            }
14426        }
14427    }
14428
14429    /**
14430     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14431     * This draw() method is an implementation detail and is not intended to be overridden or
14432     * to be called from anywhere else other than ViewGroup.drawChild().
14433     */
14434    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14435        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14436        boolean more = false;
14437        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14438        final int flags = parent.mGroupFlags;
14439
14440        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14441            parent.getChildTransformation().clear();
14442            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14443        }
14444
14445        Transformation transformToApply = null;
14446        boolean concatMatrix = false;
14447
14448        boolean scalingRequired = false;
14449        boolean caching;
14450        int layerType = getLayerType();
14451
14452        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14453        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14454                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14455            caching = true;
14456            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14457            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14458        } else {
14459            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14460        }
14461
14462        final Animation a = getAnimation();
14463        if (a != null) {
14464            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14465            concatMatrix = a.willChangeTransformationMatrix();
14466            if (concatMatrix) {
14467                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14468            }
14469            transformToApply = parent.getChildTransformation();
14470        } else {
14471            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14472                // No longer animating: clear out old animation matrix
14473                mRenderNode.setAnimationMatrix(null);
14474                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14475            }
14476            if (!usingRenderNodeProperties &&
14477                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14478                final Transformation t = parent.getChildTransformation();
14479                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14480                if (hasTransform) {
14481                    final int transformType = t.getTransformationType();
14482                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14483                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14484                }
14485            }
14486        }
14487
14488        concatMatrix |= !childHasIdentityMatrix;
14489
14490        // Sets the flag as early as possible to allow draw() implementations
14491        // to call invalidate() successfully when doing animations
14492        mPrivateFlags |= PFLAG_DRAWN;
14493
14494        if (!concatMatrix &&
14495                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14496                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14497                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14498                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14499            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14500            return more;
14501        }
14502        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14503
14504        if (hardwareAccelerated) {
14505            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14506            // retain the flag's value temporarily in the mRecreateDisplayList flag
14507            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14508            mPrivateFlags &= ~PFLAG_INVALIDATED;
14509        }
14510
14511        RenderNode renderNode = null;
14512        Bitmap cache = null;
14513        boolean hasDisplayList = false;
14514        if (caching) {
14515            if (!hardwareAccelerated) {
14516                if (layerType != LAYER_TYPE_NONE) {
14517                    layerType = LAYER_TYPE_SOFTWARE;
14518                    buildDrawingCache(true);
14519                }
14520                cache = getDrawingCache(true);
14521            } else {
14522                switch (layerType) {
14523                    case LAYER_TYPE_SOFTWARE:
14524                        if (usingRenderNodeProperties) {
14525                            hasDisplayList = canHaveDisplayList();
14526                        } else {
14527                            buildDrawingCache(true);
14528                            cache = getDrawingCache(true);
14529                        }
14530                        break;
14531                    case LAYER_TYPE_HARDWARE:
14532                        if (usingRenderNodeProperties) {
14533                            hasDisplayList = canHaveDisplayList();
14534                        }
14535                        break;
14536                    case LAYER_TYPE_NONE:
14537                        // Delay getting the display list until animation-driven alpha values are
14538                        // set up and possibly passed on to the view
14539                        hasDisplayList = canHaveDisplayList();
14540                        break;
14541                }
14542            }
14543        }
14544        usingRenderNodeProperties &= hasDisplayList;
14545        if (usingRenderNodeProperties) {
14546            renderNode = getDisplayList();
14547            if (!renderNode.isValid()) {
14548                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14549                // to getDisplayList(), the display list will be marked invalid and we should not
14550                // try to use it again.
14551                renderNode = null;
14552                hasDisplayList = false;
14553                usingRenderNodeProperties = false;
14554            }
14555        }
14556
14557        int sx = 0;
14558        int sy = 0;
14559        if (!hasDisplayList) {
14560            computeScroll();
14561            sx = mScrollX;
14562            sy = mScrollY;
14563        }
14564
14565        final boolean hasNoCache = cache == null || hasDisplayList;
14566        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14567                layerType != LAYER_TYPE_HARDWARE;
14568
14569        int restoreTo = -1;
14570        if (!usingRenderNodeProperties || transformToApply != null) {
14571            restoreTo = canvas.save();
14572        }
14573        if (offsetForScroll) {
14574            canvas.translate(mLeft - sx, mTop - sy);
14575        } else {
14576            if (!usingRenderNodeProperties) {
14577                canvas.translate(mLeft, mTop);
14578            }
14579            if (scalingRequired) {
14580                if (usingRenderNodeProperties) {
14581                    // TODO: Might not need this if we put everything inside the DL
14582                    restoreTo = canvas.save();
14583                }
14584                // mAttachInfo cannot be null, otherwise scalingRequired == false
14585                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14586                canvas.scale(scale, scale);
14587            }
14588        }
14589
14590        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14591        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14592                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14593            if (transformToApply != null || !childHasIdentityMatrix) {
14594                int transX = 0;
14595                int transY = 0;
14596
14597                if (offsetForScroll) {
14598                    transX = -sx;
14599                    transY = -sy;
14600                }
14601
14602                if (transformToApply != null) {
14603                    if (concatMatrix) {
14604                        if (usingRenderNodeProperties) {
14605                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14606                        } else {
14607                            // Undo the scroll translation, apply the transformation matrix,
14608                            // then redo the scroll translate to get the correct result.
14609                            canvas.translate(-transX, -transY);
14610                            canvas.concat(transformToApply.getMatrix());
14611                            canvas.translate(transX, transY);
14612                        }
14613                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14614                    }
14615
14616                    float transformAlpha = transformToApply.getAlpha();
14617                    if (transformAlpha < 1) {
14618                        alpha *= transformAlpha;
14619                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14620                    }
14621                }
14622
14623                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14624                    canvas.translate(-transX, -transY);
14625                    canvas.concat(getMatrix());
14626                    canvas.translate(transX, transY);
14627                }
14628            }
14629
14630            // Deal with alpha if it is or used to be <1
14631            if (alpha < 1 ||
14632                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14633                if (alpha < 1) {
14634                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14635                } else {
14636                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14637                }
14638                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14639                if (hasNoCache) {
14640                    final int multipliedAlpha = (int) (255 * alpha);
14641                    if (!onSetAlpha(multipliedAlpha)) {
14642                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14643                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14644                                layerType != LAYER_TYPE_NONE) {
14645                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14646                        }
14647                        if (usingRenderNodeProperties) {
14648                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14649                        } else  if (layerType == LAYER_TYPE_NONE) {
14650                            final int scrollX = hasDisplayList ? 0 : sx;
14651                            final int scrollY = hasDisplayList ? 0 : sy;
14652                            canvas.saveLayerAlpha(scrollX, scrollY,
14653                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14654                                    multipliedAlpha, layerFlags);
14655                        }
14656                    } else {
14657                        // Alpha is handled by the child directly, clobber the layer's alpha
14658                        mPrivateFlags |= PFLAG_ALPHA_SET;
14659                    }
14660                }
14661            }
14662        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14663            onSetAlpha(255);
14664            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14665        }
14666
14667        if (!usingRenderNodeProperties) {
14668            // apply clips directly, since RenderNode won't do it for this draw
14669            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14670                    && cache == null) {
14671                if (offsetForScroll) {
14672                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14673                } else {
14674                    if (!scalingRequired || cache == null) {
14675                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14676                    } else {
14677                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14678                    }
14679                }
14680            }
14681
14682            if (mClipBounds != null) {
14683                // clip bounds ignore scroll
14684                canvas.clipRect(mClipBounds);
14685            }
14686        }
14687
14688
14689
14690        if (!usingRenderNodeProperties && hasDisplayList) {
14691            renderNode = getDisplayList();
14692            if (!renderNode.isValid()) {
14693                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14694                // to getDisplayList(), the display list will be marked invalid and we should not
14695                // try to use it again.
14696                renderNode = null;
14697                hasDisplayList = false;
14698            }
14699        }
14700
14701        if (hasNoCache) {
14702            boolean layerRendered = false;
14703            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14704                final HardwareLayer layer = getHardwareLayer();
14705                if (layer != null && layer.isValid()) {
14706                    mLayerPaint.setAlpha((int) (alpha * 255));
14707                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14708                    layerRendered = true;
14709                } else {
14710                    final int scrollX = hasDisplayList ? 0 : sx;
14711                    final int scrollY = hasDisplayList ? 0 : sy;
14712                    canvas.saveLayer(scrollX, scrollY,
14713                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14714                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14715                }
14716            }
14717
14718            if (!layerRendered) {
14719                if (!hasDisplayList) {
14720                    // Fast path for layouts with no backgrounds
14721                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14722                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14723                        dispatchDraw(canvas);
14724                    } else {
14725                        draw(canvas);
14726                    }
14727                } else {
14728                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14729                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14730                }
14731            }
14732        } else if (cache != null) {
14733            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14734            Paint cachePaint;
14735
14736            if (layerType == LAYER_TYPE_NONE) {
14737                cachePaint = parent.mCachePaint;
14738                if (cachePaint == null) {
14739                    cachePaint = new Paint();
14740                    cachePaint.setDither(false);
14741                    parent.mCachePaint = cachePaint;
14742                }
14743                if (alpha < 1) {
14744                    cachePaint.setAlpha((int) (alpha * 255));
14745                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14746                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14747                    cachePaint.setAlpha(255);
14748                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14749                }
14750            } else {
14751                cachePaint = mLayerPaint;
14752                cachePaint.setAlpha((int) (alpha * 255));
14753            }
14754            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14755        }
14756
14757        if (restoreTo >= 0) {
14758            canvas.restoreToCount(restoreTo);
14759        }
14760
14761        if (a != null && !more) {
14762            if (!hardwareAccelerated && !a.getFillAfter()) {
14763                onSetAlpha(255);
14764            }
14765            parent.finishAnimatingView(this, a);
14766        }
14767
14768        if (more && hardwareAccelerated) {
14769            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14770                // alpha animations should cause the child to recreate its display list
14771                invalidate(true);
14772            }
14773        }
14774
14775        mRecreateDisplayList = false;
14776
14777        return more;
14778    }
14779
14780    /**
14781     * Manually render this view (and all of its children) to the given Canvas.
14782     * The view must have already done a full layout before this function is
14783     * called.  When implementing a view, implement
14784     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14785     * If you do need to override this method, call the superclass version.
14786     *
14787     * @param canvas The Canvas to which the View is rendered.
14788     */
14789    public void draw(Canvas canvas) {
14790        final int privateFlags = mPrivateFlags;
14791        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14792                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14793        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14794
14795        /*
14796         * Draw traversal performs several drawing steps which must be executed
14797         * in the appropriate order:
14798         *
14799         *      1. Draw the background
14800         *      2. If necessary, save the canvas' layers to prepare for fading
14801         *      3. Draw view's content
14802         *      4. Draw children
14803         *      5. If necessary, draw the fading edges and restore layers
14804         *      6. Draw decorations (scrollbars for instance)
14805         */
14806
14807        // Step 1, draw the background, if needed
14808        int saveCount;
14809
14810        if (!dirtyOpaque) {
14811            drawBackground(canvas);
14812        }
14813
14814        // skip step 2 & 5 if possible (common case)
14815        final int viewFlags = mViewFlags;
14816        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14817        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14818        if (!verticalEdges && !horizontalEdges) {
14819            // Step 3, draw the content
14820            if (!dirtyOpaque) onDraw(canvas);
14821
14822            // Step 4, draw the children
14823            dispatchDraw(canvas);
14824
14825            // Step 6, draw decorations (scrollbars)
14826            onDrawScrollBars(canvas);
14827
14828            if (mOverlay != null && !mOverlay.isEmpty()) {
14829                mOverlay.getOverlayView().dispatchDraw(canvas);
14830            }
14831
14832            // we're done...
14833            return;
14834        }
14835
14836        /*
14837         * Here we do the full fledged routine...
14838         * (this is an uncommon case where speed matters less,
14839         * this is why we repeat some of the tests that have been
14840         * done above)
14841         */
14842
14843        boolean drawTop = false;
14844        boolean drawBottom = false;
14845        boolean drawLeft = false;
14846        boolean drawRight = false;
14847
14848        float topFadeStrength = 0.0f;
14849        float bottomFadeStrength = 0.0f;
14850        float leftFadeStrength = 0.0f;
14851        float rightFadeStrength = 0.0f;
14852
14853        // Step 2, save the canvas' layers
14854        int paddingLeft = mPaddingLeft;
14855
14856        final boolean offsetRequired = isPaddingOffsetRequired();
14857        if (offsetRequired) {
14858            paddingLeft += getLeftPaddingOffset();
14859        }
14860
14861        int left = mScrollX + paddingLeft;
14862        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14863        int top = mScrollY + getFadeTop(offsetRequired);
14864        int bottom = top + getFadeHeight(offsetRequired);
14865
14866        if (offsetRequired) {
14867            right += getRightPaddingOffset();
14868            bottom += getBottomPaddingOffset();
14869        }
14870
14871        final ScrollabilityCache scrollabilityCache = mScrollCache;
14872        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14873        int length = (int) fadeHeight;
14874
14875        // clip the fade length if top and bottom fades overlap
14876        // overlapping fades produce odd-looking artifacts
14877        if (verticalEdges && (top + length > bottom - length)) {
14878            length = (bottom - top) / 2;
14879        }
14880
14881        // also clip horizontal fades if necessary
14882        if (horizontalEdges && (left + length > right - length)) {
14883            length = (right - left) / 2;
14884        }
14885
14886        if (verticalEdges) {
14887            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14888            drawTop = topFadeStrength * fadeHeight > 1.0f;
14889            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14890            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14891        }
14892
14893        if (horizontalEdges) {
14894            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14895            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14896            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14897            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14898        }
14899
14900        saveCount = canvas.getSaveCount();
14901
14902        int solidColor = getSolidColor();
14903        if (solidColor == 0) {
14904            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14905
14906            if (drawTop) {
14907                canvas.saveLayer(left, top, right, top + length, null, flags);
14908            }
14909
14910            if (drawBottom) {
14911                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14912            }
14913
14914            if (drawLeft) {
14915                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14916            }
14917
14918            if (drawRight) {
14919                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14920            }
14921        } else {
14922            scrollabilityCache.setFadeColor(solidColor);
14923        }
14924
14925        // Step 3, draw the content
14926        if (!dirtyOpaque) onDraw(canvas);
14927
14928        // Step 4, draw the children
14929        dispatchDraw(canvas);
14930
14931        // Step 5, draw the fade effect and restore layers
14932        final Paint p = scrollabilityCache.paint;
14933        final Matrix matrix = scrollabilityCache.matrix;
14934        final Shader fade = scrollabilityCache.shader;
14935
14936        if (drawTop) {
14937            matrix.setScale(1, fadeHeight * topFadeStrength);
14938            matrix.postTranslate(left, top);
14939            fade.setLocalMatrix(matrix);
14940            p.setShader(fade);
14941            canvas.drawRect(left, top, right, top + length, p);
14942        }
14943
14944        if (drawBottom) {
14945            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14946            matrix.postRotate(180);
14947            matrix.postTranslate(left, bottom);
14948            fade.setLocalMatrix(matrix);
14949            p.setShader(fade);
14950            canvas.drawRect(left, bottom - length, right, bottom, p);
14951        }
14952
14953        if (drawLeft) {
14954            matrix.setScale(1, fadeHeight * leftFadeStrength);
14955            matrix.postRotate(-90);
14956            matrix.postTranslate(left, top);
14957            fade.setLocalMatrix(matrix);
14958            p.setShader(fade);
14959            canvas.drawRect(left, top, left + length, bottom, p);
14960        }
14961
14962        if (drawRight) {
14963            matrix.setScale(1, fadeHeight * rightFadeStrength);
14964            matrix.postRotate(90);
14965            matrix.postTranslate(right, top);
14966            fade.setLocalMatrix(matrix);
14967            p.setShader(fade);
14968            canvas.drawRect(right - length, top, right, bottom, p);
14969        }
14970
14971        canvas.restoreToCount(saveCount);
14972
14973        // Step 6, draw decorations (scrollbars)
14974        onDrawScrollBars(canvas);
14975
14976        if (mOverlay != null && !mOverlay.isEmpty()) {
14977            mOverlay.getOverlayView().dispatchDraw(canvas);
14978        }
14979    }
14980
14981    /**
14982     * Draws the background onto the specified canvas.
14983     *
14984     * @param canvas Canvas on which to draw the background
14985     */
14986    private void drawBackground(Canvas canvas) {
14987        final Drawable background = mBackground;
14988        if (background == null) {
14989            return;
14990        }
14991
14992        if (mBackgroundSizeChanged) {
14993            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14994            mBackgroundSizeChanged = false;
14995            invalidateOutline();
14996        }
14997
14998        // Attempt to use a display list if requested.
14999        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15000                && mAttachInfo.mHardwareRenderer != null) {
15001            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15002
15003            final RenderNode displayList = mBackgroundRenderNode;
15004            if (displayList != null && displayList.isValid()) {
15005                setBackgroundDisplayListProperties(displayList);
15006                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15007                return;
15008            }
15009        }
15010
15011        final int scrollX = mScrollX;
15012        final int scrollY = mScrollY;
15013        if ((scrollX | scrollY) == 0) {
15014            background.draw(canvas);
15015        } else {
15016            canvas.translate(scrollX, scrollY);
15017            background.draw(canvas);
15018            canvas.translate(-scrollX, -scrollY);
15019        }
15020    }
15021
15022    /**
15023     * Set up background drawable display list properties.
15024     *
15025     * @param displayList Valid display list for the background drawable
15026     */
15027    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15028        displayList.setTranslationX(mScrollX);
15029        displayList.setTranslationY(mScrollY);
15030    }
15031
15032    /**
15033     * Creates a new display list or updates the existing display list for the
15034     * specified Drawable.
15035     *
15036     * @param drawable Drawable for which to create a display list
15037     * @param renderNode Existing RenderNode, or {@code null}
15038     * @return A valid display list for the specified drawable
15039     */
15040    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15041        if (renderNode == null) {
15042            renderNode = RenderNode.create(drawable.getClass().getName());
15043        }
15044
15045        final Rect bounds = drawable.getBounds();
15046        final int width = bounds.width();
15047        final int height = bounds.height();
15048        final HardwareCanvas canvas = renderNode.start(width, height);
15049        try {
15050            drawable.draw(canvas);
15051        } finally {
15052            renderNode.end(canvas);
15053        }
15054
15055        // Set up drawable properties that are view-independent.
15056        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15057        renderNode.setProjectBackwards(drawable.isProjected());
15058        renderNode.setProjectionReceiver(true);
15059        renderNode.setClipToBounds(false);
15060        return renderNode;
15061    }
15062
15063    /**
15064     * Returns the overlay for this view, creating it if it does not yet exist.
15065     * Adding drawables to the overlay will cause them to be displayed whenever
15066     * the view itself is redrawn. Objects in the overlay should be actively
15067     * managed: remove them when they should not be displayed anymore. The
15068     * overlay will always have the same size as its host view.
15069     *
15070     * <p>Note: Overlays do not currently work correctly with {@link
15071     * SurfaceView} or {@link TextureView}; contents in overlays for these
15072     * types of views may not display correctly.</p>
15073     *
15074     * @return The ViewOverlay object for this view.
15075     * @see ViewOverlay
15076     */
15077    public ViewOverlay getOverlay() {
15078        if (mOverlay == null) {
15079            mOverlay = new ViewOverlay(mContext, this);
15080        }
15081        return mOverlay;
15082    }
15083
15084    /**
15085     * Override this if your view is known to always be drawn on top of a solid color background,
15086     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15087     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15088     * should be set to 0xFF.
15089     *
15090     * @see #setVerticalFadingEdgeEnabled(boolean)
15091     * @see #setHorizontalFadingEdgeEnabled(boolean)
15092     *
15093     * @return The known solid color background for this view, or 0 if the color may vary
15094     */
15095    @ViewDebug.ExportedProperty(category = "drawing")
15096    public int getSolidColor() {
15097        return 0;
15098    }
15099
15100    /**
15101     * Build a human readable string representation of the specified view flags.
15102     *
15103     * @param flags the view flags to convert to a string
15104     * @return a String representing the supplied flags
15105     */
15106    private static String printFlags(int flags) {
15107        String output = "";
15108        int numFlags = 0;
15109        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15110            output += "TAKES_FOCUS";
15111            numFlags++;
15112        }
15113
15114        switch (flags & VISIBILITY_MASK) {
15115        case INVISIBLE:
15116            if (numFlags > 0) {
15117                output += " ";
15118            }
15119            output += "INVISIBLE";
15120            // USELESS HERE numFlags++;
15121            break;
15122        case GONE:
15123            if (numFlags > 0) {
15124                output += " ";
15125            }
15126            output += "GONE";
15127            // USELESS HERE numFlags++;
15128            break;
15129        default:
15130            break;
15131        }
15132        return output;
15133    }
15134
15135    /**
15136     * Build a human readable string representation of the specified private
15137     * view flags.
15138     *
15139     * @param privateFlags the private view flags to convert to a string
15140     * @return a String representing the supplied flags
15141     */
15142    private static String printPrivateFlags(int privateFlags) {
15143        String output = "";
15144        int numFlags = 0;
15145
15146        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15147            output += "WANTS_FOCUS";
15148            numFlags++;
15149        }
15150
15151        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15152            if (numFlags > 0) {
15153                output += " ";
15154            }
15155            output += "FOCUSED";
15156            numFlags++;
15157        }
15158
15159        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15160            if (numFlags > 0) {
15161                output += " ";
15162            }
15163            output += "SELECTED";
15164            numFlags++;
15165        }
15166
15167        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15168            if (numFlags > 0) {
15169                output += " ";
15170            }
15171            output += "IS_ROOT_NAMESPACE";
15172            numFlags++;
15173        }
15174
15175        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15176            if (numFlags > 0) {
15177                output += " ";
15178            }
15179            output += "HAS_BOUNDS";
15180            numFlags++;
15181        }
15182
15183        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15184            if (numFlags > 0) {
15185                output += " ";
15186            }
15187            output += "DRAWN";
15188            // USELESS HERE numFlags++;
15189        }
15190        return output;
15191    }
15192
15193    /**
15194     * <p>Indicates whether or not this view's layout will be requested during
15195     * the next hierarchy layout pass.</p>
15196     *
15197     * @return true if the layout will be forced during next layout pass
15198     */
15199    public boolean isLayoutRequested() {
15200        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15201    }
15202
15203    /**
15204     * Return true if o is a ViewGroup that is laying out using optical bounds.
15205     * @hide
15206     */
15207    public static boolean isLayoutModeOptical(Object o) {
15208        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15209    }
15210
15211    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15212        Insets parentInsets = mParent instanceof View ?
15213                ((View) mParent).getOpticalInsets() : Insets.NONE;
15214        Insets childInsets = getOpticalInsets();
15215        return setFrame(
15216                left   + parentInsets.left - childInsets.left,
15217                top    + parentInsets.top  - childInsets.top,
15218                right  + parentInsets.left + childInsets.right,
15219                bottom + parentInsets.top  + childInsets.bottom);
15220    }
15221
15222    /**
15223     * Assign a size and position to a view and all of its
15224     * descendants
15225     *
15226     * <p>This is the second phase of the layout mechanism.
15227     * (The first is measuring). In this phase, each parent calls
15228     * layout on all of its children to position them.
15229     * This is typically done using the child measurements
15230     * that were stored in the measure pass().</p>
15231     *
15232     * <p>Derived classes should not override this method.
15233     * Derived classes with children should override
15234     * onLayout. In that method, they should
15235     * call layout on each of their children.</p>
15236     *
15237     * @param l Left position, relative to parent
15238     * @param t Top position, relative to parent
15239     * @param r Right position, relative to parent
15240     * @param b Bottom position, relative to parent
15241     */
15242    @SuppressWarnings({"unchecked"})
15243    public void layout(int l, int t, int r, int b) {
15244        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15245            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15246            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15247        }
15248
15249        int oldL = mLeft;
15250        int oldT = mTop;
15251        int oldB = mBottom;
15252        int oldR = mRight;
15253
15254        boolean changed = isLayoutModeOptical(mParent) ?
15255                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15256
15257        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15258            onLayout(changed, l, t, r, b);
15259            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15260
15261            ListenerInfo li = mListenerInfo;
15262            if (li != null && li.mOnLayoutChangeListeners != null) {
15263                ArrayList<OnLayoutChangeListener> listenersCopy =
15264                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15265                int numListeners = listenersCopy.size();
15266                for (int i = 0; i < numListeners; ++i) {
15267                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15268                }
15269            }
15270        }
15271
15272        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15273        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15274    }
15275
15276    /**
15277     * Called from layout when this view should
15278     * assign a size and position to each of its children.
15279     *
15280     * Derived classes with children should override
15281     * this method and call layout on each of
15282     * their children.
15283     * @param changed This is a new size or position for this view
15284     * @param left Left position, relative to parent
15285     * @param top Top position, relative to parent
15286     * @param right Right position, relative to parent
15287     * @param bottom Bottom position, relative to parent
15288     */
15289    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15290    }
15291
15292    /**
15293     * Assign a size and position to this view.
15294     *
15295     * This is called from layout.
15296     *
15297     * @param left Left position, relative to parent
15298     * @param top Top position, relative to parent
15299     * @param right Right position, relative to parent
15300     * @param bottom Bottom position, relative to parent
15301     * @return true if the new size and position are different than the
15302     *         previous ones
15303     * {@hide}
15304     */
15305    protected boolean setFrame(int left, int top, int right, int bottom) {
15306        boolean changed = false;
15307
15308        if (DBG) {
15309            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15310                    + right + "," + bottom + ")");
15311        }
15312
15313        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15314            changed = true;
15315
15316            // Remember our drawn bit
15317            int drawn = mPrivateFlags & PFLAG_DRAWN;
15318
15319            int oldWidth = mRight - mLeft;
15320            int oldHeight = mBottom - mTop;
15321            int newWidth = right - left;
15322            int newHeight = bottom - top;
15323            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15324
15325            // Invalidate our old position
15326            invalidate(sizeChanged);
15327
15328            mLeft = left;
15329            mTop = top;
15330            mRight = right;
15331            mBottom = bottom;
15332            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15333
15334            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15335
15336
15337            if (sizeChanged) {
15338                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15339            }
15340
15341            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15342                // If we are visible, force the DRAWN bit to on so that
15343                // this invalidate will go through (at least to our parent).
15344                // This is because someone may have invalidated this view
15345                // before this call to setFrame came in, thereby clearing
15346                // the DRAWN bit.
15347                mPrivateFlags |= PFLAG_DRAWN;
15348                invalidate(sizeChanged);
15349                // parent display list may need to be recreated based on a change in the bounds
15350                // of any child
15351                invalidateParentCaches();
15352            }
15353
15354            // Reset drawn bit to original value (invalidate turns it off)
15355            mPrivateFlags |= drawn;
15356
15357            mBackgroundSizeChanged = true;
15358
15359            notifySubtreeAccessibilityStateChangedIfNeeded();
15360        }
15361        return changed;
15362    }
15363
15364    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15365        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15366        if (mOverlay != null) {
15367            mOverlay.getOverlayView().setRight(newWidth);
15368            mOverlay.getOverlayView().setBottom(newHeight);
15369        }
15370        invalidateOutline();
15371    }
15372
15373    /**
15374     * Finalize inflating a view from XML.  This is called as the last phase
15375     * of inflation, after all child views have been added.
15376     *
15377     * <p>Even if the subclass overrides onFinishInflate, they should always be
15378     * sure to call the super method, so that we get called.
15379     */
15380    protected void onFinishInflate() {
15381    }
15382
15383    /**
15384     * Returns the resources associated with this view.
15385     *
15386     * @return Resources object.
15387     */
15388    public Resources getResources() {
15389        return mResources;
15390    }
15391
15392    /**
15393     * Invalidates the specified Drawable.
15394     *
15395     * @param drawable the drawable to invalidate
15396     */
15397    @Override
15398    public void invalidateDrawable(@NonNull Drawable drawable) {
15399        if (verifyDrawable(drawable)) {
15400            final Rect dirty = drawable.getDirtyBounds();
15401            final int scrollX = mScrollX;
15402            final int scrollY = mScrollY;
15403
15404            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15405                    dirty.right + scrollX, dirty.bottom + scrollY);
15406
15407            invalidateOutline();
15408        }
15409    }
15410
15411    /**
15412     * Schedules an action on a drawable to occur at a specified time.
15413     *
15414     * @param who the recipient of the action
15415     * @param what the action to run on the drawable
15416     * @param when the time at which the action must occur. Uses the
15417     *        {@link SystemClock#uptimeMillis} timebase.
15418     */
15419    @Override
15420    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15421        if (verifyDrawable(who) && what != null) {
15422            final long delay = when - SystemClock.uptimeMillis();
15423            if (mAttachInfo != null) {
15424                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15425                        Choreographer.CALLBACK_ANIMATION, what, who,
15426                        Choreographer.subtractFrameDelay(delay));
15427            } else {
15428                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15429            }
15430        }
15431    }
15432
15433    /**
15434     * Cancels a scheduled action on a drawable.
15435     *
15436     * @param who the recipient of the action
15437     * @param what the action to cancel
15438     */
15439    @Override
15440    public void unscheduleDrawable(Drawable who, Runnable what) {
15441        if (verifyDrawable(who) && what != null) {
15442            if (mAttachInfo != null) {
15443                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15444                        Choreographer.CALLBACK_ANIMATION, what, who);
15445            }
15446            ViewRootImpl.getRunQueue().removeCallbacks(what);
15447        }
15448    }
15449
15450    /**
15451     * Unschedule any events associated with the given Drawable.  This can be
15452     * used when selecting a new Drawable into a view, so that the previous
15453     * one is completely unscheduled.
15454     *
15455     * @param who The Drawable to unschedule.
15456     *
15457     * @see #drawableStateChanged
15458     */
15459    public void unscheduleDrawable(Drawable who) {
15460        if (mAttachInfo != null && who != null) {
15461            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15462                    Choreographer.CALLBACK_ANIMATION, null, who);
15463        }
15464    }
15465
15466    /**
15467     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15468     * that the View directionality can and will be resolved before its Drawables.
15469     *
15470     * Will call {@link View#onResolveDrawables} when resolution is done.
15471     *
15472     * @hide
15473     */
15474    protected void resolveDrawables() {
15475        // Drawables resolution may need to happen before resolving the layout direction (which is
15476        // done only during the measure() call).
15477        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15478        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15479        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15480        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15481        // direction to be resolved as its resolved value will be the same as its raw value.
15482        if (!isLayoutDirectionResolved() &&
15483                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15484            return;
15485        }
15486
15487        final int layoutDirection = isLayoutDirectionResolved() ?
15488                getLayoutDirection() : getRawLayoutDirection();
15489
15490        if (mBackground != null) {
15491            mBackground.setLayoutDirection(layoutDirection);
15492        }
15493        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15494        onResolveDrawables(layoutDirection);
15495    }
15496
15497    /**
15498     * Called when layout direction has been resolved.
15499     *
15500     * The default implementation does nothing.
15501     *
15502     * @param layoutDirection The resolved layout direction.
15503     *
15504     * @see #LAYOUT_DIRECTION_LTR
15505     * @see #LAYOUT_DIRECTION_RTL
15506     *
15507     * @hide
15508     */
15509    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15510    }
15511
15512    /**
15513     * @hide
15514     */
15515    protected void resetResolvedDrawables() {
15516        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15517    }
15518
15519    private boolean isDrawablesResolved() {
15520        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15521    }
15522
15523    /**
15524     * If your view subclass is displaying its own Drawable objects, it should
15525     * override this function and return true for any Drawable it is
15526     * displaying.  This allows animations for those drawables to be
15527     * scheduled.
15528     *
15529     * <p>Be sure to call through to the super class when overriding this
15530     * function.
15531     *
15532     * @param who The Drawable to verify.  Return true if it is one you are
15533     *            displaying, else return the result of calling through to the
15534     *            super class.
15535     *
15536     * @return boolean If true than the Drawable is being displayed in the
15537     *         view; else false and it is not allowed to animate.
15538     *
15539     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15540     * @see #drawableStateChanged()
15541     */
15542    protected boolean verifyDrawable(Drawable who) {
15543        return who == mBackground;
15544    }
15545
15546    /**
15547     * This function is called whenever the state of the view changes in such
15548     * a way that it impacts the state of drawables being shown.
15549     * <p>
15550     * If the View has a StateListAnimator, it will also be called to run necessary state
15551     * change animations.
15552     * <p>
15553     * Be sure to call through to the superclass when overriding this function.
15554     *
15555     * @see Drawable#setState(int[])
15556     */
15557    protected void drawableStateChanged() {
15558        final Drawable d = mBackground;
15559        if (d != null && d.isStateful()) {
15560            d.setState(getDrawableState());
15561        }
15562
15563        if (mStateListAnimator != null) {
15564            mStateListAnimator.setState(getDrawableState());
15565        }
15566    }
15567
15568    /**
15569     * This function is called whenever the view hotspot changes and needs to
15570     * be propagated to drawables managed by the view.
15571     * <p>
15572     * Be sure to call through to the superclass when overriding this function.
15573     *
15574     * @param x hotspot x coordinate
15575     * @param y hotspot y coordinate
15576     */
15577    public void drawableHotspotChanged(float x, float y) {
15578        if (mBackground != null) {
15579            mBackground.setHotspot(x, y);
15580        }
15581    }
15582
15583    /**
15584     * Call this to force a view to update its drawable state. This will cause
15585     * drawableStateChanged to be called on this view. Views that are interested
15586     * in the new state should call getDrawableState.
15587     *
15588     * @see #drawableStateChanged
15589     * @see #getDrawableState
15590     */
15591    public void refreshDrawableState() {
15592        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15593        drawableStateChanged();
15594
15595        ViewParent parent = mParent;
15596        if (parent != null) {
15597            parent.childDrawableStateChanged(this);
15598        }
15599    }
15600
15601    /**
15602     * Return an array of resource IDs of the drawable states representing the
15603     * current state of the view.
15604     *
15605     * @return The current drawable state
15606     *
15607     * @see Drawable#setState(int[])
15608     * @see #drawableStateChanged()
15609     * @see #onCreateDrawableState(int)
15610     */
15611    public final int[] getDrawableState() {
15612        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15613            return mDrawableState;
15614        } else {
15615            mDrawableState = onCreateDrawableState(0);
15616            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15617            return mDrawableState;
15618        }
15619    }
15620
15621    /**
15622     * Generate the new {@link android.graphics.drawable.Drawable} state for
15623     * this view. This is called by the view
15624     * system when the cached Drawable state is determined to be invalid.  To
15625     * retrieve the current state, you should use {@link #getDrawableState}.
15626     *
15627     * @param extraSpace if non-zero, this is the number of extra entries you
15628     * would like in the returned array in which you can place your own
15629     * states.
15630     *
15631     * @return Returns an array holding the current {@link Drawable} state of
15632     * the view.
15633     *
15634     * @see #mergeDrawableStates(int[], int[])
15635     */
15636    protected int[] onCreateDrawableState(int extraSpace) {
15637        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15638                mParent instanceof View) {
15639            return ((View) mParent).onCreateDrawableState(extraSpace);
15640        }
15641
15642        int[] drawableState;
15643
15644        int privateFlags = mPrivateFlags;
15645
15646        int viewStateIndex = 0;
15647        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15648        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15649        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15650        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15651        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15652        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15653        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15654                HardwareRenderer.isAvailable()) {
15655            // This is set if HW acceleration is requested, even if the current
15656            // process doesn't allow it.  This is just to allow app preview
15657            // windows to better match their app.
15658            viewStateIndex |= VIEW_STATE_ACCELERATED;
15659        }
15660        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15661
15662        final int privateFlags2 = mPrivateFlags2;
15663        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15664        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15665
15666        drawableState = VIEW_STATE_SETS[viewStateIndex];
15667
15668        //noinspection ConstantIfStatement
15669        if (false) {
15670            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15671            Log.i("View", toString()
15672                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15673                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15674                    + " fo=" + hasFocus()
15675                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15676                    + " wf=" + hasWindowFocus()
15677                    + ": " + Arrays.toString(drawableState));
15678        }
15679
15680        if (extraSpace == 0) {
15681            return drawableState;
15682        }
15683
15684        final int[] fullState;
15685        if (drawableState != null) {
15686            fullState = new int[drawableState.length + extraSpace];
15687            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15688        } else {
15689            fullState = new int[extraSpace];
15690        }
15691
15692        return fullState;
15693    }
15694
15695    /**
15696     * Merge your own state values in <var>additionalState</var> into the base
15697     * state values <var>baseState</var> that were returned by
15698     * {@link #onCreateDrawableState(int)}.
15699     *
15700     * @param baseState The base state values returned by
15701     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15702     * own additional state values.
15703     *
15704     * @param additionalState The additional state values you would like
15705     * added to <var>baseState</var>; this array is not modified.
15706     *
15707     * @return As a convenience, the <var>baseState</var> array you originally
15708     * passed into the function is returned.
15709     *
15710     * @see #onCreateDrawableState(int)
15711     */
15712    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15713        final int N = baseState.length;
15714        int i = N - 1;
15715        while (i >= 0 && baseState[i] == 0) {
15716            i--;
15717        }
15718        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15719        return baseState;
15720    }
15721
15722    /**
15723     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15724     * on all Drawable objects associated with this view.
15725     * <p>
15726     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15727     * attached to this view.
15728     */
15729    public void jumpDrawablesToCurrentState() {
15730        if (mBackground != null) {
15731            mBackground.jumpToCurrentState();
15732        }
15733        if (mStateListAnimator != null) {
15734            mStateListAnimator.jumpToCurrentState();
15735        }
15736    }
15737
15738    /**
15739     * Sets the background color for this view.
15740     * @param color the color of the background
15741     */
15742    @RemotableViewMethod
15743    public void setBackgroundColor(int color) {
15744        if (mBackground instanceof ColorDrawable) {
15745            ((ColorDrawable) mBackground.mutate()).setColor(color);
15746            computeOpaqueFlags();
15747            mBackgroundResource = 0;
15748        } else {
15749            setBackground(new ColorDrawable(color));
15750        }
15751    }
15752
15753    /**
15754     * Set the background to a given resource. The resource should refer to
15755     * a Drawable object or 0 to remove the background.
15756     * @param resid The identifier of the resource.
15757     *
15758     * @attr ref android.R.styleable#View_background
15759     */
15760    @RemotableViewMethod
15761    public void setBackgroundResource(int resid) {
15762        if (resid != 0 && resid == mBackgroundResource) {
15763            return;
15764        }
15765
15766        Drawable d = null;
15767        if (resid != 0) {
15768            d = mContext.getDrawable(resid);
15769        }
15770        setBackground(d);
15771
15772        mBackgroundResource = resid;
15773    }
15774
15775    /**
15776     * Set the background to a given Drawable, or remove the background. If the
15777     * background has padding, this View's padding is set to the background's
15778     * padding. However, when a background is removed, this View's padding isn't
15779     * touched. If setting the padding is desired, please use
15780     * {@link #setPadding(int, int, int, int)}.
15781     *
15782     * @param background The Drawable to use as the background, or null to remove the
15783     *        background
15784     */
15785    public void setBackground(Drawable background) {
15786        //noinspection deprecation
15787        setBackgroundDrawable(background);
15788    }
15789
15790    /**
15791     * @deprecated use {@link #setBackground(Drawable)} instead
15792     */
15793    @Deprecated
15794    public void setBackgroundDrawable(Drawable background) {
15795        computeOpaqueFlags();
15796
15797        if (background == mBackground) {
15798            return;
15799        }
15800
15801        boolean requestLayout = false;
15802
15803        mBackgroundResource = 0;
15804
15805        /*
15806         * Regardless of whether we're setting a new background or not, we want
15807         * to clear the previous drawable.
15808         */
15809        if (mBackground != null) {
15810            mBackground.setCallback(null);
15811            unscheduleDrawable(mBackground);
15812        }
15813
15814        if (background != null) {
15815            Rect padding = sThreadLocal.get();
15816            if (padding == null) {
15817                padding = new Rect();
15818                sThreadLocal.set(padding);
15819            }
15820            resetResolvedDrawables();
15821            background.setLayoutDirection(getLayoutDirection());
15822            if (background.getPadding(padding)) {
15823                resetResolvedPadding();
15824                switch (background.getLayoutDirection()) {
15825                    case LAYOUT_DIRECTION_RTL:
15826                        mUserPaddingLeftInitial = padding.right;
15827                        mUserPaddingRightInitial = padding.left;
15828                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15829                        break;
15830                    case LAYOUT_DIRECTION_LTR:
15831                    default:
15832                        mUserPaddingLeftInitial = padding.left;
15833                        mUserPaddingRightInitial = padding.right;
15834                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15835                }
15836                mLeftPaddingDefined = false;
15837                mRightPaddingDefined = false;
15838            }
15839
15840            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15841            // if it has a different minimum size, we should layout again
15842            if (mBackground == null
15843                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15844                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15845                requestLayout = true;
15846            }
15847
15848            background.setCallback(this);
15849            if (background.isStateful()) {
15850                background.setState(getDrawableState());
15851            }
15852            background.setVisible(getVisibility() == VISIBLE, false);
15853            mBackground = background;
15854
15855            applyBackgroundTint();
15856
15857            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15858                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15859                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15860                requestLayout = true;
15861            }
15862        } else {
15863            /* Remove the background */
15864            mBackground = null;
15865
15866            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15867                /*
15868                 * This view ONLY drew the background before and we're removing
15869                 * the background, so now it won't draw anything
15870                 * (hence we SKIP_DRAW)
15871                 */
15872                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15873                mPrivateFlags |= PFLAG_SKIP_DRAW;
15874            }
15875
15876            /*
15877             * When the background is set, we try to apply its padding to this
15878             * View. When the background is removed, we don't touch this View's
15879             * padding. This is noted in the Javadocs. Hence, we don't need to
15880             * requestLayout(), the invalidate() below is sufficient.
15881             */
15882
15883            // The old background's minimum size could have affected this
15884            // View's layout, so let's requestLayout
15885            requestLayout = true;
15886        }
15887
15888        computeOpaqueFlags();
15889
15890        if (requestLayout) {
15891            requestLayout();
15892        }
15893
15894        mBackgroundSizeChanged = true;
15895        invalidate(true);
15896    }
15897
15898    /**
15899     * Gets the background drawable
15900     *
15901     * @return The drawable used as the background for this view, if any.
15902     *
15903     * @see #setBackground(Drawable)
15904     *
15905     * @attr ref android.R.styleable#View_background
15906     */
15907    public Drawable getBackground() {
15908        return mBackground;
15909    }
15910
15911    /**
15912     * Applies a tint to the background drawable. Does not modify the current tint
15913     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
15914     * <p>
15915     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
15916     * mutate the drawable and apply the specified tint and tint mode using
15917     * {@link Drawable#setTintList(ColorStateList)}.
15918     *
15919     * @param tint the tint to apply, may be {@code null} to clear tint
15920     *
15921     * @attr ref android.R.styleable#View_backgroundTint
15922     * @see #getBackgroundTintList()
15923     * @see Drawable#setTintList(ColorStateList)
15924     */
15925    public void setBackgroundTintList(@Nullable ColorStateList tint) {
15926        mBackgroundTintList = tint;
15927        mHasBackgroundTint = true;
15928
15929        applyBackgroundTint();
15930    }
15931
15932    /**
15933     * @return the tint applied to the background drawable
15934     * @attr ref android.R.styleable#View_backgroundTint
15935     * @see #setBackgroundTintList(ColorStateList)
15936     */
15937    @Nullable
15938    public ColorStateList getBackgroundTintList() {
15939        return mBackgroundTintList;
15940    }
15941
15942    /**
15943     * Specifies the blending mode used to apply the tint specified by
15944     * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable.
15945     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
15946     *
15947     * @param tintMode the blending mode used to apply the tint, may be
15948     *                 {@code null} to clear tint
15949     * @attr ref android.R.styleable#View_backgroundTintMode
15950     * @see #getBackgroundTintMode()
15951     * @see Drawable#setTintMode(PorterDuff.Mode)
15952     */
15953    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
15954        mBackgroundTintMode = tintMode;
15955
15956        applyBackgroundTint();
15957    }
15958
15959    /**
15960     * @return the blending mode used to apply the tint to the background drawable
15961     * @attr ref android.R.styleable#View_backgroundTintMode
15962     * @see #setBackgroundTintMode(PorterDuff.Mode)
15963     */
15964    @Nullable
15965    public PorterDuff.Mode getBackgroundTintMode() {
15966        return mBackgroundTintMode;
15967    }
15968
15969    private void applyBackgroundTint() {
15970        if (mBackground != null && mHasBackgroundTint) {
15971            mBackground = mBackground.mutate();
15972            mBackground.setTintList(mBackgroundTintList);
15973            mBackground.setTintMode(mBackgroundTintMode);
15974        }
15975    }
15976
15977    /**
15978     * Sets the padding. The view may add on the space required to display
15979     * the scrollbars, depending on the style and visibility of the scrollbars.
15980     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15981     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15982     * from the values set in this call.
15983     *
15984     * @attr ref android.R.styleable#View_padding
15985     * @attr ref android.R.styleable#View_paddingBottom
15986     * @attr ref android.R.styleable#View_paddingLeft
15987     * @attr ref android.R.styleable#View_paddingRight
15988     * @attr ref android.R.styleable#View_paddingTop
15989     * @param left the left padding in pixels
15990     * @param top the top padding in pixels
15991     * @param right the right padding in pixels
15992     * @param bottom the bottom padding in pixels
15993     */
15994    public void setPadding(int left, int top, int right, int bottom) {
15995        resetResolvedPadding();
15996
15997        mUserPaddingStart = UNDEFINED_PADDING;
15998        mUserPaddingEnd = UNDEFINED_PADDING;
15999
16000        mUserPaddingLeftInitial = left;
16001        mUserPaddingRightInitial = right;
16002
16003        mLeftPaddingDefined = true;
16004        mRightPaddingDefined = true;
16005
16006        internalSetPadding(left, top, right, bottom);
16007    }
16008
16009    /**
16010     * @hide
16011     */
16012    protected void internalSetPadding(int left, int top, int right, int bottom) {
16013        mUserPaddingLeft = left;
16014        mUserPaddingRight = right;
16015        mUserPaddingBottom = bottom;
16016
16017        final int viewFlags = mViewFlags;
16018        boolean changed = false;
16019
16020        // Common case is there are no scroll bars.
16021        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16022            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16023                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16024                        ? 0 : getVerticalScrollbarWidth();
16025                switch (mVerticalScrollbarPosition) {
16026                    case SCROLLBAR_POSITION_DEFAULT:
16027                        if (isLayoutRtl()) {
16028                            left += offset;
16029                        } else {
16030                            right += offset;
16031                        }
16032                        break;
16033                    case SCROLLBAR_POSITION_RIGHT:
16034                        right += offset;
16035                        break;
16036                    case SCROLLBAR_POSITION_LEFT:
16037                        left += offset;
16038                        break;
16039                }
16040            }
16041            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16042                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16043                        ? 0 : getHorizontalScrollbarHeight();
16044            }
16045        }
16046
16047        if (mPaddingLeft != left) {
16048            changed = true;
16049            mPaddingLeft = left;
16050        }
16051        if (mPaddingTop != top) {
16052            changed = true;
16053            mPaddingTop = top;
16054        }
16055        if (mPaddingRight != right) {
16056            changed = true;
16057            mPaddingRight = right;
16058        }
16059        if (mPaddingBottom != bottom) {
16060            changed = true;
16061            mPaddingBottom = bottom;
16062        }
16063
16064        if (changed) {
16065            requestLayout();
16066        }
16067    }
16068
16069    /**
16070     * Sets the relative padding. The view may add on the space required to display
16071     * the scrollbars, depending on the style and visibility of the scrollbars.
16072     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16073     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16074     * from the values set in this call.
16075     *
16076     * @attr ref android.R.styleable#View_padding
16077     * @attr ref android.R.styleable#View_paddingBottom
16078     * @attr ref android.R.styleable#View_paddingStart
16079     * @attr ref android.R.styleable#View_paddingEnd
16080     * @attr ref android.R.styleable#View_paddingTop
16081     * @param start the start padding in pixels
16082     * @param top the top padding in pixels
16083     * @param end the end padding in pixels
16084     * @param bottom the bottom padding in pixels
16085     */
16086    public void setPaddingRelative(int start, int top, int end, int bottom) {
16087        resetResolvedPadding();
16088
16089        mUserPaddingStart = start;
16090        mUserPaddingEnd = end;
16091        mLeftPaddingDefined = true;
16092        mRightPaddingDefined = true;
16093
16094        switch(getLayoutDirection()) {
16095            case LAYOUT_DIRECTION_RTL:
16096                mUserPaddingLeftInitial = end;
16097                mUserPaddingRightInitial = start;
16098                internalSetPadding(end, top, start, bottom);
16099                break;
16100            case LAYOUT_DIRECTION_LTR:
16101            default:
16102                mUserPaddingLeftInitial = start;
16103                mUserPaddingRightInitial = end;
16104                internalSetPadding(start, top, end, bottom);
16105        }
16106    }
16107
16108    /**
16109     * Returns the top padding of this view.
16110     *
16111     * @return the top padding in pixels
16112     */
16113    public int getPaddingTop() {
16114        return mPaddingTop;
16115    }
16116
16117    /**
16118     * Returns the bottom padding of this view. If there are inset and enabled
16119     * scrollbars, this value may include the space required to display the
16120     * scrollbars as well.
16121     *
16122     * @return the bottom padding in pixels
16123     */
16124    public int getPaddingBottom() {
16125        return mPaddingBottom;
16126    }
16127
16128    /**
16129     * Returns the left padding of this view. If there are inset and enabled
16130     * scrollbars, this value may include the space required to display the
16131     * scrollbars as well.
16132     *
16133     * @return the left padding in pixels
16134     */
16135    public int getPaddingLeft() {
16136        if (!isPaddingResolved()) {
16137            resolvePadding();
16138        }
16139        return mPaddingLeft;
16140    }
16141
16142    /**
16143     * Returns the start padding of this view depending on its resolved layout direction.
16144     * If there are inset and enabled scrollbars, this value may include the space
16145     * required to display the scrollbars as well.
16146     *
16147     * @return the start padding in pixels
16148     */
16149    public int getPaddingStart() {
16150        if (!isPaddingResolved()) {
16151            resolvePadding();
16152        }
16153        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16154                mPaddingRight : mPaddingLeft;
16155    }
16156
16157    /**
16158     * Returns the right padding of this view. If there are inset and enabled
16159     * scrollbars, this value may include the space required to display the
16160     * scrollbars as well.
16161     *
16162     * @return the right padding in pixels
16163     */
16164    public int getPaddingRight() {
16165        if (!isPaddingResolved()) {
16166            resolvePadding();
16167        }
16168        return mPaddingRight;
16169    }
16170
16171    /**
16172     * Returns the end padding of this view depending on its resolved layout direction.
16173     * If there are inset and enabled scrollbars, this value may include the space
16174     * required to display the scrollbars as well.
16175     *
16176     * @return the end padding in pixels
16177     */
16178    public int getPaddingEnd() {
16179        if (!isPaddingResolved()) {
16180            resolvePadding();
16181        }
16182        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16183                mPaddingLeft : mPaddingRight;
16184    }
16185
16186    /**
16187     * Return if the padding as been set thru relative values
16188     * {@link #setPaddingRelative(int, int, int, int)} or thru
16189     * @attr ref android.R.styleable#View_paddingStart or
16190     * @attr ref android.R.styleable#View_paddingEnd
16191     *
16192     * @return true if the padding is relative or false if it is not.
16193     */
16194    public boolean isPaddingRelative() {
16195        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16196    }
16197
16198    Insets computeOpticalInsets() {
16199        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16200    }
16201
16202    /**
16203     * @hide
16204     */
16205    public void resetPaddingToInitialValues() {
16206        if (isRtlCompatibilityMode()) {
16207            mPaddingLeft = mUserPaddingLeftInitial;
16208            mPaddingRight = mUserPaddingRightInitial;
16209            return;
16210        }
16211        if (isLayoutRtl()) {
16212            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16213            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16214        } else {
16215            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16216            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16217        }
16218    }
16219
16220    /**
16221     * @hide
16222     */
16223    public Insets getOpticalInsets() {
16224        if (mLayoutInsets == null) {
16225            mLayoutInsets = computeOpticalInsets();
16226        }
16227        return mLayoutInsets;
16228    }
16229
16230    /**
16231     * Set this view's optical insets.
16232     *
16233     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16234     * property. Views that compute their own optical insets should call it as part of measurement.
16235     * This method does not request layout. If you are setting optical insets outside of
16236     * measure/layout itself you will want to call requestLayout() yourself.
16237     * </p>
16238     * @hide
16239     */
16240    public void setOpticalInsets(Insets insets) {
16241        mLayoutInsets = insets;
16242    }
16243
16244    /**
16245     * Changes the selection state of this view. A view can be selected or not.
16246     * Note that selection is not the same as focus. Views are typically
16247     * selected in the context of an AdapterView like ListView or GridView;
16248     * the selected view is the view that is highlighted.
16249     *
16250     * @param selected true if the view must be selected, false otherwise
16251     */
16252    public void setSelected(boolean selected) {
16253        //noinspection DoubleNegation
16254        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16255            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16256            if (!selected) resetPressedState();
16257            invalidate(true);
16258            refreshDrawableState();
16259            dispatchSetSelected(selected);
16260            notifyViewAccessibilityStateChangedIfNeeded(
16261                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16262        }
16263    }
16264
16265    /**
16266     * Dispatch setSelected to all of this View's children.
16267     *
16268     * @see #setSelected(boolean)
16269     *
16270     * @param selected The new selected state
16271     */
16272    protected void dispatchSetSelected(boolean selected) {
16273    }
16274
16275    /**
16276     * Indicates the selection state of this view.
16277     *
16278     * @return true if the view is selected, false otherwise
16279     */
16280    @ViewDebug.ExportedProperty
16281    public boolean isSelected() {
16282        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16283    }
16284
16285    /**
16286     * Changes the activated state of this view. A view can be activated or not.
16287     * Note that activation is not the same as selection.  Selection is
16288     * a transient property, representing the view (hierarchy) the user is
16289     * currently interacting with.  Activation is a longer-term state that the
16290     * user can move views in and out of.  For example, in a list view with
16291     * single or multiple selection enabled, the views in the current selection
16292     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16293     * here.)  The activated state is propagated down to children of the view it
16294     * is set on.
16295     *
16296     * @param activated true if the view must be activated, false otherwise
16297     */
16298    public void setActivated(boolean activated) {
16299        //noinspection DoubleNegation
16300        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16301            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16302            invalidate(true);
16303            refreshDrawableState();
16304            dispatchSetActivated(activated);
16305        }
16306    }
16307
16308    /**
16309     * Dispatch setActivated to all of this View's children.
16310     *
16311     * @see #setActivated(boolean)
16312     *
16313     * @param activated The new activated state
16314     */
16315    protected void dispatchSetActivated(boolean activated) {
16316    }
16317
16318    /**
16319     * Indicates the activation state of this view.
16320     *
16321     * @return true if the view is activated, false otherwise
16322     */
16323    @ViewDebug.ExportedProperty
16324    public boolean isActivated() {
16325        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16326    }
16327
16328    /**
16329     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16330     * observer can be used to get notifications when global events, like
16331     * layout, happen.
16332     *
16333     * The returned ViewTreeObserver observer is not guaranteed to remain
16334     * valid for the lifetime of this View. If the caller of this method keeps
16335     * a long-lived reference to ViewTreeObserver, it should always check for
16336     * the return value of {@link ViewTreeObserver#isAlive()}.
16337     *
16338     * @return The ViewTreeObserver for this view's hierarchy.
16339     */
16340    public ViewTreeObserver getViewTreeObserver() {
16341        if (mAttachInfo != null) {
16342            return mAttachInfo.mTreeObserver;
16343        }
16344        if (mFloatingTreeObserver == null) {
16345            mFloatingTreeObserver = new ViewTreeObserver();
16346        }
16347        return mFloatingTreeObserver;
16348    }
16349
16350    /**
16351     * <p>Finds the topmost view in the current view hierarchy.</p>
16352     *
16353     * @return the topmost view containing this view
16354     */
16355    public View getRootView() {
16356        if (mAttachInfo != null) {
16357            final View v = mAttachInfo.mRootView;
16358            if (v != null) {
16359                return v;
16360            }
16361        }
16362
16363        View parent = this;
16364
16365        while (parent.mParent != null && parent.mParent instanceof View) {
16366            parent = (View) parent.mParent;
16367        }
16368
16369        return parent;
16370    }
16371
16372    /**
16373     * Transforms a motion event from view-local coordinates to on-screen
16374     * coordinates.
16375     *
16376     * @param ev the view-local motion event
16377     * @return false if the transformation could not be applied
16378     * @hide
16379     */
16380    public boolean toGlobalMotionEvent(MotionEvent ev) {
16381        final AttachInfo info = mAttachInfo;
16382        if (info == null) {
16383            return false;
16384        }
16385
16386        final Matrix m = info.mTmpMatrix;
16387        m.set(Matrix.IDENTITY_MATRIX);
16388        transformMatrixToGlobal(m);
16389        ev.transform(m);
16390        return true;
16391    }
16392
16393    /**
16394     * Transforms a motion event from on-screen coordinates to view-local
16395     * coordinates.
16396     *
16397     * @param ev the on-screen motion event
16398     * @return false if the transformation could not be applied
16399     * @hide
16400     */
16401    public boolean toLocalMotionEvent(MotionEvent ev) {
16402        final AttachInfo info = mAttachInfo;
16403        if (info == null) {
16404            return false;
16405        }
16406
16407        final Matrix m = info.mTmpMatrix;
16408        m.set(Matrix.IDENTITY_MATRIX);
16409        transformMatrixToLocal(m);
16410        ev.transform(m);
16411        return true;
16412    }
16413
16414    /**
16415     * Modifies the input matrix such that it maps view-local coordinates to
16416     * on-screen coordinates.
16417     *
16418     * @param m input matrix to modify
16419     * @hide
16420     */
16421    public void transformMatrixToGlobal(Matrix m) {
16422        final ViewParent parent = mParent;
16423        if (parent instanceof View) {
16424            final View vp = (View) parent;
16425            vp.transformMatrixToGlobal(m);
16426            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16427        } else if (parent instanceof ViewRootImpl) {
16428            final ViewRootImpl vr = (ViewRootImpl) parent;
16429            vr.transformMatrixToGlobal(m);
16430            m.preTranslate(0, -vr.mCurScrollY);
16431        }
16432
16433        m.preTranslate(mLeft, mTop);
16434
16435        if (!hasIdentityMatrix()) {
16436            m.preConcat(getMatrix());
16437        }
16438    }
16439
16440    /**
16441     * Modifies the input matrix such that it maps on-screen coordinates to
16442     * view-local coordinates.
16443     *
16444     * @param m input matrix to modify
16445     * @hide
16446     */
16447    public void transformMatrixToLocal(Matrix m) {
16448        final ViewParent parent = mParent;
16449        if (parent instanceof View) {
16450            final View vp = (View) parent;
16451            vp.transformMatrixToLocal(m);
16452            m.postTranslate(vp.mScrollX, vp.mScrollY);
16453        } else if (parent instanceof ViewRootImpl) {
16454            final ViewRootImpl vr = (ViewRootImpl) parent;
16455            vr.transformMatrixToLocal(m);
16456            m.postTranslate(0, vr.mCurScrollY);
16457        }
16458
16459        m.postTranslate(-mLeft, -mTop);
16460
16461        if (!hasIdentityMatrix()) {
16462            m.postConcat(getInverseMatrix());
16463        }
16464    }
16465
16466    /**
16467     * @hide
16468     */
16469    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16470            @ViewDebug.IntToString(from = 0, to = "x"),
16471            @ViewDebug.IntToString(from = 1, to = "y")
16472    })
16473    public int[] getLocationOnScreen() {
16474        int[] location = new int[2];
16475        getLocationOnScreen(location);
16476        return location;
16477    }
16478
16479    /**
16480     * <p>Computes the coordinates of this view on the screen. The argument
16481     * must be an array of two integers. After the method returns, the array
16482     * contains the x and y location in that order.</p>
16483     *
16484     * @param location an array of two integers in which to hold the coordinates
16485     */
16486    public void getLocationOnScreen(int[] location) {
16487        getLocationInWindow(location);
16488
16489        final AttachInfo info = mAttachInfo;
16490        if (info != null) {
16491            location[0] += info.mWindowLeft;
16492            location[1] += info.mWindowTop;
16493        }
16494    }
16495
16496    /**
16497     * <p>Computes the coordinates of this view in its window. The argument
16498     * must be an array of two integers. After the method returns, the array
16499     * contains the x and y location in that order.</p>
16500     *
16501     * @param location an array of two integers in which to hold the coordinates
16502     */
16503    public void getLocationInWindow(int[] location) {
16504        if (location == null || location.length < 2) {
16505            throw new IllegalArgumentException("location must be an array of two integers");
16506        }
16507
16508        if (mAttachInfo == null) {
16509            // When the view is not attached to a window, this method does not make sense
16510            location[0] = location[1] = 0;
16511            return;
16512        }
16513
16514        float[] position = mAttachInfo.mTmpTransformLocation;
16515        position[0] = position[1] = 0.0f;
16516
16517        if (!hasIdentityMatrix()) {
16518            getMatrix().mapPoints(position);
16519        }
16520
16521        position[0] += mLeft;
16522        position[1] += mTop;
16523
16524        ViewParent viewParent = mParent;
16525        while (viewParent instanceof View) {
16526            final View view = (View) viewParent;
16527
16528            position[0] -= view.mScrollX;
16529            position[1] -= view.mScrollY;
16530
16531            if (!view.hasIdentityMatrix()) {
16532                view.getMatrix().mapPoints(position);
16533            }
16534
16535            position[0] += view.mLeft;
16536            position[1] += view.mTop;
16537
16538            viewParent = view.mParent;
16539         }
16540
16541        if (viewParent instanceof ViewRootImpl) {
16542            // *cough*
16543            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16544            position[1] -= vr.mCurScrollY;
16545        }
16546
16547        location[0] = (int) (position[0] + 0.5f);
16548        location[1] = (int) (position[1] + 0.5f);
16549    }
16550
16551    /**
16552     * {@hide}
16553     * @param id the id of the view to be found
16554     * @return the view of the specified id, null if cannot be found
16555     */
16556    protected View findViewTraversal(int id) {
16557        if (id == mID) {
16558            return this;
16559        }
16560        return null;
16561    }
16562
16563    /**
16564     * {@hide}
16565     * @param tag the tag of the view to be found
16566     * @return the view of specified tag, null if cannot be found
16567     */
16568    protected View findViewWithTagTraversal(Object tag) {
16569        if (tag != null && tag.equals(mTag)) {
16570            return this;
16571        }
16572        return null;
16573    }
16574
16575    /**
16576     * {@hide}
16577     * @param predicate The predicate to evaluate.
16578     * @param childToSkip If not null, ignores this child during the recursive traversal.
16579     * @return The first view that matches the predicate or null.
16580     */
16581    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16582        if (predicate.apply(this)) {
16583            return this;
16584        }
16585        return null;
16586    }
16587
16588    /**
16589     * Look for a child view with the given id.  If this view has the given
16590     * id, return this view.
16591     *
16592     * @param id The id to search for.
16593     * @return The view that has the given id in the hierarchy or null
16594     */
16595    public final View findViewById(int id) {
16596        if (id < 0) {
16597            return null;
16598        }
16599        return findViewTraversal(id);
16600    }
16601
16602    /**
16603     * Finds a view by its unuque and stable accessibility id.
16604     *
16605     * @param accessibilityId The searched accessibility id.
16606     * @return The found view.
16607     */
16608    final View findViewByAccessibilityId(int accessibilityId) {
16609        if (accessibilityId < 0) {
16610            return null;
16611        }
16612        return findViewByAccessibilityIdTraversal(accessibilityId);
16613    }
16614
16615    /**
16616     * Performs the traversal to find a view by its unuque and stable accessibility id.
16617     *
16618     * <strong>Note:</strong>This method does not stop at the root namespace
16619     * boundary since the user can touch the screen at an arbitrary location
16620     * potentially crossing the root namespace bounday which will send an
16621     * accessibility event to accessibility services and they should be able
16622     * to obtain the event source. Also accessibility ids are guaranteed to be
16623     * unique in the window.
16624     *
16625     * @param accessibilityId The accessibility id.
16626     * @return The found view.
16627     *
16628     * @hide
16629     */
16630    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16631        if (getAccessibilityViewId() == accessibilityId) {
16632            return this;
16633        }
16634        return null;
16635    }
16636
16637    /**
16638     * Look for a child view with the given tag.  If this view has the given
16639     * tag, return this view.
16640     *
16641     * @param tag The tag to search for, using "tag.equals(getTag())".
16642     * @return The View that has the given tag in the hierarchy or null
16643     */
16644    public final View findViewWithTag(Object tag) {
16645        if (tag == null) {
16646            return null;
16647        }
16648        return findViewWithTagTraversal(tag);
16649    }
16650
16651    /**
16652     * {@hide}
16653     * Look for a child view that matches the specified predicate.
16654     * If this view matches the predicate, return this view.
16655     *
16656     * @param predicate The predicate to evaluate.
16657     * @return The first view that matches the predicate or null.
16658     */
16659    public final View findViewByPredicate(Predicate<View> predicate) {
16660        return findViewByPredicateTraversal(predicate, null);
16661    }
16662
16663    /**
16664     * {@hide}
16665     * Look for a child view that matches the specified predicate,
16666     * starting with the specified view and its descendents and then
16667     * recusively searching the ancestors and siblings of that view
16668     * until this view is reached.
16669     *
16670     * This method is useful in cases where the predicate does not match
16671     * a single unique view (perhaps multiple views use the same id)
16672     * and we are trying to find the view that is "closest" in scope to the
16673     * starting view.
16674     *
16675     * @param start The view to start from.
16676     * @param predicate The predicate to evaluate.
16677     * @return The first view that matches the predicate or null.
16678     */
16679    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16680        View childToSkip = null;
16681        for (;;) {
16682            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16683            if (view != null || start == this) {
16684                return view;
16685            }
16686
16687            ViewParent parent = start.getParent();
16688            if (parent == null || !(parent instanceof View)) {
16689                return null;
16690            }
16691
16692            childToSkip = start;
16693            start = (View) parent;
16694        }
16695    }
16696
16697    /**
16698     * Sets the identifier for this view. The identifier does not have to be
16699     * unique in this view's hierarchy. The identifier should be a positive
16700     * number.
16701     *
16702     * @see #NO_ID
16703     * @see #getId()
16704     * @see #findViewById(int)
16705     *
16706     * @param id a number used to identify the view
16707     *
16708     * @attr ref android.R.styleable#View_id
16709     */
16710    public void setId(int id) {
16711        mID = id;
16712        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16713            mID = generateViewId();
16714        }
16715    }
16716
16717    /**
16718     * {@hide}
16719     *
16720     * @param isRoot true if the view belongs to the root namespace, false
16721     *        otherwise
16722     */
16723    public void setIsRootNamespace(boolean isRoot) {
16724        if (isRoot) {
16725            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16726        } else {
16727            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16728        }
16729    }
16730
16731    /**
16732     * {@hide}
16733     *
16734     * @return true if the view belongs to the root namespace, false otherwise
16735     */
16736    public boolean isRootNamespace() {
16737        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16738    }
16739
16740    /**
16741     * Returns this view's identifier.
16742     *
16743     * @return a positive integer used to identify the view or {@link #NO_ID}
16744     *         if the view has no ID
16745     *
16746     * @see #setId(int)
16747     * @see #findViewById(int)
16748     * @attr ref android.R.styleable#View_id
16749     */
16750    @ViewDebug.CapturedViewProperty
16751    public int getId() {
16752        return mID;
16753    }
16754
16755    /**
16756     * Returns this view's tag.
16757     *
16758     * @return the Object stored in this view as a tag, or {@code null} if not
16759     *         set
16760     *
16761     * @see #setTag(Object)
16762     * @see #getTag(int)
16763     */
16764    @ViewDebug.ExportedProperty
16765    public Object getTag() {
16766        return mTag;
16767    }
16768
16769    /**
16770     * Sets the tag associated with this view. A tag can be used to mark
16771     * a view in its hierarchy and does not have to be unique within the
16772     * hierarchy. Tags can also be used to store data within a view without
16773     * resorting to another data structure.
16774     *
16775     * @param tag an Object to tag the view with
16776     *
16777     * @see #getTag()
16778     * @see #setTag(int, Object)
16779     */
16780    public void setTag(final Object tag) {
16781        mTag = tag;
16782    }
16783
16784    /**
16785     * Returns the tag associated with this view and the specified key.
16786     *
16787     * @param key The key identifying the tag
16788     *
16789     * @return the Object stored in this view as a tag, or {@code null} if not
16790     *         set
16791     *
16792     * @see #setTag(int, Object)
16793     * @see #getTag()
16794     */
16795    public Object getTag(int key) {
16796        if (mKeyedTags != null) return mKeyedTags.get(key);
16797        return null;
16798    }
16799
16800    /**
16801     * Sets a tag associated with this view and a key. A tag can be used
16802     * to mark a view in its hierarchy and does not have to be unique within
16803     * the hierarchy. Tags can also be used to store data within a view
16804     * without resorting to another data structure.
16805     *
16806     * The specified key should be an id declared in the resources of the
16807     * application to ensure it is unique (see the <a
16808     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16809     * Keys identified as belonging to
16810     * the Android framework or not associated with any package will cause
16811     * an {@link IllegalArgumentException} to be thrown.
16812     *
16813     * @param key The key identifying the tag
16814     * @param tag An Object to tag the view with
16815     *
16816     * @throws IllegalArgumentException If they specified key is not valid
16817     *
16818     * @see #setTag(Object)
16819     * @see #getTag(int)
16820     */
16821    public void setTag(int key, final Object tag) {
16822        // If the package id is 0x00 or 0x01, it's either an undefined package
16823        // or a framework id
16824        if ((key >>> 24) < 2) {
16825            throw new IllegalArgumentException("The key must be an application-specific "
16826                    + "resource id.");
16827        }
16828
16829        setKeyedTag(key, tag);
16830    }
16831
16832    /**
16833     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16834     * framework id.
16835     *
16836     * @hide
16837     */
16838    public void setTagInternal(int key, Object tag) {
16839        if ((key >>> 24) != 0x1) {
16840            throw new IllegalArgumentException("The key must be a framework-specific "
16841                    + "resource id.");
16842        }
16843
16844        setKeyedTag(key, tag);
16845    }
16846
16847    private void setKeyedTag(int key, Object tag) {
16848        if (mKeyedTags == null) {
16849            mKeyedTags = new SparseArray<Object>(2);
16850        }
16851
16852        mKeyedTags.put(key, tag);
16853    }
16854
16855    /**
16856     * Prints information about this view in the log output, with the tag
16857     * {@link #VIEW_LOG_TAG}.
16858     *
16859     * @hide
16860     */
16861    public void debug() {
16862        debug(0);
16863    }
16864
16865    /**
16866     * Prints information about this view in the log output, with the tag
16867     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16868     * indentation defined by the <code>depth</code>.
16869     *
16870     * @param depth the indentation level
16871     *
16872     * @hide
16873     */
16874    protected void debug(int depth) {
16875        String output = debugIndent(depth - 1);
16876
16877        output += "+ " + this;
16878        int id = getId();
16879        if (id != -1) {
16880            output += " (id=" + id + ")";
16881        }
16882        Object tag = getTag();
16883        if (tag != null) {
16884            output += " (tag=" + tag + ")";
16885        }
16886        Log.d(VIEW_LOG_TAG, output);
16887
16888        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16889            output = debugIndent(depth) + " FOCUSED";
16890            Log.d(VIEW_LOG_TAG, output);
16891        }
16892
16893        output = debugIndent(depth);
16894        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16895                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16896                + "} ";
16897        Log.d(VIEW_LOG_TAG, output);
16898
16899        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16900                || mPaddingBottom != 0) {
16901            output = debugIndent(depth);
16902            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16903                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16904            Log.d(VIEW_LOG_TAG, output);
16905        }
16906
16907        output = debugIndent(depth);
16908        output += "mMeasureWidth=" + mMeasuredWidth +
16909                " mMeasureHeight=" + mMeasuredHeight;
16910        Log.d(VIEW_LOG_TAG, output);
16911
16912        output = debugIndent(depth);
16913        if (mLayoutParams == null) {
16914            output += "BAD! no layout params";
16915        } else {
16916            output = mLayoutParams.debug(output);
16917        }
16918        Log.d(VIEW_LOG_TAG, output);
16919
16920        output = debugIndent(depth);
16921        output += "flags={";
16922        output += View.printFlags(mViewFlags);
16923        output += "}";
16924        Log.d(VIEW_LOG_TAG, output);
16925
16926        output = debugIndent(depth);
16927        output += "privateFlags={";
16928        output += View.printPrivateFlags(mPrivateFlags);
16929        output += "}";
16930        Log.d(VIEW_LOG_TAG, output);
16931    }
16932
16933    /**
16934     * Creates a string of whitespaces used for indentation.
16935     *
16936     * @param depth the indentation level
16937     * @return a String containing (depth * 2 + 3) * 2 white spaces
16938     *
16939     * @hide
16940     */
16941    protected static String debugIndent(int depth) {
16942        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16943        for (int i = 0; i < (depth * 2) + 3; i++) {
16944            spaces.append(' ').append(' ');
16945        }
16946        return spaces.toString();
16947    }
16948
16949    /**
16950     * <p>Return the offset of the widget's text baseline from the widget's top
16951     * boundary. If this widget does not support baseline alignment, this
16952     * method returns -1. </p>
16953     *
16954     * @return the offset of the baseline within the widget's bounds or -1
16955     *         if baseline alignment is not supported
16956     */
16957    @ViewDebug.ExportedProperty(category = "layout")
16958    public int getBaseline() {
16959        return -1;
16960    }
16961
16962    /**
16963     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16964     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16965     * a layout pass.
16966     *
16967     * @return whether the view hierarchy is currently undergoing a layout pass
16968     */
16969    public boolean isInLayout() {
16970        ViewRootImpl viewRoot = getViewRootImpl();
16971        return (viewRoot != null && viewRoot.isInLayout());
16972    }
16973
16974    /**
16975     * Call this when something has changed which has invalidated the
16976     * layout of this view. This will schedule a layout pass of the view
16977     * tree. This should not be called while the view hierarchy is currently in a layout
16978     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16979     * end of the current layout pass (and then layout will run again) or after the current
16980     * frame is drawn and the next layout occurs.
16981     *
16982     * <p>Subclasses which override this method should call the superclass method to
16983     * handle possible request-during-layout errors correctly.</p>
16984     */
16985    public void requestLayout() {
16986        if (mMeasureCache != null) mMeasureCache.clear();
16987
16988        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16989            // Only trigger request-during-layout logic if this is the view requesting it,
16990            // not the views in its parent hierarchy
16991            ViewRootImpl viewRoot = getViewRootImpl();
16992            if (viewRoot != null && viewRoot.isInLayout()) {
16993                if (!viewRoot.requestLayoutDuringLayout(this)) {
16994                    return;
16995                }
16996            }
16997            mAttachInfo.mViewRequestingLayout = this;
16998        }
16999
17000        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17001        mPrivateFlags |= PFLAG_INVALIDATED;
17002
17003        if (mParent != null && !mParent.isLayoutRequested()) {
17004            mParent.requestLayout();
17005        }
17006        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17007            mAttachInfo.mViewRequestingLayout = null;
17008        }
17009    }
17010
17011    /**
17012     * Forces this view to be laid out during the next layout pass.
17013     * This method does not call requestLayout() or forceLayout()
17014     * on the parent.
17015     */
17016    public void forceLayout() {
17017        if (mMeasureCache != null) mMeasureCache.clear();
17018
17019        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17020        mPrivateFlags |= PFLAG_INVALIDATED;
17021    }
17022
17023    /**
17024     * <p>
17025     * This is called to find out how big a view should be. The parent
17026     * supplies constraint information in the width and height parameters.
17027     * </p>
17028     *
17029     * <p>
17030     * The actual measurement work of a view is performed in
17031     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17032     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17033     * </p>
17034     *
17035     *
17036     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17037     *        parent
17038     * @param heightMeasureSpec Vertical space requirements as imposed by the
17039     *        parent
17040     *
17041     * @see #onMeasure(int, int)
17042     */
17043    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17044        boolean optical = isLayoutModeOptical(this);
17045        if (optical != isLayoutModeOptical(mParent)) {
17046            Insets insets = getOpticalInsets();
17047            int oWidth  = insets.left + insets.right;
17048            int oHeight = insets.top  + insets.bottom;
17049            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17050            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17051        }
17052
17053        // Suppress sign extension for the low bytes
17054        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17055        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17056
17057        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17058                widthMeasureSpec != mOldWidthMeasureSpec ||
17059                heightMeasureSpec != mOldHeightMeasureSpec) {
17060
17061            // first clears the measured dimension flag
17062            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17063
17064            resolveRtlPropertiesIfNeeded();
17065
17066            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17067                    mMeasureCache.indexOfKey(key);
17068            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17069                // measure ourselves, this should set the measured dimension flag back
17070                onMeasure(widthMeasureSpec, heightMeasureSpec);
17071                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17072            } else {
17073                long value = mMeasureCache.valueAt(cacheIndex);
17074                // Casting a long to int drops the high 32 bits, no mask needed
17075                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17076                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17077            }
17078
17079            // flag not set, setMeasuredDimension() was not invoked, we raise
17080            // an exception to warn the developer
17081            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17082                throw new IllegalStateException("onMeasure() did not set the"
17083                        + " measured dimension by calling"
17084                        + " setMeasuredDimension()");
17085            }
17086
17087            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17088        }
17089
17090        mOldWidthMeasureSpec = widthMeasureSpec;
17091        mOldHeightMeasureSpec = heightMeasureSpec;
17092
17093        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17094                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17095    }
17096
17097    /**
17098     * <p>
17099     * Measure the view and its content to determine the measured width and the
17100     * measured height. This method is invoked by {@link #measure(int, int)} and
17101     * should be overriden by subclasses to provide accurate and efficient
17102     * measurement of their contents.
17103     * </p>
17104     *
17105     * <p>
17106     * <strong>CONTRACT:</strong> When overriding this method, you
17107     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17108     * measured width and height of this view. Failure to do so will trigger an
17109     * <code>IllegalStateException</code>, thrown by
17110     * {@link #measure(int, int)}. Calling the superclass'
17111     * {@link #onMeasure(int, int)} is a valid use.
17112     * </p>
17113     *
17114     * <p>
17115     * The base class implementation of measure defaults to the background size,
17116     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17117     * override {@link #onMeasure(int, int)} to provide better measurements of
17118     * their content.
17119     * </p>
17120     *
17121     * <p>
17122     * If this method is overridden, it is the subclass's responsibility to make
17123     * sure the measured height and width are at least the view's minimum height
17124     * and width ({@link #getSuggestedMinimumHeight()} and
17125     * {@link #getSuggestedMinimumWidth()}).
17126     * </p>
17127     *
17128     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17129     *                         The requirements are encoded with
17130     *                         {@link android.view.View.MeasureSpec}.
17131     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17132     *                         The requirements are encoded with
17133     *                         {@link android.view.View.MeasureSpec}.
17134     *
17135     * @see #getMeasuredWidth()
17136     * @see #getMeasuredHeight()
17137     * @see #setMeasuredDimension(int, int)
17138     * @see #getSuggestedMinimumHeight()
17139     * @see #getSuggestedMinimumWidth()
17140     * @see android.view.View.MeasureSpec#getMode(int)
17141     * @see android.view.View.MeasureSpec#getSize(int)
17142     */
17143    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17144        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17145                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17146    }
17147
17148    /**
17149     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17150     * measured width and measured height. Failing to do so will trigger an
17151     * exception at measurement time.</p>
17152     *
17153     * @param measuredWidth The measured width of this view.  May be a complex
17154     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17155     * {@link #MEASURED_STATE_TOO_SMALL}.
17156     * @param measuredHeight The measured height of this view.  May be a complex
17157     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17158     * {@link #MEASURED_STATE_TOO_SMALL}.
17159     */
17160    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17161        boolean optical = isLayoutModeOptical(this);
17162        if (optical != isLayoutModeOptical(mParent)) {
17163            Insets insets = getOpticalInsets();
17164            int opticalWidth  = insets.left + insets.right;
17165            int opticalHeight = insets.top  + insets.bottom;
17166
17167            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17168            measuredHeight += optical ? opticalHeight : -opticalHeight;
17169        }
17170        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17171    }
17172
17173    /**
17174     * Sets the measured dimension without extra processing for things like optical bounds.
17175     * Useful for reapplying consistent values that have already been cooked with adjustments
17176     * for optical bounds, etc. such as those from the measurement cache.
17177     *
17178     * @param measuredWidth The measured width of this view.  May be a complex
17179     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17180     * {@link #MEASURED_STATE_TOO_SMALL}.
17181     * @param measuredHeight The measured height of this view.  May be a complex
17182     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17183     * {@link #MEASURED_STATE_TOO_SMALL}.
17184     */
17185    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17186        mMeasuredWidth = measuredWidth;
17187        mMeasuredHeight = measuredHeight;
17188
17189        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17190    }
17191
17192    /**
17193     * Merge two states as returned by {@link #getMeasuredState()}.
17194     * @param curState The current state as returned from a view or the result
17195     * of combining multiple views.
17196     * @param newState The new view state to combine.
17197     * @return Returns a new integer reflecting the combination of the two
17198     * states.
17199     */
17200    public static int combineMeasuredStates(int curState, int newState) {
17201        return curState | newState;
17202    }
17203
17204    /**
17205     * Version of {@link #resolveSizeAndState(int, int, int)}
17206     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17207     */
17208    public static int resolveSize(int size, int measureSpec) {
17209        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17210    }
17211
17212    /**
17213     * Utility to reconcile a desired size and state, with constraints imposed
17214     * by a MeasureSpec.  Will take the desired size, unless a different size
17215     * is imposed by the constraints.  The returned value is a compound integer,
17216     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17217     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17218     * size is smaller than the size the view wants to be.
17219     *
17220     * @param size How big the view wants to be
17221     * @param measureSpec Constraints imposed by the parent
17222     * @return Size information bit mask as defined by
17223     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17224     */
17225    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17226        int result = size;
17227        int specMode = MeasureSpec.getMode(measureSpec);
17228        int specSize =  MeasureSpec.getSize(measureSpec);
17229        switch (specMode) {
17230        case MeasureSpec.UNSPECIFIED:
17231            result = size;
17232            break;
17233        case MeasureSpec.AT_MOST:
17234            if (specSize < size) {
17235                result = specSize | MEASURED_STATE_TOO_SMALL;
17236            } else {
17237                result = size;
17238            }
17239            break;
17240        case MeasureSpec.EXACTLY:
17241            result = specSize;
17242            break;
17243        }
17244        return result | (childMeasuredState&MEASURED_STATE_MASK);
17245    }
17246
17247    /**
17248     * Utility to return a default size. Uses the supplied size if the
17249     * MeasureSpec imposed no constraints. Will get larger if allowed
17250     * by the MeasureSpec.
17251     *
17252     * @param size Default size for this view
17253     * @param measureSpec Constraints imposed by the parent
17254     * @return The size this view should be.
17255     */
17256    public static int getDefaultSize(int size, int measureSpec) {
17257        int result = size;
17258        int specMode = MeasureSpec.getMode(measureSpec);
17259        int specSize = MeasureSpec.getSize(measureSpec);
17260
17261        switch (specMode) {
17262        case MeasureSpec.UNSPECIFIED:
17263            result = size;
17264            break;
17265        case MeasureSpec.AT_MOST:
17266        case MeasureSpec.EXACTLY:
17267            result = specSize;
17268            break;
17269        }
17270        return result;
17271    }
17272
17273    /**
17274     * Returns the suggested minimum height that the view should use. This
17275     * returns the maximum of the view's minimum height
17276     * and the background's minimum height
17277     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17278     * <p>
17279     * When being used in {@link #onMeasure(int, int)}, the caller should still
17280     * ensure the returned height is within the requirements of the parent.
17281     *
17282     * @return The suggested minimum height of the view.
17283     */
17284    protected int getSuggestedMinimumHeight() {
17285        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17286
17287    }
17288
17289    /**
17290     * Returns the suggested minimum width that the view should use. This
17291     * returns the maximum of the view's minimum width)
17292     * and the background's minimum width
17293     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17294     * <p>
17295     * When being used in {@link #onMeasure(int, int)}, the caller should still
17296     * ensure the returned width is within the requirements of the parent.
17297     *
17298     * @return The suggested minimum width of the view.
17299     */
17300    protected int getSuggestedMinimumWidth() {
17301        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17302    }
17303
17304    /**
17305     * Returns the minimum height of the view.
17306     *
17307     * @return the minimum height the view will try to be.
17308     *
17309     * @see #setMinimumHeight(int)
17310     *
17311     * @attr ref android.R.styleable#View_minHeight
17312     */
17313    public int getMinimumHeight() {
17314        return mMinHeight;
17315    }
17316
17317    /**
17318     * Sets the minimum height of the view. It is not guaranteed the view will
17319     * be able to achieve this minimum height (for example, if its parent layout
17320     * constrains it with less available height).
17321     *
17322     * @param minHeight The minimum height the view will try to be.
17323     *
17324     * @see #getMinimumHeight()
17325     *
17326     * @attr ref android.R.styleable#View_minHeight
17327     */
17328    public void setMinimumHeight(int minHeight) {
17329        mMinHeight = minHeight;
17330        requestLayout();
17331    }
17332
17333    /**
17334     * Returns the minimum width of the view.
17335     *
17336     * @return the minimum width the view will try to be.
17337     *
17338     * @see #setMinimumWidth(int)
17339     *
17340     * @attr ref android.R.styleable#View_minWidth
17341     */
17342    public int getMinimumWidth() {
17343        return mMinWidth;
17344    }
17345
17346    /**
17347     * Sets the minimum width of the view. It is not guaranteed the view will
17348     * be able to achieve this minimum width (for example, if its parent layout
17349     * constrains it with less available width).
17350     *
17351     * @param minWidth The minimum width the view will try to be.
17352     *
17353     * @see #getMinimumWidth()
17354     *
17355     * @attr ref android.R.styleable#View_minWidth
17356     */
17357    public void setMinimumWidth(int minWidth) {
17358        mMinWidth = minWidth;
17359        requestLayout();
17360
17361    }
17362
17363    /**
17364     * Get the animation currently associated with this view.
17365     *
17366     * @return The animation that is currently playing or
17367     *         scheduled to play for this view.
17368     */
17369    public Animation getAnimation() {
17370        return mCurrentAnimation;
17371    }
17372
17373    /**
17374     * Start the specified animation now.
17375     *
17376     * @param animation the animation to start now
17377     */
17378    public void startAnimation(Animation animation) {
17379        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17380        setAnimation(animation);
17381        invalidateParentCaches();
17382        invalidate(true);
17383    }
17384
17385    /**
17386     * Cancels any animations for this view.
17387     */
17388    public void clearAnimation() {
17389        if (mCurrentAnimation != null) {
17390            mCurrentAnimation.detach();
17391        }
17392        mCurrentAnimation = null;
17393        invalidateParentIfNeeded();
17394    }
17395
17396    /**
17397     * Sets the next animation to play for this view.
17398     * If you want the animation to play immediately, use
17399     * {@link #startAnimation(android.view.animation.Animation)} instead.
17400     * This method provides allows fine-grained
17401     * control over the start time and invalidation, but you
17402     * must make sure that 1) the animation has a start time set, and
17403     * 2) the view's parent (which controls animations on its children)
17404     * will be invalidated when the animation is supposed to
17405     * start.
17406     *
17407     * @param animation The next animation, or null.
17408     */
17409    public void setAnimation(Animation animation) {
17410        mCurrentAnimation = animation;
17411
17412        if (animation != null) {
17413            // If the screen is off assume the animation start time is now instead of
17414            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17415            // would cause the animation to start when the screen turns back on
17416            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17417                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17418                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17419            }
17420            animation.reset();
17421        }
17422    }
17423
17424    /**
17425     * Invoked by a parent ViewGroup to notify the start of the animation
17426     * currently associated with this view. If you override this method,
17427     * always call super.onAnimationStart();
17428     *
17429     * @see #setAnimation(android.view.animation.Animation)
17430     * @see #getAnimation()
17431     */
17432    protected void onAnimationStart() {
17433        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17434    }
17435
17436    /**
17437     * Invoked by a parent ViewGroup to notify the end of the animation
17438     * currently associated with this view. If you override this method,
17439     * always call super.onAnimationEnd();
17440     *
17441     * @see #setAnimation(android.view.animation.Animation)
17442     * @see #getAnimation()
17443     */
17444    protected void onAnimationEnd() {
17445        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17446    }
17447
17448    /**
17449     * Invoked if there is a Transform that involves alpha. Subclass that can
17450     * draw themselves with the specified alpha should return true, and then
17451     * respect that alpha when their onDraw() is called. If this returns false
17452     * then the view may be redirected to draw into an offscreen buffer to
17453     * fulfill the request, which will look fine, but may be slower than if the
17454     * subclass handles it internally. The default implementation returns false.
17455     *
17456     * @param alpha The alpha (0..255) to apply to the view's drawing
17457     * @return true if the view can draw with the specified alpha.
17458     */
17459    protected boolean onSetAlpha(int alpha) {
17460        return false;
17461    }
17462
17463    /**
17464     * This is used by the RootView to perform an optimization when
17465     * the view hierarchy contains one or several SurfaceView.
17466     * SurfaceView is always considered transparent, but its children are not,
17467     * therefore all View objects remove themselves from the global transparent
17468     * region (passed as a parameter to this function).
17469     *
17470     * @param region The transparent region for this ViewAncestor (window).
17471     *
17472     * @return Returns true if the effective visibility of the view at this
17473     * point is opaque, regardless of the transparent region; returns false
17474     * if it is possible for underlying windows to be seen behind the view.
17475     *
17476     * {@hide}
17477     */
17478    public boolean gatherTransparentRegion(Region region) {
17479        final AttachInfo attachInfo = mAttachInfo;
17480        if (region != null && attachInfo != null) {
17481            final int pflags = mPrivateFlags;
17482            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17483                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17484                // remove it from the transparent region.
17485                final int[] location = attachInfo.mTransparentLocation;
17486                getLocationInWindow(location);
17487                region.op(location[0], location[1], location[0] + mRight - mLeft,
17488                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17489            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17490                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17491                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17492                // exists, so we remove the background drawable's non-transparent
17493                // parts from this transparent region.
17494                applyDrawableToTransparentRegion(mBackground, region);
17495            }
17496        }
17497        return true;
17498    }
17499
17500    /**
17501     * Play a sound effect for this view.
17502     *
17503     * <p>The framework will play sound effects for some built in actions, such as
17504     * clicking, but you may wish to play these effects in your widget,
17505     * for instance, for internal navigation.
17506     *
17507     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17508     * {@link #isSoundEffectsEnabled()} is true.
17509     *
17510     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17511     */
17512    public void playSoundEffect(int soundConstant) {
17513        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17514            return;
17515        }
17516        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17517    }
17518
17519    /**
17520     * BZZZTT!!1!
17521     *
17522     * <p>Provide haptic feedback to the user for this view.
17523     *
17524     * <p>The framework will provide haptic feedback for some built in actions,
17525     * such as long presses, but you may wish to provide feedback for your
17526     * own widget.
17527     *
17528     * <p>The feedback will only be performed if
17529     * {@link #isHapticFeedbackEnabled()} is true.
17530     *
17531     * @param feedbackConstant One of the constants defined in
17532     * {@link HapticFeedbackConstants}
17533     */
17534    public boolean performHapticFeedback(int feedbackConstant) {
17535        return performHapticFeedback(feedbackConstant, 0);
17536    }
17537
17538    /**
17539     * BZZZTT!!1!
17540     *
17541     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17542     *
17543     * @param feedbackConstant One of the constants defined in
17544     * {@link HapticFeedbackConstants}
17545     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17546     */
17547    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17548        if (mAttachInfo == null) {
17549            return false;
17550        }
17551        //noinspection SimplifiableIfStatement
17552        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17553                && !isHapticFeedbackEnabled()) {
17554            return false;
17555        }
17556        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17557                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17558    }
17559
17560    /**
17561     * Request that the visibility of the status bar or other screen/window
17562     * decorations be changed.
17563     *
17564     * <p>This method is used to put the over device UI into temporary modes
17565     * where the user's attention is focused more on the application content,
17566     * by dimming or hiding surrounding system affordances.  This is typically
17567     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17568     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17569     * to be placed behind the action bar (and with these flags other system
17570     * affordances) so that smooth transitions between hiding and showing them
17571     * can be done.
17572     *
17573     * <p>Two representative examples of the use of system UI visibility is
17574     * implementing a content browsing application (like a magazine reader)
17575     * and a video playing application.
17576     *
17577     * <p>The first code shows a typical implementation of a View in a content
17578     * browsing application.  In this implementation, the application goes
17579     * into a content-oriented mode by hiding the status bar and action bar,
17580     * and putting the navigation elements into lights out mode.  The user can
17581     * then interact with content while in this mode.  Such an application should
17582     * provide an easy way for the user to toggle out of the mode (such as to
17583     * check information in the status bar or access notifications).  In the
17584     * implementation here, this is done simply by tapping on the content.
17585     *
17586     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17587     *      content}
17588     *
17589     * <p>This second code sample shows a typical implementation of a View
17590     * in a video playing application.  In this situation, while the video is
17591     * playing the application would like to go into a complete full-screen mode,
17592     * to use as much of the display as possible for the video.  When in this state
17593     * the user can not interact with the application; the system intercepts
17594     * touching on the screen to pop the UI out of full screen mode.  See
17595     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17596     *
17597     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17598     *      content}
17599     *
17600     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17601     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17602     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17603     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17604     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17605     */
17606    public void setSystemUiVisibility(int visibility) {
17607        if (visibility != mSystemUiVisibility) {
17608            mSystemUiVisibility = visibility;
17609            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17610                mParent.recomputeViewAttributes(this);
17611            }
17612        }
17613    }
17614
17615    /**
17616     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17617     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17618     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17619     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17620     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17621     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17622     */
17623    public int getSystemUiVisibility() {
17624        return mSystemUiVisibility;
17625    }
17626
17627    /**
17628     * Returns the current system UI visibility that is currently set for
17629     * the entire window.  This is the combination of the
17630     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17631     * views in the window.
17632     */
17633    public int getWindowSystemUiVisibility() {
17634        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17635    }
17636
17637    /**
17638     * Override to find out when the window's requested system UI visibility
17639     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17640     * This is different from the callbacks received through
17641     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17642     * in that this is only telling you about the local request of the window,
17643     * not the actual values applied by the system.
17644     */
17645    public void onWindowSystemUiVisibilityChanged(int visible) {
17646    }
17647
17648    /**
17649     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17650     * the view hierarchy.
17651     */
17652    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17653        onWindowSystemUiVisibilityChanged(visible);
17654    }
17655
17656    /**
17657     * Set a listener to receive callbacks when the visibility of the system bar changes.
17658     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17659     */
17660    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17661        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17662        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17663            mParent.recomputeViewAttributes(this);
17664        }
17665    }
17666
17667    /**
17668     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17669     * the view hierarchy.
17670     */
17671    public void dispatchSystemUiVisibilityChanged(int visibility) {
17672        ListenerInfo li = mListenerInfo;
17673        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17674            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17675                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17676        }
17677    }
17678
17679    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17680        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17681        if (val != mSystemUiVisibility) {
17682            setSystemUiVisibility(val);
17683            return true;
17684        }
17685        return false;
17686    }
17687
17688    /** @hide */
17689    public void setDisabledSystemUiVisibility(int flags) {
17690        if (mAttachInfo != null) {
17691            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17692                mAttachInfo.mDisabledSystemUiVisibility = flags;
17693                if (mParent != null) {
17694                    mParent.recomputeViewAttributes(this);
17695                }
17696            }
17697        }
17698    }
17699
17700    /**
17701     * Creates an image that the system displays during the drag and drop
17702     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17703     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17704     * appearance as the given View. The default also positions the center of the drag shadow
17705     * directly under the touch point. If no View is provided (the constructor with no parameters
17706     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17707     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17708     * default is an invisible drag shadow.
17709     * <p>
17710     * You are not required to use the View you provide to the constructor as the basis of the
17711     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17712     * anything you want as the drag shadow.
17713     * </p>
17714     * <p>
17715     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17716     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17717     *  size and position of the drag shadow. It uses this data to construct a
17718     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17719     *  so that your application can draw the shadow image in the Canvas.
17720     * </p>
17721     *
17722     * <div class="special reference">
17723     * <h3>Developer Guides</h3>
17724     * <p>For a guide to implementing drag and drop features, read the
17725     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17726     * </div>
17727     */
17728    public static class DragShadowBuilder {
17729        private final WeakReference<View> mView;
17730
17731        /**
17732         * Constructs a shadow image builder based on a View. By default, the resulting drag
17733         * shadow will have the same appearance and dimensions as the View, with the touch point
17734         * over the center of the View.
17735         * @param view A View. Any View in scope can be used.
17736         */
17737        public DragShadowBuilder(View view) {
17738            mView = new WeakReference<View>(view);
17739        }
17740
17741        /**
17742         * Construct a shadow builder object with no associated View.  This
17743         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17744         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17745         * to supply the drag shadow's dimensions and appearance without
17746         * reference to any View object. If they are not overridden, then the result is an
17747         * invisible drag shadow.
17748         */
17749        public DragShadowBuilder() {
17750            mView = new WeakReference<View>(null);
17751        }
17752
17753        /**
17754         * Returns the View object that had been passed to the
17755         * {@link #View.DragShadowBuilder(View)}
17756         * constructor.  If that View parameter was {@code null} or if the
17757         * {@link #View.DragShadowBuilder()}
17758         * constructor was used to instantiate the builder object, this method will return
17759         * null.
17760         *
17761         * @return The View object associate with this builder object.
17762         */
17763        @SuppressWarnings({"JavadocReference"})
17764        final public View getView() {
17765            return mView.get();
17766        }
17767
17768        /**
17769         * Provides the metrics for the shadow image. These include the dimensions of
17770         * the shadow image, and the point within that shadow that should
17771         * be centered under the touch location while dragging.
17772         * <p>
17773         * The default implementation sets the dimensions of the shadow to be the
17774         * same as the dimensions of the View itself and centers the shadow under
17775         * the touch point.
17776         * </p>
17777         *
17778         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17779         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17780         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17781         * image.
17782         *
17783         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17784         * shadow image that should be underneath the touch point during the drag and drop
17785         * operation. Your application must set {@link android.graphics.Point#x} to the
17786         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17787         */
17788        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17789            final View view = mView.get();
17790            if (view != null) {
17791                shadowSize.set(view.getWidth(), view.getHeight());
17792                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17793            } else {
17794                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17795            }
17796        }
17797
17798        /**
17799         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17800         * based on the dimensions it received from the
17801         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17802         *
17803         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17804         */
17805        public void onDrawShadow(Canvas canvas) {
17806            final View view = mView.get();
17807            if (view != null) {
17808                view.draw(canvas);
17809            } else {
17810                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17811            }
17812        }
17813    }
17814
17815    /**
17816     * Starts a drag and drop operation. When your application calls this method, it passes a
17817     * {@link android.view.View.DragShadowBuilder} object to the system. The
17818     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17819     * to get metrics for the drag shadow, and then calls the object's
17820     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17821     * <p>
17822     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17823     *  drag events to all the View objects in your application that are currently visible. It does
17824     *  this either by calling the View object's drag listener (an implementation of
17825     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17826     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17827     *  Both are passed a {@link android.view.DragEvent} object that has a
17828     *  {@link android.view.DragEvent#getAction()} value of
17829     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17830     * </p>
17831     * <p>
17832     * Your application can invoke startDrag() on any attached View object. The View object does not
17833     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17834     * be related to the View the user selected for dragging.
17835     * </p>
17836     * @param data A {@link android.content.ClipData} object pointing to the data to be
17837     * transferred by the drag and drop operation.
17838     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17839     * drag shadow.
17840     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17841     * drop operation. This Object is put into every DragEvent object sent by the system during the
17842     * current drag.
17843     * <p>
17844     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17845     * to the target Views. For example, it can contain flags that differentiate between a
17846     * a copy operation and a move operation.
17847     * </p>
17848     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17849     * so the parameter should be set to 0.
17850     * @return {@code true} if the method completes successfully, or
17851     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17852     * do a drag, and so no drag operation is in progress.
17853     */
17854    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17855            Object myLocalState, int flags) {
17856        if (ViewDebug.DEBUG_DRAG) {
17857            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17858        }
17859        boolean okay = false;
17860
17861        Point shadowSize = new Point();
17862        Point shadowTouchPoint = new Point();
17863        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17864
17865        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17866                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17867            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17868        }
17869
17870        if (ViewDebug.DEBUG_DRAG) {
17871            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17872                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17873        }
17874        Surface surface = new Surface();
17875        try {
17876            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17877                    flags, shadowSize.x, shadowSize.y, surface);
17878            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17879                    + " surface=" + surface);
17880            if (token != null) {
17881                Canvas canvas = surface.lockCanvas(null);
17882                try {
17883                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17884                    shadowBuilder.onDrawShadow(canvas);
17885                } finally {
17886                    surface.unlockCanvasAndPost(canvas);
17887                }
17888
17889                final ViewRootImpl root = getViewRootImpl();
17890
17891                // Cache the local state object for delivery with DragEvents
17892                root.setLocalDragState(myLocalState);
17893
17894                // repurpose 'shadowSize' for the last touch point
17895                root.getLastTouchPoint(shadowSize);
17896
17897                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17898                        shadowSize.x, shadowSize.y,
17899                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17900                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17901
17902                // Off and running!  Release our local surface instance; the drag
17903                // shadow surface is now managed by the system process.
17904                surface.release();
17905            }
17906        } catch (Exception e) {
17907            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17908            surface.destroy();
17909        }
17910
17911        return okay;
17912    }
17913
17914    /**
17915     * Handles drag events sent by the system following a call to
17916     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17917     *<p>
17918     * When the system calls this method, it passes a
17919     * {@link android.view.DragEvent} object. A call to
17920     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17921     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17922     * operation.
17923     * @param event The {@link android.view.DragEvent} sent by the system.
17924     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17925     * in DragEvent, indicating the type of drag event represented by this object.
17926     * @return {@code true} if the method was successful, otherwise {@code false}.
17927     * <p>
17928     *  The method should return {@code true} in response to an action type of
17929     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17930     *  operation.
17931     * </p>
17932     * <p>
17933     *  The method should also return {@code true} in response to an action type of
17934     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17935     *  {@code false} if it didn't.
17936     * </p>
17937     */
17938    public boolean onDragEvent(DragEvent event) {
17939        return false;
17940    }
17941
17942    /**
17943     * Detects if this View is enabled and has a drag event listener.
17944     * If both are true, then it calls the drag event listener with the
17945     * {@link android.view.DragEvent} it received. If the drag event listener returns
17946     * {@code true}, then dispatchDragEvent() returns {@code true}.
17947     * <p>
17948     * For all other cases, the method calls the
17949     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17950     * method and returns its result.
17951     * </p>
17952     * <p>
17953     * This ensures that a drag event is always consumed, even if the View does not have a drag
17954     * event listener. However, if the View has a listener and the listener returns true, then
17955     * onDragEvent() is not called.
17956     * </p>
17957     */
17958    public boolean dispatchDragEvent(DragEvent event) {
17959        ListenerInfo li = mListenerInfo;
17960        //noinspection SimplifiableIfStatement
17961        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17962                && li.mOnDragListener.onDrag(this, event)) {
17963            return true;
17964        }
17965        return onDragEvent(event);
17966    }
17967
17968    boolean canAcceptDrag() {
17969        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17970    }
17971
17972    /**
17973     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17974     * it is ever exposed at all.
17975     * @hide
17976     */
17977    public void onCloseSystemDialogs(String reason) {
17978    }
17979
17980    /**
17981     * Given a Drawable whose bounds have been set to draw into this view,
17982     * update a Region being computed for
17983     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17984     * that any non-transparent parts of the Drawable are removed from the
17985     * given transparent region.
17986     *
17987     * @param dr The Drawable whose transparency is to be applied to the region.
17988     * @param region A Region holding the current transparency information,
17989     * where any parts of the region that are set are considered to be
17990     * transparent.  On return, this region will be modified to have the
17991     * transparency information reduced by the corresponding parts of the
17992     * Drawable that are not transparent.
17993     * {@hide}
17994     */
17995    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17996        if (DBG) {
17997            Log.i("View", "Getting transparent region for: " + this);
17998        }
17999        final Region r = dr.getTransparentRegion();
18000        final Rect db = dr.getBounds();
18001        final AttachInfo attachInfo = mAttachInfo;
18002        if (r != null && attachInfo != null) {
18003            final int w = getRight()-getLeft();
18004            final int h = getBottom()-getTop();
18005            if (db.left > 0) {
18006                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18007                r.op(0, 0, db.left, h, Region.Op.UNION);
18008            }
18009            if (db.right < w) {
18010                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18011                r.op(db.right, 0, w, h, Region.Op.UNION);
18012            }
18013            if (db.top > 0) {
18014                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18015                r.op(0, 0, w, db.top, Region.Op.UNION);
18016            }
18017            if (db.bottom < h) {
18018                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18019                r.op(0, db.bottom, w, h, Region.Op.UNION);
18020            }
18021            final int[] location = attachInfo.mTransparentLocation;
18022            getLocationInWindow(location);
18023            r.translate(location[0], location[1]);
18024            region.op(r, Region.Op.INTERSECT);
18025        } else {
18026            region.op(db, Region.Op.DIFFERENCE);
18027        }
18028    }
18029
18030    private void checkForLongClick(int delayOffset) {
18031        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18032            mHasPerformedLongPress = false;
18033
18034            if (mPendingCheckForLongPress == null) {
18035                mPendingCheckForLongPress = new CheckForLongPress();
18036            }
18037            mPendingCheckForLongPress.rememberWindowAttachCount();
18038            postDelayed(mPendingCheckForLongPress,
18039                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18040        }
18041    }
18042
18043    /**
18044     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18045     * LayoutInflater} class, which provides a full range of options for view inflation.
18046     *
18047     * @param context The Context object for your activity or application.
18048     * @param resource The resource ID to inflate
18049     * @param root A view group that will be the parent.  Used to properly inflate the
18050     * layout_* parameters.
18051     * @see LayoutInflater
18052     */
18053    public static View inflate(Context context, int resource, ViewGroup root) {
18054        LayoutInflater factory = LayoutInflater.from(context);
18055        return factory.inflate(resource, root);
18056    }
18057
18058    /**
18059     * Scroll the view with standard behavior for scrolling beyond the normal
18060     * content boundaries. Views that call this method should override
18061     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18062     * results of an over-scroll operation.
18063     *
18064     * Views can use this method to handle any touch or fling-based scrolling.
18065     *
18066     * @param deltaX Change in X in pixels
18067     * @param deltaY Change in Y in pixels
18068     * @param scrollX Current X scroll value in pixels before applying deltaX
18069     * @param scrollY Current Y scroll value in pixels before applying deltaY
18070     * @param scrollRangeX Maximum content scroll range along the X axis
18071     * @param scrollRangeY Maximum content scroll range along the Y axis
18072     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18073     *          along the X axis.
18074     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18075     *          along the Y axis.
18076     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18077     * @return true if scrolling was clamped to an over-scroll boundary along either
18078     *          axis, false otherwise.
18079     */
18080    @SuppressWarnings({"UnusedParameters"})
18081    protected boolean overScrollBy(int deltaX, int deltaY,
18082            int scrollX, int scrollY,
18083            int scrollRangeX, int scrollRangeY,
18084            int maxOverScrollX, int maxOverScrollY,
18085            boolean isTouchEvent) {
18086        final int overScrollMode = mOverScrollMode;
18087        final boolean canScrollHorizontal =
18088                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18089        final boolean canScrollVertical =
18090                computeVerticalScrollRange() > computeVerticalScrollExtent();
18091        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18092                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18093        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18094                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18095
18096        int newScrollX = scrollX + deltaX;
18097        if (!overScrollHorizontal) {
18098            maxOverScrollX = 0;
18099        }
18100
18101        int newScrollY = scrollY + deltaY;
18102        if (!overScrollVertical) {
18103            maxOverScrollY = 0;
18104        }
18105
18106        // Clamp values if at the limits and record
18107        final int left = -maxOverScrollX;
18108        final int right = maxOverScrollX + scrollRangeX;
18109        final int top = -maxOverScrollY;
18110        final int bottom = maxOverScrollY + scrollRangeY;
18111
18112        boolean clampedX = false;
18113        if (newScrollX > right) {
18114            newScrollX = right;
18115            clampedX = true;
18116        } else if (newScrollX < left) {
18117            newScrollX = left;
18118            clampedX = true;
18119        }
18120
18121        boolean clampedY = false;
18122        if (newScrollY > bottom) {
18123            newScrollY = bottom;
18124            clampedY = true;
18125        } else if (newScrollY < top) {
18126            newScrollY = top;
18127            clampedY = true;
18128        }
18129
18130        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18131
18132        return clampedX || clampedY;
18133    }
18134
18135    /**
18136     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18137     * respond to the results of an over-scroll operation.
18138     *
18139     * @param scrollX New X scroll value in pixels
18140     * @param scrollY New Y scroll value in pixels
18141     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18142     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18143     */
18144    protected void onOverScrolled(int scrollX, int scrollY,
18145            boolean clampedX, boolean clampedY) {
18146        // Intentionally empty.
18147    }
18148
18149    /**
18150     * Returns the over-scroll mode for this view. The result will be
18151     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18152     * (allow over-scrolling only if the view content is larger than the container),
18153     * or {@link #OVER_SCROLL_NEVER}.
18154     *
18155     * @return This view's over-scroll mode.
18156     */
18157    public int getOverScrollMode() {
18158        return mOverScrollMode;
18159    }
18160
18161    /**
18162     * Set the over-scroll mode for this view. Valid over-scroll modes are
18163     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18164     * (allow over-scrolling only if the view content is larger than the container),
18165     * or {@link #OVER_SCROLL_NEVER}.
18166     *
18167     * Setting the over-scroll mode of a view will have an effect only if the
18168     * view is capable of scrolling.
18169     *
18170     * @param overScrollMode The new over-scroll mode for this view.
18171     */
18172    public void setOverScrollMode(int overScrollMode) {
18173        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18174                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18175                overScrollMode != OVER_SCROLL_NEVER) {
18176            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18177        }
18178        mOverScrollMode = overScrollMode;
18179    }
18180
18181    /**
18182     * Enable or disable nested scrolling for this view.
18183     *
18184     * <p>If this property is set to true the view will be permitted to initiate nested
18185     * scrolling operations with a compatible parent view in the current hierarchy. If this
18186     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18187     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18188     * the nested scroll.</p>
18189     *
18190     * @param enabled true to enable nested scrolling, false to disable
18191     *
18192     * @see #isNestedScrollingEnabled()
18193     */
18194    public void setNestedScrollingEnabled(boolean enabled) {
18195        if (enabled) {
18196            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18197        } else {
18198            stopNestedScroll();
18199            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18200        }
18201    }
18202
18203    /**
18204     * Returns true if nested scrolling is enabled for this view.
18205     *
18206     * <p>If nested scrolling is enabled and this View class implementation supports it,
18207     * this view will act as a nested scrolling child view when applicable, forwarding data
18208     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18209     * parent.</p>
18210     *
18211     * @return true if nested scrolling is enabled
18212     *
18213     * @see #setNestedScrollingEnabled(boolean)
18214     */
18215    public boolean isNestedScrollingEnabled() {
18216        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18217                PFLAG3_NESTED_SCROLLING_ENABLED;
18218    }
18219
18220    /**
18221     * Begin a nestable scroll operation along the given axes.
18222     *
18223     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18224     *
18225     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18226     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18227     * In the case of touch scrolling the nested scroll will be terminated automatically in
18228     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18229     * In the event of programmatic scrolling the caller must explicitly call
18230     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18231     *
18232     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18233     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18234     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18235     *
18236     * <p>At each incremental step of the scroll the caller should invoke
18237     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18238     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18239     * parent at least partially consumed the scroll and the caller should adjust the amount it
18240     * scrolls by.</p>
18241     *
18242     * <p>After applying the remainder of the scroll delta the caller should invoke
18243     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18244     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18245     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18246     * </p>
18247     *
18248     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18249     *             {@link #SCROLL_AXIS_VERTICAL}.
18250     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18251     *         the current gesture.
18252     *
18253     * @see #stopNestedScroll()
18254     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18255     * @see #dispatchNestedScroll(int, int, int, int, int[])
18256     */
18257    public boolean startNestedScroll(int axes) {
18258        if (hasNestedScrollingParent()) {
18259            // Already in progress
18260            return true;
18261        }
18262        if (isNestedScrollingEnabled()) {
18263            ViewParent p = getParent();
18264            View child = this;
18265            while (p != null) {
18266                try {
18267                    if (p.onStartNestedScroll(child, this, axes)) {
18268                        mNestedScrollingParent = p;
18269                        p.onNestedScrollAccepted(child, this, axes);
18270                        return true;
18271                    }
18272                } catch (AbstractMethodError e) {
18273                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18274                            "method onStartNestedScroll", e);
18275                    // Allow the search upward to continue
18276                }
18277                if (p instanceof View) {
18278                    child = (View) p;
18279                }
18280                p = p.getParent();
18281            }
18282        }
18283        return false;
18284    }
18285
18286    /**
18287     * Stop a nested scroll in progress.
18288     *
18289     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18290     *
18291     * @see #startNestedScroll(int)
18292     */
18293    public void stopNestedScroll() {
18294        if (mNestedScrollingParent != null) {
18295            mNestedScrollingParent.onStopNestedScroll(this);
18296            mNestedScrollingParent = null;
18297        }
18298    }
18299
18300    /**
18301     * Returns true if this view has a nested scrolling parent.
18302     *
18303     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18304     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18305     *
18306     * @return whether this view has a nested scrolling parent
18307     */
18308    public boolean hasNestedScrollingParent() {
18309        return mNestedScrollingParent != null;
18310    }
18311
18312    /**
18313     * Dispatch one step of a nested scroll in progress.
18314     *
18315     * <p>Implementations of views that support nested scrolling should call this to report
18316     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18317     * is not currently in progress or nested scrolling is not
18318     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18319     *
18320     * <p>Compatible View implementations should also call
18321     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18322     * consuming a component of the scroll event themselves.</p>
18323     *
18324     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18325     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18326     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18327     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18328     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18329     *                       in local view coordinates of this view from before this operation
18330     *                       to after it completes. View implementations may use this to adjust
18331     *                       expected input coordinate tracking.
18332     * @return true if the event was dispatched, false if it could not be dispatched.
18333     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18334     */
18335    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18336            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18337        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18338            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18339                int startX = 0;
18340                int startY = 0;
18341                if (offsetInWindow != null) {
18342                    getLocationInWindow(offsetInWindow);
18343                    startX = offsetInWindow[0];
18344                    startY = offsetInWindow[1];
18345                }
18346
18347                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18348                        dxUnconsumed, dyUnconsumed);
18349
18350                if (offsetInWindow != null) {
18351                    getLocationInWindow(offsetInWindow);
18352                    offsetInWindow[0] -= startX;
18353                    offsetInWindow[1] -= startY;
18354                }
18355                return true;
18356            } else if (offsetInWindow != null) {
18357                // No motion, no dispatch. Keep offsetInWindow up to date.
18358                offsetInWindow[0] = 0;
18359                offsetInWindow[1] = 0;
18360            }
18361        }
18362        return false;
18363    }
18364
18365    /**
18366     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18367     *
18368     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18369     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18370     * scrolling operation to consume some or all of the scroll operation before the child view
18371     * consumes it.</p>
18372     *
18373     * @param dx Horizontal scroll distance in pixels
18374     * @param dy Vertical scroll distance in pixels
18375     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18376     *                 and consumed[1] the consumed dy.
18377     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18378     *                       in local view coordinates of this view from before this operation
18379     *                       to after it completes. View implementations may use this to adjust
18380     *                       expected input coordinate tracking.
18381     * @return true if the parent consumed some or all of the scroll delta
18382     * @see #dispatchNestedScroll(int, int, int, int, int[])
18383     */
18384    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18385        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18386            if (dx != 0 || dy != 0) {
18387                int startX = 0;
18388                int startY = 0;
18389                if (offsetInWindow != null) {
18390                    getLocationInWindow(offsetInWindow);
18391                    startX = offsetInWindow[0];
18392                    startY = offsetInWindow[1];
18393                }
18394
18395                if (consumed == null) {
18396                    if (mTempNestedScrollConsumed == null) {
18397                        mTempNestedScrollConsumed = new int[2];
18398                    }
18399                    consumed = mTempNestedScrollConsumed;
18400                }
18401                consumed[0] = 0;
18402                consumed[1] = 0;
18403                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18404
18405                if (offsetInWindow != null) {
18406                    getLocationInWindow(offsetInWindow);
18407                    offsetInWindow[0] -= startX;
18408                    offsetInWindow[1] -= startY;
18409                }
18410                return consumed[0] != 0 || consumed[1] != 0;
18411            } else if (offsetInWindow != null) {
18412                offsetInWindow[0] = 0;
18413                offsetInWindow[1] = 0;
18414            }
18415        }
18416        return false;
18417    }
18418
18419    /**
18420     * Dispatch a fling to a nested scrolling parent.
18421     *
18422     * <p>This method should be used to indicate that a nested scrolling child has detected
18423     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18424     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18425     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18426     * along a scrollable axis.</p>
18427     *
18428     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18429     * its own content, it can use this method to delegate the fling to its nested scrolling
18430     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18431     *
18432     * @param velocityX Horizontal fling velocity in pixels per second
18433     * @param velocityY Vertical fling velocity in pixels per second
18434     * @param consumed true if the child consumed the fling, false otherwise
18435     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18436     */
18437    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18438        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18439            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18440        }
18441        return false;
18442    }
18443
18444    /**
18445     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18446     *
18447     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18448     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18449     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18450     * before the child view consumes it. If this method returns <code>true</code>, a nested
18451     * parent view consumed the fling and this view should not scroll as a result.</p>
18452     *
18453     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18454     * the fling at a time. If a parent view consumed the fling this method will return false.
18455     * Custom view implementations should account for this in two ways:</p>
18456     *
18457     * <ul>
18458     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18459     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18460     *     position regardless.</li>
18461     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18462     *     even to settle back to a valid idle position.</li>
18463     * </ul>
18464     *
18465     * <p>Views should also not offer fling velocities to nested parent views along an axis
18466     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18467     * should not offer a horizontal fling velocity to its parents since scrolling along that
18468     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18469     *
18470     * @param velocityX Horizontal fling velocity in pixels per second
18471     * @param velocityY Vertical fling velocity in pixels per second
18472     * @return true if a nested scrolling parent consumed the fling
18473     */
18474    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18475        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18476            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18477        }
18478        return false;
18479    }
18480
18481    /**
18482     * Gets a scale factor that determines the distance the view should scroll
18483     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18484     * @return The vertical scroll scale factor.
18485     * @hide
18486     */
18487    protected float getVerticalScrollFactor() {
18488        if (mVerticalScrollFactor == 0) {
18489            TypedValue outValue = new TypedValue();
18490            if (!mContext.getTheme().resolveAttribute(
18491                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18492                throw new IllegalStateException(
18493                        "Expected theme to define listPreferredItemHeight.");
18494            }
18495            mVerticalScrollFactor = outValue.getDimension(
18496                    mContext.getResources().getDisplayMetrics());
18497        }
18498        return mVerticalScrollFactor;
18499    }
18500
18501    /**
18502     * Gets a scale factor that determines the distance the view should scroll
18503     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18504     * @return The horizontal scroll scale factor.
18505     * @hide
18506     */
18507    protected float getHorizontalScrollFactor() {
18508        // TODO: Should use something else.
18509        return getVerticalScrollFactor();
18510    }
18511
18512    /**
18513     * Return the value specifying the text direction or policy that was set with
18514     * {@link #setTextDirection(int)}.
18515     *
18516     * @return the defined text direction. It can be one of:
18517     *
18518     * {@link #TEXT_DIRECTION_INHERIT},
18519     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18520     * {@link #TEXT_DIRECTION_ANY_RTL},
18521     * {@link #TEXT_DIRECTION_LTR},
18522     * {@link #TEXT_DIRECTION_RTL},
18523     * {@link #TEXT_DIRECTION_LOCALE}
18524     *
18525     * @attr ref android.R.styleable#View_textDirection
18526     *
18527     * @hide
18528     */
18529    @ViewDebug.ExportedProperty(category = "text", mapping = {
18530            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18531            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18532            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18533            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18534            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18535            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18536    })
18537    public int getRawTextDirection() {
18538        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18539    }
18540
18541    /**
18542     * Set the text direction.
18543     *
18544     * @param textDirection the direction to set. Should be one of:
18545     *
18546     * {@link #TEXT_DIRECTION_INHERIT},
18547     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18548     * {@link #TEXT_DIRECTION_ANY_RTL},
18549     * {@link #TEXT_DIRECTION_LTR},
18550     * {@link #TEXT_DIRECTION_RTL},
18551     * {@link #TEXT_DIRECTION_LOCALE}
18552     *
18553     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18554     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18555     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18556     *
18557     * @attr ref android.R.styleable#View_textDirection
18558     */
18559    public void setTextDirection(int textDirection) {
18560        if (getRawTextDirection() != textDirection) {
18561            // Reset the current text direction and the resolved one
18562            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18563            resetResolvedTextDirection();
18564            // Set the new text direction
18565            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18566            // Do resolution
18567            resolveTextDirection();
18568            // Notify change
18569            onRtlPropertiesChanged(getLayoutDirection());
18570            // Refresh
18571            requestLayout();
18572            invalidate(true);
18573        }
18574    }
18575
18576    /**
18577     * Return the resolved text direction.
18578     *
18579     * @return the resolved text direction. Returns one of:
18580     *
18581     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18582     * {@link #TEXT_DIRECTION_ANY_RTL},
18583     * {@link #TEXT_DIRECTION_LTR},
18584     * {@link #TEXT_DIRECTION_RTL},
18585     * {@link #TEXT_DIRECTION_LOCALE}
18586     *
18587     * @attr ref android.R.styleable#View_textDirection
18588     */
18589    @ViewDebug.ExportedProperty(category = "text", mapping = {
18590            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18591            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18592            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18593            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18594            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18595            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18596    })
18597    public int getTextDirection() {
18598        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18599    }
18600
18601    /**
18602     * Resolve the text direction.
18603     *
18604     * @return true if resolution has been done, false otherwise.
18605     *
18606     * @hide
18607     */
18608    public boolean resolveTextDirection() {
18609        // Reset any previous text direction resolution
18610        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18611
18612        if (hasRtlSupport()) {
18613            // Set resolved text direction flag depending on text direction flag
18614            final int textDirection = getRawTextDirection();
18615            switch(textDirection) {
18616                case TEXT_DIRECTION_INHERIT:
18617                    if (!canResolveTextDirection()) {
18618                        // We cannot do the resolution if there is no parent, so use the default one
18619                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18620                        // Resolution will need to happen again later
18621                        return false;
18622                    }
18623
18624                    // Parent has not yet resolved, so we still return the default
18625                    try {
18626                        if (!mParent.isTextDirectionResolved()) {
18627                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18628                            // Resolution will need to happen again later
18629                            return false;
18630                        }
18631                    } catch (AbstractMethodError e) {
18632                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18633                                " does not fully implement ViewParent", e);
18634                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18635                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18636                        return true;
18637                    }
18638
18639                    // Set current resolved direction to the same value as the parent's one
18640                    int parentResolvedDirection;
18641                    try {
18642                        parentResolvedDirection = mParent.getTextDirection();
18643                    } catch (AbstractMethodError e) {
18644                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18645                                " does not fully implement ViewParent", e);
18646                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18647                    }
18648                    switch (parentResolvedDirection) {
18649                        case TEXT_DIRECTION_FIRST_STRONG:
18650                        case TEXT_DIRECTION_ANY_RTL:
18651                        case TEXT_DIRECTION_LTR:
18652                        case TEXT_DIRECTION_RTL:
18653                        case TEXT_DIRECTION_LOCALE:
18654                            mPrivateFlags2 |=
18655                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18656                            break;
18657                        default:
18658                            // Default resolved direction is "first strong" heuristic
18659                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18660                    }
18661                    break;
18662                case TEXT_DIRECTION_FIRST_STRONG:
18663                case TEXT_DIRECTION_ANY_RTL:
18664                case TEXT_DIRECTION_LTR:
18665                case TEXT_DIRECTION_RTL:
18666                case TEXT_DIRECTION_LOCALE:
18667                    // Resolved direction is the same as text direction
18668                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18669                    break;
18670                default:
18671                    // Default resolved direction is "first strong" heuristic
18672                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18673            }
18674        } else {
18675            // Default resolved direction is "first strong" heuristic
18676            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18677        }
18678
18679        // Set to resolved
18680        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18681        return true;
18682    }
18683
18684    /**
18685     * Check if text direction resolution can be done.
18686     *
18687     * @return true if text direction resolution can be done otherwise return false.
18688     */
18689    public boolean canResolveTextDirection() {
18690        switch (getRawTextDirection()) {
18691            case TEXT_DIRECTION_INHERIT:
18692                if (mParent != null) {
18693                    try {
18694                        return mParent.canResolveTextDirection();
18695                    } catch (AbstractMethodError e) {
18696                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18697                                " does not fully implement ViewParent", e);
18698                    }
18699                }
18700                return false;
18701
18702            default:
18703                return true;
18704        }
18705    }
18706
18707    /**
18708     * Reset resolved text direction. Text direction will be resolved during a call to
18709     * {@link #onMeasure(int, int)}.
18710     *
18711     * @hide
18712     */
18713    public void resetResolvedTextDirection() {
18714        // Reset any previous text direction resolution
18715        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18716        // Set to default value
18717        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18718    }
18719
18720    /**
18721     * @return true if text direction is inherited.
18722     *
18723     * @hide
18724     */
18725    public boolean isTextDirectionInherited() {
18726        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18727    }
18728
18729    /**
18730     * @return true if text direction is resolved.
18731     */
18732    public boolean isTextDirectionResolved() {
18733        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18734    }
18735
18736    /**
18737     * Return the value specifying the text alignment or policy that was set with
18738     * {@link #setTextAlignment(int)}.
18739     *
18740     * @return the defined text alignment. It can be one of:
18741     *
18742     * {@link #TEXT_ALIGNMENT_INHERIT},
18743     * {@link #TEXT_ALIGNMENT_GRAVITY},
18744     * {@link #TEXT_ALIGNMENT_CENTER},
18745     * {@link #TEXT_ALIGNMENT_TEXT_START},
18746     * {@link #TEXT_ALIGNMENT_TEXT_END},
18747     * {@link #TEXT_ALIGNMENT_VIEW_START},
18748     * {@link #TEXT_ALIGNMENT_VIEW_END}
18749     *
18750     * @attr ref android.R.styleable#View_textAlignment
18751     *
18752     * @hide
18753     */
18754    @ViewDebug.ExportedProperty(category = "text", mapping = {
18755            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18756            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18757            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18758            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18759            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18760            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18761            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18762    })
18763    @TextAlignment
18764    public int getRawTextAlignment() {
18765        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18766    }
18767
18768    /**
18769     * Set the text alignment.
18770     *
18771     * @param textAlignment The text alignment to set. Should be one of
18772     *
18773     * {@link #TEXT_ALIGNMENT_INHERIT},
18774     * {@link #TEXT_ALIGNMENT_GRAVITY},
18775     * {@link #TEXT_ALIGNMENT_CENTER},
18776     * {@link #TEXT_ALIGNMENT_TEXT_START},
18777     * {@link #TEXT_ALIGNMENT_TEXT_END},
18778     * {@link #TEXT_ALIGNMENT_VIEW_START},
18779     * {@link #TEXT_ALIGNMENT_VIEW_END}
18780     *
18781     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18782     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18783     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18784     *
18785     * @attr ref android.R.styleable#View_textAlignment
18786     */
18787    public void setTextAlignment(@TextAlignment int textAlignment) {
18788        if (textAlignment != getRawTextAlignment()) {
18789            // Reset the current and resolved text alignment
18790            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18791            resetResolvedTextAlignment();
18792            // Set the new text alignment
18793            mPrivateFlags2 |=
18794                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18795            // Do resolution
18796            resolveTextAlignment();
18797            // Notify change
18798            onRtlPropertiesChanged(getLayoutDirection());
18799            // Refresh
18800            requestLayout();
18801            invalidate(true);
18802        }
18803    }
18804
18805    /**
18806     * Return the resolved text alignment.
18807     *
18808     * @return the resolved text alignment. Returns one of:
18809     *
18810     * {@link #TEXT_ALIGNMENT_GRAVITY},
18811     * {@link #TEXT_ALIGNMENT_CENTER},
18812     * {@link #TEXT_ALIGNMENT_TEXT_START},
18813     * {@link #TEXT_ALIGNMENT_TEXT_END},
18814     * {@link #TEXT_ALIGNMENT_VIEW_START},
18815     * {@link #TEXT_ALIGNMENT_VIEW_END}
18816     *
18817     * @attr ref android.R.styleable#View_textAlignment
18818     */
18819    @ViewDebug.ExportedProperty(category = "text", mapping = {
18820            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18821            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18822            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18823            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18824            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18825            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18826            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18827    })
18828    @TextAlignment
18829    public int getTextAlignment() {
18830        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18831                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18832    }
18833
18834    /**
18835     * Resolve the text alignment.
18836     *
18837     * @return true if resolution has been done, false otherwise.
18838     *
18839     * @hide
18840     */
18841    public boolean resolveTextAlignment() {
18842        // Reset any previous text alignment resolution
18843        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18844
18845        if (hasRtlSupport()) {
18846            // Set resolved text alignment flag depending on text alignment flag
18847            final int textAlignment = getRawTextAlignment();
18848            switch (textAlignment) {
18849                case TEXT_ALIGNMENT_INHERIT:
18850                    // Check if we can resolve the text alignment
18851                    if (!canResolveTextAlignment()) {
18852                        // We cannot do the resolution if there is no parent so use the default
18853                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18854                        // Resolution will need to happen again later
18855                        return false;
18856                    }
18857
18858                    // Parent has not yet resolved, so we still return the default
18859                    try {
18860                        if (!mParent.isTextAlignmentResolved()) {
18861                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18862                            // Resolution will need to happen again later
18863                            return false;
18864                        }
18865                    } catch (AbstractMethodError e) {
18866                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18867                                " does not fully implement ViewParent", e);
18868                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18869                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18870                        return true;
18871                    }
18872
18873                    int parentResolvedTextAlignment;
18874                    try {
18875                        parentResolvedTextAlignment = mParent.getTextAlignment();
18876                    } catch (AbstractMethodError e) {
18877                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18878                                " does not fully implement ViewParent", e);
18879                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18880                    }
18881                    switch (parentResolvedTextAlignment) {
18882                        case TEXT_ALIGNMENT_GRAVITY:
18883                        case TEXT_ALIGNMENT_TEXT_START:
18884                        case TEXT_ALIGNMENT_TEXT_END:
18885                        case TEXT_ALIGNMENT_CENTER:
18886                        case TEXT_ALIGNMENT_VIEW_START:
18887                        case TEXT_ALIGNMENT_VIEW_END:
18888                            // Resolved text alignment is the same as the parent resolved
18889                            // text alignment
18890                            mPrivateFlags2 |=
18891                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18892                            break;
18893                        default:
18894                            // Use default resolved text alignment
18895                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18896                    }
18897                    break;
18898                case TEXT_ALIGNMENT_GRAVITY:
18899                case TEXT_ALIGNMENT_TEXT_START:
18900                case TEXT_ALIGNMENT_TEXT_END:
18901                case TEXT_ALIGNMENT_CENTER:
18902                case TEXT_ALIGNMENT_VIEW_START:
18903                case TEXT_ALIGNMENT_VIEW_END:
18904                    // Resolved text alignment is the same as text alignment
18905                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18906                    break;
18907                default:
18908                    // Use default resolved text alignment
18909                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18910            }
18911        } else {
18912            // Use default resolved text alignment
18913            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18914        }
18915
18916        // Set the resolved
18917        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18918        return true;
18919    }
18920
18921    /**
18922     * Check if text alignment resolution can be done.
18923     *
18924     * @return true if text alignment resolution can be done otherwise return false.
18925     */
18926    public boolean canResolveTextAlignment() {
18927        switch (getRawTextAlignment()) {
18928            case TEXT_DIRECTION_INHERIT:
18929                if (mParent != null) {
18930                    try {
18931                        return mParent.canResolveTextAlignment();
18932                    } catch (AbstractMethodError e) {
18933                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18934                                " does not fully implement ViewParent", e);
18935                    }
18936                }
18937                return false;
18938
18939            default:
18940                return true;
18941        }
18942    }
18943
18944    /**
18945     * Reset resolved text alignment. Text alignment will be resolved during a call to
18946     * {@link #onMeasure(int, int)}.
18947     *
18948     * @hide
18949     */
18950    public void resetResolvedTextAlignment() {
18951        // Reset any previous text alignment resolution
18952        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18953        // Set to default
18954        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18955    }
18956
18957    /**
18958     * @return true if text alignment is inherited.
18959     *
18960     * @hide
18961     */
18962    public boolean isTextAlignmentInherited() {
18963        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18964    }
18965
18966    /**
18967     * @return true if text alignment is resolved.
18968     */
18969    public boolean isTextAlignmentResolved() {
18970        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18971    }
18972
18973    /**
18974     * Generate a value suitable for use in {@link #setId(int)}.
18975     * This value will not collide with ID values generated at build time by aapt for R.id.
18976     *
18977     * @return a generated ID value
18978     */
18979    public static int generateViewId() {
18980        for (;;) {
18981            final int result = sNextGeneratedId.get();
18982            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18983            int newValue = result + 1;
18984            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18985            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18986                return result;
18987            }
18988        }
18989    }
18990
18991    /**
18992     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18993     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18994     *                           a normal View or a ViewGroup with
18995     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18996     * @hide
18997     */
18998    public void captureTransitioningViews(List<View> transitioningViews) {
18999        if (getVisibility() == View.VISIBLE) {
19000            transitioningViews.add(this);
19001        }
19002    }
19003
19004    /**
19005     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19006     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19007     * @hide
19008     */
19009    public void findNamedViews(Map<String, View> namedElements) {
19010        if (getVisibility() == VISIBLE || mGhostView != null) {
19011            String transitionName = getTransitionName();
19012            if (transitionName != null) {
19013                namedElements.put(transitionName, this);
19014            }
19015        }
19016    }
19017
19018    //
19019    // Properties
19020    //
19021    /**
19022     * A Property wrapper around the <code>alpha</code> functionality handled by the
19023     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19024     */
19025    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19026        @Override
19027        public void setValue(View object, float value) {
19028            object.setAlpha(value);
19029        }
19030
19031        @Override
19032        public Float get(View object) {
19033            return object.getAlpha();
19034        }
19035    };
19036
19037    /**
19038     * A Property wrapper around the <code>translationX</code> functionality handled by the
19039     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19040     */
19041    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19042        @Override
19043        public void setValue(View object, float value) {
19044            object.setTranslationX(value);
19045        }
19046
19047                @Override
19048        public Float get(View object) {
19049            return object.getTranslationX();
19050        }
19051    };
19052
19053    /**
19054     * A Property wrapper around the <code>translationY</code> functionality handled by the
19055     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19056     */
19057    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19058        @Override
19059        public void setValue(View object, float value) {
19060            object.setTranslationY(value);
19061        }
19062
19063        @Override
19064        public Float get(View object) {
19065            return object.getTranslationY();
19066        }
19067    };
19068
19069    /**
19070     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19071     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19072     */
19073    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19074        @Override
19075        public void setValue(View object, float value) {
19076            object.setTranslationZ(value);
19077        }
19078
19079        @Override
19080        public Float get(View object) {
19081            return object.getTranslationZ();
19082        }
19083    };
19084
19085    /**
19086     * A Property wrapper around the <code>x</code> functionality handled by the
19087     * {@link View#setX(float)} and {@link View#getX()} methods.
19088     */
19089    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19090        @Override
19091        public void setValue(View object, float value) {
19092            object.setX(value);
19093        }
19094
19095        @Override
19096        public Float get(View object) {
19097            return object.getX();
19098        }
19099    };
19100
19101    /**
19102     * A Property wrapper around the <code>y</code> functionality handled by the
19103     * {@link View#setY(float)} and {@link View#getY()} methods.
19104     */
19105    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19106        @Override
19107        public void setValue(View object, float value) {
19108            object.setY(value);
19109        }
19110
19111        @Override
19112        public Float get(View object) {
19113            return object.getY();
19114        }
19115    };
19116
19117    /**
19118     * A Property wrapper around the <code>z</code> functionality handled by the
19119     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19120     */
19121    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19122        @Override
19123        public void setValue(View object, float value) {
19124            object.setZ(value);
19125        }
19126
19127        @Override
19128        public Float get(View object) {
19129            return object.getZ();
19130        }
19131    };
19132
19133    /**
19134     * A Property wrapper around the <code>rotation</code> functionality handled by the
19135     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19136     */
19137    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19138        @Override
19139        public void setValue(View object, float value) {
19140            object.setRotation(value);
19141        }
19142
19143        @Override
19144        public Float get(View object) {
19145            return object.getRotation();
19146        }
19147    };
19148
19149    /**
19150     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19151     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19152     */
19153    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19154        @Override
19155        public void setValue(View object, float value) {
19156            object.setRotationX(value);
19157        }
19158
19159        @Override
19160        public Float get(View object) {
19161            return object.getRotationX();
19162        }
19163    };
19164
19165    /**
19166     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19167     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19168     */
19169    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19170        @Override
19171        public void setValue(View object, float value) {
19172            object.setRotationY(value);
19173        }
19174
19175        @Override
19176        public Float get(View object) {
19177            return object.getRotationY();
19178        }
19179    };
19180
19181    /**
19182     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19183     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19184     */
19185    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19186        @Override
19187        public void setValue(View object, float value) {
19188            object.setScaleX(value);
19189        }
19190
19191        @Override
19192        public Float get(View object) {
19193            return object.getScaleX();
19194        }
19195    };
19196
19197    /**
19198     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19199     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19200     */
19201    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19202        @Override
19203        public void setValue(View object, float value) {
19204            object.setScaleY(value);
19205        }
19206
19207        @Override
19208        public Float get(View object) {
19209            return object.getScaleY();
19210        }
19211    };
19212
19213    /**
19214     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19215     * Each MeasureSpec represents a requirement for either the width or the height.
19216     * A MeasureSpec is comprised of a size and a mode. There are three possible
19217     * modes:
19218     * <dl>
19219     * <dt>UNSPECIFIED</dt>
19220     * <dd>
19221     * The parent has not imposed any constraint on the child. It can be whatever size
19222     * it wants.
19223     * </dd>
19224     *
19225     * <dt>EXACTLY</dt>
19226     * <dd>
19227     * The parent has determined an exact size for the child. The child is going to be
19228     * given those bounds regardless of how big it wants to be.
19229     * </dd>
19230     *
19231     * <dt>AT_MOST</dt>
19232     * <dd>
19233     * The child can be as large as it wants up to the specified size.
19234     * </dd>
19235     * </dl>
19236     *
19237     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19238     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19239     */
19240    public static class MeasureSpec {
19241        private static final int MODE_SHIFT = 30;
19242        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19243
19244        /**
19245         * Measure specification mode: The parent has not imposed any constraint
19246         * on the child. It can be whatever size it wants.
19247         */
19248        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19249
19250        /**
19251         * Measure specification mode: The parent has determined an exact size
19252         * for the child. The child is going to be given those bounds regardless
19253         * of how big it wants to be.
19254         */
19255        public static final int EXACTLY     = 1 << MODE_SHIFT;
19256
19257        /**
19258         * Measure specification mode: The child can be as large as it wants up
19259         * to the specified size.
19260         */
19261        public static final int AT_MOST     = 2 << MODE_SHIFT;
19262
19263        /**
19264         * Creates a measure specification based on the supplied size and mode.
19265         *
19266         * The mode must always be one of the following:
19267         * <ul>
19268         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19269         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19270         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19271         * </ul>
19272         *
19273         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19274         * implementation was such that the order of arguments did not matter
19275         * and overflow in either value could impact the resulting MeasureSpec.
19276         * {@link android.widget.RelativeLayout} was affected by this bug.
19277         * Apps targeting API levels greater than 17 will get the fixed, more strict
19278         * behavior.</p>
19279         *
19280         * @param size the size of the measure specification
19281         * @param mode the mode of the measure specification
19282         * @return the measure specification based on size and mode
19283         */
19284        public static int makeMeasureSpec(int size, int mode) {
19285            if (sUseBrokenMakeMeasureSpec) {
19286                return size + mode;
19287            } else {
19288                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19289            }
19290        }
19291
19292        /**
19293         * Extracts the mode from the supplied measure specification.
19294         *
19295         * @param measureSpec the measure specification to extract the mode from
19296         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19297         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19298         *         {@link android.view.View.MeasureSpec#EXACTLY}
19299         */
19300        public static int getMode(int measureSpec) {
19301            return (measureSpec & MODE_MASK);
19302        }
19303
19304        /**
19305         * Extracts the size from the supplied measure specification.
19306         *
19307         * @param measureSpec the measure specification to extract the size from
19308         * @return the size in pixels defined in the supplied measure specification
19309         */
19310        public static int getSize(int measureSpec) {
19311            return (measureSpec & ~MODE_MASK);
19312        }
19313
19314        static int adjust(int measureSpec, int delta) {
19315            final int mode = getMode(measureSpec);
19316            if (mode == UNSPECIFIED) {
19317                // No need to adjust size for UNSPECIFIED mode.
19318                return makeMeasureSpec(0, UNSPECIFIED);
19319            }
19320            int size = getSize(measureSpec) + delta;
19321            if (size < 0) {
19322                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19323                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19324                size = 0;
19325            }
19326            return makeMeasureSpec(size, mode);
19327        }
19328
19329        /**
19330         * Returns a String representation of the specified measure
19331         * specification.
19332         *
19333         * @param measureSpec the measure specification to convert to a String
19334         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19335         */
19336        public static String toString(int measureSpec) {
19337            int mode = getMode(measureSpec);
19338            int size = getSize(measureSpec);
19339
19340            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19341
19342            if (mode == UNSPECIFIED)
19343                sb.append("UNSPECIFIED ");
19344            else if (mode == EXACTLY)
19345                sb.append("EXACTLY ");
19346            else if (mode == AT_MOST)
19347                sb.append("AT_MOST ");
19348            else
19349                sb.append(mode).append(" ");
19350
19351            sb.append(size);
19352            return sb.toString();
19353        }
19354    }
19355
19356    private final class CheckForLongPress implements Runnable {
19357        private int mOriginalWindowAttachCount;
19358
19359        @Override
19360        public void run() {
19361            if (isPressed() && (mParent != null)
19362                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19363                if (performLongClick()) {
19364                    mHasPerformedLongPress = true;
19365                }
19366            }
19367        }
19368
19369        public void rememberWindowAttachCount() {
19370            mOriginalWindowAttachCount = mWindowAttachCount;
19371        }
19372    }
19373
19374    private final class CheckForTap implements Runnable {
19375        public float x;
19376        public float y;
19377
19378        @Override
19379        public void run() {
19380            mPrivateFlags &= ~PFLAG_PREPRESSED;
19381            setPressed(true, x, y);
19382            checkForLongClick(ViewConfiguration.getTapTimeout());
19383        }
19384    }
19385
19386    private final class PerformClick implements Runnable {
19387        @Override
19388        public void run() {
19389            performClick();
19390        }
19391    }
19392
19393    /** @hide */
19394    public void hackTurnOffWindowResizeAnim(boolean off) {
19395        mAttachInfo.mTurnOffWindowResizeAnim = off;
19396    }
19397
19398    /**
19399     * This method returns a ViewPropertyAnimator object, which can be used to animate
19400     * specific properties on this View.
19401     *
19402     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19403     */
19404    public ViewPropertyAnimator animate() {
19405        if (mAnimator == null) {
19406            mAnimator = new ViewPropertyAnimator(this);
19407        }
19408        return mAnimator;
19409    }
19410
19411    /**
19412     * Sets the name of the View to be used to identify Views in Transitions.
19413     * Names should be unique in the View hierarchy.
19414     *
19415     * @param transitionName The name of the View to uniquely identify it for Transitions.
19416     */
19417    public final void setTransitionName(String transitionName) {
19418        mTransitionName = transitionName;
19419    }
19420
19421    /**
19422     * Returns the name of the View to be used to identify Views in Transitions.
19423     * Names should be unique in the View hierarchy.
19424     *
19425     * <p>This returns null if the View has not been given a name.</p>
19426     *
19427     * @return The name used of the View to be used to identify Views in Transitions or null
19428     * if no name has been given.
19429     */
19430    @ViewDebug.ExportedProperty
19431    public String getTransitionName() {
19432        return mTransitionName;
19433    }
19434
19435    /**
19436     * Interface definition for a callback to be invoked when a hardware key event is
19437     * dispatched to this view. The callback will be invoked before the key event is
19438     * given to the view. This is only useful for hardware keyboards; a software input
19439     * method has no obligation to trigger this listener.
19440     */
19441    public interface OnKeyListener {
19442        /**
19443         * Called when a hardware key is dispatched to a view. This allows listeners to
19444         * get a chance to respond before the target view.
19445         * <p>Key presses in software keyboards will generally NOT trigger this method,
19446         * although some may elect to do so in some situations. Do not assume a
19447         * software input method has to be key-based; even if it is, it may use key presses
19448         * in a different way than you expect, so there is no way to reliably catch soft
19449         * input key presses.
19450         *
19451         * @param v The view the key has been dispatched to.
19452         * @param keyCode The code for the physical key that was pressed
19453         * @param event The KeyEvent object containing full information about
19454         *        the event.
19455         * @return True if the listener has consumed the event, false otherwise.
19456         */
19457        boolean onKey(View v, int keyCode, KeyEvent event);
19458    }
19459
19460    /**
19461     * Interface definition for a callback to be invoked when a touch event is
19462     * dispatched to this view. The callback will be invoked before the touch
19463     * event is given to the view.
19464     */
19465    public interface OnTouchListener {
19466        /**
19467         * Called when a touch event is dispatched to a view. This allows listeners to
19468         * get a chance to respond before the target view.
19469         *
19470         * @param v The view the touch event has been dispatched to.
19471         * @param event The MotionEvent object containing full information about
19472         *        the event.
19473         * @return True if the listener has consumed the event, false otherwise.
19474         */
19475        boolean onTouch(View v, MotionEvent event);
19476    }
19477
19478    /**
19479     * Interface definition for a callback to be invoked when a hover event is
19480     * dispatched to this view. The callback will be invoked before the hover
19481     * event is given to the view.
19482     */
19483    public interface OnHoverListener {
19484        /**
19485         * Called when a hover event is dispatched to a view. This allows listeners to
19486         * get a chance to respond before the target view.
19487         *
19488         * @param v The view the hover event has been dispatched to.
19489         * @param event The MotionEvent object containing full information about
19490         *        the event.
19491         * @return True if the listener has consumed the event, false otherwise.
19492         */
19493        boolean onHover(View v, MotionEvent event);
19494    }
19495
19496    /**
19497     * Interface definition for a callback to be invoked when a generic motion event is
19498     * dispatched to this view. The callback will be invoked before the generic motion
19499     * event is given to the view.
19500     */
19501    public interface OnGenericMotionListener {
19502        /**
19503         * Called when a generic motion event is dispatched to a view. This allows listeners to
19504         * get a chance to respond before the target view.
19505         *
19506         * @param v The view the generic motion event has been dispatched to.
19507         * @param event The MotionEvent object containing full information about
19508         *        the event.
19509         * @return True if the listener has consumed the event, false otherwise.
19510         */
19511        boolean onGenericMotion(View v, MotionEvent event);
19512    }
19513
19514    /**
19515     * Interface definition for a callback to be invoked when a view has been clicked and held.
19516     */
19517    public interface OnLongClickListener {
19518        /**
19519         * Called when a view has been clicked and held.
19520         *
19521         * @param v The view that was clicked and held.
19522         *
19523         * @return true if the callback consumed the long click, false otherwise.
19524         */
19525        boolean onLongClick(View v);
19526    }
19527
19528    /**
19529     * Interface definition for a callback to be invoked when a drag is being dispatched
19530     * to this view.  The callback will be invoked before the hosting view's own
19531     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19532     * onDrag(event) behavior, it should return 'false' from this callback.
19533     *
19534     * <div class="special reference">
19535     * <h3>Developer Guides</h3>
19536     * <p>For a guide to implementing drag and drop features, read the
19537     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19538     * </div>
19539     */
19540    public interface OnDragListener {
19541        /**
19542         * Called when a drag event is dispatched to a view. This allows listeners
19543         * to get a chance to override base View behavior.
19544         *
19545         * @param v The View that received the drag event.
19546         * @param event The {@link android.view.DragEvent} object for the drag event.
19547         * @return {@code true} if the drag event was handled successfully, or {@code false}
19548         * if the drag event was not handled. Note that {@code false} will trigger the View
19549         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19550         */
19551        boolean onDrag(View v, DragEvent event);
19552    }
19553
19554    /**
19555     * Interface definition for a callback to be invoked when the focus state of
19556     * a view changed.
19557     */
19558    public interface OnFocusChangeListener {
19559        /**
19560         * Called when the focus state of a view has changed.
19561         *
19562         * @param v The view whose state has changed.
19563         * @param hasFocus The new focus state of v.
19564         */
19565        void onFocusChange(View v, boolean hasFocus);
19566    }
19567
19568    /**
19569     * Interface definition for a callback to be invoked when a view is clicked.
19570     */
19571    public interface OnClickListener {
19572        /**
19573         * Called when a view has been clicked.
19574         *
19575         * @param v The view that was clicked.
19576         */
19577        void onClick(View v);
19578    }
19579
19580    /**
19581     * Interface definition for a callback to be invoked when the context menu
19582     * for this view is being built.
19583     */
19584    public interface OnCreateContextMenuListener {
19585        /**
19586         * Called when the context menu for this view is being built. It is not
19587         * safe to hold onto the menu after this method returns.
19588         *
19589         * @param menu The context menu that is being built
19590         * @param v The view for which the context menu is being built
19591         * @param menuInfo Extra information about the item for which the
19592         *            context menu should be shown. This information will vary
19593         *            depending on the class of v.
19594         */
19595        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19596    }
19597
19598    /**
19599     * Interface definition for a callback to be invoked when the status bar changes
19600     * visibility.  This reports <strong>global</strong> changes to the system UI
19601     * state, not what the application is requesting.
19602     *
19603     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19604     */
19605    public interface OnSystemUiVisibilityChangeListener {
19606        /**
19607         * Called when the status bar changes visibility because of a call to
19608         * {@link View#setSystemUiVisibility(int)}.
19609         *
19610         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19611         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19612         * This tells you the <strong>global</strong> state of these UI visibility
19613         * flags, not what your app is currently applying.
19614         */
19615        public void onSystemUiVisibilityChange(int visibility);
19616    }
19617
19618    /**
19619     * Interface definition for a callback to be invoked when this view is attached
19620     * or detached from its window.
19621     */
19622    public interface OnAttachStateChangeListener {
19623        /**
19624         * Called when the view is attached to a window.
19625         * @param v The view that was attached
19626         */
19627        public void onViewAttachedToWindow(View v);
19628        /**
19629         * Called when the view is detached from a window.
19630         * @param v The view that was detached
19631         */
19632        public void onViewDetachedFromWindow(View v);
19633    }
19634
19635    /**
19636     * Listener for applying window insets on a view in a custom way.
19637     *
19638     * <p>Apps may choose to implement this interface if they want to apply custom policy
19639     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19640     * is set, its
19641     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19642     * method will be called instead of the View's own
19643     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19644     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19645     * the View's normal behavior as part of its own.</p>
19646     */
19647    public interface OnApplyWindowInsetsListener {
19648        /**
19649         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19650         * on a View, this listener method will be called instead of the view's own
19651         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19652         *
19653         * @param v The view applying window insets
19654         * @param insets The insets to apply
19655         * @return The insets supplied, minus any insets that were consumed
19656         */
19657        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19658    }
19659
19660    private final class UnsetPressedState implements Runnable {
19661        @Override
19662        public void run() {
19663            setPressed(false);
19664        }
19665    }
19666
19667    /**
19668     * Base class for derived classes that want to save and restore their own
19669     * state in {@link android.view.View#onSaveInstanceState()}.
19670     */
19671    public static class BaseSavedState extends AbsSavedState {
19672        /**
19673         * Constructor used when reading from a parcel. Reads the state of the superclass.
19674         *
19675         * @param source
19676         */
19677        public BaseSavedState(Parcel source) {
19678            super(source);
19679        }
19680
19681        /**
19682         * Constructor called by derived classes when creating their SavedState objects
19683         *
19684         * @param superState The state of the superclass of this view
19685         */
19686        public BaseSavedState(Parcelable superState) {
19687            super(superState);
19688        }
19689
19690        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19691                new Parcelable.Creator<BaseSavedState>() {
19692            public BaseSavedState createFromParcel(Parcel in) {
19693                return new BaseSavedState(in);
19694            }
19695
19696            public BaseSavedState[] newArray(int size) {
19697                return new BaseSavedState[size];
19698            }
19699        };
19700    }
19701
19702    /**
19703     * A set of information given to a view when it is attached to its parent
19704     * window.
19705     */
19706    final static class AttachInfo {
19707        interface Callbacks {
19708            void playSoundEffect(int effectId);
19709            boolean performHapticFeedback(int effectId, boolean always);
19710        }
19711
19712        /**
19713         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19714         * to a Handler. This class contains the target (View) to invalidate and
19715         * the coordinates of the dirty rectangle.
19716         *
19717         * For performance purposes, this class also implements a pool of up to
19718         * POOL_LIMIT objects that get reused. This reduces memory allocations
19719         * whenever possible.
19720         */
19721        static class InvalidateInfo {
19722            private static final int POOL_LIMIT = 10;
19723
19724            private static final SynchronizedPool<InvalidateInfo> sPool =
19725                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19726
19727            View target;
19728
19729            int left;
19730            int top;
19731            int right;
19732            int bottom;
19733
19734            public static InvalidateInfo obtain() {
19735                InvalidateInfo instance = sPool.acquire();
19736                return (instance != null) ? instance : new InvalidateInfo();
19737            }
19738
19739            public void recycle() {
19740                target = null;
19741                sPool.release(this);
19742            }
19743        }
19744
19745        final IWindowSession mSession;
19746
19747        final IWindow mWindow;
19748
19749        final IBinder mWindowToken;
19750
19751        final Display mDisplay;
19752
19753        final Callbacks mRootCallbacks;
19754
19755        IWindowId mIWindowId;
19756        WindowId mWindowId;
19757
19758        /**
19759         * The top view of the hierarchy.
19760         */
19761        View mRootView;
19762
19763        IBinder mPanelParentWindowToken;
19764
19765        boolean mHardwareAccelerated;
19766        boolean mHardwareAccelerationRequested;
19767        HardwareRenderer mHardwareRenderer;
19768
19769        /**
19770         * The state of the display to which the window is attached, as reported
19771         * by {@link Display#getState()}.  Note that the display state constants
19772         * declared by {@link Display} do not exactly line up with the screen state
19773         * constants declared by {@link View} (there are more display states than
19774         * screen states).
19775         */
19776        int mDisplayState = Display.STATE_UNKNOWN;
19777
19778        /**
19779         * Scale factor used by the compatibility mode
19780         */
19781        float mApplicationScale;
19782
19783        /**
19784         * Indicates whether the application is in compatibility mode
19785         */
19786        boolean mScalingRequired;
19787
19788        /**
19789         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19790         */
19791        boolean mTurnOffWindowResizeAnim;
19792
19793        /**
19794         * Left position of this view's window
19795         */
19796        int mWindowLeft;
19797
19798        /**
19799         * Top position of this view's window
19800         */
19801        int mWindowTop;
19802
19803        /**
19804         * Indicates whether views need to use 32-bit drawing caches
19805         */
19806        boolean mUse32BitDrawingCache;
19807
19808        /**
19809         * For windows that are full-screen but using insets to layout inside
19810         * of the screen areas, these are the current insets to appear inside
19811         * the overscan area of the display.
19812         */
19813        final Rect mOverscanInsets = new Rect();
19814
19815        /**
19816         * For windows that are full-screen but using insets to layout inside
19817         * of the screen decorations, these are the current insets for the
19818         * content of the window.
19819         */
19820        final Rect mContentInsets = new Rect();
19821
19822        /**
19823         * For windows that are full-screen but using insets to layout inside
19824         * of the screen decorations, these are the current insets for the
19825         * actual visible parts of the window.
19826         */
19827        final Rect mVisibleInsets = new Rect();
19828
19829        /**
19830         * For windows that are full-screen but using insets to layout inside
19831         * of the screen decorations, these are the current insets for the
19832         * stable system windows.
19833         */
19834        final Rect mStableInsets = new Rect();
19835
19836        /**
19837         * The internal insets given by this window.  This value is
19838         * supplied by the client (through
19839         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19840         * be given to the window manager when changed to be used in laying
19841         * out windows behind it.
19842         */
19843        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19844                = new ViewTreeObserver.InternalInsetsInfo();
19845
19846        /**
19847         * Set to true when mGivenInternalInsets is non-empty.
19848         */
19849        boolean mHasNonEmptyGivenInternalInsets;
19850
19851        /**
19852         * All views in the window's hierarchy that serve as scroll containers,
19853         * used to determine if the window can be resized or must be panned
19854         * to adjust for a soft input area.
19855         */
19856        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19857
19858        final KeyEvent.DispatcherState mKeyDispatchState
19859                = new KeyEvent.DispatcherState();
19860
19861        /**
19862         * Indicates whether the view's window currently has the focus.
19863         */
19864        boolean mHasWindowFocus;
19865
19866        /**
19867         * The current visibility of the window.
19868         */
19869        int mWindowVisibility;
19870
19871        /**
19872         * Indicates the time at which drawing started to occur.
19873         */
19874        long mDrawingTime;
19875
19876        /**
19877         * Indicates whether or not ignoring the DIRTY_MASK flags.
19878         */
19879        boolean mIgnoreDirtyState;
19880
19881        /**
19882         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19883         * to avoid clearing that flag prematurely.
19884         */
19885        boolean mSetIgnoreDirtyState = false;
19886
19887        /**
19888         * Indicates whether the view's window is currently in touch mode.
19889         */
19890        boolean mInTouchMode;
19891
19892        /**
19893         * Indicates whether the view has requested unbuffered input dispatching for the current
19894         * event stream.
19895         */
19896        boolean mUnbufferedDispatchRequested;
19897
19898        /**
19899         * Indicates that ViewAncestor should trigger a global layout change
19900         * the next time it performs a traversal
19901         */
19902        boolean mRecomputeGlobalAttributes;
19903
19904        /**
19905         * Always report new attributes at next traversal.
19906         */
19907        boolean mForceReportNewAttributes;
19908
19909        /**
19910         * Set during a traveral if any views want to keep the screen on.
19911         */
19912        boolean mKeepScreenOn;
19913
19914        /**
19915         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19916         */
19917        int mSystemUiVisibility;
19918
19919        /**
19920         * Hack to force certain system UI visibility flags to be cleared.
19921         */
19922        int mDisabledSystemUiVisibility;
19923
19924        /**
19925         * Last global system UI visibility reported by the window manager.
19926         */
19927        int mGlobalSystemUiVisibility;
19928
19929        /**
19930         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19931         * attached.
19932         */
19933        boolean mHasSystemUiListeners;
19934
19935        /**
19936         * Set if the window has requested to extend into the overscan region
19937         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19938         */
19939        boolean mOverscanRequested;
19940
19941        /**
19942         * Set if the visibility of any views has changed.
19943         */
19944        boolean mViewVisibilityChanged;
19945
19946        /**
19947         * Set to true if a view has been scrolled.
19948         */
19949        boolean mViewScrollChanged;
19950
19951        /**
19952         * Set to true if high contrast mode enabled
19953         */
19954        boolean mHighContrastText;
19955
19956        /**
19957         * Global to the view hierarchy used as a temporary for dealing with
19958         * x/y points in the transparent region computations.
19959         */
19960        final int[] mTransparentLocation = new int[2];
19961
19962        /**
19963         * Global to the view hierarchy used as a temporary for dealing with
19964         * x/y points in the ViewGroup.invalidateChild implementation.
19965         */
19966        final int[] mInvalidateChildLocation = new int[2];
19967
19968        /**
19969         * Global to the view hierarchy used as a temporary for dealng with
19970         * computing absolute on-screen location.
19971         */
19972        final int[] mTmpLocation = new int[2];
19973
19974        /**
19975         * Global to the view hierarchy used as a temporary for dealing with
19976         * x/y location when view is transformed.
19977         */
19978        final float[] mTmpTransformLocation = new float[2];
19979
19980        /**
19981         * The view tree observer used to dispatch global events like
19982         * layout, pre-draw, touch mode change, etc.
19983         */
19984        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19985
19986        /**
19987         * A Canvas used by the view hierarchy to perform bitmap caching.
19988         */
19989        Canvas mCanvas;
19990
19991        /**
19992         * The view root impl.
19993         */
19994        final ViewRootImpl mViewRootImpl;
19995
19996        /**
19997         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19998         * handler can be used to pump events in the UI events queue.
19999         */
20000        final Handler mHandler;
20001
20002        /**
20003         * Temporary for use in computing invalidate rectangles while
20004         * calling up the hierarchy.
20005         */
20006        final Rect mTmpInvalRect = new Rect();
20007
20008        /**
20009         * Temporary for use in computing hit areas with transformed views
20010         */
20011        final RectF mTmpTransformRect = new RectF();
20012
20013        /**
20014         * Temporary for use in transforming invalidation rect
20015         */
20016        final Matrix mTmpMatrix = new Matrix();
20017
20018        /**
20019         * Temporary for use in transforming invalidation rect
20020         */
20021        final Transformation mTmpTransformation = new Transformation();
20022
20023        /**
20024         * Temporary for use in querying outlines from OutlineProviders
20025         */
20026        final Outline mTmpOutline = new Outline();
20027
20028        /**
20029         * Temporary list for use in collecting focusable descendents of a view.
20030         */
20031        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20032
20033        /**
20034         * The id of the window for accessibility purposes.
20035         */
20036        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20037
20038        /**
20039         * Flags related to accessibility processing.
20040         *
20041         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20042         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20043         */
20044        int mAccessibilityFetchFlags;
20045
20046        /**
20047         * The drawable for highlighting accessibility focus.
20048         */
20049        Drawable mAccessibilityFocusDrawable;
20050
20051        /**
20052         * Show where the margins, bounds and layout bounds are for each view.
20053         */
20054        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20055
20056        /**
20057         * Point used to compute visible regions.
20058         */
20059        final Point mPoint = new Point();
20060
20061        /**
20062         * Used to track which View originated a requestLayout() call, used when
20063         * requestLayout() is called during layout.
20064         */
20065        View mViewRequestingLayout;
20066
20067        /**
20068         * Creates a new set of attachment information with the specified
20069         * events handler and thread.
20070         *
20071         * @param handler the events handler the view must use
20072         */
20073        AttachInfo(IWindowSession session, IWindow window, Display display,
20074                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20075            mSession = session;
20076            mWindow = window;
20077            mWindowToken = window.asBinder();
20078            mDisplay = display;
20079            mViewRootImpl = viewRootImpl;
20080            mHandler = handler;
20081            mRootCallbacks = effectPlayer;
20082        }
20083    }
20084
20085    /**
20086     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20087     * is supported. This avoids keeping too many unused fields in most
20088     * instances of View.</p>
20089     */
20090    private static class ScrollabilityCache implements Runnable {
20091
20092        /**
20093         * Scrollbars are not visible
20094         */
20095        public static final int OFF = 0;
20096
20097        /**
20098         * Scrollbars are visible
20099         */
20100        public static final int ON = 1;
20101
20102        /**
20103         * Scrollbars are fading away
20104         */
20105        public static final int FADING = 2;
20106
20107        public boolean fadeScrollBars;
20108
20109        public int fadingEdgeLength;
20110        public int scrollBarDefaultDelayBeforeFade;
20111        public int scrollBarFadeDuration;
20112
20113        public int scrollBarSize;
20114        public ScrollBarDrawable scrollBar;
20115        public float[] interpolatorValues;
20116        public View host;
20117
20118        public final Paint paint;
20119        public final Matrix matrix;
20120        public Shader shader;
20121
20122        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20123
20124        private static final float[] OPAQUE = { 255 };
20125        private static final float[] TRANSPARENT = { 0.0f };
20126
20127        /**
20128         * When fading should start. This time moves into the future every time
20129         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20130         */
20131        public long fadeStartTime;
20132
20133
20134        /**
20135         * The current state of the scrollbars: ON, OFF, or FADING
20136         */
20137        public int state = OFF;
20138
20139        private int mLastColor;
20140
20141        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20142            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20143            scrollBarSize = configuration.getScaledScrollBarSize();
20144            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20145            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20146
20147            paint = new Paint();
20148            matrix = new Matrix();
20149            // use use a height of 1, and then wack the matrix each time we
20150            // actually use it.
20151            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20152            paint.setShader(shader);
20153            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20154
20155            this.host = host;
20156        }
20157
20158        public void setFadeColor(int color) {
20159            if (color != mLastColor) {
20160                mLastColor = color;
20161
20162                if (color != 0) {
20163                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20164                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20165                    paint.setShader(shader);
20166                    // Restore the default transfer mode (src_over)
20167                    paint.setXfermode(null);
20168                } else {
20169                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20170                    paint.setShader(shader);
20171                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20172                }
20173            }
20174        }
20175
20176        public void run() {
20177            long now = AnimationUtils.currentAnimationTimeMillis();
20178            if (now >= fadeStartTime) {
20179
20180                // the animation fades the scrollbars out by changing
20181                // the opacity (alpha) from fully opaque to fully
20182                // transparent
20183                int nextFrame = (int) now;
20184                int framesCount = 0;
20185
20186                Interpolator interpolator = scrollBarInterpolator;
20187
20188                // Start opaque
20189                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20190
20191                // End transparent
20192                nextFrame += scrollBarFadeDuration;
20193                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20194
20195                state = FADING;
20196
20197                // Kick off the fade animation
20198                host.invalidate(true);
20199            }
20200        }
20201    }
20202
20203    /**
20204     * Resuable callback for sending
20205     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20206     */
20207    private class SendViewScrolledAccessibilityEvent implements Runnable {
20208        public volatile boolean mIsPending;
20209
20210        public void run() {
20211            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20212            mIsPending = false;
20213        }
20214    }
20215
20216    /**
20217     * <p>
20218     * This class represents a delegate that can be registered in a {@link View}
20219     * to enhance accessibility support via composition rather via inheritance.
20220     * It is specifically targeted to widget developers that extend basic View
20221     * classes i.e. classes in package android.view, that would like their
20222     * applications to be backwards compatible.
20223     * </p>
20224     * <div class="special reference">
20225     * <h3>Developer Guides</h3>
20226     * <p>For more information about making applications accessible, read the
20227     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20228     * developer guide.</p>
20229     * </div>
20230     * <p>
20231     * A scenario in which a developer would like to use an accessibility delegate
20232     * is overriding a method introduced in a later API version then the minimal API
20233     * version supported by the application. For example, the method
20234     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20235     * in API version 4 when the accessibility APIs were first introduced. If a
20236     * developer would like his application to run on API version 4 devices (assuming
20237     * all other APIs used by the application are version 4 or lower) and take advantage
20238     * of this method, instead of overriding the method which would break the application's
20239     * backwards compatibility, he can override the corresponding method in this
20240     * delegate and register the delegate in the target View if the API version of
20241     * the system is high enough i.e. the API version is same or higher to the API
20242     * version that introduced
20243     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20244     * </p>
20245     * <p>
20246     * Here is an example implementation:
20247     * </p>
20248     * <code><pre><p>
20249     * if (Build.VERSION.SDK_INT >= 14) {
20250     *     // If the API version is equal of higher than the version in
20251     *     // which onInitializeAccessibilityNodeInfo was introduced we
20252     *     // register a delegate with a customized implementation.
20253     *     View view = findViewById(R.id.view_id);
20254     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20255     *         public void onInitializeAccessibilityNodeInfo(View host,
20256     *                 AccessibilityNodeInfo info) {
20257     *             // Let the default implementation populate the info.
20258     *             super.onInitializeAccessibilityNodeInfo(host, info);
20259     *             // Set some other information.
20260     *             info.setEnabled(host.isEnabled());
20261     *         }
20262     *     });
20263     * }
20264     * </code></pre></p>
20265     * <p>
20266     * This delegate contains methods that correspond to the accessibility methods
20267     * in View. If a delegate has been specified the implementation in View hands
20268     * off handling to the corresponding method in this delegate. The default
20269     * implementation the delegate methods behaves exactly as the corresponding
20270     * method in View for the case of no accessibility delegate been set. Hence,
20271     * to customize the behavior of a View method, clients can override only the
20272     * corresponding delegate method without altering the behavior of the rest
20273     * accessibility related methods of the host view.
20274     * </p>
20275     */
20276    public static class AccessibilityDelegate {
20277
20278        /**
20279         * Sends an accessibility event of the given type. If accessibility is not
20280         * enabled this method has no effect.
20281         * <p>
20282         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20283         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20284         * been set.
20285         * </p>
20286         *
20287         * @param host The View hosting the delegate.
20288         * @param eventType The type of the event to send.
20289         *
20290         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20291         */
20292        public void sendAccessibilityEvent(View host, int eventType) {
20293            host.sendAccessibilityEventInternal(eventType);
20294        }
20295
20296        /**
20297         * Performs the specified accessibility action on the view. For
20298         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20299         * <p>
20300         * The default implementation behaves as
20301         * {@link View#performAccessibilityAction(int, Bundle)
20302         *  View#performAccessibilityAction(int, Bundle)} for the case of
20303         *  no accessibility delegate been set.
20304         * </p>
20305         *
20306         * @param action The action to perform.
20307         * @return Whether the action was performed.
20308         *
20309         * @see View#performAccessibilityAction(int, Bundle)
20310         *      View#performAccessibilityAction(int, Bundle)
20311         */
20312        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20313            return host.performAccessibilityActionInternal(action, args);
20314        }
20315
20316        /**
20317         * Sends an accessibility event. This method behaves exactly as
20318         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20319         * empty {@link AccessibilityEvent} and does not perform a check whether
20320         * accessibility is enabled.
20321         * <p>
20322         * The default implementation behaves as
20323         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20324         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20325         * the case of no accessibility delegate been set.
20326         * </p>
20327         *
20328         * @param host The View hosting the delegate.
20329         * @param event The event to send.
20330         *
20331         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20332         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20333         */
20334        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20335            host.sendAccessibilityEventUncheckedInternal(event);
20336        }
20337
20338        /**
20339         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20340         * to its children for adding their text content to the event.
20341         * <p>
20342         * The default implementation behaves as
20343         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20344         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20345         * the case of no accessibility delegate been set.
20346         * </p>
20347         *
20348         * @param host The View hosting the delegate.
20349         * @param event The event.
20350         * @return True if the event population was completed.
20351         *
20352         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20353         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20354         */
20355        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20356            return host.dispatchPopulateAccessibilityEventInternal(event);
20357        }
20358
20359        /**
20360         * Gives a chance to the host View to populate the accessibility event with its
20361         * text content.
20362         * <p>
20363         * The default implementation behaves as
20364         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20365         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20366         * the case of no accessibility delegate been set.
20367         * </p>
20368         *
20369         * @param host The View hosting the delegate.
20370         * @param event The accessibility event which to populate.
20371         *
20372         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20373         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20374         */
20375        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20376            host.onPopulateAccessibilityEventInternal(event);
20377        }
20378
20379        /**
20380         * Initializes an {@link AccessibilityEvent} with information about the
20381         * the host View which is the event source.
20382         * <p>
20383         * The default implementation behaves as
20384         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20385         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20386         * the case of no accessibility delegate been set.
20387         * </p>
20388         *
20389         * @param host The View hosting the delegate.
20390         * @param event The event to initialize.
20391         *
20392         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20393         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20394         */
20395        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20396            host.onInitializeAccessibilityEventInternal(event);
20397        }
20398
20399        /**
20400         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20401         * <p>
20402         * The default implementation behaves as
20403         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20404         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20405         * the case of no accessibility delegate been set.
20406         * </p>
20407         *
20408         * @param host The View hosting the delegate.
20409         * @param info The instance to initialize.
20410         *
20411         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20412         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20413         */
20414        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20415            host.onInitializeAccessibilityNodeInfoInternal(info);
20416        }
20417
20418        /**
20419         * Called when a child of the host View has requested sending an
20420         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20421         * to augment the event.
20422         * <p>
20423         * The default implementation behaves as
20424         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20425         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20426         * the case of no accessibility delegate been set.
20427         * </p>
20428         *
20429         * @param host The View hosting the delegate.
20430         * @param child The child which requests sending the event.
20431         * @param event The event to be sent.
20432         * @return True if the event should be sent
20433         *
20434         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20435         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20436         */
20437        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20438                AccessibilityEvent event) {
20439            return host.onRequestSendAccessibilityEventInternal(child, event);
20440        }
20441
20442        /**
20443         * Gets the provider for managing a virtual view hierarchy rooted at this View
20444         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20445         * that explore the window content.
20446         * <p>
20447         * The default implementation behaves as
20448         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20449         * the case of no accessibility delegate been set.
20450         * </p>
20451         *
20452         * @return The provider.
20453         *
20454         * @see AccessibilityNodeProvider
20455         */
20456        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20457            return null;
20458        }
20459
20460        /**
20461         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20462         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20463         * This method is responsible for obtaining an accessibility node info from a
20464         * pool of reusable instances and calling
20465         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20466         * view to initialize the former.
20467         * <p>
20468         * <strong>Note:</strong> The client is responsible for recycling the obtained
20469         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20470         * creation.
20471         * </p>
20472         * <p>
20473         * The default implementation behaves as
20474         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20475         * the case of no accessibility delegate been set.
20476         * </p>
20477         * @return A populated {@link AccessibilityNodeInfo}.
20478         *
20479         * @see AccessibilityNodeInfo
20480         *
20481         * @hide
20482         */
20483        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20484            return host.createAccessibilityNodeInfoInternal();
20485        }
20486    }
20487
20488    private class MatchIdPredicate implements Predicate<View> {
20489        public int mId;
20490
20491        @Override
20492        public boolean apply(View view) {
20493            return (view.mID == mId);
20494        }
20495    }
20496
20497    private class MatchLabelForPredicate implements Predicate<View> {
20498        private int mLabeledId;
20499
20500        @Override
20501        public boolean apply(View view) {
20502            return (view.mLabelForId == mLabeledId);
20503        }
20504    }
20505
20506    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20507        private int mChangeTypes = 0;
20508        private boolean mPosted;
20509        private boolean mPostedWithDelay;
20510        private long mLastEventTimeMillis;
20511
20512        @Override
20513        public void run() {
20514            mPosted = false;
20515            mPostedWithDelay = false;
20516            mLastEventTimeMillis = SystemClock.uptimeMillis();
20517            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20518                final AccessibilityEvent event = AccessibilityEvent.obtain();
20519                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20520                event.setContentChangeTypes(mChangeTypes);
20521                sendAccessibilityEventUnchecked(event);
20522            }
20523            mChangeTypes = 0;
20524        }
20525
20526        public void runOrPost(int changeType) {
20527            mChangeTypes |= changeType;
20528
20529            // If this is a live region or the child of a live region, collect
20530            // all events from this frame and send them on the next frame.
20531            if (inLiveRegion()) {
20532                // If we're already posted with a delay, remove that.
20533                if (mPostedWithDelay) {
20534                    removeCallbacks(this);
20535                    mPostedWithDelay = false;
20536                }
20537                // Only post if we're not already posted.
20538                if (!mPosted) {
20539                    post(this);
20540                    mPosted = true;
20541                }
20542                return;
20543            }
20544
20545            if (mPosted) {
20546                return;
20547            }
20548            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20549            final long minEventIntevalMillis =
20550                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20551            if (timeSinceLastMillis >= minEventIntevalMillis) {
20552                removeCallbacks(this);
20553                run();
20554            } else {
20555                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20556                mPosted = true;
20557                mPostedWithDelay = true;
20558            }
20559        }
20560    }
20561
20562    private boolean inLiveRegion() {
20563        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20564            return true;
20565        }
20566
20567        ViewParent parent = getParent();
20568        while (parent instanceof View) {
20569            if (((View) parent).getAccessibilityLiveRegion()
20570                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20571                return true;
20572            }
20573            parent = parent.getParent();
20574        }
20575
20576        return false;
20577    }
20578
20579    /**
20580     * Dump all private flags in readable format, useful for documentation and
20581     * sanity checking.
20582     */
20583    private static void dumpFlags() {
20584        final HashMap<String, String> found = Maps.newHashMap();
20585        try {
20586            for (Field field : View.class.getDeclaredFields()) {
20587                final int modifiers = field.getModifiers();
20588                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20589                    if (field.getType().equals(int.class)) {
20590                        final int value = field.getInt(null);
20591                        dumpFlag(found, field.getName(), value);
20592                    } else if (field.getType().equals(int[].class)) {
20593                        final int[] values = (int[]) field.get(null);
20594                        for (int i = 0; i < values.length; i++) {
20595                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20596                        }
20597                    }
20598                }
20599            }
20600        } catch (IllegalAccessException e) {
20601            throw new RuntimeException(e);
20602        }
20603
20604        final ArrayList<String> keys = Lists.newArrayList();
20605        keys.addAll(found.keySet());
20606        Collections.sort(keys);
20607        for (String key : keys) {
20608            Log.d(VIEW_LOG_TAG, found.get(key));
20609        }
20610    }
20611
20612    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20613        // Sort flags by prefix, then by bits, always keeping unique keys
20614        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20615        final int prefix = name.indexOf('_');
20616        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20617        final String output = bits + " " + name;
20618        found.put(key, output);
20619    }
20620}
20621